They were www.guzzle.com at https://marsh.mallows.com and FOX news
' # noqa: E501\n expected_body = 'They were www.guzzle.com at https://marsh.mallows.com and FOX news
' # noqa: E501\n updated_note_response = self._api_note_update(\n app,\n client,\n note_id=mock_coe_advising_note.id,\n subject=expected_subject,\n body=body,\n )\n assert updated_note_response['read'] is True\n updated_note = Note.find_by_id(note_id=mock_coe_advising_note.id)\n assert updated_note.subject == expected_subject\n assert updated_note.body == expected_body\n\n def test_update_note_topics(self, app, client, fake_auth, mock_asc_advising_note):\n \"\"\"Update note topics.\"\"\"\n fake_auth.login(mock_asc_advising_note.author_uid)\n expected_topics = ['Blinking lights', ' and other revelations']\n api_json = self._api_note_update(\n app,\n client,\n note_id=mock_asc_advising_note.id,\n subject=mock_asc_advising_note.subject,\n body=mock_asc_advising_note.body,\n topics=expected_topics,\n )\n assert api_json['read'] is True\n assert len(api_json['topics']) == 2\n assert 'Blinking lights' in api_json['topics']\n assert ' and other revelations' in api_json['topics']\n\n def test_remove_note_topics(self, app, client, fake_auth, mock_asc_advising_note):\n \"\"\"Delete note topics.\"\"\"\n fake_auth.login(mock_asc_advising_note.author_uid)\n original_topics = mock_asc_advising_note.topics\n assert len(original_topics)\n api_json = self._api_note_update(\n app,\n client,\n note_id=mock_asc_advising_note.id,\n subject=mock_asc_advising_note.subject,\n body=mock_asc_advising_note.body,\n topics=[],\n )\n assert not api_json['topics']\n # Put those topics back\n api_json = self._api_note_update(\n app,\n client,\n note_id=mock_asc_advising_note.id,\n subject=mock_asc_advising_note.subject,\n body=mock_asc_advising_note.body,\n topics=[t.topic for t in original_topics],\n )\n assert set(api_json['topics']) == set([t.topic for t in original_topics])\n\n\nclass TestDeleteNote:\n \"\"\"Delete note API.\"\"\"\n\n def test_not_authenticated(self, client):\n \"\"\"You must log in to delete a note.\"\"\"\n response = client.delete('/api/notes/delete/123')\n assert response.status_code == 401\n\n def test_user_without_advising_data_access(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n fake_auth.login(coe_advisor_no_advising_data_uid)\n response = client.delete(f'/api/notes/delete/{mock_coe_advising_note.id}')\n assert response.status_code == 401\n assert Note.find_by_id(mock_coe_advising_note.id)\n\n def test_unauthorized(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Advisor cannot delete the note of another.\"\"\"\n fake_auth.login('6446')\n response = client.delete(f'/api/notes/delete/{mock_coe_advising_note.id}')\n assert response.status_code == 403\n assert Note.find_by_id(mock_coe_advising_note.id)\n\n def test_advisor_cannot_delete(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Advisor cannot delete her own note.\"\"\"\n fake_auth.login(mock_coe_advising_note.author_uid)\n response = client.delete(f'/api/notes/delete/{mock_coe_advising_note.id}')\n assert response.status_code == 403\n assert Note.find_by_id(mock_coe_advising_note.id)\n\n def test_admin_delete(self, client, fake_auth, mock_coe_advising_note):\n \"\"\"Admin can delete another user's note.\"\"\"\n original_count_per_sid = len(Note.get_notes_by_sid(mock_coe_advising_note.sid))\n fake_auth.login(admin_uid)\n note_id = mock_coe_advising_note.id\n response = client.delete(f'/api/notes/delete/{note_id}')\n assert response.status_code == 200\n assert not Note.find_by_id(note_id)\n assert 1 == original_count_per_sid - len(Note.get_notes_by_sid(mock_coe_advising_note.sid))\n assert not Note.update(note_id=note_id, subject='Deleted note cannot be updated')\n\n def test_delete_note_with_topics(self, app, client, fake_auth):\n \"\"\"Delete a note with topics.\"\"\"\n fake_auth.login(coe_advisor_uid)\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='Recontextualize open-source supply-chains',\n body='Conveniently repurpose enterprise-wide action items',\n topics=['strategic interfaces'],\n )\n # Log in as Admin and delete the note\n fake_auth.login(admin_uid)\n note_id = note.get('id')\n response = client.delete(f'/api/notes/delete/{note_id}')\n assert response.status_code == 200\n # TODO: add deleted_at column to NoteTopic and populate it when parent Note is deleted.\n # assert not NoteTopic.find_by_note_id(note_id)\n\n def test_delete_note_with_attachments(self, app, client, fake_auth):\n \"\"\"Delete a note with two attachments.\"\"\"\n fake_auth.login(coe_advisor_uid)\n base_dir = app.config['BASE_DIR']\n note = _api_note_create(\n app,\n client,\n author_id=AuthorizedUser.get_id_per_uid(coe_advisor_uid),\n sids=[coe_student['sid']],\n subject='My little dog Lassie packed her bags and went out on to the porch',\n body='Then my little dog Lassie, she sailed off to the moon',\n attachments=[\n f'{base_dir}/fixtures/mock_advising_note_attachment_1.txt',\n f'{base_dir}/fixtures/mock_advising_note_attachment_2.txt',\n ],\n )\n attachment_ids = [a['id'] for a in note.get('attachments')]\n assert len(attachment_ids) == 2\n assert NoteAttachment.find_by_id(attachment_ids[0]) and NoteAttachment.find_by_id(attachment_ids[1])\n\n # Log in as Admin and delete the note\n fake_auth.login(admin_uid)\n note_id = note['id']\n response = client.delete(f'/api/notes/delete/{note_id}')\n assert response.status_code == 200\n assert not NoteAttachment.find_by_id(attachment_ids[0])\n assert not NoteAttachment.find_by_id(attachment_ids[1])\n\n\nclass TestStreamNoteAttachments:\n\n def test_not_authenticated(self, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n assert client.get('/api/notes/attachment/9000000000_00002_1.pdf').status_code == 401\n\n def test_user_without_advising_data_access(self, app, client, fake_auth):\n \"\"\"Denies access to a user who cannot access notes and appointments.\"\"\"\n with mock_legacy_note_attachment(app):\n fake_auth.login(coe_advisor_no_advising_data_uid)\n assert client.get('/api/notes/attachment/9000000000_00002_1.pdf').status_code == 401\n\n def test_stream_attachment(self, app, client, fake_auth):\n with mock_legacy_note_attachment(app):\n fake_auth.login(coe_advisor_uid)\n response = client.get('/api/notes/attachment/9000000000_00002_1.pdf')\n assert response.status_code == 200\n assert response.headers['Content-Type'] == 'application/octet-stream'\n assert response.headers['Content-Disposition'] == \"attachment; filename*=UTF-8''dog_eaten_homework.pdf\"\n assert response.data == b'When in the course of human events, it becomes necessarf arf woof woof woof'\n\n def test_stream_attachment_reports_missing_files_not_found(self, app, client, fake_auth):\n with mock_legacy_note_attachment(app):\n fake_auth.login(asc_advisor_uid)\n response = client.get('/api/notes/attachment/h0ax.lol')\n assert response.status_code == 404\n assert response.data == b'Sorry, attachment not available.'\n\n\nclass TestStreamNotesZip:\n\n def test_not_authenticated(self, client):\n \"\"\"Returns 401 if not authenticated.\"\"\"\n assert client.get('/api/notes/download_for_sid/9000000000').status_code == 401\n\n def test_not_authorized(self, client, fake_auth):\n \"\"\"Returns 401 if not admin or director.\"\"\"\n fake_auth.login(coe_advisor_uid)\n assert client.get('/api/notes/download_for_sid/9000000000').status_code == 401\n\n def test_director_without_advising_data_access(self, client, fake_auth):\n \"\"\"Denies access to a director who cannot access notes and appointments.\"\"\"\n fake_auth.login(l_s_director_no_advising_data_uid)\n assert client.get('/api/notes/download_for_sid/9000000000').status_code == 401\n\n def test_not_found(self, client, fake_auth):\n \"\"\"Returns 404 if SID not found.\"\"\"\n fake_auth.login(admin_uid)\n assert client.get('/api/notes/download_for_sid/9999999999').status_code == 404\n\n def _assert_zip_download(self, app, client):\n today = localize_datetime(utc_now()).strftime('%Y%m%d')\n with mock_legacy_note_attachment(app):\n response = client.get('/api/notes/download_for_sid/9000000000')\n assert response.status_code == 200\n assert response.headers['Content-Type'] == 'application/zip'\n assert response.headers['Content-Disposition'] == f\"attachment; filename=advising_notes_wolfgang_pauli-o'rourke_{today}.zip\"\n assert response.data\n\n def test_authorizes_director(self, app, client, fake_auth):\n fake_auth.login(l_s_director_uid)\n self._assert_zip_download(app, client)\n\n def test_authorizes_admin(self, app, client, fake_auth):\n fake_auth.login(admin_uid)\n self._assert_zip_download(app, client)\n\n\ndef _get_notes(client, uid):\n response = client.get(f'/api/student/by_uid/{uid}')\n assert response.status_code == 200\n return response.json['notifications']['note']\n\n\ndef _asc_note_with_attachment():\n for note in Note.get_notes_by_sid('11667051'):\n if len(note.attachments):\n return note\n return None\n\n\ndef _api_note_create(\n app,\n client,\n author_id,\n sids,\n subject,\n body,\n topics=(),\n attachments=(),\n template_attachment_ids=(),\n expected_status_code=200,\n):\n with mock_advising_note_s3_bucket(app):\n data = {\n 'authorId': author_id,\n 'sids': sids,\n 'subject': subject,\n 'body': body,\n 'topics': ','.join(topics),\n 'templateAttachmentIds': ','.join(str(_id) for _id in template_attachment_ids),\n }\n for index, path in enumerate(attachments):\n data[f'attachment[{index}]'] = open(path, 'rb')\n response = client.post(\n '/api/notes/create',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == expected_status_code\n return response.json\n\n\ndef _api_batch_note_create(\n app,\n client,\n author_id,\n subject,\n body,\n sids=None,\n cohort_ids=None,\n curated_group_ids=None,\n topics=(),\n attachments=(),\n template_attachment_ids=(),\n expected_status_code=200,\n):\n with mock_advising_note_s3_bucket(app):\n data = {\n 'authorId': author_id,\n 'isBatchMode': sids and len(sids) > 1,\n 'sids': sids or [],\n 'cohortIds': cohort_ids or [],\n 'curatedGroupIds': curated_group_ids or [],\n 'subject': subject,\n 'body': body,\n 'templateAttachmentIds': template_attachment_ids or [],\n 'topics': ','.join(topics),\n }\n for index, path in enumerate(attachments):\n data[f'attachment[{index}]'] = open(path, 'rb')\n response = client.post(\n '/api/notes/create',\n buffered=True,\n content_type='multipart/form-data',\n data=data,\n )\n assert response.status_code == expected_status_code\n\n\ndef _get_curated_groups_ids_and_sids(advisor):\n sids = []\n curated_group_ids = []\n for curated_group in CuratedGroup.get_curated_groups_by_owner_id(advisor.id):\n curated_group_ids.append(curated_group.id)\n sids = sids + CuratedGroup.get_all_sids(curated_group.id)\n return curated_group_ids, sids\n\n\ndef _get_cohorts_ids_and_sids(advisor):\n cohort_ids = [c['id'] for c in all_cohorts_owned_by(advisor.uid)]\n sids = []\n for cohort_id in cohort_ids:\n sids = sids + CohortFilter.get_sids(cohort_id)\n return cohort_ids, sids\n","sub_path":"tests/test_api/test_notes_controller.py","file_name":"test_notes_controller.py","file_ext":"py","file_size_in_byte":38706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"71576975","text":"# -*- coding: utf-8 -*-\n\"\"\"\n This spider is a JobRu spider created on top of the ATSSpider\n scrapy crawl jobrujobs -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.job.ru/seeker/job/?period=0&rgnc=B2&srch=1\"\n\n sample job url:\n http://www.job.ru/sales/6498172\n\"\"\"\n\nfrom re import compile, sub\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin, \\\n ConvertDateString, Replace\nfrom brightcorp.lib.utils import extract_first\n\n\nclass JobRu(ATSSpider):\n\n name = \"jobrujobs\"\n RNGC_Value = compile(r\"&rgnc=(\\S+)\")\n common_xpath = '//div[contains(text(), \"%s\")]/text()'\n desc_tag_xpath = '//h2[contains(text(), \"%s\")]'\n desc_xpath = '//h2[contains(text(), \"%s\")]/following-sibling::p[1]'\n\n def parse(self, response):\n # Adding these values, to get jobs from other regions as well.\n # This is hard-coded because we are unable to get them from site\n url_values = [\n 'B2', 'B167', 'B251', 'B259', 'B267', 'B271', 'B275',\n 'B281', 'B285', 'B294', 'B304', 'B310', 'B323', 'B335',\n 'B340', 'B350', 'B354', 'B360', 'B541', 'B372', 'B379',\n 'B383', 'B391', 'B395', 'B235', 'B399', 'B403', 'B407',\n 'B411', 'B415', 'B419', 'B423', 'B427', 'B431', 'B435',\n 'B440', 'B239', 'B448', 'B452', 'B462', 'A1', 'B243',\n ]\n rngc_value = self.RNGC_Value.search(response.url)\n if rngc_value:\n for url_value in url_values:\n job_list_url = sub(rngc_value.group(1), url_value, response.url)\n yield Request(\n callback=self.parse_jobs_list,\n dont_filter=True,\n url=job_list_url\n )\n\n def parse_jobs_list(self, response):\n selector = Selector(response)\n jobs = selector.xpath(\n '//div[@class=\"sr_list sr_search\"]/div[contains(@class, \"sr_row dotbrdr js_job_item\")]'\n )\n for job in jobs:\n url = job.xpath('.//td[1]//a/@href').extract()\n if url:\n meta = {\n 'salary': job.xpath(\n './/span[@class=\"srSalary\"]//text()'\n ).extract(),\n 'title': job.xpath(\n './/div[@class=\"wrapTD\"]/a/text()'\n ).extract(),\n 'company': job.xpath(\n './/a[@class=\"srCompName nonv\"]/text()'\n ).extract(),\n 'location': job.xpath(\n './/div[@class=\"srAdress\"]/text()'\n ).extract(),\n 'ref_num': job.xpath('./@data-id').extract(),\n }\n yield Request(\n callback=self.parse_job_callback(),\n meta=meta,\n url=urljoin(response.url, url[0])\n )\n\n next_page_url = extract_first(selector.xpath(\n '//ul[@class=\"paging\"]/li[@class=\"sel\"]/following-sibling::li/a/@href'\n ))\n if next_page_url:\n yield Request(\n callback=self.parse_jobs_list,\n url=urljoin(response.url, next_page_url)\n )\n\n def parse_job(self, response):\n selector = Selector(response)\n loader = BrightcorpItemLoader(selector=selector)\n\n other_fields = selector.xpath(\n '//div[@class=\"info-block\"]/div'\n ).extract()\n if len(other_fields) == 3:\n loader.add_xpath(\n 'educationrequirements',\n '//div[@class=\"info-block\"]/div[2]/text()'\n )\n\n loader.add_xpath(\n 'benefits',\n [\n self.desc_tag_xpath % unicode('Условия', 'utf-8'),\n self.desc_xpath % unicode('Условия', 'utf-8')\n ],\n NormalizedJoin()\n )\n loader.add_xpath(\n 'date',\n self.common_xpath % unicode('Размещено', 'utf-8'),\n Replace(unicode('Размещено', 'utf-8')),\n ConvertDateString('%d.%m.%Y')\n )\n loader.add_xpath(\n 'description',\n [\n self.desc_tag_xpath % unicode('Описание вакансии', 'utf-8'),\n self.desc_xpath % unicode('Описание вакансии', 'utf-8'),\n ]\n )\n loader.add_xpath(\n 'jobcategory',\n '//div[@class=\"job-sphere\"]//a[@class=\"pseudo-link nowrap\"]/text()'\n )\n loader.add_xpath(\n 'experiencerequirements',\n self.common_xpath % unicode('Опыт работы:', 'utf-8'),\n Replace(unicode('Опыт работы:', 'utf-8'))\n )\n loader.add_xpath(\n 'requirements',\n [\n self.desc_tag_xpath % unicode('Требования', 'utf-8'),\n self.desc_xpath % unicode('Требования', 'utf-8'),\n ]\n )\n\n loader.add_value(\n 'baseSalary', response.meta.get('salary'), NormalizedJoin()\n )\n loader.add_value(\n 'referencenumber',\n response.meta.get('ref_num'),\n Prefix('%s-' % self.name)\n )\n loader.add_value('apply_url', response.url)\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/jobrujobs.py","file_name":"jobrujobs.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"358244696","text":"import pandas as pd\nimport numpy as np\nimport os\nimport argparse\nimport _utils\nfrom sklearn.model_selection import train_test_split\n\n\"\"\"\nSplits input data into n folds for Flair model training and later ML.\nExample use:\n\npython3 input_data_splitter.py --folds=5 --dependent_variable=respect\n\"\"\"\n\nparser = argparse.ArgumentParser(description='split_input_data')\nparser.add_argument(\"--dependent_variable\", required=False, default=\"respect\", type=str)\nparser.add_argument(\"--folds\", required=False, default=5, type=int)\nparser.add_argument(\"--filepath\", required=False, default='input_file.xlsx', type=str)\nargs = parser.parse_args()\n\nfilepath = os.path.join('./data/source_data/', args.filepath)\ndata_file_name = args.filepath.split('.')[0]\ndata_file_extension = args.filepath.split('.')[1]\ndependent_variable = args.dependent_variable\nfolds = args.folds\n\n# read original data file\nif data_file_extension == \"xlsx\":\n df = pd.read_excel(filepath, converters={'dummy_id': str})\nelif data_file_extension == \"csv\":\n df = pd.read_csv(filepath, converters={'dummy_id': str})\n\n# use only selected columns\ndf = df[[dependent_variable, \"text\"]]\n# change format of 'sentiment' label for further training in Flair framework\ndf[dependent_variable] = '__label__' + df[dependent_variable].astype(str)\n\n# Cross validation\n# create data splits for Deep Learning Language Models trained with Flair framework\ntrain_indexes = dict()\nval_indexes = dict()\ntest_indexes = dict()\n\n# train sets for Machine Learning\ntrain_ml = dict()\n\nkf = _utils.splitter(folds=folds, df=df)\n\ni = 0\nfor train_index, test_index in kf:\n test_indexes[i] = test_index\n train_ml[i] = train_index\n train_index, val_index = train_test_split(train_index, test_size=0.125, random_state=13, shuffle=True)\n train_indexes[i] = train_index\n val_indexes[i] = val_index\n i += 1\n \n# test sets for Machine Learning are equal to those for Flair framework\ntest_ml = test_indexes\n\n# create folders for FLAIR data splits and .tsv files for training\nfolds_path = list()\nfor fold in range(folds):\n folds_path.append(f'./data/models/{dependent_variable}_{data_file_name}_{str(fold)}/')\n try:\n os.mkdir(f'./data/models/{dependent_variable}_{data_file_name}_{str(fold)}')\n except FileExistsError:\n pass # continue\n df.iloc[test_indexes[fold]].to_csv(os.path.join(folds_path[fold], \"test_.tsv\"),\n index=False, header=False, encoding='utf-8', sep='\\t')\n df.iloc[train_indexes[fold]].to_csv(os.path.join(folds_path[fold], \"train.tsv\"),\n index=False, header=False, encoding='utf-8', sep='\\t')\n df.iloc[val_indexes[fold]].to_csv(os.path.join(folds_path[fold], \"dev.tsv\"),\n index=False, header=False, encoding='utf-8', sep='\\t')\n","sub_path":"input_data_splitter.py","file_name":"input_data_splitter.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"332706397","text":"#!/usr/bin/env python3\n\nimport requests\nimport json\nimport base64\n\n\nclass Picture(object):\n def __init__(self, path):\n self.path = path\n\n def get_ocr_result(self, ocr_api):\n data = {\"images\": [self._to_base64()]}\n headers = {\"Content-type\": \"application/json\"}\n res = requests.post(url=ocr_api, headers=headers, data=json.dumps(data))\n text = [x[\"text\"] for x in res.json()[\"results\"][0][\"data\"]]\n return \"\\n\".join(text)\n\n def _to_base64(self):\n with open(self.path, \"rb\") as f:\n data = f.read()\n return base64.b64encode(data).decode(\"utf8\")\n\n\nif __name__ == \"__main__\":\n ocr_api = \"http://198.18.0.153:8865/predict/chinese_ocr_db_crnn_mobile\"\n pic_path = \"/Users/yuchen/Notes/imgs/Shao Nian Kai Ge - Chen Kai Ge-annot-44-0.png\"\n Picture(pic_path).get_ocr_result(ocr_api)\n","sub_path":"picture_handler.py","file_name":"picture_handler.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"631636132","text":"from collections import namedtuple\nimport tensorflow as tf\n\n\ndef get_cityscapes():\n Label = namedtuple('Label', ['name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances', 'ignoreInEval', 'color'])\n\n labels = [\n # name id trainId category catId hasInstances ignoreInEval color\n Label('unlabeled', 0, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('ego vehicle', 1, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('rectification border', 2, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('out of roi', 3, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('static', 4, 255, 'void', 0, False, True, (0, 0, 0)),\n Label('dynamic', 5, 255, 'void', 0, False, True, (111, 74, 0)),\n Label('ground', 6, 255, 'void', 0, False, True, (81, 0, 81)),\n Label('road', 7, 0, 'flat', 1, False, False, (128, 64, 128)),\n Label('sidewalk', 8, 1, 'flat', 1, False, False, (244, 35, 232)),\n Label('parking', 9, 255, 'flat', 1, False, True, (250, 170, 160)),\n Label('rail track', 10, 255, 'flat', 1, False, True, (230, 150, 140)),\n Label('building', 11, 2, 'construction', 2, False, False, (70, 70, 70)),\n Label('wall', 12, 3, 'construction', 2, False, False, (102, 102, 156)),\n Label('fence', 13, 4, 'construction', 2, False, False, (190, 153, 153)),\n Label('guard rail', 14, 255, 'construction', 2, False, True, (180, 165, 180)),\n Label('bridge', 15, 255, 'construction', 2, False, True, (150, 100, 100)),\n Label('tunnel', 16, 255, 'construction', 2, False, True, (150, 120, 90)),\n Label('pole', 17, 5, 'object', 3, False, False, (153, 153, 153)),\n Label('polegroup', 18, 255, 'object', 3, False, True, (153, 153, 153)),\n Label('traffic light', 19, 6, 'object', 3, False, False, (250, 170, 30)),\n Label('traffic sign', 20, 7, 'object', 3, False, False, (220, 220, 0)),\n Label('vegetation', 21, 8, 'nature', 4, False, False, (107, 142, 35)),\n Label('terrain', 22, 9, 'nature', 4, False, False, (152, 251, 152)),\n Label('sky', 23, 10, 'sky', 5, False, False, (70, 130, 180)),\n Label('person', 24, 11, 'human', 6, True, False, (220, 20, 60)),\n Label('rider', 25, 12, 'human', 6, True, False, (255, 0, 0)),\n Label('car', 26, 13, 'vehicle', 7, True, False, (0, 0, 142)),\n Label('truck', 27, 14, 'vehicle', 7, True, False, (0, 0, 70)),\n Label('bus', 28, 15, 'vehicle', 7, True, False, (0, 60, 100)),\n Label('caravan', 29, 255, 'vehicle', 7, True, True, (0, 0, 90)),\n Label('trailer', 30, 255, 'vehicle', 7, True, True, (0, 0, 110)),\n Label('train', 31, 16, 'vehicle', 7, True, False, (0, 80, 100)),\n Label('motorcycle', 32, 17, 'vehicle', 7, True, False, (0, 0, 230)),\n Label('bicycle', 33, 18, 'vehicle', 7, True, False, (119, 11, 32)),\n Label('license plate', -1, -1, 'vehicle', 7, False, True, (255, 234, 142)),\n ]\n return labels\n\n\ndef generate_random_colors(n=256, seed=0, bg_class=0):\n cmap_mask = 1 - tf.one_hot(bg_class, depth=256, dtype=tf.int32)[..., tf.newaxis]\n cmp = tf.random.uniform((n, 3), minval=0, maxval=255, dtype=tf.int32, seed=seed) * cmap_mask\n return cmp\n\n\ndef convert_cs_19(segmentation):\n cs_19_map = [tf.where(segmentation == label[1], label[2] + 1, 0)\n for label in get_cityscapes()\n if (label[2] != 255 and label[2] != -1)]\n cs_19_map = sum(cs_19_map) - 1\n cs_19_map = tf.cast(cs_19_map, tf.int32)\n return cs_19_map\n\n\ndef gpu_cs_labels(segmentation_maps):\n \"\"\"\n segmentation_map: (b, h, w, 1) or (b, h, w)\n \"\"\"\n ncmap = [label[-1] for label in get_cityscapes() if (label[2] != 255 and label[2] != -1)]\n color_imgs = tf.gather(params=ncmap, indices=tf.cast(segmentation_maps, dtype=tf.int32))\n return color_imgs\n\n\ndef gpu_random_labels(segmentation_maps, cmp):\n \"\"\"\n segmentation_map: (b, h, w, 1) or (b, h, w)\n \"\"\"\n if len(segmentation_maps.shape) == 4:\n segmentation_maps = segmentation_maps[..., 0]\n color_imgs = tf.gather(params=cmp, indices=tf.cast(segmentation_maps, dtype=tf.int32))\n return color_imgs\n\n\nif __name__ == \"__main__\":\n cs_dict = get_cityscapes()\n ncmap = [label[-1] if (label[2] != 255 and label[2] != -1) else (0, 0, 0) for label in cs_dict]\n print(\"a\")\n","sub_path":"visualization_dicts.py","file_name":"visualization_dicts.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"407674167","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBarycenters\n===========\n\nThis example shows three methods to compute barycenters of time series.\n\"\"\"\n\n# Author: Romain Tavenard\n# License: BSD 3 clause\n\nimport numpy\nimport matplotlib.pyplot as plt\n\nfrom tslearn.barycenters import EuclideanBarycenter, DTWBarycenterAveraging, SoftDTWBarycenter\nfrom tslearn.datasets import CachedDatasets\n\nnumpy.random.seed(0)\nX_train, y_train, X_test, y_test = CachedDatasets().load_dataset(\"Trace\")\nX = X_train[y_train == 2]\n\nplt.figure()\nplt.subplot(3, 1, 1)\nfor ts in X:\n plt.plot(ts.ravel(), \"k-\", alpha=.2)\nplt.plot(EuclideanBarycenter().fit(X).ravel(), \"r-\", linewidth=2)\nplt.title(\"Euclidean barycenter\")\n\nplt.subplot(3, 1, 2)\ndba = DTWBarycenterAveraging(max_iter=100, verbose=False)\ndba_bar = dba.fit(X)\nfor ts in X:\n plt.plot(ts.ravel(), \"k-\", alpha=.2)\nplt.plot(dba_bar.ravel(), \"r-\", linewidth=2)\nplt.title(\"DBA\")\n\nplt.subplot(3, 1, 3)\nsdtw = SoftDTWBarycenter(gamma=1., max_iter=100)\nsdtw_bar = sdtw.fit(X)\nfor ts in X:\n plt.plot(ts.ravel(), \"k-\", alpha=.2)\nplt.plot(sdtw_bar.ravel(), \"r-\", linewidth=2)\nplt.title(\"Soft-DTW barycenter ($\\gamma$=1.)\")\n\nplt.tight_layout()\nplt.show()\n","sub_path":"tslearn/docs/examples/plot_barycenters.py","file_name":"plot_barycenters.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"592989000","text":"\n# coding: utf-8\n\n# In[ ]:\n\ndef cleanDicts(adict):\n import re\n req = {}\n imp = {'Cooling',\n 'Exterior material',\n 'Floor Description',\n 'Flooring',\n 'Fuel Information',\n 'Heating',\n 'MLS #',\n 'Parcel #',\n 'Stories',\n 'Unit count',\n 'Views since listing', \n 'Zillow Home ID',\n 'Last remodel year'\n }\n for items in adict:\n if items in imp:\n req[items] = adict[items]\n elif items in ['Floor size','Price/sqft','Lot depth', 'Lot width'] :\n x = re.sub('\\W+',\"\",adict[items])\n req[items] = re.findall('(\\d+)',x)[0]\n elif items == 'Last sold':\n groups = re.findall('(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{4})\\s(\\w{3})\\s(\\$.*)',adict[items])[0]\n month_dict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4,'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}\n req['last_sold_on'] = str(month_dict[groups[0]]) + '/' + str(groups[1])\n req['last_sold_for'] = re.sub('\\W+',\"\",groups[3])\n elif items in ['MLS #','Parcel #','Zillow Home ID']:\n req[items] = re.sub('\\s+',\"\",adict[items])\n return req\n\n","sub_path":"download_zillow/zillow/spiders/clean_dicts.py","file_name":"clean_dicts.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"627294697","text":"class Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n cols = len(grid[0])\n \n if rows == 0 or cols == 0:\n return 0\n \n count = 0\n points = []\n com_per_row = [0] * rows\n com_per_col = [0] * cols\n \n for i in range(rows):\n for j in range(cols):\n if grid[i][j] != 0:\n points.append((i, j))\n com_per_row[i] += 1 \n com_per_col[j] += 1\n \n for i, j in points:\n if com_per_row[i] > 1 or com_per_col[j] > 1:\n count += 1\n \n return count\n\n\n\n\n\n# class Solution:\n# def countServers(self, grid: List[List[int]]) -> int:\n# res = 0\n# al = 0\n# row = []\n# col = []\n# for i in range(len(grid)):\n# row.append(sum(grid[i]))\n# for j in range(len(grid[0])):\n# tmp = 0\n# for i in range(len(grid)):\n# tmp += grid[i][j]\n# col.append(tmp)\n# for i in range(len(grid)):\n# for j in range(len(grid[0])):\n# if grid[i][j] == 1:\n# al += 1\n# if row[i] == 1 and col[j] == 1:\n# res += 1\n# return al - res","sub_path":"2020_02_11/saurystand_1267.py","file_name":"saurystand_1267.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"641780561","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom alfred_bot import Bot\nfrom alfred_bot.settings import TOKEN_BOT\n\nlogging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO)\n\n\ndef main():\n try:\n bot = Bot(TOKEN_BOT)\n bot.start()\n except Exception as error:\n raise error\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"alfred_bot/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"236288551","text":"__all__ = [\"TacsModel\"]\n\nimport pyCAPS\nfrom .tacs_aim import TacsAim\nfrom .egads_aim import EgadsAim\nfrom .analysis_function import AnalysisFunction, Derivative\nfrom .materials import Material\nfrom .constraints import Constraint\nfrom .property import ShellProperty\nfrom .loads import Load\nfrom .variables import ShapeVariable, ThicknessVariable\nfrom .egads_aim import EgadsAim\nfrom .aflr_aim import AflrAim\nfrom typing import List\nfrom tacs.pytacs import pyTACS\n\n\nclass TacsModel:\n MESH_AIMS = [\"egads\", \"aflr\"]\n\n def __init__(self, tacs_aim: TacsAim, mesh_aim, comm=None):\n self._tacs_aim = tacs_aim\n self._mesh_aim = mesh_aim\n self.comm = comm\n\n self._analysis_functions = []\n self.SPs = None\n self._setup = False\n self._first_analysis = True\n\n @property\n def tacs_aim(self) -> TacsAim:\n return self._tacs_aim\n\n @property\n def mesh_aim(self) -> AflrAim:\n return self._mesh_aim\n\n @property\n def uses_egads(self):\n return isinstance(self.mesh_aim, EgadsAim)\n\n @property\n def uses_aflr(self):\n return isinstance(self.mesh_aim, AflrAim)\n\n @classmethod\n def build(cls, csm_file, comm=None, mesh=\"egads\", problem_name: str = \"capsStruct\", verbosity=1):\n \"\"\"\n make a pyCAPS problem with the tacsAIM and egadsAIM on serial / root proc\n\n Parameters\n ---------------------------------\n csm_file : filepath\n filename / full path of ESP/CAPS Constructive Solid Model or .CSM file\n comm : MPI.COMM\n MPI communicator\n \"\"\"\n\n caps_problem = None\n assert mesh in cls.MESH_AIMS\n if comm is None or comm.rank == 0:\n caps_problem = pyCAPS.Problem(\n problemName=problem_name, capsFile=csm_file, outLevel=verbosity\n )\n tacs_aim = TacsAim(caps_problem, comm)\n mesh_aim = None\n if mesh == \"egads\":\n mesh_aim = EgadsAim(caps_problem, comm)\n elif mesh == \"aflr\":\n mesh_aim = AflrAim(caps_problem, comm)\n return cls(tacs_aim, mesh_aim, comm)\n\n def get_config_parameter(self, param_name: str):\n return self.tacs_aim.get_config_parameter(param_name=param_name)\n\n def register(self, obj):\n \"\"\"\n register each of the objects to the tacs model\n can also register any object for the tacs aim to the tacs model which passes it on\n \"\"\"\n\n if isinstance(obj, AnalysisFunction):\n self._analysis_functions.append(obj)\n\n tacs_aim_objects = [\n Material,\n ThicknessVariable,\n ShapeVariable,\n ShellProperty,\n Constraint,\n Load,\n EgadsAim,\n AflrAim,\n ]\n for tacs_aim_obj in tacs_aim_objects:\n if isinstance(obj, tacs_aim_obj):\n self.tacs_aim.register(obj)\n return\n\n return\n\n def setup(self, include_aim: bool = True):\n \"\"\"\n setup the analysis functions to store derivatives\n\n Parameters\n --------------------------------------------\n auto_tacs_aim : bool\n automatically setup the tacs aim too\n \"\"\"\n # add each variable as a derivative object for each analysis function\n for func in self.analysis_functions:\n for var in self.variables:\n func._derivatives.append(Derivative(name=var.name, value=0.0))\n\n if include_aim:\n self.tacs_aim.setup_aim()\n\n # Set additional options for meshing AIM through dictionaries\n if self.mesh_aim._dictOptions is not None:\n self.mesh_aim._set_dict_options()\n\n # go ahead and generate the first input files and mesh for TACS\n if not self.tacs_aim.change_shape:\n self.tacs_aim.pre_analysis()\n\n self._setup = True\n\n return self\n\n @property\n def analysis_functions(self) -> List[AnalysisFunction]:\n \"\"\"\n return the list of analysis function objects registered to the tacs aim wrapper class\n to add more functions use Function.(...).register_to(tacs_aim) or tacs_aim.register(my_analysis_function)\n \"\"\"\n return self._analysis_functions\n\n @property\n def function_names(self) -> List[str]:\n \"\"\"\n list of names of each analysis function\n \"\"\"\n return [func.name for func in self.analysis_functions]\n\n @property\n def analysis_dir(self) -> str:\n return self.tacs_aim.analysis_dir\n\n @property\n def geometry(self):\n \"\"\"\n link to pyCAPS geometry object to enable shape change in tacsAIM\n \"\"\"\n return self.tacs_aim.geometry\n\n @property\n def variables(self) -> List[ShapeVariable or ThicknessVariable]:\n return self.tacs_aim.variables\n\n @property\n def variable_dict(self) -> dict:\n return {var.name: var.value for var in self.variables}\n\n @property\n def shape_variables(self) -> List[ShapeVariable]:\n return self.tacs_aim.shape_variables\n\n @property\n def thickness_variables(self) -> List[ThicknessVariable]:\n return self.tacs_aim.thickness_variables\n\n @property\n def root_proc(self) -> bool:\n return self.comm is None or self.comm.rank == 0\n\n def update_design(self, input_dict: dict = None):\n \"\"\"\n method to change the values of each design variable in tacsAim wrapper and ESP/CAPS\n \"\"\"\n\n input_dict = input_dict if input_dict is not None else self.variable_dict\n\n # track any design change to monitor capsDirty\n changed_design = False\n\n # change all shape variables in TacsAim and update CAD geometry\n for shape_var in self.shape_variables:\n if shape_var.name in input_dict:\n if input_dict[shape_var.name] is not None:\n shape_var.value = float(input_dict[shape_var.name])\n\n # update the CAD geometry on root proc / serial since ESP/CAPS doesn't handle MPI directly\n if self.root_proc:\n if self.geometry.despmtr[shape_var.name].value != shape_var.value:\n changed_design = True\n if shape_var.value is not None:\n self.geometry.despmtr[\n shape_var.name\n ].value = shape_var.value\n else:\n shape_var.value = self.geometry.despmtr[\n shape_var.name\n ].value\n\n # change all thickness variables in TacsAim\n for thick_var in self.thickness_variables:\n if thick_var.name in input_dict:\n if thick_var.value != float(input_dict[thick_var.name]):\n thick_var.value = float(input_dict[thick_var.name])\n changed_design = True\n\n # update thickness prop cards in t\n if self.tacs_aim.change_shape:\n self.tacs_aim.update_properties()\n\n # record whether the design has changed & first analysis flag as well\n if self._first_analysis:\n self._first_analysis = False\n changed_design = True\n\n return changed_design\n\n @property\n def fea_solver(self) -> pyTACS:\n \"\"\"\n build pyTACS from nastran dat file and comm\n \"\"\"\n return pyTACS(self.tacs_aim.dat_file_path, self.comm)\n\n def createTACSProbs(self, addFunctions: bool = True):\n \"\"\"\n creates TACS list of static, transient, or modal analysis TACS problems from the TacsAim class\n most important call method from the tacsAim class: SPs = tacs_aim.createTACSProbs\n \"\"\"\n fea_solver = self.fea_solver\n fea_solver.initialize()\n SPs = fea_solver.createTACSProbsFromBDF()\n self.SPs = SPs # store the static problems as well\n\n # add the analysis functions of the model into the static problems\n # add each analysis function into the static problems\n if addFunctions:\n for caseID in self.SPs:\n for analysis_function in self.analysis_functions:\n self.SPs[caseID].addFunction(\n funcName=analysis_function.name,\n funcHandle=analysis_function.handle,\n compIDs=analysis_function.compIDs,\n **(analysis_function.kwargs),\n )\n return self.SPs\n\n def pre_analysis(self):\n \"\"\"\n call tacs aim pre_analysis to build TACS input files and mesh\n only regenerate the mesh each time if there are shape variables\n \"\"\"\n if self.tacs_aim.change_shape:\n self.tacs_aim.pre_analysis()\n\n def run_analysis(self, write_f5: bool = True, iteration: float = 0):\n \"\"\"\n run the static problem analysis\n \"\"\"\n\n assert self._setup\n\n # create a new set of static problems for w/ or w/o shape change\n self.SPs = self.createTACSProbs(addFunctions=True)\n\n # solve the forward and adjoint analysis for each struct problem\n self._tacs_funcs = {}\n self._tacs_sens = {}\n for caseID in self.SPs:\n # write in the new thickness variables for sizing only case\n if not self.tacs_aim.change_shape:\n xarray = self.SPs[caseID].x.getArray()\n for ithick, thick_var in enumerate(self.thickness_variables):\n xarray[ithick] = float(thick_var.value)\n\n self.SPs[caseID].solve()\n\n if (\n self.tacs_aim.change_shape\n ): # if the shape changes write a sensitivity file to the tacsAim directory\n self.SPs[caseID].writeSensFile(\n evalFuncs=self.function_names,\n tacsAim=self.tacs_aim,\n )\n else: # only call evalFunctions and evalFunctionSens if not shape change else redundant\n self.SPs[caseID].evalFunctions(\n self._tacs_funcs, evalFuncs=self.function_names\n )\n self.SPs[caseID].evalFunctionsSens(\n self._tacs_sens, evalFuncs=self.function_names\n )\n\n if write_f5:\n self.SPs[caseID].writeSolution(\n baseName=\"tacs_output\",\n outputDir=self.tacs_aim.analysis_dir,\n number=iteration,\n )\n\n # return this object for method cascading\n return self\n\n def post_analysis(self):\n \"\"\"\n call tacs aim wrapper postAnalysis and update analysis functions and gradients\n \"\"\"\n\n if self.tacs_aim.change_shape:\n # call serial tacsAim postAnalysis if shape changes\n functions_dict = None\n gradients_dict = None\n\n if self.root_proc:\n self.tacs_aim.post_analysis()\n functions_dict = {}\n gradients_dict = {}\n # update functions and gradients on root proc from tacsAim dynout of ESP/CAPS serial\n for func in self.analysis_functions:\n functions_dict[func.name] = self.tacs_aim.aim.dynout[\n func.name\n ].value\n gradients_dict[func.name] = {}\n for var in self.variables:\n gradients_dict[func.name][var.name] = self.tacs_aim.aim.dynout[\n func.name\n ].deriv(var.name)\n\n # broadcast functions and gradients dict to all other processors from root proc\n if self.comm is not None:\n functions_dict = self.comm.bcast(functions_dict, root=0)\n gradients_dict = self.comm.bcast(gradients_dict, root=0)\n\n # update functions and gradients into the tacsAim analysis_functions\n for func in self.analysis_functions:\n func.value = functions_dict[func.name]\n for var in self.variables:\n func.set_derivative(var, gradients_dict[func.name][var.name])\n\n # otherwise use struct problems to read in function values and gradients\n else: # just thickness variable case\n for func in self.analysis_functions:\n # corresponding tacs key for single loadset (key=\"loadset#\" + \"func_name\")\n for tacs_key in self._tacs_funcs:\n if func.name in tacs_key:\n break\n\n # add the function and gradients to each analysis function\n func.value = self._tacs_funcs[tacs_key].real\n\n struct_derivs = self._tacs_sens[tacs_key][\"struct\"]\n for ithick, thick_var in enumerate(self.thickness_variables):\n func.set_derivative(thick_var, struct_derivs[ithick].real)\n\n return self\n","sub_path":"tacs/caps2tacs/tacs_model.py","file_name":"tacs_model.py","file_ext":"py","file_size_in_byte":12998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"2518357","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\n\ndef parse_requirements(fn):\n \"\"\" Currently only supports tarball and pypi-style requirements. \"\"\"\n ir, dl = [], []\n for req in open(fn).readlines():\n req = req.strip()\n if req:\n tgt = dl if req.startswith('http') else ir\n tgt.append(req.strip())\n return ir, dl\n\ninstall_requires, dependency_links = parse_requirements('requirements.txt')\nsetup(name=u'{{ project_name }}',\n version=u'git',\n description=u'',\n author=u'',\n author_email=u'',\n url=u'',\n install_requires=install_requires,\n dependency_links=dependency_links,\n provides=(u'{{ project_name }}',),\n packages=find_packages())\n","sub_path":"virtualenvwrapper/templates/project_template/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"146780809","text":"import tensorflow as tf\nfrom util.utils import find_first, AddInputsWrapper\n\n\ndef lemma_decoder(word_rnn_outputs, tag_feats, word_cle_states, word_cle_outputs, word_form_len,\n target_seqs, target_lens, charseq_lens, words_count, lem_num_chars, rnn_cell, rnn_cell_type,\n rnn_cell_dim, cle_dim, beams, beam_len_penalty, lem_smoothing, bow, eow):\n \"\"\"Decodes lemmas from a variety of inputs\"\"\"\n # Target embedding and target sequences\n tchar_emb = tf.get_variable('tchar_emb', [lem_num_chars, cle_dim])\n target_seqs_bow = tf.pad(target_seqs, [[0, 0], [1, 0]], constant_values=bow)[:, :-1]\n tseq_emb = tf.nn.embedding_lookup(tchar_emb, target_seqs_bow)\n\n decoder_layer = tf.layers.Dense(lem_num_chars, name=\"decoder_layer\")\n base_cell = rnn_cell(rnn_cell_dim, name=\"decoder_cell\")\n\n def create_attn_cell(beams=None):\n with tf.variable_scope(\"lem_cell\", reuse=tf.AUTO_REUSE):\n def btile(x):\n return tf.contrib.seq2seq.tile_batch(x, beams) if beams else x\n cell = base_cell\n cell = AddInputsWrapper(cell, btile(word_rnn_outputs)) # Already dropped out\n cell = AddInputsWrapper(cell, btile(tag_feats)) # Already dropped out\n cell = AddInputsWrapper(cell, btile(word_cle_states))\n att = tf.contrib.seq2seq.LuongAttention(rnn_cell_dim, btile(word_cle_outputs),\n memory_sequence_length=btile(word_form_len))\n cell = tf.contrib.seq2seq.AttentionWrapper(cell, att, output_attention=False)\n return cell\n\n train_cell = create_attn_cell()\n pred_cell = create_attn_cell(beams) # Reuses the attention memory\n\n if rnn_cell_type == \"LSTM\":\n initial_state = tf.nn.rnn_cell.LSTMStateTuple(c=word_cle_states, h=word_cle_states)\n else:\n initial_state = word_cle_states\n\n # Training\n with tf.variable_scope(\"lem_decoder\", reuse=tf.AUTO_REUSE):\n train_helper = tf.contrib.seq2seq.TrainingHelper(tseq_emb, sequence_length=target_lens, name=\"train_helper\")\n train_initial_state = train_cell.zero_state(words_count, tf.float32).clone(cell_state=initial_state)\n train_decoder = tf.contrib.seq2seq.BasicDecoder(cell=train_cell, helper=train_helper, output_layer=decoder_layer, initial_state=train_initial_state)\n train_outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder=train_decoder)\n train_logits = train_outputs.rnn_output\n lemma_predictions_training = train_outputs.sample_id\n\n # Compute loss with smoothing\n with tf.variable_scope(\"lem_loss\"):\n weights_reshaped = tf.reshape(tf.sequence_mask(target_lens, dtype=tf.float32), [-1])\n if lem_smoothing:\n train_logits_reshaped = tf.reshape(train_logits, [-1, train_logits.shape[-1]])\n gold_lemma_onehot = tf.one_hot(tf.reshape(target_seqs, [-1]), lem_num_chars)\n loss_lem = tf.losses.softmax_cross_entropy(gold_lemma_onehot,\n train_logits_reshaped,\n weights=weights_reshaped,\n label_smoothing=lem_smoothing)\n else:\n loss_lem = tf.losses.sparse_softmax_cross_entropy(target_seqs, train_logits, weights=tf.sequence_mask(target_lens, dtype=tf.float32))\n\n # Predictions\n with tf.variable_scope(\"lem_decoder\", reuse=tf.AUTO_REUSE):\n if not beams:\n pred_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding=tchar_emb, start_tokens=tf.tile([bow], [words_count]), end_token=eow)\n pred_initial_state = pred_cell.zero_state(words_count, tf.float32).clone(cell_state=initial_state)\n pred_decoder = tf.contrib.seq2seq.BasicDecoder(cell=pred_cell, helper=pred_helper, output_layer=decoder_layer, initial_state=pred_initial_state)\n pred_outputs, _, lemma_prediction_lengths = tf.contrib.seq2seq.dynamic_decode(\n decoder=pred_decoder, maximum_iterations=tf.reduce_max(charseq_lens) + 10)\n lemma_predictions = tf.argmax(pred_outputs.rnn_output, axis=2, output_type=tf.int32)\n else:\n # Beam search predictions\n pred_initial_state = pred_cell.zero_state(words_count * beams, tf.float32).clone(cell_state=tf.contrib.seq2seq.tile_batch(initial_state, args.beams))\n pred_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n pred_cell, embedding=tchar_emb, start_tokens=tf.tile([bow], [words_count]),\n end_token=eow, output_layer=decoder_layer, beam_width=beams,\n initial_state=pred_initial_state, length_penalty_weight=beam_len_penalty)\n dec_outputs, dec_state, dec_lens = tf.contrib.seq2seq.dynamic_decode(decoder=pred_decoder,\n maximum_iterations=tf.reduce_max(charseq_lens) + 10)\n lemma_predictions = dec_outputs.predicted_ids[:, :, 0]\n lemma_prediction_lengths = 1 + find_first(lemma_predictions, eow)\n\n return loss_lem, (lemma_predictions_training, lemma_predictions, lemma_prediction_lengths)\n\n\ndef sense_predictor(word_rnn_outputs, tag_feats, target_senses, num_senses, words_count,\n predict_sense, sense_smoothing):\n \"\"\"Network for predicting sense separately\"\"\"\n if predict_sense:\n sense_features = word_rnn_outputs\n sense_features = tf.concat([sense_features, tag_feats], axis=-1)\n sense_layer = tf.layers.dense(sense_features, num_senses)\n sense_prediction = tf.argmax(sense_layer, axis=1)\n _gold_senses = tf.one_hot(target_senses, num_senses)\n sense_loss = tf.losses.softmax_cross_entropy(\n _gold_senses, sense_layer, label_smoothing=sense_smoothing)\n else:\n sense_prediction = tf.zeros([words_count], dtype=tf.int64)\n sense_loss = 0.0\n\n return sense_loss, sense_prediction\n","sub_path":"model/lemma_decoder.py","file_name":"lemma_decoder.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"651123825","text":"# -*- encoding = utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\nlearn = tf.contrib.learn\n\nHIDDEN_SIZE = 30 # LSTM中隐藏节点的个数\nNUM_LAYERS = 2 # LSTM的层数\n\nTRAINING_EXAMPLES = 10000\nTESTING_EXAMPLES = 1000\nSAMPLE_GAP = 0.01\n\nTRAIN_BATCH_SIZE = 100\nTRAIN_NUM_STEPS = 50 # 循环网络神经网络截断的长度\n\nEVAL_BATCH_SIZE = 1\nEVAL_NUM_STEPS = 1\nSTEPS = 5000\n\ndef generate_data(seq):\n \"\"\"\n 从采样序列中获取数据\n :param seq:\n :return:\n \"\"\"\n X = []\n y = []\n # 序列的第i项一直到i + TIMESTEPS - 1项做为输入,而第i + TIMESTEPS做为输出.也就是根据前面TIMESTEPS个点来预测第TIMESTEPS + 1个点\n for i in range(len(seq) - 1 - TRAIN_NUM_STEPS):\n X.append([seq[i: i + TRAIN_NUM_STEPS]])\n y.append([seq[i + TRAIN_NUM_STEPS]])\n return np.array(X, dtype=np.float32), np.array(y, dtype=np.float32)\n\nclass LSTMModel:\n def __init__(self, batch_size, num_steps):\n # 使用多层的LSTM结构,不采用dropout\n lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE)\n cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * NUM_LAYERS)\n\n self.batch_size = batch_size\n self.num_steps = num_steps\n\n # 定义输入层\n self.input_data = tf.placeholder(tf.float32, [batch_size, num_steps])\n # 定义预期输出\n self.target = tf.placeholder(tf.float32, [batch_size, 1])\n\n # 初始化最初的状态.全零向量\n self.initial_state = cell.zero_state(batch_size, tf.float32)\n\n # 定义输出,只关心最后一个时刻的输出结果\n # state存储不同batch中LSTM的状态,将其初始化为0\n state = self.initial_state\n print('state:',state[0])\n inputs = self.input_data\n print('inputs:', inputs)\n with tf.variable_scope('RNN'):\n cell_output, _ = tf.contrib.rnn.static_rnn(cell, inputs)\n # for time_step in range(num_steps):\n # if time_step > 0:\n # tf.get_variable_scope().reuse_variables()\n # # 从输入数据中获取当前时刻的输入并传入LSTM结构\n # print('inputs:',inputs[:, time_step])\n # cell_output, state = cell(tf.reshape(inputs[:, time_step], shape=[TRAIN_BATCH_SIZE,1]), state)\n output = cell_output[-1]\n\n # 用linear_regression()默认的平均平方差定义损失函数,并得出加上一层全连接层之后的预测值\n self.prediction, self.loss = learn.models.linear_regression(output, self.target)\n self.cost = self.loss\n # 创建优化模型\n self.train_op = tf.contrib.layers.optimize_loss(self.loss, tf.contrib.framewrok.get_global_step(),\n optimizer='Adagrad', learning_rate=0.1)\ndef main():\n # 生成数据\n test_start = TRAINING_EXAMPLES * SAMPLE_GAP\n test_end = (TRAINING_EXAMPLES + TESTING_EXAMPLES) * SAMPLE_GAP\n test_X, test_y = generate_data(np.sin(np.linspace(test_start, test_end, TESTING_EXAMPLES, dtype=np.float32)))\n train_model = LSTMModel(TRAIN_BATCH_SIZE, TRAIN_NUM_STEPS)\n test_model = LSTMModel(EVAL_BATCH_SIZE, EVAL_NUM_STEPS)\n with tf.Session() as sess:\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n state = sess.run(train_model.initial_state)\n for i in STEPS:\n start = (i * TRAIN_BATCH_SIZE) % len(train_X)\n end = min(start + TRAIN_BATCH_SIZE, len(train_X))\n sess.run(train_model.train_op,feed_dict={train_model.input_data: train_X[start:end],\n train_model.target: train_y[start:end],\n train_model.initial_state: state})\n if i % 100 == 0:\n cost = sess.run(train_model.cost, feed_dict={train_model.input_data: train_X,\n train_model.target: train_y,\n train_model.initial_state: state})\n print('After %d steps, the cost is:', cost)\n\n\nif __name__ == '__main__':\n main()","sub_path":"RNN/predict_sine_function.py","file_name":"predict_sine_function.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"642061656","text":"import numpy as np\n# import scipy.linalg\n# import sys\n\n\ndef gradient_descent(initial_guess, cost, grad, eta=1e-3,\n num_iterations=1e4, cost_target=0):\n M = initial_guess\n for iter_num in range(int(num_iterations)):\n g = grad(M)\n g = g / np.linalg.norm(g)\n newM = M - eta * g\n if cost(newM) > cost(M):\n eta = eta / 2\n if eta < 1e-14:\n print('eta too small, aborting mission.')\n break\n print(eta)\n continue\n M = newM\n if cost_target > 0 and cost(M) < cost_target:\n break\n\n if (1 and num_iterations > 100 and\n iter_num % int(num_iterations / 100) == 0):\n print((\"{0:2.0f}%: loss: {1}\").format(\n 100 * iter_num / num_iterations,\n cost(M)\n ))\n return M\n","sub_path":"gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"460395011","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport os\nimport Helper\n\nSTR_DOWNLOAD_SUCCESS='DownLoad Success!'\nSTR_DOWNLOAD_FAILED='DownLoad Failed!'\n\ndef run():\n tmpUrl=raw_input(\"Input Url:\")\n if Helper.CheckUrl_Http_Https(tmpUrl):\n tmpSavePath=raw_input(\"Input SavePath:\")\n tmpSavePathStr=str(tmpSavePath)\n tmpSavePathStr=Helper.Remove_r_n(tmpSavePathStr)\n\n # 开始下载\n tmpRet=Helper.DownLoad(tmpUrl,tmpSavePathStr)\n if tmpRet:\n print(STR_DOWNLOAD_SUCCESS)\n else:\n print(STR_DOWNLOAD_FAILED)\n run()\n else:\n print(Helper.STR_INVALID_URL)\n run()\n\n\nif __name__==\"__main__\":\n run()\n","sub_path":"Tools/SimpleDownload.py","file_name":"SimpleDownload.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"503007","text":"\"\"\"arclib URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url,include\nfrom book.views import homePage,addBook,showAdd,search,document,post,book,rep,review\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\n\nurlpatterns = [\n url('^review$', review),\n url('^rep$', rep),\n url('^doc$', document),\n url('^search$', search),\n url(r'^$', homePage),\n url(r'^form$', showAdd),\n url(r'^add$', addBook),\n url(r'^book(\\w+)$', book),\n url(r'^doc(\\w+)$', post),\n path('admin/', admin.site.urls),\n url(r'mdeditor/', include('mdeditor.urls')),\n]\n\nif settings.DEBUG:\n # static files (images, css, javascript, etc.)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"arclib/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"389693200","text":"#VERSION: 1.01\n#AUTHORS:lima66\n\n\ntry:\n # python3\n from html.parser import HTMLParser\nexcept ImportError:\n # python2\n from HTMLParser import HTMLParser\n\nfrom novaprinter import prettyPrinter\nfrom helpers import retrieve_url, download_file\nimport re\n\nDOWNLOAD_PATTERN = r'Download Torrent from torrentproject\\.se'\n\nclass torrentproject(object):\n url = \"https://torrentproject.se\"\n name = \"TorrentProject\"\n\n supported_categories = {'all': '9000',\n 'movies': '2000',\n 'tv': '2101',\n 'music': '1000',\n 'books': '3000',\n 'games': '6000',\n 'software': '7000',\n 'others': '4000'}\n page_empty = 0\n\n def download_torrent(self, info):\n torrent_page = retrieve_url(info)\n torrent_link_match = re.search(DOWNLOAD_PATTERN, torrent_page)\n if torrent_link_match and torrent_link_match.groups():\n clean_name = torrent_link_match.groups()[0].strip()\n torrent_file = self.url + clean_name\n print(download_file(torrent_file))\n else:\n print('')\n\n class MyHtmlParser(HTMLParser):\n \"\"\" Sub-class for parsing results \"\"\"\n DIV, A, HREF, CLASS, SPAN, LI = ('div', 'a', 'href', 'class', 'span', 'li')\n\n def __init__(self, url):\n HTMLParser.__init__(self)\n self.url = url\n self.current_item = {} # dict for found item\n self.item_name = None # key's name in current_item dict\n self.inside_li = False\n self.find_data = False\n self.find_number = False\n self.parser_class = {\"l tl\": \"name\", # class\n \"bc torrent-size\": \"size\",\n \"bc seeders\": \"seeds\",\n \"bc leechers\": \"leech\"}\n\n def handle_starttag(self, tag, attrs):\n params = dict(attrs)\n\n if tag == self.LI and self.CLASS in params:\n if params.get(self.CLASS) == 'g w0':\n self.inside_li = True\n if not self.inside_li:\n return\n\n if self.CLASS in params:\n value_find = self.parser_class.get(params[self.CLASS], None)\n if value_find:\n self.item_name = value_find\n self.find_data = True\n self.current_item[self.item_name] = \"\"\n\n if self.HREF in params and params.get(self.CLASS) == 'l tl':\n link = params[self.HREF]\n if tag == self.A and link.endswith('.html'):\n self.current_item[\"desc_link\"] = \"\".join((self.url, link))\n self.current_item[\"link\"] = \"\".join((self.url, link))\n self.current_item[\"engine_url\"] = self.url\n self.find_data = True\n\n if tag == self.SPAN and self.CLASS in params:\n if params.get(self.CLASS) == \"gac_b\":\n self.find_data = True\n\n def handle_data(self, data):\n if self.inside_li and self.item_name and self.find_data:\n self.find_data = False\n self.current_item[self.item_name] = data.strip().replace(',', '')\n\n def handle_endtag(self, tag):\n if self.inside_li and tag == self.LI:\n self.inside_li = False\n self.item_name = None\n self.find_data = False\n array_length = len(self.current_item)\n\n if array_length < 7:\n return\n\n prettyPrinter(self.current_item)\n self.current_item = {}\n\n def search(self, query, cat='9000'):\n \"\"\" Performs search \"\"\"\n parser = self.MyHtmlParser(self.url)\n\n query = query.replace(\"%20\", \"+\")\n \"\"\"http://torrentproject.se/?hl=en&safe=off&num=20&start=0&orderby=seeders&s=2017&filter=9000\"\"\"\n\n category = self.supported_categories[cat]\n number_page = 0\n while True:\n page = \"\".join((self.url, \"/?hl=en&safe=off&num=20&start={0}\"\n \"&orderby=seeders&s={1}&filter={2}\")).format(number_page, query, category)\n\n html = retrieve_url(page)\n length_html = len(html)\n if length_html <= self.page_empty:\n break\n\n parser.feed(html)\n parser.close()\n\n number_page += 1\n\n\n","sub_path":"torrentproject_KO.py","file_name":"torrentproject_KO.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"488149664","text":"#!/usr/bin/env python\nimport sys\n\nfrom thrift import Thrift\n#from shared.ttypes import SharedStruct\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom thrift.server import TServer\n\nfrom cassspectr.interface.spectrograph_interface.PLC import Processor\nfrom cassspectr.plcmodel.plc_driver import PLCDriver\n\nimport logging as log\nimport argparse\nimport sys\n\ndef process_commandline_args():\n \"\"\"Process the command line arguments.\"\"\"\n parser = argparse.ArgumentParser(description=\"Driver program for the PLC controller.\")\n parser.add_argument('--serial', default='/dev/ttyUSB1',\n dest='serial_port',\n help='Specify the serial port to use.')\n parser.add_argument('--log', \n help=\"Specify the logging level.\", default='info', \n choices=['debug', 'info', 'warn', 'error', 'critical'])\n parser.add_argument('--test_mode', help=\"Enable test mode.\", action=\"store_true\")\n parser.add_argument('--tcp_port', default=\"9090\", dest='tcp_port', help=\"Specify the TCP port.\")\n parser.add_argument('--logfile', \n help=\"Specify the log file.\")\n args = parser.parse_args()\n return args\n\ndef setup_logging(args):\n # Set up logging\n logfile = __file__.split('.py')[0] + \".log\"\n if \"logfile\" in args and args.logfile != None:\n logfile = args.logfile\n print(\"Writing logs to {}\".format(logfile))\n loglevel = args.log\n\n log.basicConfig(filename = logfile, \n format='%(asctime)s: %(message)s', \n level=getattr(log, loglevel.upper()))\n\n\nif __name__ == '__main__':\n # Basics\n args = process_commandline_args()\n setup_logging(args)\n log.info(\"Starting {}.\".format(__file__))\n\n # Create the PLCDriver class\n log.debug(\"Instantiating PLCDriver class.\")\n try:\n if args.test_mode:\n print(\"Starting in test mode\")\n plcd = PLCDriver(port=args.serial_port, test=True)\n else:\n plcd = PLCDriver(port=args.serial_port)\n \n except Exception as e:\n print(\"Error initializing PLC driver. Reason: \" + str(e))\n sys.exit(1)\n\n handler = plcd\n processor = Processor(handler)\n transport = TSocket.TServerSocket(port=args.tcp_port)\n tfactory = TTransport.TBufferedTransportFactory()\n pfactory = TBinaryProtocol.TBinaryProtocolFactory()\n\n server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)\n\n print('Starting the server. Listening on port={}.'.format(args.tcp_port))\n server.serve()\n print(\"Server exiting... Done.\")\n","sub_path":"saao/saao/usr/local/lib/python2.7/dist-packages/cassspectr/plcmodel/plc_server.py","file_name":"plc_server.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"580981077","text":"import argparse\nimport cv2\n\nap = argparse.ArgumentParser()\nap.add_argument('-i', '--image', required=True, help='Path to image')\nargs = vars(ap.parse_args())\n\n\nimage = cv2.imread(args['image'])\ncv2.imshow('Original', image)\ncv2.waitKey(0)\n\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nprint(image.shape, gray.shape)\nprint(type(gray))\n# When sigmaX = sigmaY = 0 in the input arguments, \n# they will be calculated from the kernel size\nblurred = cv2.GaussianBlur(gray, (7, 7), 0)\ncv2.imshow('Blurred', blurred)\ncv2.waitKey(0)\n\n\n(T, thresh) = cv2.threshold(\n\tblurred, 95, 255, cv2.THRESH_BINARY\n\t)\ncv2.imshow('Thresholded', thresh)\ncv2.waitKey(0)\n\ncv2.imshow('Output', cv2.bitwise_and(image, image, mask=thresh))\ncv2.waitKey(0)\n\ncv2.destroyAllWindows()","sub_path":"lesson1.9-thresholding/thresholding_quiz.py","file_name":"thresholding_quiz.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"456351703","text":"# vim:set ff=unix expandtab ts=4 sw=4:\n\n# from pathlib import Path\nimport re\n# from sympy import flatten\nimport yaml\n# import copy\n# import builtins\n#from mendeley import Mendeley\n#from mendeley.exception import MendeleyException\n# from Latex import Latex\n# from helpers import pp\nfrom string import Template\nimport unicodedata\nimport bibtexparser\nfrom bibtexparser.bparser import BibTexParser \nfrom bibtexparser.customization import homogeneize_latex_encoding \nfrom bibtexparser.customization import convert_to_unicode\nimport requests\n\nclass DoiNotFoundException(Exception):\n def __init__(self, doi):\n self.doi = doi\n\n def __str__(self):\n return(\"the doi \" + self.doi + \" could not be resolved\")\n \n\ndef strip_accents(s):\n return ''.join(c for c in unicodedata.normalize(\"NFD\",s) if unicodedata.category(c)!=\"Mn\")\n # return unicodedata.normalize(\"NFD\",s) # why not just this way?\n\n\ndef clean_key(key):\n key = key.replace(' ', '_')\n key = key.replace('.', '')\n key = key.replace(':', '')\n return strip_accents(key)\n\n\ndef bibtex_entry_from_str(entry_str):\n # converts a BibTeX entry from string to dictionary\n\n parser = BibTexParser()\n bib_database = bibtexparser.loads(entry_str, parser=parser)\n return(bib_database.entries[0])\n\n\ndef bibtex_entry_str(entry):\n # converts a BibTeX entry from string to dictionary\n\n bib_database = bibtexparser.bibdatabase.BibDatabase()\n bib_database.entries.append(entry)\n\n bibtex_string = bibtexparser.dumps(bib_database)\n return bibtex_string\n\n\n#def mendeley_data_by_doi(doi):\n# # returns Mendeley data or 'None'\n#\n# with open('mendeley_user_config.yml') as f:\n# config = yaml.load(f,Loader=yaml.FullLoader)\n# mendeley = Mendeley(config['clientId'], config['clientSecret'])\n# session = mendeley.start_client_credentials_flow().authenticate()\n#\n# try:\n# doc = session.catalog.by_identifier(doi=doi, view='bib')\n# except MendeleyException:\n# return None\n#\n# mendeley_doi = doc.identifiers['doi']\n# if doi == mendeley_doi:\n# return doc\n#\n# # either an error or doi could not be resolved\n# return None\n#\n#\n#def mendeley_bibtex_entry_str_by_doi(doi):\n# # returns a BibTeX entry as a string or 'None'\n#\n# doc = mendeley_data_by_doi(doi)\n# if doc:\n# # doi could be resolved by Mendeley\n# # now create a BibTex entry as a string\n#\n# full_names=[a.last_name +\", \" +a.first_name for a in doc.authors]\n# author_string=\" and \".join(full_names)\n# key_str=clean_key(doc.authors[0].last_name+str(doc.year)+(doc.source))\n#\n# t=Template(\"\"\"\\\n#@article{$key,\n# author = {$authors},\n# doi = {$doi},\n# journal = {$source},\n# link = {http://dx.doi.org/$doi},\n# number = {$issue},\n# pages = {$pages},\n# title = {$title},\n# volume = {$volume},\n# year = {$year}\n#}\"\"\")\n# entry_str=t.substitute(\n# key=key_str,\n# authors=author_string,\n# doi=doi,\n# source=doc.source,\n# issue=doc.issue,\n# pages=doc.pages,\n# title=doc.title,\n# volume=doc.volume,\n# year=doc.year \n# )\n#\n# return entry_str\n#\n#\n#def mendeley_bibtex_entry_by_doi(doi):\n# # returns a BibTeX entry as dictionary or 'None'\n#\n# entry_str = mendeley_bibtex_entry_str_by_doi(doi)\n#\n# if entry_str:\n# return bibtex_entry_from_str(entry_str)\n# else:\n# return None\n\n\ndef direct_data_by_doi(doi):\n # returns the data coming directly from doi or 'None'\n\n url = \"http://dx.doi.org/\" + doi\n headers = {\"accept\": \"application/x-bibtex\"}\n doi_result = requests.get(url, headers = headers).text\n\n pattern = re.compile(r\"((\\w|-)+$)|((\\w|-)+ (\\w|-)+\\.$))\")\n reg_result = regexp.search(author)\n last_name = reg_result.group(\"last_name\")\n first_name = regexp.sub(\"\", author).strip() # the rest is the first name, cut leading and trailing whitespaces\n author_lst.append(last_name + \", \" + first_name)\n\n entry['author'] = (\" and \").join(author_lst)\n\n # generate citation key (same as in Mendeley case)\n auth = entry['author']\n auth = auth.split(',', 1)[0] # last name of first author\n yr = entry['year']\n \n # insert either journal, journaltitle or booktitle into key\n if 'journal' in entry.keys():\n jour = entry['journal']\n elif 'journaltitle' in entry.keys():\n jour = entry['journaltitle']\n elif 'booktitle' in entry.keys():\n jour = entry['booktitle']\n else:\n jour = \"\"\n\n key_str = auth + yr + jour\n key_str = strip_accents(key_str.replace(\" \", \"_\")) # no accents or spaces in key\n\n entry['ID'] = key_str\n return(entry)\n else:\n return None\n\n\ndef direct_bibtex_entry_str_by_doi(doi):\n # returns a BibTeX entry as a dictionary or 'None'\n\n entry = direct_bibtex_entry_by_doi(doi)\n if entry:\n return bibtex_entry_str(entry)\n else:\n return None\n\n\ndef storable_bibtex_entry_by_doi(doi):\n # returns a dictionary with the BibTex entry or 'None'\n\n ## 1st: check on Mendeley, because they provide abstracts\n #entry = mendeley_bibtex_entry_by_doi(doi)\n #if entry: \n # return entry\n\n # 2nd: check doi.org directly\n entry = direct_bibtex_entry_by_doi(doi)\n if entry: \n return entry\n\n # doi could not be resolved\n raise DoiNotFoundException(doi)\n\n\ndef printable_bibtex_entry(entry):\n # converts a dictionary BibTeX entry to LaTeX format\n\n entry_str = bibtex_entry_str(entry)\n parser = BibTexParser()\n parser.customization = homogeneize_latex_encoding\n bib_database = bibtexparser.loads(entry_str, parser = parser)\n return(bib_database.entries[0])\n\n\ndef printable_bibtex_entry_by_doi(doi):\n # returns a BibTex entry in LaTeX format as dictionary or 'None'\n\n entry = storable_bibtex_entry_by_doi(doi)\n if entry:\n return(printable_bibtex_entry(entry))\n else:\n return None\n\n\ndef biblatex_entry_by_doi(doi):\n # returns a BibLateX entry as dictionary or 'None'\n\n entry = printable_bibtex_entry_by_doi(doi)\n if entry:\n entry_str = bibtex_entry_str(entry)\n parser = BibTexParser()\n parser.customization = convert_to_unicode\n \n bib_database = bibtexparser.loads(entry_str, parser=parser)\n \n # convert 'journal' to 'journaltitle'\n for e in bib_database.entries:\n if 'journal' in e.keys():\n e['journaltitle'] = e['journal']\n del e['journal']\n\n bibtex_string = bibtexparser.dumps(bib_database)\n return bibtex_entry_from_str(bibtex_string)\n else:\n return None\n return(bibtex_string)\n","sub_path":"bgc_md/bibtex.py","file_name":"bibtex.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"536673388","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 21 11:05:07 2020\r\n\r\n@author: 徐满阳\r\n\"\"\"\r\nimport queue\r\nimport threading\r\nimport cv2\r\nimport subprocess as sp\r\nimport datetime,time\r\nimport math\r\nimport tkinter\r\nimport matplotlib.pyplot as plt\r\n#import sys\r\nfrom playsound import playsound\r\n#import matplotlib.pyplot as plt\r\n#配置文件\r\nprotoFile = './models/pose/coco/pose_deploy_linevec.prototxt'\r\nweightsfile = './models/pose/coco/pose_iter_440000.caffemodel'\r\n#face_cascade = cv2.CascadeClassifier('./models/face.xml')\r\n#eye_cascade = cv2.CascadeClassifier('./models/eye.xml')\r\nnpoints = 18\r\nPOSE_PAIRS = [[1,0],[1,2],[1,5],[2,3],[3,4],[5,6],[6,7],[1,8],[8,9],[9,10],[1,11],[11,12],[12,13],[0,14],[0,15],[14,16],[15,17]]\r\n#加载网络\r\nnet = cv2.dnn.readNetFromCaffe(protoFile,weightsfile)\r\n#读取图片\r\ndef _readImage(file,num):\r\n #im = cv2.imread('./images/'+file+'.jpg')\r\n #(1440*1080)\r\n im = cv2.cvtColor(file,cv2.COLOR_BGR2RGB)\r\n inHeight = im.shape[0] #1440\r\n inWidth = im.shape[1] #1080\r\n netInputsize = (368,368)\r\n #转为inpBlob格式\r\n inpBlob = cv2.dnn.blobFromImage(im,1.0/255,netInputsize,(0,0,0),swapRB=True,crop=False)\r\n #归一化后的图片最为输入传入net网络,然后输出\r\n net.setInput(inpBlob)\r\n output = net.forward() #1*57*46*46\r\n scaleX = float(inWidth) / output.shape[3] #float(1080)/64 = 23.47826086956522\r\n scaleY = float(inHeight)/ output.shape[2] #float(1440)/64 = 31.304347826086957\r\n points = []\r\n threshold = 0.1\r\n tantou=0\r\n boolean=0\r\n for i in range(npoints):\r\n probMap = output[0,i,:,:] #shape(46*46)\r\n minVal,prob,minLoc,point =cv2.minMaxLoc(probMap)\r\n x = scaleX * point[0]\r\n y = scaleY * point[1]\r\n if prob > threshold:\r\n points.append((int(x),int(y)))\r\n else:\r\n if i==16:\r\n tantou=17\r\n elif i==17:\r\n tantou=16\r\n points.append(None)\r\n #points[]最后为18个关键点的坐标\r\n #[(516, 313), (516, 438), (399, 438), (375, 626), (352, 751), (610, 438), (633, 594), (657, 751), (446, 751),\r\n # (446, 970), (446, 1158), (563, 782), (540, 1001), (540, 1064), (493, 281), (540, 281), (446, 313), (563, 313)]\r\n\r\n imPoints = im.copy()\r\n #imSkeleton = im.copy()\r\n for i,p in enumerate(points):\r\n #enumerate把points的值前面带上索引i\r\n if points[i]!=None:\r\n cv2.circle(imPoints,p,8,(255,255,0),thickness=1,lineType=cv2.FILLED)\r\n cv2.putText(imPoints,'{}'.format(i),p,cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,lineType=cv2.LINE_AA)\r\n \"\"\"\r\n for pair in POSE_PAIRS:\r\n partA = pair[0]\r\n partB = pair[1]\r\n #if points[partA] and points[partB]:\r\n cv2.line(imSkeleton,points[partA],points[partB],(255, 255,0),2)\r\n cv2.circle(imSkeleton, points[partA],8,(255,0,0),thickness=-1, lineType=cv2.FILLED)\r\n \"\"\"\r\n music='tantou.mp3'\r\n info='请勿交头接耳'\r\n #检测探头\r\n if tantou!=0 and points[tantou]!=None and points[1]!=None:\r\n dy=abs(points[tantou][0]-points[1][0])\r\n dx=abs(points[tantou][1]-points[1][1])\r\n angle=math.atan2(dy,dx)\r\n #print(points[tantou],points[0])\r\n angle=int(angle*180/math.pi)\r\n #print(file,angle,dx,dy)\r\n if angle<15:\r\n #print(num,'请勿交头接耳',datetime.datetime.now())#tkinter.messagebox.showwarning('警告','请勿交头接耳')#\r\n #threading.Thread(target=playsound, args=(\"tantou.mp3\",)).start()\r\n boolean=1\r\n count0=0\r\n if points[0]!=None:count0+=1\r\n for i in range(14, 18):\r\n if points[i]!=None:count0+=1\r\n count1=0\r\n for i in range(1, 8):\r\n if points[i]!=None:count1+=1\r\n #if (points[0]==None or points[14]==None or points[15]==None)and(points[1]!=None or points[2]!=None or points[5]!=None):\r\n if count0<3 and count1>=2:\r\n #print(num,'别睡了,起来嗨',datetime.datetime.now())#tkinter.messagebox.showinfo('提示','别睡了起来嗨')#\r\n #threading.Thread(target=playsound, args=(\"tantou.mp3\",)).start()\r\n #th.setDaemon(True)\r\n #th.start()\r\n music='tantou.mp3'\r\n info='别睡了起来嗨'\r\n boolean=1\r\n #if points[0]==None or points[1]==None or points[2]==None or points[5]==None or points[14]==None or points[15]==None or points[16]==None or points[17]==None:\r\n if count0<3 and count1<2:\r\n #print(num,'人呢',datetime.datetime.now())#tkinter.messagebox.showinfo('提示','人呢')#\r\n #threading.Thread(target=playsound, args=(\"yinxiao.mp3\",)).start()\r\n #th.setDaemon(True)\r\n #th.start()\r\n music='yinxiao.mp3'\r\n info='人呢'\r\n boolean=1\r\n if points[4]==None and points[7]==None:\r\n #print(num,'手呢',datetime.datetime.now())#tkinter.messagebox.showinfo('提示','手呢')#\r\n #threading.Thread(target=playsound, args=(\"yinxiao.mp3\",)).start()\r\n #th.setDaemon(True)\r\n #th.start()\r\n music='yinxiao.mp3'\r\n info='手呢'\r\n boolean=1\r\n #ths=[\r\n #threading.Thread(target=playsound, args=(music,)),\r\n #threading.Thread(target=tkinter.messagebox.showinfo,args=('提示',info))]\r\n #[thread.setDaemon(True) for thread in ths]\r\n #[thread.start() for thread in ths]\r\n if boolean==1:\r\n #cv2.putText(imPoints,'别睡了',(100,150),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,lineType=cv2.LINE_AA)\r\n print(num,info,datetime.datetime.now())\r\n threading.Thread(target=playsound, args=(music,)).start()\r\n plt.figure('提示:'+info,figsize=(3,2))\r\n plt.axis('off')#;plt.imshow(imPoints)\r\n #plt.title(r'注意:'+info,fontproperties='SimHei',fontsize=25)\r\n plt.show()\r\n cv2.imwrite('./images/'+'res'+str(num)+'.jpg',imPoints)\r\n time.sleep(2)\r\n #else:\r\n #cv2.imwrite('./images/res/'+'res'+str(num)+'.jpg',imPoints)\r\n #plt.subplot(121)\r\n #plt.subplot(122)\r\n #plt.axis('off');plt.imshow(imSkeleton)\r\n #cv2.imwrite('D:/openpose-master/images/'+'res'+str(file)+'.jpg',imPoints)\r\n#def showInfo(string):\r\n #tkinter.messagebox.showinfo('提示',string)\r\nclass Live(object):\r\n def __init__(self):\r\n self.frame_queue = queue.Queue()\r\n #self.frame_queueC = queue.Queue()\r\n self.frame_queueS = queue.Queue()\r\n self.command = \"\"\r\n # 自行设置\r\n self.rtmpUrl = \"rtmp://106.54.116.250:1935/live/hwtadie\"\r\n self.camera_path = 0\r\n self.count=0\r\n self.cap = cv2.VideoCapture(self.camera_path)\r\n self.cap.set(3,640)\r\n self.cap.set(4,480)\r\n self.start=datetime.datetime.now()\r\n self.end=datetime.datetime.now()\r\n #self.start1=datetime.datetime.now()\r\n #self.end1=datetime.datetime.now()\r\n #self.bool=0\r\n self.flag=0\r\n def read_frame(self):\r\n print(\"开启推流\")\r\n # Get video information\r\n fps = 25#int(cap.get(cv2.CAP_PROP_FPS))\r\n width = 640#int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = 480#int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n # ffmpeg command\r\n self.command = ['ffmpeg',\r\n '-y',\r\n '-f', 'rawvideo',\r\n '-vcodec','rawvideo',\r\n '-pix_fmt', 'bgr24',\r\n '-s', \"{}x{}\".format(width, height),\r\n '-r', str(fps),\r\n '-i', '-',\r\n '-c:v', 'libx264',\r\n '-pix_fmt', 'yuv420p',\r\n '-preset', 'ultrafast',\r\n '-f', 'flv',\r\n self.rtmpUrl]\r\n\r\n # read webcamera\r\n while(self.cap.isOpened()):\r\n ret, frame = self.cap.read()\r\n if not ret:\r\n print(\"Opening camera is failed\")\r\n # 说实话这里的break应该替换为:\r\n # cap = cv2.VideoCapture(self.camera_path)\r\n # 因为我这俩天遇到的项目里出现断流的毛病\r\n # 特别是拉取rtmp流的时候!!!!\r\n break\r\n # put frame into queue\r\n #if self.bool==0:self.bool=1\r\n self.frame_queue.put(frame)\r\n self.frame_queueS.put(frame)#cv2.imshow(\"frame\",frame)\r\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n # 人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数\r\n #faceRects = classfier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\r\n #if len(faceRects) > 0: # 大于0则检测到人脸\r\n #for faceRect in faceRects: # 单独框出每一张人脸\r\n #x, y, w, h = faceRect\r\n #cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), (0, 255, 0), 2)\r\n # 展示结果\r\n #cv2.imshow('frame', frame)\r\n #if cv2.waitKey(1) & 0xFF == ord('q'): # 按q键退出\r\n #break\r\n # process frame\r\n # 你处理图片的代码\r\n self.end=datetime.datetime.now()\r\n if self.count==0 or (self.end-self.start).seconds>=3:\r\n print(self.count,'-----捕捉照片-----',datetime.datetime.now())\r\n self.start=self.end\r\n th=threading.Thread(target=_readImage, args=(frame,str(self.count)))#self.frame_queueC.put(frame)#cv2.imwrite('D:/openpose-master/images/'+str(self.count)+'.jpg',frame)\r\n th.setDaemon(True)\r\n th.start()\r\n self.count+=1#print(self.count,datetime.datetime.now())#print('2--',self.start,self.end)\r\n\r\n def push_frame(self):\r\n # 防止多线程时 command 未被设置\r\n while True:\r\n if len(self.command) > 0:\r\n # 管道配置\r\n p = sp.Popen(self.command, stdin=sp.PIPE)\r\n break\r\n while True:\r\n if self.frame_queue.empty() != True:\r\n frame = self.frame_queue.get()\r\n p.stdin.write(frame.tostring())\r\n def show(self):\r\n #time.sleep(1)\r\n while True:\r\n if self.frame_queueS.empty()!=True:\r\n frame=self.frame_queueS.get()\r\n '''\r\n self.end1=datetime.datetime.now()\r\n if (self.end1-self.start1).seconds>=3:\r\n #print('1--',self.start,self.end)\r\n self.start1=self.end1\r\n faces=face_cascade.detectMultiScale(frame, 1.3, 2)\r\n #img=frame\r\n if len(faces)==0:\r\n print('脸呢')\r\n playsound('tantou.mp3')\r\n for (x,y,w,h) in faces:\r\n #frame=cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\r\n face_area=frame[y:y+h,x:x+w]\r\n eyes = eye_cascade.detectMultiScale(face_area,1.3,10)\r\n if len(eyes)==0:\r\n print('眼呢')\r\n playsound('yinxiao.mp3')\r\n #for (ex,ey,ew,eh) in eyes:\r\n #画出人眼框,绿色,画笔宽度为1\r\n #cv2.rectangle(face_area,(ex,ey),(ex+ew,ey+eh),(0,255,0),1)\r\n '''\r\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n #faceRects = classfier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\r\n #if len(faceRects) > 0: # 大于0则检测到人脸\r\n #for faceRect in faceRects: # 单独框出每一张人脸\r\n #x, y, w, h = faceRect\r\n #cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), (0, 255, 0), 2)\r\n #else:\r\n #print('快回来考试')\r\n #playsound(\"tantou.mp3\")\r\n cv2.imshow(\"capture\",frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n def handle(self,delay):\r\n count=0\r\n while True:\r\n time.sleep(delay)\r\n if self.frame_queueC.empty()!=True:\r\n print(count,'开始处理照片',datetime.datetime.now())\r\n th=threading.Thread(target=_readImage, args=(self.frame_queueC.get(),str(count)))\r\n th.setDaemon(True)\r\n th.start()\r\n #print('-------------',count,datetime.datetime.now())\r\n #_readImage(self.frame_queueC.get(),str(count))\r\n count+=1\r\n if self.flag==1:\r\n print('停止处理')\r\n break\r\n def warning(self):\r\n for i in range(10):\r\n time.sleep(30)\r\n playsound('time.mp3')\r\n if self.flag==1:\r\n print('停止计时')\r\n break\r\n def run(self):\r\n print(\"开启线程\")\r\n threads = [\r\n threading.Thread(target=Live.read_frame, args=(self,)),\r\n threading.Thread(target=Live.push_frame, args=(self,)),\r\n #threading.Thread(target=Live.handle, args=(self,4)),\r\n threading.Thread(target=Live.warning, args=(self,)),\r\n threading.Thread(target=Live.show, args=(self,))\r\n ]\r\n [thread.setDaemon(True) for thread in threads]\r\n self.start=datetime.datetime.now()\r\n #self.start1=datetime.datetime.now()\r\n [thread.start() for thread in threads]\r\n '''\r\n while True:\r\n if self.bool==1:\r\n if self.frame_queueS.empty()!=True:\r\n cv2.imshow(\"监控\",self.frame_queueS.get())\r\n if flag==1:\r\n cv2.destroyAllWindows()\r\n break\r\n '''\r\nlive=Live()\r\nlive.run()\r\nprint('按0结束')\r\nstring=input()\r\nif string=='0':\r\n live.flag=1\r\n live.cap.release()\r\n cv2.destroyAllWindows()\r\nelse:\r\n print(string)\r\n\r\n","sub_path":"声音图像处理/实验/后/实验1/code/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":13979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"457283200","text":"\nimport sys\nimport os\n\nfrom name2idx import parameters as C\nfrom name2idx import species as V\ndef diffeq(y, t, *x):\n\n v = [0.0]*114\n # Rate equations\n ## Production\n #v[1] = x[C.EGFR_prod]\n v[1] = 2*(x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/(x[C.init_RTKph]* x[C.pEGFR_phosphatase_binding]+ x[C.pEGFR_degradation]))* \\\n x[C.pEGFR_degradation]+ (x[C.EGFR_ErbB2_basal_act]*\tx[C.init_EGFR]*\tx[C.init_ErbB2]/(x[C.init_RTKph]* x[C.pErbB12i_phosphatase]\t+ \\\n x[C.pErbB12_degradation]))* x[C.pErbB12_degradation]+ (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* x[C.init_ErbB3]/ (x[C.init_RTKph]* \\\n x[C.pErbB13i_phosphatase]+ x[C.pErbB13_degradation]))* x[C.pErbB13_degradation]+ (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n (x[C.init_RTKph]* x[C.pMetEGFRi_phosphatase]+x [C.pMetEGFR_degradation]))* x[C.pMetEGFR_degradation]\n #v[2] = x[C.ErbB2_prod]\n v[2] = (x[C.EGFR_ErbB2_basal_act]* x[C.init_EGFR]* x[C.init_ErbB2]/ (x[C.init_RTKph]* x[C.pErbB12i_phosphatase]\t+ x[C.pErbB12_degradation]))* \\\n x[C.pErbB12_degradation]+ 2*(x[C.ErbB2_dimerize]* x[C.init_ErbB2]**2/ (x[C.init_RTKph]* x[C.pErbB2i_phosphatase]+ x[C.pErbB2_degradation]))* \\\n x[C.pErbB2_degradation]+ (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/\t(x[C.init_RTKph]* x[C.pErbB32i_phosphatase]+ \\\n x[C.pErbB32_degradation]))* x[C.pErbB32_degradation]\n #v[3] = x[C.ErbB3_prod]\n v[3] = (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]*\tx[C.init_ErbB3]/(x[C.init_RTKph]* x[C.pErbB13i_phosphatase]+ x[C.pErbB13_degradation]))* \\\n x[C.pErbB13_degradation]+ (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ (x[C.init_RTKph]* x[C.pErbB32i_phosphatase]+ \\\n x[C.pErbB32_degradation]))*\tx[C.pErbB32_degradation]+ (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ (x[C.init_RTKph]* \\\n x[C.pMetErbB3i_phosphatase]+ x[C.pMetErbB3_degradation]))* x[C.pMetErbB3_degradation]\n #v[4] = x[C.IGF1R_prod]\n v[4] = 2* (x[C.IGF1R_basal_activation]*\tx[C.init_IGF1R]**2/ (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))* x[C.pIGF1R_degradation]\n #v[5] = x[C.Met_prod]\n v[5] = (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ (x[C.init_RTKph]* x[C.pMetEGFRi_phosphatase]+ x[C.pMetEGFR_degradation]))* \\\n x[C.pMetEGFR_degradation]+\t(x[C.Met_ErbB3_basal_act]*\tx[C.init_ErbB3]* x[C.init_Met]/\t(x[C.init_RTKph]* x[C.pMetErbB3i_phosphatase]+ \\\n x[C.pMetErbB3_degradation]))* x[C.pMetErbB3_degradation]+ 2*(x[C.Met_basal_act]* x[C.init_Met]**2/ (x[C.init_RTKph]* x[C.pMeti_phosphatase]\t+\t\\\n x[C.pMet_degradation]))* x[C.pMet_degradation]\n\n ## Ligand binding\n v[6] = y[V.EGFR]* x[C.EGFR_lig_binding]* y[V.dose_EGF]\n v[7] = y[V.EGFR_EGF]* x[C.EGFR_lig_binding]* x[C.EGF_kD]\n v[8] = y[V.EGFR]* x[C.EGFR_BTC_binding]* y[V.dose_BTC]\n v[9] = y[V.EGFR_BTC]* x[C.EGFR_BTC_binding]* x[C.EGF_kD]\n\n v[10] = y[V.ErbB3]* x[C.ErbB3_lig_binding]* y[V.dose_HRG] \n v[11] = y[V.ErbB3_HRG]* x[C.ErbB3_lig_binding]* x[C.HRG_kD]\n v[12] = y[V.IGF1R]* x[C.IGF1R_lig_binding]* y[V.dose_IGF1]\n v[13] = y[V.IGF1R_IGF1]* x[C.IGF1R_lig_binding]* x[C.IGF1_kD]\n v[14] = y[V.Met]* x[C.Met_lig_binding]* y[V.dose_HGF]\n v[15] = x[C.HGF_kD]* y[V.Met_HGF]* x[C.Met_lig_binding]\n\n ##Dimerization\n v[16] = (y[V.EGFR_EGF]**2)* x[C.EGFR_dimerize]\n v[17] = (y[V.EGFR_BTC]**2)* x[C.EGFR_BTC_dimerize]\n\n v[18] = (y[V.ErbB2]**2)* x[C.ErbB2_dimerize]\n\n v[19] = (y[V.ErbB3_HRG]**2)* x[C.ErbB3_dimerize]\n\n v[20] = (y[V.IGF1R_IGF1]**2)* x[C.IGF1R_dimerize]\n\n v[21] = y[V.EGFR_EGF]* x[C.EGFR_ErbB2_dimerize]* y[V.ErbB2]\n v[22] = y[V.EGFR_BTC]* x[C.EGFR_ErbB2_BTC_dimerize]* y[V.ErbB2]\n\n v[23] = y[V.EGFR_EGF]* x[C.EGFR_ErbB3_dimerize]* y[V.ErbB3_HRG]\n v[24] = y[V.EGFR_BTC]* x[C.EGFR_ErbB3_BTC_dimerize]* y[V.ErbB3_HRG]\n #v[25] = y[V.EGFR_BTC]* x[V.EGFR_ErbB3_dimerize_noHRG]* y[V.ErbB3]\n\n v[26] = y[V.ErbB2]* x[C.ErbB2_ErbB3_dimerize]* y[V.ErbB3_HRG]\n\n v[27] = (y[V.Met_HGF]**2)* x[C.Met_dimerize]\n\n v[28] = y[V.ErbB3_HRG]* y[V.Met]* x[C.Met_ErbB3_dimerize]\n\n v[29] = y[V.ErbB3_HRG]* y[V.Met_HGF]* x[C.Met_lig_ErbB3_dimerize]\n\n v[30] = y[V.EGFR_EGF]* x[C.Met_EGFR_dimerize]* y[V.Met_HGF]\n v[31] = y[V.EGFR_BTC]* x[C.Met_EGFR_BTC_dimerize]* y[V.Met_HGF]\n\n ##Basal phosphorylations\n v[32] = (y[V.EGFR]**2)* x[C.EGFR_basal_activation]\n v[33] = (y[V.ErbB3]**2)* x[C.ErbB3_basal_activation]\n v[34] = (y[V.IGF1R]**2)* x[C.IGF1R_basal_activation]\n\n v[35] = y[V.EGFR]* x[C.EGFR_ErbB2_basal_act]* y[V.ErbB2]\n v[36] = y[V.EGFR]* x[C.EGFR_ErbB3_basal_act]* y[V.ErbB3]\n v[37] = y[V.ErbB2]* y[V.ErbB3]* x[C.ErbB3_ErbB2_basal_act]\n v[38] = y[V.ErbB3]* y[V.Met]* x[C.Met_ErbB3_basal_act]\n v[39] = (y[V.Met]**2)*x[C.Met_basal_act]\n v[40] = y[V.EGFR]* y[V.Met]* x[C.Met_EGFR_basal_act]\n\n ##Phosphorylation\n ###EGFR homodimers\n v[41] = x[C.pEGFR_internalize]* y[V.pEGFRd]\n v[42] = x[C.pEGFR_degradation]* y[V.pEGFRi]\n v[43] = y[V.RTKph]* x[C.pEGFR_phosphatase_binding]* y[V.pEGFRi]\n v[44] = x[C.pEGFRi_dephosph]* y[V.pEGFRi_ph]\n v[45] = x[C.EGFR_basal_recycle]* y[V.EGFRi]\n\n ###ErbB2 homodimers\n v[46] = y[V.pErbB2]* x[C.pErbB2_internalize]\n v[47] = y[V.RTKph]* y[V.pErbB2i]* x[C.pErbB2i_phosphatase]\n v[48] = x[C.pErbB2i_dephosph]* y[V.pErbB2i_ph]\n v[49] = x[C.pErbB2_degradation]* y[V.pErbB2i]\n v[50] = x[C.ErbB2_recycle]* y[V.ErbB2i]\n\n ###ErbB3 homodimers\n v[51] = x[C.pErbB3_internalize]* y[V.pErbB3d]\n v[52] = x[C.pErbB3_degradation]* y[V.pErbB3i]\n v[53] = y[V.RTKph]* y[V.pErbB3i]* x[C.pErbB3i_phosphatase]\n v[54] = x[C.pErbB3i_dephosph]* y[V.pErbB3i_ph]\n v[55] = x[C.ErbB3_basal_recycle]* y[V.ErbB3i]\n\n ###IGF1R homodimers\n v[56] = x[C.pIGF1R_internalize]* y[V.pIGF1Rd]\n v[57] = x[C.pIGF1R_degradation]* y[V.pIGF1Ri]\n v[58] = y[V.RTKph]* y[V.pIGF1Ri]* x[C.pIGF1Ri_phosphatase]\n v[59] = x[C.pIGF1Ri_dephosph]* y[V.pIGF1Ri_ph]\n v[60] = x[C.IGF1R_basal_recycle]* y[V.IGF1Ri]\n\n ###EGFR-ErbB2 heterodimers\n v[61] = y[V.pErbB12]* x[C.pErbB12_internalize]\n v[62] = x[C.pErbB12_degradation]* y[V.pErbB12i]\n v[63] = y[V.RTKph]* y[V.pErbB12i]* x[C.pErbB12i_phosphatase]\n v[64] = x[C.pErbB12i_dephosph]* y[V.pErbB12i_ph]\n\n ###ErbB2 - ErbB3 heterodimers\n v[65] = y[V.pErbB32]* x[C.pErbB32_internalize]\n v[66] = x[C.pErbB32_degradation]* y[V.pErbB32i]\n v[67] = y[V.RTKph]* y[V.pErbB32i]* x[C.pErbB32i_phosphatase]\n v[68] = x[C.pErbB32i_dephosph]* y[V.pErbB32i_ph]\n\n ###EGFR-ErbB3 heterodimers\n v[69] = y[V.pErbB13]* x[C.pErbB13_internalize]\n v[70] = x[C.pErbB13_degradation]* y[V.pErbB13i]\n v[71] = y[V.RTKph]* y[V.pErbB13i]* x[C.pErbB13i_phosphatase]\n v[72] = x[C.pErbB13i_dephosph]* y[V.pErbB13i_ph]\n\n ###MET homodimers\n v[73] = x[C.pMet_internalize]* y[V.pMetd]\n v[74] = x[C.pMet_degradation]* y[V.pMeti]\n v[75] = y[V.RTKph]* y[V.pMeti]* x[C.pMeti_phosphatase]\n v[76] = x[C.pMeti_dephosph]* y[V.pMeti_ph]\n v[77] = x[C.Met_recycle]* y[V.Meti]\n\n ###MET-ErbB3 heterodimers\n v[78] = y[V.pMetErbB3]* x[C.pMetErbB3_internalize]\n v[79] = x[C.pMetErbB3_degradation]* y[V.pMetErbB3i]\n v[80] = y[V.RTKph]* y[V.pMetErbB3i]* x[C.pMetErbB3i_phosphatase]\n v[81] = x[C.pMetErbB3i_dephosph]* y[V.pMetErbB3i_ph]\n\n ###MET-EGFR heterodimers\n v[82] = y[V.pMetEGFR]* x[C.pMetEGFR_internalize]\n v[83] = x[C.pMetEGFR_degradation]* y[V.pMetEGFRi]\n v[84] = y[V.RTKph]* y[V.pMetEGFRi]* x[C.pMetEGFRi_phosphatase]\n v[85] = x[C.pMetEGFRi_dephosph]* y[V.pMetEGFRi_ph]\n\n ##DOWNSTREAM\n ###ERK branch !init_pAKT, init_pEGFRd, init_pErbB12,init_pErbB13,init_pErbB32,init_pIGF1Ri, init_pIGF1Rd, init_pMetEGFR=Init_pMET_EGFR, init_pMetErbB3,init_pMetd\n v[86] = (y[V.MEK]* x[C.MEK_phosphorylation_pEGFR]* y[V.pEGFRd])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]* x[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]*\t(x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+\tx[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+\tx[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[87] = (y[V.MEK]* x[C.MEK_phosphorylation_pErbB12]* y[V.pErbB12])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]*\t\\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]*\t(x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]*\t(x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+\tx[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[88] = (y[V.MEK]* x[C.MEK_phosphorylation_pErbB13]* y[V.pErbB13])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]*\t(x[C.AKT_activation_pEGFR]*\t\\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]* x[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[89] = (y[V.MEK]* x[C.MEK_phosphorylation_pErbB32]* y[V.pErbB32])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]*\t(x[C.AKT_activation_pEGFR]*\t\\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]* x[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]*\t(x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]*\t(x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[90] = (y[V.MEK]* x[C.MEK_phosphorylation_pMetd]* y[V.pMetd])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+\tx[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]* x[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[91] = (y[V.MEK]* x[C.MEK_phosphorylation_pMetEGFR]* y[V.pMetEGFR])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]*\t(x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+\tx[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n \n v[92] = (y[V.MEK]* x[C.MEK_phosphorylation_pIGF1R]* y[V.pIGF1Rd])/( 1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n \n v[93] = (y[V.MEK]* x[C.MEK_phosphorylation_pMetErbB3]* y[V.pMetErbB3])/ (1+ x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/ x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+\tx[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[94] = (y[V.MEK]* x[C.MEK_internIGF1R_effect]* x[C.MEK_phosphorylation_pIGF1R]* y[V.pIGF1Ri])/(1+x[C.feedback_pAKT]* (x[C.init_AKT]* (x[C.AKT_activation_pEGFR]* \\\n (x[C.EGFR_basal_activation]* x[C.init_EGFR]**2/ x[C.pEGFR_internalize])+ x[C.AKT_activation_pErbB12]* (x[C.EGFR_ErbB2_basal_act]* \\\n x[C.init_EGFR]*\tx[C.init_ErbB2]/ x[C.pErbB12_internalize])+ x[C.AKT_activation_pErbB13]* (x[C.EGFR_ErbB3_basal_act]* x[C.init_EGFR]* \\\n x[C.init_ErbB3]/x[C.pErbB13_internalize])+ x[C.AKT_activation_pErbB32]* (x[C.ErbB3_ErbB2_basal_act]* x[C.init_ErbB2]* x[C.init_ErbB3]/ \\\n x[C.pErbB32_internalize])+ x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* (x[C.IGF1R_basal_activation]* x[C.init_IGF1R]**2/ \\\n (x[C.init_RTKph]* x[C.pIGF1Ri_phosphatase]+ x[C.pIGF1R_degradation]))+ x[C.AKT_activation_pIGF1R]* (x[C.IGF1R_basal_activation]* \\\n x[C.init_IGF1R]**2/ x[C.pIGF1R_internalize])+ x[C.AKT_activation_pMetEGFR]* (x[C.Met_EGFR_basal_act]* x[C.init_EGFR]* x[C.init_Met]/ \\\n x[C.pMetEGFR_internalize])+ x[C.AKT_activation_pMetErbB3]* (x[C.Met_ErbB3_basal_act]* x[C.init_ErbB3]* x[C.init_Met]/ x[C.pMetErbB3_internalize])+ \\\n x[C.AKT_activation_pMetd]* (x[C.Met_basal_act]*\tx[C.init_Met]**2/ x[C.pMet_internalize]))/ (x[C.pAKT_deactivation]* (x[C.feedback_pERK_on_AKT]* \\\n x[C.init_pERK]+ x[C.feedback_pS6K1]* x[C.init_pS6K1]+ 1)))+ x[C.feedback_pERK]* y[V.pERK])\n\n v[95] = y[V.pMEK]* x[C.pMEK_dephosphorylation]\n\n v[96] = y[V.ERK]* x[C.ERK_phosphorylation_pMEK]* y[V.pMEK]\n v[97] = y[V.pERK]* x[C.pERK_dephosphorylation]\n \n ###AKT branch\n v[98] = (y[V.AKT]* x[C.AKT_activation_pEGFR]* y[V.pEGFRd])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[99] = (y[V.AKT]* x[C.AKT_activation_pErbB12]* y[V.pErbB12])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[100] = (y[V.AKT]* x[C.AKT_activation_pErbB13]* y[V.pErbB13])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[101] = (y[V.AKT]* x[C.AKT_activation_pErbB32]* y[V.pErbB32])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[102] = (y[V.AKT]* x[C.AKT_activation_pMetEGFR]* y[V.pMetEGFR])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[103] = (y[V.AKT]* x[C.AKT_activation_pMetd]* y[V.pMetd])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[104] = (y[V.AKT]* x[C.AKT_activation_pIGF1R]* y[V.pIGF1Rd])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[105] = (y[V.AKT]* x[C.AKT_activation_pMetErbB3]* y[V.pMetErbB3])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[106] = (y[V.AKT]* x[C.AKT_activation_pIGF1R]* x[C.AKT_internIGF1R_effect]* y[V.pIGF1Ri])/(x[C.feedback_pERK_on_AKT]* y[V.pERK] + x[C.feedback_pS6K1]* y[V.pS6K1] + 1)\n v[107] = y[V.pAKT]* x[C.pAKT_deactivation]\n\n ###GSK3-S6K-S6 \n v[108] = y[V.S6K1]* x[C.S6K1_phosphorylation_pAKT]* y[V.pAKT]\n v[109] = y[V.S6K1]* x[C.S6K1_phosphorylation_pERK]* y[V.pERK]\n v[110] = y[V.pS6K1]* x[C.pS6K1_dephosphorylation]\n\n v[111] = y[V.S6]* x[C.S6_phosphorylation_pS6K1]* y[V.pS6K1]\n v[112] = y[V.S6]* x[C.S6_phosphorylation_pERK]* y[V.pERK]\n v[113] = y[V.pS6]* x[C.pS6_dephosphorylation]\n\n #ODE of the law of the mass action\n dydt = [0]* V.NUM\n dydt[V.dose_EGF] = -v[6] + v[7]\n dydt[V.dose_HGF] = -v[14] + v[15]\n dydt[V.RTKph] = -v[43] + v[44] - v[47] + v[48] - v[53] + v[54] - v[58] + v[59] - v[63] + v[64] - v[67] + v[68] - v[71] + v[72] - v[75] + v[76] - v[80] + v[81] - v[84] + v[85] \n dydt[V.dose_IGF1] = - v[12] + v[13]\n dydt[V.dose_HRG] = -v[10] + v[11]\n dydt[V.dose_BTC] = -v[8] + v[9]\n dydt[V.EGFR] = v[1] - v[6] + v[7] - v[8] + v[9] - 2*v[32] - v[35] - v[36] - v[40] + v[45]\n dydt[V.EGFR_EGF] = v[6] - v[7] - 2*v[16] - v[21] - v[23] - v[30]\n dydt[V.EGFR_BTC] = v[8] - v[9] - 2*v[17] - v[22] - v[24] - v[25] - v[31]\n dydt[V.pEGFRd] = v[16] + v[17] + v[32] - v[41]\n dydt[V.pEGFRi] = v[41] - v[42] - v[43]\n dydt[V.pEGFRi_ph] = v[43] - v[44]\n dydt[V.EGFRi] = +2*v[44] - v[45] + v[64] + v[72] + v[85]\n dydt[V.ErbB2] = v[2] - 2*v[18] - v[21] - v[22] - v[26] - v[35] - v[37] + v[50]\n dydt[V.pErbB2] = v[18] - v[46]\n dydt[V.pErbB2i] = v[46] - v[47] - v[49]\n dydt[V.ErbB2i] = +2*v[48] - v[50] + v[64] + v[68]\n dydt[V.pErbB2i_ph] = v[47] - v[48]\n dydt[V.pErbB12] = v[21] + v[22] + v[35] - v[61]\n dydt[V.pErbB12i] = v[61] - v[62] - v[63]\n dydt[V.pErbB12i_ph] = v[63] - v[64]\n dydt[V.ErbB3] = v[3] - v[10] + v[11] - v[25] - 2*v[33] - v[36] - v[37] - v[38] + v[55]\n dydt[V.ErbB3_HRG] = v[10] - v[11] - 2*v[19] - v[23] - v[24] - v[26] - v[28] - v[29]\n dydt[V.pErbB3d] = v[19] + v[33] - v[51]\n dydt[V.pErbB3i] = v[51] - v[52] - v[53]\n dydt[V.pErbB3i_ph] = v[53] - v[54]\n dydt[V.ErbB3i] = +2*v[54] - v[55] + v[68] + v[72] + v[81]\n dydt[V.pErbB13] = v[23] + v[24] + v[25] + v[36] - v[69]\n dydt[V.pErbB13i] = v[69] - v[70] - v[71]\n dydt[V.pErbB13i_ph] = v[71] - v[72]\n dydt[V.pErbB32] = v[26] + v[37] - v[65]\n dydt[V.pErbB32i] = v[65] - v[66] - v[67]\n dydt[V.pErbB32i_ph] = v[67] - v[68]\n dydt[V.IGF1R] = v[4] - v[12] + v[13] -2*v[34] + v[60]\n dydt[V.IGF1R_IGF1] = v[12] - v[13] -2*v[20]\n dydt[V.pIGF1Rd] = v[20] + v[34] - v[56]\n dydt[V.pIGF1Ri] = v[56] - v[57] - v[58]\n dydt[V.pIGF1Ri_ph] = v[58] - v[59]\n dydt[V.IGF1Ri] = +2*v[59 ] - v[60]\n dydt[V.Met] = v[5] - v[14] + v[15] - v[28] - v[38] - 2*v[39] - v[40] + v[77]\n dydt[V.Met_HGF] = v[14] - v[15] - 2*v[27] - v[29] - v[30] - v[31]\n dydt[V.pMetd] = v[27] + v[39] - v[73]\n dydt[V.pMeti] = v[73] - v[74] - v[75]\n dydt[V.pMeti_ph] = v[75] - v[76]\n dydt[V.Meti] = +2*v[76] - v[77] + v[81] + v[85]\n dydt[V.pMetErbB3] = v[28] + v[29] + v[38] - v[78]\n dydt[V.pMetErbB3i] = v[78] - v[79] - v[80]\n dydt[V.pMetErbB3i_ph] = v[80] - v[81]\n dydt[V.pMetEGFR] = v[30] + v[31] + v[40] - v[82]\n dydt[V.pMetEGFRi] = v[82] - v[83] - v[84]\n dydt[V.pMetEGFRi_ph] = v[84] - v[85]\n dydt[V.MEK] = -v[86] - v[87] - v[88] - v[89] - v[90] - v[91] - v[92] - v[93] - v[94] + v[95]\n dydt[V.pMEK] = v[86] + v[87] + v[88] + v[89] + v[90] + v[91] + v[92] + v[93] + v[94] - v[95]\n dydt[V.ERK] = -v[96] + v[97]\n dydt[V.pERK] = v[96] - v[97]\n dydt[V.AKT] = -v[98] - v[99] - v[100] - v[101] - v[102] - v[103] - v[104] - v[105] - v[106] + v[107]\n dydt[V.pAKT] = v[98] + v[99] + v[100] + v[101] + v[102] + v[103] + v[104] + v[105] + v[106] - v[107]\n dydt[V.S6K1] = -v[108] - v[109] + v[110]\n dydt[V.pS6K1] = v[108] + v[109] - v[110]\n dydt[V.S6] = -v[111] - v[112] + v[113]\n dydt[V.pS6] = v[111] + v[112] - v[113]\n\n return dydt\n\n\ndef param_values():\n x = [0]*C.NUM\n # 1-82\n \n x[C.AKT_activation_pEGFR] = 1.00*10**(-5) \n x[C.AKT_activation_pErbB12] = 6.40*10**(-2) \n x[C.AKT_activation_pErbB13] = 1.31*10**(1)\n x[C.AKT_activation_pErbB32] = 5.61*10**(-1)\n x[C.AKT_activation_pIGF1R] = 6.85*10**(-1)\n #x[C.AKT_activatio_pMetEGFR] = 1.00*10**(-5)\n x[C.AKT_activation_pMetErbB3] = 3.70*10**(-2)\n x[C.AKT_activation_pMetd] = 8.96*10**(-1)\n x[C.AKT_internIGF1R_effect] = 1.02*10**(-5)\n x[C.EGFR_BTC_binding] = 2.24*10**(-5)\n x[C.EGFR_BTC_dimerize] = 1.00*10**(3)\n x[C.EGFR_ErbB2_BTC_dimerize] = 1.61*10**(0)\n x[C.EGFR_ErbB2_basal_act] = 1.00*10**(-5)\n x[C.EGFR_ErbB2_dimerize] = 1.57*10**(-2)\n x[C.EGFR_ErbB3_BTC_dimerize] = 3.52*10**(-2)\n x[C.EGFR_ErbB3_basal_act] = 7.51*10**(-4)\n x[C.EGFR_ErbB3_dimerize] = 1.18*10**(-3)\n x[C.EGFR_ErbB3_dimerize_noHRG] = 1.00*10**(-5)\n x[C.EGFR_basal_activation] = 1.00*10**(-5)\n x[C.EGFR_basal_recycle] = 5.19*10**(5)\n x[C.EGFR_dimerize] = 6.30*10**(-2)\n x[C.EGFR_lig_binding] = 1.89*10**(-5)\n x[C.EGF_kD] = 1.00*10**(0)\n x[C.ERK_phosphorylation_pMEK] = 2.58*10**(-4)\n x[C.ErbB2_ErbB3_dimerize] = 3.03*10**(-2)\n x[C.ErbB2_dimerize] = 6.79*10**(-3)\n x[C.ErbB2_recycle] = 6.57*10**(-3)\n x[C.ErbB3_ErbB2_basal_act] = 1.00*10**(-5)\n x[C.ErbB3_basal_activation] = 2.93*10**(-2)\n x[C.ErbB3_basal_recycle] = 7.37*10**(-1)\n x[C.ErbB3_dimerize] = 4.46*10**(-2)\n x[C.ErbB3_lig_binding] = 5.71*10**(-5)\n x[C.HGF_kD] = 3.00*10**(-1)\n x[C.HRG_kD] = 5.00*10**(-2)\n x[C.IGF1R_basal_activation] = 1.17*10**(-3)\n x[C.IGF1R_basal_recycle] = 1.00*10**(3)\n x[C.IGF1R_dimerize] = 1.71*10**(1)\n x[C.IGF1R_lig_binding] = 1.53*10**(-3)\n x[C.IGF1_kD] = 3.00*10**(-1)\n x[C.MEK_internIGF1R_effect] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pEGFR] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pErbB12] = 2.74*10**(-1)\n x[C.MEK_phosphorylation_pErbB13] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pErbB32] = 6.06*10**(-2)\n x[C.MEK_phosphorylation_pIGF1R] = 2.99*10**(-2)\n x[C.MEK_phosphorylation_pMetEGFR] = 1.00*10**(-5)\n x[C.MEK_phosphorylation_pMetErbB3] = 3.83*10**(-2)\n x[C.MEK_phosphorylation_pMetd] = 1.88*10**(0)\n x[C.Met_EGFR_BTC_dimerize] = 1.11*10**(-2)\n x[C.Met_EGFR_basal_act] = 1.75*10**(-5)\n x[C.Met_EGFR_dimerize] = 5.13*10**(-4)\n x[C.Met_ErbB3_basal_act] = 3.29*10**(0)\n x[C.Met_ErbB3_dimerize] = 3.71*10**(-2)\n x[C.Met_basal_act] = 1.00*10**(-5)\n x[C.Met_dimerize] = 9.17*10**(-3)\n x[C.Met_lig_ErbB3_dimerize] = 5.67*10**(2)\n x[C.Met_lig_binding] = 4.52*10**(-3)\n x[C.Met_recycle] = 5.42*10**(-1)\n x[C.S6K1_phosphorylation_pAKT] = 2.50*10**(-1)\n x[C.S6K1_phosphorylation_pERK] = 1.07*10**(-5)\n x[C.S6_phosphorylation_pERK] = 1.00*10**(-5) #\n x[C.S6_phosphorylation_pS6K1] = 8.57*10**(-3) #\n x[C.feedback_pAKT] = 1.06*10**(-5)\n x[C.feedback_pERK] = 1.00*10**(3)\n x[C.feedback_pERK_on_AKT] = 1.00*10**(-5)\n x[C.feedback_pS6K1] = 2.09*10**(-5)\n x[C.init_AKT] = 2.71*10**(0)\n x[C.init_EGFR] = 1.79*10**(1)\n #x[C.init_EGFR_BTC] = 0.00*10**(0)\n x[C.init_EGFR_EGF] = 0.00*10**(0)\n x[C.init_ErbB2] = 5.70*10**(0)\n x[C.init_ErbB3] = 2.48*10**(0)\n x[C.init_ErbB3_HRG] = 0.00*10**(0)\n x[C.init_IGF1R] = 4.73*10**(0)\n x[C.init_IGF1R_IGF1] = 0.00*10**(0)\n x[C.init_MEK] = 4.24*10**(0)\n x[C.init_Met] = 7.90*10**(0)\n x[C.init_Met_HGF] = 0.00*10**(0)\n x[C.init_RTKph] = 6.19*10**(-1)\n x[C.init_S6] = 1.46*10**(2)\n x[C.init_pERK] = 3.34*10**(-1)\n x[C.init_pS6K1] = 1.24*10**(-3)\n\n #251-326\n x[C.pAKT_deactivation] = 3.03*10**(-1)\n x[C.pEGFR_degradation] = 1.00*10**(-5)\n x[C.pEGFR_internalize] = 6.23*10**(0)\n x[C.pEGFR_phosphatase_binding] = 1.85*10**(2)\n x[C.pEGFRi_dephosph] = 2.17*10**(1)\n x[C.pERK_dephosphorylation] = 5.43*10**(-1)\n x[C.pErbB12_degradation] = 1.82*10**(-1)\n x[C.pErbB12_internalize] = 1.90*10**(0)\n x[C.pErbB12i_dephosph] = 1.00*10**(3)\n x[C.pErbB12i_phosphatase] = 8.45*10**(-1)\n x[C.pErbB13_degradation] = 4.97*10**(1)\n x[C.pErbB13_internalize] = 1.00*10**(3)\n x[C.pErbB13i_dephosph] = 5.84*10**(1)\n x[C.pErbB13i_phosphatase] = 1.60*10**(-5)\n x[C.pErbB2_degradation] = 3.19*10**(2)\n x[C.pErbB2_internalize] = 1.00*10**(3)\n x[C.pErbB2i_dephosph] = 8.24*10**(0)\n x[C.pErbB2i_phosphatase] = 1.00*10**(3)\n x[C.pErbB32_degradation] = 5.74*10**(-1)\n x[C.pErbB32_internalize] = 1.09*10**(0)\n x[C.pErbB32i_dephosph] = 1.19*10**(-2)\n x[C.pErbB32i_phosphatase] = 4.88*10**(-2)\n x[C.pErbB3_degradation] = 9.08*10**(-1)\n x[C.pErbB3_internalize] = 1.00*10**(3)\n x[C.pErbB3i_dephosph] = 1.63*10**(1)\n x[C.pErbB3i_phosphatase] = .22*10**(1)\n x[C.pIGF1R_degradation] = 1.00*10**(-5)\n x[C.pIGF1R_internalize] = 1.00*10**(3)\n x[C.pIGF1Ri_dephosph] = 3.32*10**(2)\n x[C.pIGF1Ri_phosphatase] = 1.00*10**(3)\n x[C.pMEK_dephosphorylation] = 3.28*10**(-1)\n x[C.pMetEGFR_degradation] = 1.43*10**(0)\n x[C.pMetEGFR_internalize] = 1.33*10**(0)\n x[C.pMetEGFRi_dephosph] = 5.04*10**(-1)\n x[C.pMetEGFRi_phosphatase] = 3.57*10**(-5)\n x[C.pMetErbB3_degradation] = 9.84*10**(2)\n x[C.pMetErbB3_internalize] = 1.00*10**(3)\n x[C.pMetErbB3i_dephosph] = 1.00*10**(3)\n x[C.pMetErbB3i_phosphatase] = 1.00*10**(3)\n x[C.pMet_degradation] = 1.91*10**(0)\n x[C.pMet_internalize] = 1.00*10**(3)\n x[C.pMeti_dephosph] = 1.30*10**(1)\n x[C.pMeti_phosphatase] = 1.00*10**(3)\n x[C.pS6K1_dephosphorylation] = 1.03*10**(-2)\n x[C.pS6_dephosphorylation] = 1.19*10**(-1) #\n #x[C.relto_A431_init_EGFR] = 9.63*10**(0)\n #x[C.relto_A431_init_ErbB2] = 1.00*10**(0)\n '''\n x[C.relto_A431_init_ErbB3] = 9.11*10**(-1)\n x[C.relto_A431_init_IGF1R] = 2.65*10**(0)\n x[C.relto_A431_init_Met] = 2.24*10**(-1)\n x[C.relto_ACHN_init_EGFR] = 5.40*10**(0)\n x[C.relto_ACHN_init_ErbB2] = 7.33*10**(-1)\n x[C.relto_ACHN_init_ErbB3] = 4.46*10**(-1)\n x[C.relto_ACHN_init_IGF1R] = 7.03*10**(-1)\n x[C.relto_ACHN_init_Met] = 1.29*10**(0)\n x[C.relto_ADRr_init_EGFR] = 1.03*10**(0)\n x[C.relto_ADRr_init_ErbB2] = 1.07*10**(0)\n x[C.relto_ADRr_init_ErbB3] = 5.74*10**(-1)\n x[C.relto_ADRr_init_IGF1R] = 2.02*10**(0)\n x[C.relto_ADRr_init_Met] = 4.82*10**(-1)\n x[C.relto_BT20_init_EGFR] = 1.05*10**(1)\n x[C.relto_BT20_init_ErbB2] = 1.50*10**(0)\n x[C.relto_BT20_init_ErbB3] = 1.85*10**(0)\n x[C.relto_BT20_init_IGF1R] = 3.55*10**(0)\n x[C.relto_BT20_init_Met] = 3.82*10**(-1)\n x[C.relto_IGROV_init_EGFR] = 9.41*10**(-1)\n x[C.relto_IGROV_init_ErbB2] = 4.25*10**(0)\n x[C.relto_IGROV_init_ErbB3] = 5.76*10**(-1)\n x[C.relto_IGROV_init_IGF1R] = 1.59*10**(-1)\n x[C.relto_IGROV_init_Met] = 6.42*10**(-1)\n x[C.relto_init_EGFR] = 1.83*10**(0)\n x[C.relto_init_ErbB2] = 6.07*10**(-1)\n x[C.relto_init_ErbB3] = 1.04*10**(0)\n x[C.relto_init_IGF1R] = 1.48*10**(0)\n x[C.relto_init_Met] = 1.80*10**(0)\n '''\n x[C.scale_Ligand] = 3.78*10**(4) \n\n #scale\n x[C.scale_pAKT_CelllineA431] = 7.83*10**(0)\n x[C.scale_pAKT_CelllineACHN_197] = 3.44*10**(4)\n x[C.scale_pAKT_CelllineACHN_200] = 5.18*10**(5)\n x[C.scale_pAKT_CelllineACHN_218] = 1.35*10**(3)\n x[C.scale_pAKT_CelllineACHN_DM] = 1.62*10**(5)\n x[C.scale_pAKT_CelllineADRr] = 1.31*10**(1)\n x[C.scale_pAKT_CelllineADRr_B] = 5.65*10**(3)\n x[C.scale_pAKT_CelllineADRr_B2] = 4.18*10**(2)\n x[C.scale_pAKT_CelllineBT20] = 4.38*10**(0)\n x[C.scale_pAKT_CelllineBxPc3] = 9.87*10**(-1)\n x[C.scale_pAKT_CelllineH322M] = 7.14*10**(-1)\n x[C.scale_pAKT_CelllineIGROV1] = 1.24*10**(1)\n x[C.scale_pEGFR_CelllineA431] = 7.89*10**(2)\n x[C.scale_pEGFR_CelllineACHN_197] = 9.71*10**(4)\n x[C.scale_pEGFR_CelllineACHN_200] = 3.13*10**(-1)\n x[C.scale_pEGFR_CelllineACHN_218] = 1.72*10**(-4)\n x[C.scale_pEGFR_CelllineACHN_DM] = 1.43*10**(4)\n x[C.scale_pEGFR_CelllineADRr] = 7.54*10**(-1)\n x[C.scale_pEGFR_CelllineADRr_B] = 1.41*10**(3)\n x[C.scale_pEGFR_CelllineADRr_B2] = 1.90*10**(2)\n x[C.scale_pEGFR_CelllineBT20] = 1.39*10**(3)\n x[C.scale_pEGFR_CelllineBxPc3] = 2.45*10**(1)\n x[C.scale_pEGFR_CelllineH322M] = 3.30*10**(1)\n x[C.scale_pEGFR_CelllineIGROV1] = 5.01*10**(3)\n x[C.scale_pERK_CelllineA431] = 4.18*10**(-1)\n x[C.scale_pERK_CelllineACHN_197] = 3.40*10**(4)\n x[C.scale_pERK_CelllineACHN_200] = 9.02*10**(4)\n x[C.scale_pERK_CelllineACHN_218] = 3.33*10**(4)\n x[C.scale_pERK_CelllineACHN_DM] = 4.58*10**(4)\n x[C.scale_pERK_CelllineADRr] = 8.92*10**(-1)\n x[C.scale_pERK_CelllineADRr_B] = 5.76*10**(3)\n x[C.scale_pERK_CelllineADRr_B2] = 2.26*10**(2)\n x[C.scale_pERK_CelllineBT20] = 5.72*10**(-1)\n \n x[C.scale_pERK_CelllineBxPc3] = 9.12*10**(-1)\n x[C.scale_pERK_CelllineH322M] = 3.85*10**(-1)\n x[C.scale_pERK_CelllineIGROV1] = 5.80*10**(-1)\n x[C.scale_pErbB2_CelllineA431] = 8.48*10**(2)\n x[C.scale_pErbB2_CelllineACHN_197] = 3.89*10**(5)\n x[C.scale_pErbB2_CelllineACHN_200] = 3.97*10**(-2)\n x[C.scale_pErbB2_CelllineACHN_218] = 2.82*10**(5)\n x[C.scale_pErbB2_CelllineACHN_DM] = 2.11*10**(3)\n x[C.scale_pErbB2_CelllineADRr] = 6.91*10**(2)\n x[C.scale_pErbB2_CelllineADRr_B] = 2.08*10**(3)\n x[C.scale_pErbB2_CelllineADRr_B2] = 8.00*10**(1)\n x[C.scale_pErbB2_CelllineBT20] = 2.97*10**(2)\n x[C.scale_pErbB2_CelllineBxPc3] = 3.79*10**(0)\n x[C.scale_pErbB2_CelllineH322M] = 5.27*10**(0)\n x[C.scale_pErbB2_CelllineIGROV1] = 6.37*10**(2)\n x[C.scale_pErbB3_CelllineA431] = 1.54*10**(3)\n x[C.scale_pErbB3_CelllineACHN_197] = 1.71*10**(3)\n x[C.scale_pErbB3_CelllineACHN_200] = 5.63*10**(-1)\n x[C.scale_pErbB3_CelllineACHN_218] = 3.95*10**(5)\n x[C.scale_pErbB3_CelllineACHN_DM] = 1.75*10**(-3)\n x[C.scale_pErbB3_CelllineADRr] = 1.02*10**(3)\n x[C.scale_pErbB3_CelllineADRr_B] = 6.75*10**(2)\n x[C.scale_pErbB3_CelllineADRr_B2] = 1.31*10**(-4)\n x[C.scale_pErbB3_CelllineBT20] = 5.42*10**(2)\n x[C.scale_pErbB3_CelllineBxPc3] = 2.76*10**(-1)\n x[C.scale_pErbB3_CelllineH322M] = 2.71*10**(0)\n x[C.scale_pErbB3_CelllineIGROV1] = 1.82*10**(1)\n x[C.scale_pIGF1R_CelllineA431] = 1.10*10**(3)\n x[C.scale_pIGF1R_CelllineACHN_197] = 6.62*10**(2)\n x[C.scale_pIGF1R_CelllineACHN_200] = 4.54*10**(2)\n x[C.scale_pIGF1R_CelllineACHN_218] = 2.31*10**(-4)\n x[C.scale_pIGF1R_CelllineACHN_DM] = 1.05*10**(1)\n x[C.scale_pIGF1R_CelllineADRr] = 1.97*10**(2)\n x[C.scale_pIGF1R_CelllineADRr_B] = 1.44*10**(-2)\n x[C.scale_pIGF1R_CelllineADRr_B2] = 2.17*10**(5)\n x[C.scale_pIGF1R_CelllineBT20] = 9.08*10**(1)\n x[C.scale_pIGF1R_CelllineBxPc3] = 3.43*10**(2)\n x[C.scale_pIGF1R_CelllineH322M] = 1.19*10**(4)\n x[C.scale_pIGF1R_CelllineIGROV1] = 2.35*10**(3)\n x[C.scale_pMEK_CelllineA431] = 2.20*10**(3)\n x[C.scale_pMEK_CelllineACHN_197] = 2.14*10**(-4)\n x[C.scale_pMEK_CelllineACHN_200] = 6.79*10**(-4)\n x[C.scale_pMEK_CelllineACHN_218] = 2.06*10**(1)\n x[C.scale_pMEK_CelllineACHN_DM] = 6.92*10**(0)\n x[C.scale_pMEK_CelllineADRr] = 6.76*10**(-4)\n\n x[C.scale_pMEK_CelllineADRr_B] = 4.70*10**(2)\n x[C.scale_pMEK_CelllineADRr_B2] = 2.51*10**(3)\n x[C.scale_pMEK_CelllineBT20] = 3.66*10**(3)\n x[C.scale_pMEK_CelllineBxPc3] = 1.34*10**(3)\n x[C.scale_pMEK_CelllineH322M] = 3.51*10**(2)\n x[C.scale_pMEK_CelllineIGROV1] = 7.66*10**(3)\n x[C.scale_pMet_CelllineA431] = 6.41*10**(-3)\n x[C.scale_pMet_CelllineACHN_197] = 2.83*10**(3)\n x[C.scale_pMet_CelllineACHN_200] = 2.52*10**(3)\n x[C.scale_pMet_CelllineACHN_218] = 1.24*10**(3)\n x[C.scale_pMet_CelllineACHN_DM] = 8.92*10**(3)\n x[C.scale_pMet_CelllineADRr] = 9.16*10**(0)\n x[C.scale_pMet_CelllineADRr_B] = 1.52*10**(-2)\n x[C.scale_pMet_CelllineADRr_B2] = 6.40*10**(-2)\n x[C.scale_pMet_CelllineBT20] = 9.33*10**(-4)\n x[C.scale_pMet_CelllineBxPc3] = 4.84*10**(3)\n x[C.scale_pMet_CelllineH322M] = 6.53*10**(-3)\n x[C.scale_pMet_CelllineIGROV1] = 3.61*10**(-4)\n x[C.scale_pS6K1_CelllineA431] = 5.92*10**(-1)\n x[C.scale_pS6K1_CelllineACHN_197] = 4.40*10**(5)\n x[C.scale_pS6K1_CelllineACHN_200] = 3.76*10**(-4)\n x[C.scale_pS6K1_CelllineACHN_218] = 1.71*10**(4)\n x[C.scale_pS6K1_CelllineACHN_DM] = 1.63*10**(-1)\n x[C.scale_pS6K1_CelllineADRr] = 1.39*10**(1)\n x[C.scale_pS6K1_CelllineADRr_B] = 4.00*10**(5)\n x[C.scale_pS6K1_CelllineADRr_B2] = 1.14*10**(0)\n x[C.scale_pS6K1_CelllineBT20] = 6.97*10**(4)\n x[C.scale_pS6K1_CelllineBxPc3] = 4.69*10**(2)\n x[C.scale_pS6K1_CelllineH322M] = 3.22*10**(2)\n x[C.scale_pS6K1_CelllineIGROV1] = 6.14*10**(3)\n x[C.scale_pS6_CelllineA431] = 5.45*10**(2)\n x[C.scale_pS6_CelllineACHN_197] = 2.75*10**(2)\n x[C.scale_pS6_CelllineACHN_200] = 4.86*10**(3)\n x[C.scale_pS6_CelllineACHN_218] = 2.30*10**(5)\n x[C.scale_pS6_CelllineACHN_DM] = 6.14*10**(4)\n x[C.scale_pS6_CelllineADRr] = 3.48*10**(2)\n x[C.scale_pS6_CelllineADRr_B] = 5.72*10**(4)\n x[C.scale_pS6_CelllineADRr_B2] = 1.70*10**(0)\n x[C.scale_pS6_CelllineBT20] = 2.40*10**(2)\n x[C.scale_pS6_CelllineBxPc3] = 4.10*10**(1)\n x[C.scale_pS6_CelllineH322M] = 2.65*10**(1)\n x[C.scale_pS6_CelllineIGROV1] = 2.33*10**(2)\n x[C.scale_tEGFR_CelllineA431] = 1.16*10**(2)\n x[C.scale_tEGFR_CelllineACHN_197] = 1.64*10**(-2)\n x[C.scale_tEGFR_CelllineACHN_200] = 3.71*10**(-2)\n x[C.scale_tEGFR_CelllineACHN_218] = 2.02*10**(5)\n x[C.scale_tEGFR_CelllineACHN_DM] = 2.42*10**(3)\n x[C.scale_tEGFR_CelllineADRr] = 8.24*10**(-4)\n x[C.scale_tEGFR_CelllineADRr_B] = 2.47*10**(5)\n x[C.scale_tEGFR_CelllineADRr_B2] = 2.04*10**(4)\n x[C.scale_tEGFR_CelllineBT20] = 8.20*10**(0)\n x[C.scale_tEGFR_CelllineBxPc3] = 8.62*10**(-1)\n x[C.scale_tEGFR_CelllineH322M] = 7.91*10**(-1)\n x[C.scale_tEGFR_CelllineIGROV1] = 2.57*10**(1)\n x[C.scale_tErbB2_CelllineA431] = 1.67*10**(1)\n x[C.scale_tErbB2_CelllineACHN_197] = 1.70*10**(5)\n x[C.scale_tErbB2_CelllineACHN_200] = 4.55*10**(3)\n x[C.scale_tErbB2_CelllineACHN_218] = 2.84*10**(-4)\n x[C.scale_tErbB2_CelllineACHN_DM] = 3.45*10**(1)\n x[C.scale_tErbB2_CelllineADRr] = 2.00*10**(0)\n x[C.scale_tErbB2_CelllineADRr_B] = 7.73*10**(3)\n x[C.scale_tErbB2_CelllineADRr_B2] = 3.40*10**(4)\n x[C.scale_tErbB2_CelllineBT20] = 7.52*10**(0)\n x[C.scale_tErbB2_CelllineBxPc3] = 1.00*10**(-4)\n x[C.scale_tErbB2_CelllineH322M] = 1.00*10**(-4)\n x[C.scale_tErbB2_CelllineIGROV1] = 9.41*10**(-1)\n x[C.scale_tErbB3_CelllineA431] = 4.57*10**(-4)\n #x[C.scale_ErbB3_CelllineACHN_197] = 3.67*10**(3)\n x[C.scale_tErbB3_CelllineACHN_200] = 4.08*10**(0)\n x[C.scale_tErbB3_CelllineACHN_218] = 9.14*10**(-2)\n x[C.scale_tErbB3_CelllineACHN_DM] = 9.27*10**(1)\n x[C.scale_tErbB3_CelllineADRr] = 1.25*10**(0)\n x[C.scale_tErbB3_CelllineADRr_B] = 6.25*10**(1)\n x[C.scale_tErbB3_CelllineADRr_B2] = 1.15*10**(-2)\n x[C.scale_tErbB3_CelllineBT20] = 9.93*10**(-2)\n x[C.scale_tErbB3_CelllineBxPc3] = 5.74*10**(-4)\n x[C.scale_tErbB3_CelllineH322M] = 3.69*10**(-4)\n x[C.scale_tErbB3_CelllineIGROV1] = 4.18*10**(-1)\n x[C.scale_tIGF1R_CelllineA431] = 2.26*10**(1)\n x[C.scale_tIGF1R_CelllineACHN_197] = 3.70*10**(5)\n x[C.scale_tIGF1R_CelllineACHN_200] = 6.73*10**(0)\n x[C.scale_tIGF1R_CelllineACHN_218] = 2.35*10**(3)\n x[C.scale_tIGF1R_CelllineACHN_DM] = 2.39*10**(3)\n x[C.scale_tIGF1R_CelllineADRr] = 2.03*10**(1)\n x[C.scale_tIGF1R_CelllineADRr_B] = 1.63*10**(1)\n x[C.scale_tIGF1R_CelllineADRr_B2] = 2.51*10**(0)\n x[C.scale_tIGF1R_CelllineBT20] = 1.08*10**(1)\n x[C.scale_tIGF1R_CelllineBxPc3] = 1.70*10**(-5)\n x[C.scale_tIGF1R_CelllineH322M] = 2.17*10**(0)\n x[C.scale_tIGF1R_CelllineIGROV1] = 1.45*10**(1)\n \n \n\n #offset\n x[C.offset_tEGFR_CelllineH322M] = 1.46*10**(0) \n x[C.offset_tErbB2_CelllineH322M] = 7.91*10**(0) \n x[C.offset_tErbB3_CelllineH322M] = 7.86*10**(-1)\n x[C.offset_tIGF1R_CelllineH322M] = 4.21*10**(-2) \n x[C.offset_pEGFR_CelllineH322M] = 4.90*10**(0) \n x[C.offset_pErbB2_CelllineH322M] = 1.09*10**(0)\n x[C.offset_pErbB3_CelllineH322M] = 1.00*10**(-5) \n x[C.offset_pIGF1R_CelllineH322M] = 4.07*10**(2) \n x[C.offset_pMet_CelllineH322M] = 3.14*10**(-2) \n x[C.offset_pMEK_CelllineH322M] = 1.37*10**(-1) \n x[C.offset_pERK_CelllineH322M] = 1.00*10**(-7)\n x[C.offset_pAKT_CelllineH322M] = 1.87*10**(-1)\n x[C.offset_pS6K1_CelllineH322M] = 1.00*10**(-7) \n x[C.offset_pS6_CelllineH322M] = 1.00*10**(-7) \n \n\n\n return x\n\n\ndef initial_values():\n y0 = [0]*V.NUM\n \n y0[V.dose_EGF] = 0.0\n y0[V.dose_HGF] = 0.0\n y0[V.RTKph] = 0.618911491797731 \n y0[V.dose_IGF1] = 0.0\n y0[V.dose_HRG] = 0.0\n y0[V.dose_BTC] = 0.0\n y0[V.EGFR] = 17.8621933083143 \n y0[V.EGFR_EGF] = 0.0\n y0[V.EGFR_BTC] = 0.0\n \n \n y0[V.pEGFRd] = 5.12011130278668E-4\n y0[V.pEGFRi] = 2.79223720669219E-5\n y0[V.pEGFRi_ph] = 1.4687856601509E-4\n y0[V.EGFRi] = 1.37508187561569E-8 \n \n y0[V.ErbB2] = 5.70185166249099\n \n \n y0[V.pErbB2] = 2.20826262632109E-4 \n y0[V.pErbB2i] = 2.35511421879916E-4\n y0[V.ErbB2i] = 44.4835113645705\n y0[V.pErbB2i_ph] = 0.0176807431775487 \n y0[V.pErbB12] = 5.37306859494303E-4 \n y0[V.pErbB12i] = 0.00144471037537624\n y0[V.pErbB12i_ph] = 7.55785246775258E-7\n \n y0[V.ErbB3] = 2.47992342696256\n y0[V.ErbB3_HRG] = 0.0\n \n \n y0[V.pErbB3d] = 1.8018926279905E-4\n y0[V.pErbB3i] = 0.00348026782363202\n y0[V.pErbB3i_ph] = 0.0108514486150842\n y0[V.ErbB3i] = 34.3224209878038\n y0[V.pErbB13] = 3.32712466211581E-5\n y0[V.pErbB13i] = 6.69142208681604E-4\n y0[V.pErbB13i_ph] = 1.13074197411592E-10\n y0[V.pErbB32] = 1.30059969850016E-4\n y0[V.pErbB32i] = 2.34208535412277E-4\n y0[V.pErbB32i_ph] = 5.93238579976826E-4\n \n y0[V.IGF1R] = 4.73494621402554\n y0[V.IGF1R_IGF1] = 0.0\n \n y0[V.pIGF1Rd] = 2.6239258403409E-5\n y0[V.pIGF1Ri] = 4.2395816408642E-5\n y0[V.pIGF1Ri_ph] = 7.91085256809129E-5\n y0[V.IGF1Ri] = 5.24785159589016E-5\n \n y0[V.Met] = 7.90290414461229\n y0[V.Met_HGF] = 0.0\n \n y0[V.pMetd] = 6.24560598662565E-7\n y0[V.pMeti] = 1.0060257690714E-6\n y0[V.pMeti_ph] = 4.79508059771836E-5\n y0[V.Meti] = 45.960014100956\n y0[V.pMetErbB3] = 0.0645520569171923\n y0[V.pMetErbB3i] = 0.0402793824584546\n y0[V.pMetErbB3i_ph] = 0.0249293726860515\n y0[V.pMetEGFR] = 0.00185677841647765 \n y0[V.pMetEGFRi] = 0.00172863499055847\n y0[V.pMetEGFRi_ph] = 7.58806259570584E-8\n \n y0[V.MEK] = 4.2412663925898 \n \n y0[V.pMEK] = 1.014543757693E-4\n y0[V.ERK] = 6922167.20947519\n \n\n y0[V.pERK] = 0.334274838149849 #\n \n y0[V.AKT] = 2.70857345464684\n y0[V.pAKT] = 0.0263677143207646\n y0[V.S6K1] = 0.00194894402116983\n \n y0[V.pS6K1] = 0.00124327830478657 #\n y0[V.S6] = 145.50079875804 #\n \n y0[V.pS6] = 0.0171533722671392 #\n \n \n return y0","sub_path":"Hass_2017/set_modell.py","file_name":"set_modell.py","file_ext":"py","file_size_in_byte":45070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"516185747","text":"import math\r\nimport numpy as np\r\n\r\nimport torch\r\n\r\n\r\nclass BPTTDataLoader(object):\r\n \"\"\"Back Propagation Through Time Data Loader\r\n\r\n DataLoader class for loading back propagate through time batches. This\r\n class does not support multiprocess batch loading as original DataLoader\r\n of PyTorch.\r\n It support several BPTT block settings:\r\n\r\n 1. Truncated BPTT (fix length)\r\n 2. Full Sequence BPTT\r\n 3. Variable Truncated BPTT (online length)\r\n\r\n \"\"\"\r\n def __init__(self, dataset, bptt, batch_size=1, shuffle=False):\r\n \"\"\"Initialize the Class\r\n\r\n Args\r\n ----\r\n dataset : dataset\r\n Raw dataset containing time related inputs.\r\n The dataset should be a list of sequences. The indexing of it\r\n should take sequence index and item index in a sequenc as input,\r\n and return coressponding input and target items.\r\n bptt : Int\r\n Length of back propagate through time block.\r\n batch_size : Int\r\n Batch size.\r\n Pay attention that it will break each sequence into batch_size\r\n sequences and ignore remaining parts, so it will break some time\r\n dependencies.\r\n shuffle : Bool\r\n If shuffle different sequences. Pay attenion that item order of\r\n a sequence will not change.\r\n\r\n \"\"\"\r\n # parse arguments\r\n self.dataset = dataset\r\n self.bptt = bptt\r\n self.batch_size = batch_size\r\n self.shuffle = shuffle\r\n\r\n def __iter__(self):\r\n \"\"\"Reference to the Class Iterator\"\"\"\r\n return self._DataIterator(self)\r\n\r\n class _DataIterator(object):\r\n \"\"\"Batch Iterator\"\"\"\r\n def __init__(self, loader):\r\n \"\"\"Initialize the Class\r\n\r\n Args\r\n ----\r\n loader : loader\r\n Data loader to iterate.\r\n\r\n \"\"\"\r\n # parse arguments\r\n self.loader = loader\r\n self.dataset = self.loader.dataset\r\n self.bptt = self.loader.bptt\r\n self.batch_size = self.loader.batch_size\r\n self.shuffle = self.loader.shuffle\r\n\r\n # sequence list\r\n self.seq_idx_buffer = list(range(len(self.dataset.data)))\r\n\r\n # shuffle sequence list if necessary\r\n if self.shuffle:\r\n np.random.shuffle(self.seq_idx_buffer)\r\n else:\r\n pass\r\n\r\n # initialize pointers\r\n self.seq_ptr = 0\r\n self.set_focus_data(self.seq_idx_buffer[self.seq_ptr])\r\n\r\n def __iter__(self):\r\n \"\"\"Reference to the Class Iterator\"\"\"\r\n return self\r\n\r\n def __next__(self, bptt):\r\n \"\"\"Return Next BPTT Batch\r\n\r\n Args\r\n ----\r\n bptt : Int\r\n Online bptt length.\r\n\r\n Returns\r\n -------\r\n input, is_new : tensor-like, bool\r\n Input tensor and if it is beginning of a sequence.\r\n target : tensor-like\r\n Target tensor.\r\n\r\n \"\"\"\r\n # move to next sequence data if necessary\r\n if self.batch_ptr == self.focus_data.size(0) - 1:\r\n self.seq_ptr += 1\r\n if self.seq_ptr == len(self.seq_idx_buffer):\r\n raise StopIteration\r\n else:\r\n self.set_focus_data(self.seq_idx_buffer[self.seq_ptr])\r\n else:\r\n pass\r\n\r\n # get a new batch\r\n bptt = bptt or self.bptt\r\n bptt = min(self.focus_data.size(0) - 1 - self.batch_ptr, bptt)\r\n is_new = (self.batch_ptr == 0)\r\n input = self.focus_data[self.batch_ptr:self.batch_ptr + bptt]\r\n target = self.focus_data[self.batch_ptr + 1:self.batch_ptr + bptt + 1]\r\n\r\n # move pointer\r\n self.batch_ptr += bptt\r\n return (input, is_new), target\r\n\r\n def set_focus_data(self, seq_idx):\r\n \"\"\"Initialize BPTT Pointer\"\"\"\r\n # focus on corresponding sequence data\r\n self.focus_data = self.dataset.data[seq_idx]\r\n\r\n # truncate data to perfectly fit batch size\r\n num_batches = self.focus_data.size(0) // self.batch_size\r\n self.focus_data = self.focus_data.narrow(0, 0, num_batches * self.batch_size)\r\n\r\n # break the whole sequence into several sequences batches\r\n new_shape = [self.batch_size, num_batches] + list(self.focus_data.size())[1:]\r\n self.focus_data = self.focus_data.view(*new_shape)\r\n new_axes = [1, 0] + list(range(len(self.focus_data.size())))[2:]\r\n self.focus_data = self.focus_data.permute(*new_axes).contiguous()\r\n\r\n # initialize batch pointer\r\n self.batch_ptr = 0\r\n","sub_path":"nnlearn/dataset/bptt.py","file_name":"bptt.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"147472256","text":"#!/usr/bin/env python\n\"\"\"\nthis is a mock version of runcry17,\nwhich compares an input file to a hash and writes an appropriate outputfile st stdoout\n\nto add find hashkeys:\n\ninput_path = 'path/to/input.d12'\nwith open(input_path, \"rb\") as f:\n hashkey = hashlib.md5(f.read()).digest()\nhashkey\n\n\"\"\"\nimport hashlib\nimport os\nimport sys\nfrom shutil import copyfile\n\nimport aiida_crystal17.tests as tests\n\nstdoutfiles = {\n '\\xf6\\t\\x0e\\x9f\\r\\xa6\\t\\x8ea,\\xd2l\\xb2\\xf1\\x16 ': None,\n '\\xffw\\xb9\\x96\\xa5\\x08\\x1ed\\xab.\\x99p\\xc6\\xcd\\x15\\xcb': None,\n ']\\x14\\xa7|\\xb2~\\xe2\\x1a\\xd5\\xd1Q\\xff7i\\xc0\\x94': None,\n '.\\xaec\\xd6b\\xd8Q\\x83v\\xa2\\x08\\x89+\\xe0{\\x1d': None\n}\n\nadditional_files = {\n '\\xf6\\t\\x0e\\x9f\\r\\xa6\\t\\x8ea,\\xd2l\\xb2\\xf1\\x16 ':\n [(\"mgo_sto3g_scf.crystal.out\", \".out\")],\n '\\xffw\\xb9\\x96\\xa5\\x08\\x1ed\\xab.\\x99p\\xc6\\xcd\\x15\\xcb':\n [('mgo_sto3g_external.crystal.out', \".out\")],\n ']\\x14\\xa7|\\xb2~\\xe2\\x1a\\xd5\\xd1Q\\xff7i\\xc0\\x94':\n [('nio_sto3g_afm.crystal.out', \".out\")],\n '.\\xaec\\xd6b\\xd8Q\\x83v\\xa2\\x08\\x89+\\xe0{\\x1d':\n [('nio_sto3g_afm_opt.crystal.out', \".out\")]\n}\n\n\ndef main(sys_args=None):\n\n if sys_args is None:\n sys_args = sys.argv[1:]\n\n if len(sys_args) < 1:\n raise ValueError(\"no input name given (as 1st argument)\")\n \n if sys_args[0] == \"--test\":\n return\n\n # script_path = os.path.dirname(os.path.realpath(__file__))\n test_path = os.path.dirname(tests.__file__)\n # runcry17 requires input file name without extension as first arg\n input_name = sys_args[0]\n\n with open(input_name + \".d12\", \"rb\") as f:\n hashkey = hashlib.md5(f.read()).digest()\n\n if hashkey not in stdoutfiles:\n raise IOError(\"contents of {0} not in hash list, hashkey: {1}\".format(\n os.path.basename(input_name + \".d12\"), str(hashkey)))\n\n for inname, outext in additional_files.get(hashkey, []):\n src = os.path.join(test_path, \"output_files\", inname)\n dst = os.path.join(\".\", input_name + outext)\n copyfile(src, dst)\n\n if stdoutfiles[hashkey] is None:\n sys.stdout.write(\n \"running mock runcry17 for input arg: {}\".format(input_name))\n else:\n outpath = os.path.join(test_path, \"output_files\", stdoutfiles[hashkey])\n with open(outpath) as f:\n sys.stdout.write(f.read())\n","sub_path":"aiida_crystal17/tests/mock_runcry17.py","file_name":"mock_runcry17.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"308563577","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport random\nimport sys\nimport lxml.html\nfrom hanfuhui.items import HanfuhuiItem\n\nreload(sys)\n\ndef LoadUserAgents(uafile):\n \"\"\"\n uafile : string\n path to text file of user agents, one per line\n \"\"\"\n uas = []\n with open(uafile,'rb') as uaf:\n for ua in uaf.readlines():\n if ua:\n uas.append(ua.strip()[1:-1 - 1])\n random.shuffle(uas)\n return uas\n\n\nclass HanfuSpider(scrapy.Spider):\n name = 'hanfu'\n allowed_domains = ['www.hanfuhui.cn']\n page = 1\n url = \"http://www.hanfuhui.cn/comm/album.ashx?action=loadAlbumGood&count=50&page=\"+str(page)\n start_urls = [url]\n uas = LoadUserAgents(\"user_agents.txt\")\n\n\n def start_requests(self):\n ua = random.choice(self.uas)\n head = {'User-Agent': ua,\n 'Host': 'www.hanfuhui.cn',\n 'Referer':'http://www.hanfuhui.cn/album/'\n }\n for u in self.start_urls:\n yield scrapy.Request(u, callback=self.parse,\n headers=head,\n dont_filter=True)\n\n\n\n def parse(self,response):\n tree = lxml.html.fromstring(response.text)\n album_list = tree.cssselect('ul.album_list >li')\n for album in album_list:\n item = HanfuhuiItem()\n a_name = album.cssselect('div.foot > p.top.long_hide > a.name')[0]\n a_nick = album.cssselect('div.foot > p.buttom > a.nick')[0]\n href = a_name.get('href')\n title = a_name.text\n author = a_nick.text\n item[\"href\"] = href\n item[\"title\"] = title\n item[\"author\"] = author\n ua = random.choice(self.uas)\n head = {'User-Agent': ua,\n 'Host': 'www.hanfuhui.cn',\n 'Referer': 'http://www.hanfuhui.cn/album/'\n }\n request = scrapy.Request('http://www.hanfuhui.cn'+href,callback=self.av_parse,headers=head,dont_filter=True)\n request.meta['item'] = item\n yield request\n self.page += 1\n ua = random.choice(self.uas)\n head = {'User-Agent': ua,\n 'Host': 'www.hanfuhui.cn',\n 'Referer': 'http://www.hanfuhui.cn/album/'\n }\n yield scrapy.Request(\"http://www.hanfuhui.cn/comm/album.ashx?action=loadAlbumGood&count=50&page=\"+str(self.page),callback=self.parse,\n headers=head,\n dont_filter=True)\n\n\n\n def av_parse(self,response):\n tree = lxml.html.fromstring(response.text)\n item = response.meta['item']\n list = []\n imgs = tree.cssselect('#mainer > div > div.data_info_main > div.life_piclist > li')\n for img in imgs:\n imgurl = img.cssselect('a > img')[0]\n href = imgurl.get('src')\n list.append(href[0:href.find('.jpg')+4])\n imgurls = set(list)\n item[\"imgs\"] = imgurls\n yield item","sub_path":"hanfuhui/spiders/hanfu.py","file_name":"hanfu.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"222857857","text":"from os import getcwd\r\nclass Tag:\r\n def __init__(self, tag, text=\"\", is_single=False, is_line=False, klass=None, **kwargs):\r\n self.tag = tag\r\n self.text = text\r\n self.is_single = is_single # указать True, если не нужен закрывающий тэг\r\n self.is_line = is_line # указать True, если тэг вместе с его содержимым нужно вывести в одну строку\r\n self.attributes = {} # словарь атрибутов тэга\r\n self.structure = [] # список, в котором хранится построчно собственная структура тэга\r\n self.opening =\"\" # для хранения открывающего тэга\r\n self.internal = [] # для хранения содержимого тэга\r\n self.ending = \"\" # для хранения закрывающего тэга\r\n self.tab = \"\" # для табуляции строк\r\n\r\n # заполняем self.attributes всеми входящими атрибутами тэга:\r\n if klass is not None:\r\n self.attributes[\"class\"] = \" \".join(klass)\r\n\r\n for attr, value in kwargs.items():\r\n if \"_\" in attr:\r\n attr = attr.replace(\"_\", \"-\")\r\n self.attributes[attr] = value\r\n\r\n self.make_structure()\r\n\r\n def string_of_attrs(self):\r\n \"\"\"распаковывает все атрибуты, склеивает их пробелами и возвращает в виде одной строки\"\"\"\r\n attrs = []\r\n for attribute, value in self.attributes.items():\r\n attrs.append('%s=\"%s\"' % (attribute, value))\r\n attrs = \" \".join(attrs)\r\n return attrs\r\n\r\n def make_structure(self):\r\n \"\"\"формирует полную структуру тэга и записывает результат в поле self.structure\"\"\"\r\n if self.string_of_attrs():\r\n self.opening = \"{tab}<{tag} {attrs}>\".format(tab=self.tab, tag=self.tag, attrs=self.string_of_attrs())\r\n else:\r\n self.opening = \"{tab}<{tag}>\".format(tab=self.tab, tag=self.tag)\r\n \r\n if self.text != \"\":\r\n self.internal.append(self.text)\r\n self.ending = \"{tab}{tag}>\".format(tab=self.tab, tag=self.tag)\r\n\r\n if self.is_line:\r\n self.structure.append(self.opening + self.text + self.ending)\r\n else:\r\n self.structure.append(self.opening)\r\n if self.internal:\r\n for line in self.internal:\r\n self.structure.append(line)\r\n if not self.is_single:\r\n self.structure.append(self.ending)\r\n\r\n def __iadd__(self, other):\r\n \"\"\"при добавлении другого объекта, меняет собственную структуру так, чтобы внутри оказался тот самый другой объект\"\"\"\r\n self.structure.clear()\r\n self.tab = \" \"\r\n\r\n for line in other.structure:\r\n self.internal.append(self.tab * 2 + line)\r\n self.make_structure()\r\n return self\r\n\r\n def __str__(self):\r\n return \"Ошибка! Распечатать можно только объект класса 'HTML')\"\r\n\r\nclass HTML:\r\n \"\"\"Главный класс, который создает html-документ из всех объектов класса Tag и выводит либо на экран, либо записывает в файл\"\"\"\r\n def __init__(self, output=None):\r\n self.output = output # чтобы вывести созданный документ в файл, необходимо указать output=\"имя.html\"\r\n self.structure = []\r\n self.opening =\"\"\r\n self.internal = []\r\n self.ending = \"\"\r\n\r\n def make_structure(self):\r\n \"\"\"упрощенная функция создания структуры документа\"\"\"\r\n self.structure.append(self.opening)\r\n if self.internal:\r\n for line in self.internal:\r\n self.structure.append(line)\r\n self.structure.append(self.ending)\r\n\r\n def __iadd__(self, other):\r\n \"\"\"аналогична функции класса Tag\"\"\"\r\n self.structure.clear()\r\n\r\n for line in other.structure:\r\n self.internal.append(line)\r\n self.make_structure()\r\n return self\r\n\r\n def __str__(self):\r\n \"\"\"при обращении к объекту, как к строке, выводит созданный документ либо в файл, либо на экран\"\"\"\r\n if self.output is not None:\r\n output = self.output.lower()\r\n with open(output, \"w\") as f:\r\n for line in self.structure:\r\n f.write(line +\"\\n\")\r\n return \"Документ записан в {}\\\\{}\".format(getcwd(), output)\r\n else:\r\n output = \"\"\r\n for line in self.structure:\r\n output += (line +\"\\n\")\r\n return output \r\n\r\nif __name__ == \"__main__\":\r\n doc = HTML()\r\n\r\n head = Tag(\"head\")\r\n title = Tag(\"title\", \"hello\", is_line=True)\r\n head += title\r\n\r\n doc += head\r\n\r\n body = Tag(\"body\")\r\n\r\n h1 = Tag(\"h1\", \"Test\", is_line=True, klass=(\"main-text\",))\r\n body += h1\r\n\r\n div = Tag(\"div\", klass=(\"container\", \"container-fluid\"), id=\"lead\")\r\n paragraph = Tag(\"p\", \"another test\", is_line=True)\r\n img = Tag(\"img\", is_single=True, src=\"/icon.png\", data_image=\"responsive\")\r\n div += paragraph\r\n div += img\r\n body += div\r\n \r\n doc += body\r\n # вывод созданного документа:\r\n print(doc)\r\n","sub_path":"b3_13_homework.py","file_name":"b3_13_homework.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"473715236","text":"#!/usr/bin/python\r\n# -*- coding: cp936 -*-\r\n# Author: xiepeng\r\n# Date: 2015-6-8\r\n\r\nimport time\r\nimport string\r\nimport re\r\n\r\nfrom libcom.lib_pub.logging_drv import log_info\r\nfrom libcom.lib_cmd.inter_mode import *\r\nfrom libcom.lib_cmd.config_mode import *\r\nfrom libcom.lib_cmd.shell_mode import *\r\nfrom libcom.lib_cmd.chg_mode import *\r\nfrom libcom.console_drv.console_drv import *\r\nfrom libcom.config_topo.topo_controller import *\r\nfrom cases_set.intf.nfpp.nfpp_commn_cmd import *\r\nfrom cases_set.intf.intf_commn_cmd import *\r\n\r\n__all__ = [\"bug_5pj2_257833\"]\r\n\r\nSUCCESS = 0\r\nFAIL = -1\r\n\r\ndef _bug_5pj2_257833(cb_arg):\r\n rv = SUCCESS\r\n dev_name = cb_arg.dev_names[0]\r\n bind_num = 200\r\n configure(dev_name)\r\n if bind_num > 65535:\r\n print_fail('number so large!')\r\n return FAIL\r\n \r\n for num in range(1, bind_num):\r\n quotient = int(num / 256)\r\n remainder = num % 256\r\n ip_str = 'address-bind 192.168.' + str(quotient) + '.' + str(remainder)\r\n mac_str = '0000.0000.' + \"%04d\"%(num)\r\n last_str = ip_str + ' ' + mac_str\r\n run_cmd(dev_name, last_str)\r\n \r\n info = run_cmd(dev_name, 'address-bind install')\r\n acl_busy = re.search(r'ssd_process.*', info, re.S)\r\n# acl_busy = re.findall(r'busy', info, re.M)\r\n if acl_busy != None: \r\n print_fail('ssd_process reload')\r\n rv = FAIL\r\n time.sleep(2)\r\n \r\n run_cmd(dev_name, 'no address-bind install')\r\n for num in range(1, bind_num):\r\n quotient = int(num / 256)\r\n remainder = num % 256\r\n ip_str = 'no address-bind 192.168.' + str(quotient) + '.' + str(remainder)\r\n mac_str = '0000.0000.' + \"%04d\"%(num)\r\n last_str = ip_str + ' ' + mac_str\r\n run_cmd(dev_name, last_str)\r\n \r\n return rv\r\n \r\n#this is main-function\r\ndef bug_5pj2_257833(cb_arg):\r\n if len(cb_arg.dev_names) == 0:\r\n log_info(\"Failed: Need one switch to be test.\")\r\n return FAIL\r\n\r\n dev_name = cb_arg.dev_names[0]\r\n wake_up_console(dev_name)\r\n result = FAIL\r\n try:\r\n result = _bug_5pj2_257833(cb_arg)\r\n finally:\r\n exit_console(dev_name)\r\n return result\r\n\r\n","sub_path":"cases_set/policy/bug/BUGID_257833.py","file_name":"BUGID_257833.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"457890699","text":"from os import PathLike\nimport numpy as np\nfrom ._Motif import Motif, MotifSet\nfrom ._convert import (\n _from_biopython\n)\nfrom ._utils import (\n _parse_version, \n _parse_alphabet, \n _parse_strands, \n _parse_background, \n _parse_motif, \n)\nfrom ...preprocess import decode_seq\nfrom ...preprocess._utils import _token2one_hot\n\ndef _read_meme_pymemesuite(\n filename: PathLike\n):\n \"\"\"Read motifs from a MEME file into pymemesuite.common.Motif objects.\n\n Parameters\n ----------\n filename : str\n MEME filename\n\n Returns\n -------\n list of pymemesuite.common.Motif\n List of motifs\n pymemesuite.common.Background\n A pymemesuite.common.Array object representing the background frequencies\n \"\"\"\n memesuite_motifs = []\n try:\n from pymemesuite.common import MotifFile\n except ImportError:\n raise ImportError(\"Please install pymemesuite dependency with `pip install pymemesuite`\")\n with MotifFile(filename) as motif_file:\n for motif in motif_file:\n memesuite_motifs.append(motif)\n bg = motif_file.background\n return memesuite_motifs, bg\n\ndef _read_meme_MotifSet(\n filename: PathLike\n):\n \"\"\"Read motifs from a MEME file into a MotifSet object.\n\n Parameters\n ----------\n filename : str\n MEME filename\n \n Returns\n -------\n MotifSet\n MotifSet object\n \"\"\"\n motifs = {}\n version = None\n alphabet = None\n strands = None\n background = None\n background_source = None\n with open(filename) as meme_file:\n line = meme_file.readline()\n version = _parse_version(line)\n line = meme_file.readline()\n while line:\n if line.startswith(\"ALPHABET\"):\n if alphabet is None:\n alphabet = _parse_alphabet(line)\n line = meme_file.readline()\n else:\n raise RuntimeError(\"Multiple alphabet definitions encountered in MEME file\")\n elif line.startswith(\"strands: \"):\n if strands is None:\n strands = _parse_strands(line)\n line = meme_file.readline()\n else:\n raise RuntimeError(\"Multiple strand definitions encountered in MEME file\")\n elif line.startswith(\"Background letter frequencies\"):\n if background is None:\n line = _parse_background(line, meme_file)\n else:\n raise RuntimeError(\"Multiple background frequency definitions encountered in MEME file\")\n elif line.startswith(\"MOTIF\"):\n motif = _parse_motif(line, meme_file)\n if motif.identifier in motifs:\n raise RuntimeError(\"Motif identifiers not unique within file\")\n motifs[motif.identifier] = motif\n line = meme_file.readline()\n else:\n line = meme_file.readline()\n return MotifSet(\n motifs=motifs,\n version=version,\n alphabet=alphabet,\n strands=strands,\n background=background,\n background_source=background_source,\n )\n\nREADER_REGISTRY = {\n \"pymemesuite\": _read_meme_pymemesuite,\n \"MotifSet\": _read_meme_MotifSet,\n}\n\ndef read_meme(\n filename,\n return_type=\"MotifSet\"\n):\n \"\"\"Read motifs from a MEME file into a MotifSet object.\n \n Parameters\n ----------\n filename : str\n MEME filename\n \n Returns\n -------\n MotifSet\n MotifSet object\n \"\"\"\n return READER_REGISTRY[return_type](filename)\n\n \n\ndef read_motifs(\n filename,\n transpose=True,\n counts=True\n):\n \"\"\"Read motifs from a .motif file into a MotifSet object.\n\n Parameters\n ----------\n filename : str\n .motif filename\n transpose : bool, optional\n whether to transpose the matrices, by default True\n counts : bool, optional\n whether the input matrices are counts and should be converted to pfm, by default True\n \"\"\"\n\n with open(filename) as motif_file:\n data = motif_file.readlines()\n pfm_rows = []\n pfms = []\n ids = []\n names = []\n for line in data:\n line = line.rstrip()\n if line.startswith(\">\"):\n ids.append(line.split()[0])\n names.append(line.split()[1])\n if len(pfm_rows) > 0:\n pfms.append(np.vstack(pfm_rows))\n pfm_rows = []\n else:\n pfm_row = np.array(list(map(float, line.split())))\n pfm_rows.append(pfm_row)\n pfms.append(np.vstack(pfm_rows))\n motifs = {}\n for i in range(len(pfms)):\n if transpose:\n pfms[i] = pfms[i].T\n if counts:\n pfms[i] = np.divide(pfms[i], pfms[i].sum(axis=1)[:,None])\n consensus = decode_seq(_token2one_hot(pfms[i].argmax(axis=1)))\n motif = Motif(\n pfm=pfms[i],\n identifier=ids[i],\n name=names[i],\n consensus=consensus,\n length=len(consensus)\n )\n motifs[ids[i]] = motif\n return MotifSet(motifs=motifs)\n\ndef _load_jaspar(\n motif_accs=None, \n motif_names=None, \n collection=None, \n release=\"JASPAR2022\",\n **kwargs,\n):\n \"\"\"Load motifs from JASPAR database into Bio.motifs.jaspar.Motif objects.\n\n Utility function for load_jaspar.\n\n Parameters\n ----------\n motif_accs : list of str, optional\n List of motif accessions, by default None\n motif_names : list of str, optional\n List of motif names, by default None\n collection : str, optional\n Collection name, by default None\n release : str, optional\n JASPAR release, by default \"JASPAR2020\"\n\n Returns\n -------\n list of bio.motifs.jaspar.Motif\n \"\"\"\n assert (motif_accs or motif_names or collection), \"Must provide either motif_accs, motif_names, or collection\"\n try:\n from pyjaspar import jaspardb\n except ImportError:\n raise ImportError(\"Please install pyjaspar dependency with `pip install pyjaspar`\")\n jdb_obj = jaspardb(release=release)\n if motif_accs:\n if isinstance(motif_accs, str):\n motif_accs = [motif_accs]\n motifs = [jdb_obj.fetch_motif_by_id(acc) for acc in motif_accs]\n elif motif_names:\n if isinstance(motif_names, str):\n motif_names = [motif_names]\n motifs = [jdb_obj.fetch_motifs_by_name(name) for name in motif_names]\n elif collection:\n motifs = jdb_obj.fetch_motifs(collection=collection, **kwargs)\n return motifs\n\ndef load_jaspar(\n motif_accs=None,\n motif_names=None,\n collection=None,\n release=\"JASPAR2022\",\n identifier_number=0,\n verbose=False,\n **kwargs, \n):\n \"\"\"Load motifs from JASPAR database into a MotifSet object\n\n Parameters\n ----------\n motif_accs : list of str, optional\n List of motif accessions, by default None\n motif_names : list of str, optional\n List of motif names, by default None\n collection : str, optional\n Collection name, by default None\n release : str, optional\n JASPAR release, by default \"JASPAR2020\"\n identifier_number : int, optional\n Identifier number, by default 0\n verbose : bool, optional\n Verbose, by default False\n\n Returns\n -------\n MotifSet\n \"\"\"\n motifs = _load_jaspar(\n motif_accs=motif_accs,\n motif_names=motif_names,\n collection=collection,\n release=release,\n **kwargs,\n )\n motif_set = _from_biopython(\n motifs, \n identifier_number=identifier_number, \n verbose=verbose\n )\n return motif_set\n\ndef read_array(\n filename,\n transpose=True,\n):\n \"\"\"Read from a NumPy array file into a MotifSet object.\n TODO: test this with a real case\n \"\"\"\n pass\n\ndef write_meme( \n motif_set,\n filename,\n background=[0.25, 0.25, 0.25, 0.25],\n **kwargs,\n):\n \"\"\"Write a MotifSet object to a MEME file.\n\n Parameters\n ----------\n motif_set : MotifSet\n MotifSet object\n filename : str\n Output filename\n background : list of float, optional\n Background frequencies, by default [0.25, 0.25, 0.25, 0.25]\n \"\"\"\n pass\n\ndef write_motifs(\n motif_set,\n filename,\n format=\"homer\",\n **kwargs,\n):\n \"\"\"Write a MotifSet object to a file.\n\n Parameters\n ----------\n motif_set : MotifSet\n MotifSet object\n filename : str\n Output filename\n format : str, optional\n Output format, by default \"homer\"\n \"\"\"\n pass\n\ndef write_meme_from_array(\n array,\n outfile,\n vocab=\"DNA\",\n background=[0.25, 0.25, 0.25, 0.25],\n):\n \"\"\"\n Function to convert pwm as ndarray to meme file\n Adapted from:: nnexplain GitHub:\n TODO: Depracate in favor of first converting to MotifSet and then writing to file\n\n Parameters\n ----------\n array:\n numpy.array, often pwm matrices, shape (U, 4, filter_size), where U - number of units\n outfile:\n string, the name of the output meme file\n \"\"\"\n from ...preprocess._utils import _get_vocab\n\n vocab = \"\".join(_get_vocab(vocab))\n n_filters = array.shape[0]\n filter_size = array.shape[2]\n meme_file = open(outfile, \"w\")\n meme_file.write(\"MEME version 4\\n\\n\")\n meme_file.write(f\"ALPHABET= {vocab}\\n\\n\")\n meme_file.write(\"strands: + -\\n\\n\")\n meme_file.write(\"Background letter frequencies\\n\")\n meme_file.write(f\"{vocab[0]} {background[0]} {vocab[1]} {background[1]} {vocab[2]} {background[2]} {vocab[3]} {background[3]}\\n\")\n\n for i in range(0, n_filters):\n if np.sum(array[i, :, :]) > 0:\n meme_file.write(\"\\n\")\n meme_file.write(\"MOTIF filter%s\\n\" % i)\n meme_file.write(\n \"letter-probability matrix: alength= 4 w= %d \\n\"\n % np.count_nonzero(np.sum(array[i, :, :], axis=0))\n )\n for j in range(0, filter_size):\n if np.sum(array[i, :, j]) > 0:\n meme_file.write(\n str(array[i, 0, j])\n + \"\\t\"\n + str(array[i, 1, j])\n + \"\\t\"\n + str(array[i, 2, j])\n + \"\\t\"\n + str(array[i, 3, j])\n + \"\\n\"\n )\n meme_file.close()\n print(\"Saved array in as : {}\".format(outfile))\n","sub_path":"eugene/dataload/motif/_io.py","file_name":"_io.py","file_ext":"py","file_size_in_byte":10382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"227130824","text":"from collections import deque\nfrom VEE_events import VEE_StopEngineEvent, VEE_TimerEvent, \\\n VEE_StartEngineEvent, VEE_BaseAbstractEvent\nfrom VEE_timer import VEE_timer\nfrom VEE_logs import EngineMessage\nfrom VEE_utils import encodeUTF8\nfrom datetime import datetime\nimport Queue\nimport logging\nfrom prosuite_logging import DequeMemoryHandler, app_logger as root_logger\n\n\nMAX_LOG_LEN = 200\n\ndisable = getattr(application, 'ENV_DISABLE_VSCRIPT', False)\n\nworkflow_queue = Queue.Queue()\ncompiler_queue = Queue.Queue()\nqueue_thread = None\ncompiler_thread = None\n\nclass VdomEventEngine:\n def __init__( self ):\n self.listeners = {}\n self.timers = {}\n self.setup_logging()\n self.engine_start()\n\n def setup_logging(self):\n '''\n '''\n memory_hdlr = DequeMemoryHandler(capacity=MAX_LOG_LEN)\n self.logs = memory_hdlr\n\n self.engine_logger = root_logger.getChild('Engine')\n self.engine_logger.addHandler(memory_hdlr)\n self.engine_logger.setLevel(logging.DEBUG)\n self.engine_logger.info('Engine logger initialized!')\n\n self.plugin_logger = root_logger.getChild('Plugin')\n self.plugin_logger.addHandler(memory_hdlr)\n self.plugin_logger.setLevel(logging.DEBUG)\n self.plugin_logger.info('Plugin logger initialized!')\n\n def engine_start( self ):\n if disable:\n return\n\n from VEE_time_trigger import engineTimeTrigger\n from VEE_compiler_trigger import compilerTimeTrigger\n self.put_event( VEE_StartEngineEvent() )\n\n self.engine_logger.info(\"Starting engine thread...\")\n engineTimeTrigger().start()\n\n self.engine_logger.info(\"Starting compiler thread...\")\n compilerTimeTrigger().start()\n\n self.engine_logger.info( u\"Engine started.\" )\n\n\n def engine_stop( self ):\n self.engine_logger.info( u\"Engine stopped.\" )\n if queue_thread:\n queue_thread.stop()\n if compiler_thread:\n compiler_thread.stop()\n self.clear_all()\n\n\n def load_listeners( self ):\n from class_macro import register_all_event_macro\n register_all_event_macro()\n\n\n def put_event( self, event ):\n # enqueue application events only if there are listeners for them\n if isinstance(event, VEE_BaseAbstractEvent) and \\\n (event.__class__, hash(event)) not in self.listeners:\n return\n workflow_queue.put( event )\n\n\n def process_queue( self ):\n event = None\n try:\n event = workflow_queue.get( True, 5 )\n except Queue.Empty:\n self.check_timers()\n return 2.0\n\n if isinstance( event, VEE_TimerEvent ):\n self.engine_logger.info( u\"Recieved event of class '{timeClass}' with name '{timerName}'\".format(\n timeClass = event.__class__.__name__[ 4: ],\n timerName = event.timer.timer.name.split( \":\", 1 )[ 1 ] ) )\n\n else:\n self.info( ( u\"Recieved event of class '{className}' ({cls}:{hash})\".format(\n className = event.__class__.__name__[ 4: ],\n cls = event.__class__.__name__,\n hash = hash( event ) ) ) )\n self.engine_logger.info( ( u\"Recieved event of class '{className}'\".format(\n className = event.__class__.__name__[ 4: ] ) ) )\n\n\n if isinstance( event, VEE_StopEngineEvent ):\n self.engine_stop()\n return\n\n elif isinstance( event, VEE_StartEngineEvent ):\n self.load_listeners()\n return\n\n key = ( event.__class__, hash( event ) )\n if key in self.listeners:\n dispatchers = self.listeners[ key ]\n self.engine_logger.info( u\"Event '{className}' has {dispatchersCount} dispatchers\".format(\n className = event.__class__.__name__[4:],\n dispatchersCount = len( dispatchers ) ) )\n\n for dispatcher in dispatchers.itervalues():\n dispatcher( event )\n\n else:\n self.engine_logger.info( u\"No dispatcher for given event '{className}'\".format(\n className = event.__class__.__name__[4:] ) )\n\n #check for webdav activity\n# try:\n# from webdav_server.vdom_dav_provider import get_properties\n# if (datetime.now() - get_properties.last_access()).total_seconds()<30:\n# return 10.0\n# except Exception as e:\n# return 1.0\n\n return 0.25\n\n def get_dispatcher_by_event( self, event ):\n key = ( event.__class__, hash( event ) )\n if key in self.listeners:\n return self.listeners[ key ].values()[ 0 ]\n\n return None\n\n def do_compile(self):\n task = None\n try:\n task = compiler_queue.get( True, 5 )\n except Queue.Empty:\n return\n\n macro, event_class, key, dispatcher = task\n self.engine_logger.debug(\"%s[%s] - start compiling\", macro.name, macro.guid)\n ret = dispatcher.compile()\n if ret == COMPILATION_SUCCESS:\n self.compile_done(macro, event_class, key, dispatcher)\n self.engine_logger.debug(\"%s[%s] - compiling done\", macro.name, macro.guid)\n# self.engine_logger.info(\"Compiling done\" )\n else:\n self.engine_logger.debug(\"%s[%s] - compiling failing\", macro.name, macro.guid)\n# self.engine_logger.info(\"Compiling failed\" )\n #cache, code = compile( source , environment = env )\n\n def compile_done(self, macro, event_class, key, dispatcher):\n macro.bytecode = (dispatcher.cache, dispatcher.debuginfo)\n macro.save_after_compile()\n self.register_dispatcher(event_class, key, dispatcher)\n\n def compile_and_register(self, macro, event_class, key):\n try:\n dispatcher = VEE_vmacro_dispatcher(macro)\n if macro.bytecode:\n self.engine_logger.debug(\"%s[%s] - bytecode exists\", macro.name, macro.guid)\n self.register_dispatcher(event_class, key, dispatcher)\n return COMPILATION_SUCCESS\n\n self.engine_logger.debug(\"%s[%s] - put macro in compile queue\", macro.name, macro.guid)\n compiler_queue.put((macro, event_class, key, dispatcher))\n\n except Exception as e:\n self.engine_logger.exception(\"@@@@@@@@@Error while vscript compilation.\" )\n\n\n def register_dispatcher( self, event_class, event_key, dispatcher ):\n key = ( event_class, event_key )\n disp_hash = hash( dispatcher.guid )\n self.info( u\"Register dispatcher '{dispatcherName}' for event '{eventName}' ({cls}:{hash})\".format(\n dispatcherName = dispatcher.name,\n eventName = event_class.__name__[ 4: ],\n cls = event_class.__name__,\n hash = event_key ) )\n\n self.engine_logger.info( u\"Register dispatcher '{dispatcherName}' for event '{eventName}'\".format(\n dispatcherName = dispatcher.name,\n eventName = event_class.__name__[ 4: ] ) )\n\n\n if key not in self.listeners:\n self.listeners[ key ] = {}\n\n self.listeners[ key ][ disp_hash ] = dispatcher\n\n\n def unregister_dispatcher( self, event_class, event_key, disp_guid ):\n key = ( event_class, event_key )\n if key in self.listeners:\n dispatchers = self.listeners[ key ]\n disp_hash = hash( disp_guid )\n\n if disp_hash in dispatchers:\n dispatcher = dispatchers[ disp_hash ]\n del dispatchers[ disp_hash ]\n\n self.engine_logger.info( u\"Unregister dispatcher '{dispatcherName}' for event '{eventName}'\".format(\n dispatcherName = dispatcher.name,\n eventName = event_class.__name__[ 4: ] ) )\n\n\n if len( dispatchers ) == 0:\n del self.listeners[ key ]\n\n\n def clear_all(self):\n self.clear_log()\n self.listeners = {}\n self.timers = {}\n try:\n while True:\n workflow_queue.get_nowait()\n except Queue.Empty:\n pass\n\n\n def add_timer( self, name, delay, hash_value ):\n \"\"\"Add timer with defined name and delay\"\"\"\n if name not in self.timers:\n self.timers[ name ] = VEE_timer( name, delay, hash_value )\n\n\n def update_timer( self, name, delay, hash_value ):\n \"\"\"Replace timer with defined name and delay\"\"\"\n self.timers[name] = VEE_timer( name, delay, hash_value )\n\n\n def delete_timer( self, name ):\n \"\"\"Removing timer. If there is no with such name - no exception rising\"\"\"\n try:\n del self.timers[ name ]\n except Exception:\n pass\n\n\n def activate_timer( self, name, state ):\n \"\"\"Timer change state to active. If there is no with such name - exception raised\"\"\"\n try:\n self.timers[ name ].active = state\n except Exception:\n raise Exception( \"No timer with such name\" )\n\n\n def check_timers(self):\n for timer_name in self.timers:\n if self.timers[ timer_name ].check():\n self.put_event( VEE_TimerEvent( self.timers[ timer_name ] ) )\n\n\n def get_timer_by_name( self, name ):\n return self.timers.get( name, None )\n\n\nengine = VdomEventEngine()\nfrom VEE_vmacro_dispatcher import VEE_vmacro_dispatcher, COMPILATION_SUCCESS\n","sub_path":"Libraries/VEE_core.py","file_name":"VEE_core.py","file_ext":"py","file_size_in_byte":9629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"220079196","text":"\"\"\"\nTakes a range as input\nCreates a list of that data\nReturns list\n\"\"\"\ndef create_list(c_range):\n #Create read list\n c_list = []\n #Iterate over range\n for x in CellRange(c_range):\n #Assing cell value back onto itself\n x = x.value\n #add to list\n c_list.append(x)\n \n return c_list\n\nindex_list = create_list('A2:A54')\nraw_week = create_list('M2:M366')\nsamples_list = create_list('N2:N366')\norder_list = create_list('O2:O366')\n\n\nweekly_samples = [0 for a in range(0, len(index_list))]\nweekly_orders = [0 for a in range(0, len(index_list))]\n\n# Iterate over raw data\nx = 0\nfor a in raw_week:\n y = 0\n # Iterate over index\n for b in index_list:\n # See if values are the same\n if(a == b):\n weekly_samples[y] += samples_list[x]\n weekly_orders[y] += order_list[x]\n break\n y += 1\n x += 1\n\nx = 0\nfor a in CellRange('I2:I54'):\n a.value = weekly_samples[x]\n Cell('J' + str(a.row)).value = weekly_orders[x]\n x += 1\n","sub_path":"weekly_data.py","file_name":"weekly_data.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"632674814","text":"import socket\nimport struct\n\nimport comm_types\n\n\n# Archive transfer compresion method.\nCOMPRESSION = 'bztar'\n# Format to use when serialising/de-serialising strings.\nUNICODE_FORMAT = 'utf-8'\n\n\nclass Transmitter:\n \"\"\"\n Transmit data to the server.\n\n :param conn_info: The connection information tuple for the socket.\n \"\"\"\n def __init__(self, conn_info):\n self._conn_info = conn_info\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.connect(self._conn_info)\n\n def send_file(self, file):\n \"\"\"\n Send the data of a file to the server.\n\n :param file: The file.File object to send.\n \"\"\"\n data = bytearray(struct.pack('I', len(file.path)))\n data += bytearray(file.path, encoding=UNICODE_FORMAT)\n data += bytearray(file.data)\n self._send(comm_types.FILE, data)\n\n def del_file(self, path):\n \"\"\"\n Notify the server that a file was deleted.\n\n :param path: The relative path of the file that was deleted.\n \"\"\"\n self._send(comm_types.DEL_FILE, bytearray(path,\n encoding=UNICODE_FORMAT))\n\n def send_dir(self, path):\n \"\"\"\n Notify the server of a directory that exists.\n\n :param path: The path to the directory.\n \"\"\"\n self._send(comm_types.DIR, bytearray(path, encoding=UNICODE_FORMAT))\n\n def del_dir(self, path):\n \"\"\"\n Notify the server that a directory was deleted.\n\n :param path: The path to the directory.\n \"\"\"\n self._send(comm_types.DEL_DIR, bytearray(path,\n encoding=UNICODE_FORMAT))\n\n def move(self, src, dest):\n \"\"\"\n Notify the server that an item was moved.\n\n :param src: The old relative path of the item.\n :param dest: The new relative path of the item.\n \"\"\"\n print(f\"Moving {src} to {dest}\")\n data = bytearray(struct.pack('I', len(src)))\n data += bytearray(src, encoding=UNICODE_FORMAT)\n data += bytearray(dest, encoding=UNICODE_FORMAT)\n self._send(comm_types.MOVE, data)\n\n def _send(self, comm_type, data):\n \"\"\"\n Send data in type-length-value format.\n\n :param comm_type: The comm_type enum constant representing the data\n type.\n :param data: The data to be sent, as bytes.\n \"\"\"\n # Pack a struct with two integers representing the comm type and\n # data length.\n self._socket.sendall(struct.pack('II', comm_type, len(data)))\n self._socket.sendall(data)\n\n def terminate(self):\n \"\"\"\n Terminate the connection.\n \"\"\"\n self._socket.close()\n\n\nclass Receiver:\n \"\"\"\n Receive data from the client.\n\n :param port: The TCP port to use for the connection.\n \"\"\"\n HOST = 'localhost'\n\n def __init__(self, port):\n self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,\n 1)\n self._server_socket.bind((Receiver.HOST, port))\n # Single-threaded server, so no connection backlog.\n self._server_socket.listen(0)\n (self._conn, _) = self._server_socket.accept()\n\n def receive(self):\n \"\"\"\n Receive data from the client.\n\n :return: A two-tuple containing the comm_type constant representing the\n data type, and the data itself, as a byte array.\n \"\"\"\n # Receive the comm type and data length first. Struct of two integers\n # has size 8 bytes.\n (comm_type, length) = struct.unpack('II', self._conn.recv(8))\n # Repeatedly call recv until all required bytes were read.\n recvd_len = 0\n data = []\n while recvd_len < length:\n max = length - recvd_len\n data += self._conn.recv(max)\n recvd_len += len(data)\n return (comm_type, bytearray(data))\n\n def terminate(self):\n \"\"\"\n Terminate the connection.\n \"\"\"\n self._conn.close()\n self._server_socket.close()\n","sub_path":"comms.py","file_name":"comms.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"276946570","text":"# new admission/urls.py file\n\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = 'admission'\nurlpatterns = [\n\turl(r'^$', views.SummaryView.as_view(), name='summary'),\n url(r'^(?P