diff --git "a/4909.jsonl" "b/4909.jsonl" new file mode 100644--- /dev/null +++ "b/4909.jsonl" @@ -0,0 +1,766 @@ +{"seq_id":"523441224","text":"import re\nimport json\nimport copy\nimport pytest\nimport responses\nfrom nylas import APIClient\n\n# pylint: disable=redefined-outer-name\n\n\n@pytest.fixture\ndef message_body():\n return {\n \"busy\": True,\n \"calendar_id\": \"94rssh7bd3rmsxsp19kiocxze\",\n \"description\": None,\n \"id\": \"cv4ei7syx10uvsxbs21ccsezf\",\n \"location\": \"1 Infinite loop, Cupertino\",\n \"message_id\": None,\n \"namespace_id\": \"384uhp3aj8l7rpmv9s2y2rukn\",\n \"object\": \"event\",\n \"owner\": None,\n \"participants\": [],\n \"read_only\": False,\n \"status\": \"confirmed\",\n \"title\": \"The rain song\",\n \"when\": {\n \"end_time\": 1441056790,\n \"object\": \"timespan\",\n \"start_time\": 1441053190\n }\n }\n\n@pytest.fixture\ndef api_url():\n return 'https://localhost:2222'\n\n\n@pytest.fixture\ndef account_id():\n return '4ennivvrcgsqytgybfk912dto'\n\n\n@pytest.fixture\ndef app_id():\n return 'fake-app-id'\n\n\n@pytest.fixture\ndef api_client(api_url):\n return APIClient(None, None, None, api_url)\n\n\n@pytest.fixture\ndef mocked_responses():\n rmock = responses.RequestsMock(assert_all_requests_are_fired=False)\n with rmock:\n yield rmock\n\n\n@pytest.fixture\ndef mock_save_draft(mocked_responses, api_url):\n save_endpoint = re.compile(api_url + '/drafts/')\n response_body = json.dumps({\n \"id\": \"4dl0ni6vxomazo73r5oydo16k\",\n \"version\": \"4dw0ni6txomazo33r5ozdo16j\"\n })\n mocked_responses.add(\n responses.POST,\n save_endpoint,\n content_type='application/json',\n status=200,\n body=response_body,\n match_querystring=True\n )\n\n\n@pytest.fixture\ndef mock_account(mocked_responses, api_url, account_id):\n response_body = json.dumps(\n {\n \"account_id\": account_id,\n \"email_address\": \"ben.bitdiddle1861@gmail.com\",\n \"id\": account_id,\n \"name\": \"Ben Bitdiddle\",\n \"object\": \"account\",\n \"provider\": \"gmail\",\n \"organization_unit\": \"label\",\n \"billing_state\": \"paid\",\n }\n )\n mocked_responses.add(\n responses.GET,\n re.compile(api_url + '/account/?'),\n content_type='application/json',\n status=200,\n body=response_body,\n )\n\n\n@pytest.fixture\ndef mock_accounts(mocked_responses, api_url, account_id, app_id):\n response_body = json.dumps([\n {\n \"account_id\": account_id,\n \"email_address\": \"ben.bitdiddle1861@gmail.com\",\n \"id\": account_id,\n \"name\": \"Ben Bitdiddle\",\n \"object\": \"account\",\n \"provider\": \"gmail\",\n \"organization_unit\": \"label\",\n \"billing_state\": \"paid\",\n }\n ])\n url_re = \"{base}(/a/{app_id})?/accounts/?\".format(base=api_url, app_id=app_id)\n mocked_responses.add(\n responses.GET,\n re.compile(url_re),\n content_type='application/json',\n status=200,\n body=response_body,\n )\n\n\n@pytest.fixture\ndef mock_folder_account(mocked_responses, api_url, account_id):\n response_body = json.dumps(\n {\n \"email_address\": \"ben.bitdiddle1861@office365.com\",\n \"id\": account_id,\n \"name\": \"Ben Bitdiddle\",\n \"account_id\": account_id,\n \"object\": \"account\",\n \"provider\": \"eas\",\n \"organization_unit\": \"folder\"\n }\n )\n mocked_responses.add(\n responses.GET,\n api_url + '/account',\n content_type='application/json',\n status=200,\n body=response_body,\n match_querystring=True\n )\n\n\n@pytest.fixture\ndef mock_labels(mocked_responses, api_url, account_id):\n response_body = json.dumps([\n {\n \"display_name\": \"Important\",\n \"id\": \"anuep8pe5ugmxrucchrzba2o8\",\n \"name\": \"important\",\n \"account_id\": account_id,\n \"object\": \"label\"\n },\n {\n \"display_name\": \"Trash\",\n \"id\": \"f1xgowbgcehk235xiy3c3ek42\",\n \"name\": \"trash\",\n \"account_id\": account_id,\n \"object\": \"label\"\n },\n {\n \"display_name\": \"Sent Mail\",\n \"id\": \"ah14wp5fvypvjjnplh7nxgb4h\",\n \"name\": \"sent\",\n \"account_id\": account_id,\n \"object\": \"label\"\n },\n {\n \"display_name\": \"All Mail\",\n \"id\": \"ah14wp5fvypvjjnplh7nxgb4h\",\n \"name\": \"all\",\n \"account_id\": account_id,\n \"object\": \"label\"\n },\n {\n \"display_name\": \"Inbox\",\n \"id\": \"dc11kl3s9lj4760g6zb36spms\",\n \"name\": \"inbox\",\n \"account_id\": account_id,\n \"object\": \"label\"\n }\n ])\n endpoint = re.compile(api_url + '/labels.*')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body,\n )\n\n\n@pytest.fixture\ndef mock_label(mocked_responses, api_url, account_id):\n response_body = json.dumps(\n {\n \"display_name\": \"Important\",\n \"id\": \"anuep8pe5ugmxrucchrzba2o8\",\n \"name\": \"important\",\n \"account_id\": account_id,\n \"object\": \"label\"\n }\n )\n url = api_url + '/labels/anuep8pe5ugmxrucchrzba2o8'\n mocked_responses.add(\n responses.GET,\n url,\n content_type='application/json',\n status=200,\n body=response_body,\n )\n\n\n@pytest.fixture\ndef mock_folder(mocked_responses, api_url, account_id):\n folder = {\n \"display_name\": \"My Folder\",\n \"id\": \"anuep8pe5ug3xrupchwzba2o8\",\n \"name\": None,\n \"account_id\": account_id,\n \"object\": \"folder\"\n }\n response_body = json.dumps(folder)\n url = api_url + '/folders/anuep8pe5ug3xrupchwzba2o8'\n mocked_responses.add(\n responses.GET,\n url,\n content_type='application/json',\n status=200,\n body=response_body,\n )\n\n def request_callback(request):\n payload = json.loads(request.body)\n if 'display_name' in payload:\n folder.update(payload)\n return (200, {}, json.dumps(folder))\n\n mocked_responses.add_callback(\n responses.PUT,\n url,\n content_type='application/json',\n callback=request_callback,\n )\n\n\n@pytest.fixture\ndef mock_messages(mocked_responses, api_url, account_id):\n response_body = json.dumps([\n {\n \"id\": \"1234\",\n \"subject\": \"Test Message\",\n \"account_id\": account_id,\n \"object\": \"message\",\n \"labels\": [\n {\n \"name\": \"inbox\",\n \"display_name\": \"Inbox\",\n \"id\": \"abcd\"\n }\n ],\n \"starred\": False,\n \"unread\": True,\n \"date\": 1265077342,\n }, {\n \"id\": \"1238\",\n \"subject\": \"Test Message 2\",\n \"account_id\": account_id,\n \"object\": \"message\",\n \"labels\": [\n {\n \"name\": \"inbox\",\n \"display_name\": \"Inbox\",\n \"id\": \"abcd\"\n }\n ],\n \"starred\": False,\n \"unread\": True,\n \"date\": 1265085342,\n }, {\n \"id\": \"12\",\n \"subject\": \"Test Message 3\",\n \"account_id\": account_id,\n \"object\": \"message\",\n \"labels\": [\n {\n \"name\": \"archive\",\n \"display_name\": \"Archive\",\n \"id\": \"gone\"\n }\n ],\n \"starred\": False,\n \"unread\": False,\n \"date\": 1265093842,\n }\n ])\n endpoint = re.compile(api_url + '/messages')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n\n\n@pytest.fixture\ndef mock_message(mocked_responses, api_url, account_id):\n base_msg = {\n \"id\": \"1234\",\n \"subject\": \"Test Message\",\n \"account_id\": account_id,\n \"object\": \"message\",\n \"labels\": [\n {\n \"name\": \"inbox\",\n \"display_name\": \"Inbox\",\n \"id\": \"abcd\"\n }\n ],\n \"starred\": False,\n \"unread\": True\n }\n response_body = json.dumps(base_msg)\n\n def request_callback(request):\n payload = json.loads(request.body)\n if 'labels' in payload:\n labels = [{'name': 'test', 'display_name': 'test', 'id': l}\n for l in payload['labels']]\n base_msg['labels'] = labels\n return (200, {}, json.dumps(base_msg))\n\n endpoint = re.compile(api_url + '/messages/1234')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n mocked_responses.add_callback(\n responses.PUT,\n endpoint,\n content_type='application/json',\n callback=request_callback\n )\n mocked_responses.add(\n responses.DELETE,\n endpoint,\n content_type='application/json',\n status=200,\n body=\"\",\n )\n\n\n@pytest.fixture\ndef mock_threads(mocked_responses, api_url, account_id):\n response_body = json.dumps([\n {\n \"id\": \"5678\",\n \"subject\": \"Test Thread\",\n \"account_id\": account_id,\n \"object\": \"thread\",\n \"folders\": [{\n \"name\": \"inbox\",\n \"display_name\": \"Inbox\",\n \"id\": \"abcd\"\n }],\n \"starred\": True,\n \"unread\": False,\n \"first_message_timestamp\": 1451703845,\n \"last_message_timestamp\": 1483326245,\n \"last_message_received_timestamp\": 1483326245,\n \"last_message_sent_timestamp\": 1483232461,\n }\n ])\n endpoint = re.compile(api_url + '/threads')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n\n\n@pytest.fixture\ndef mock_thread(mocked_responses, api_url, account_id):\n base_thrd = {\n \"id\": \"5678\",\n \"subject\": \"Test Thread\",\n \"account_id\": account_id,\n \"object\": \"thread\",\n \"folders\": [{\n \"name\": \"inbox\",\n \"display_name\": \"Inbox\",\n \"id\": \"abcd\"\n }],\n \"starred\": True,\n \"unread\": False,\n \"first_message_timestamp\": 1451703845,\n \"last_message_timestamp\": 1483326245,\n \"last_message_received_timestamp\": 1483326245,\n \"last_message_sent_timestamp\": 1483232461,\n }\n response_body = json.dumps(base_thrd)\n\n def request_callback(request):\n payload = json.loads(request.body)\n if 'folder' in payload:\n folder = {'name': 'test', 'display_name': 'test',\n 'id': payload['folder']}\n base_thrd['folders'] = [folder]\n return (200, {}, json.dumps(base_thrd))\n\n endpoint = re.compile(api_url + '/threads/5678')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n mocked_responses.add_callback(\n responses.PUT,\n endpoint,\n content_type='application/json',\n callback=request_callback,\n )\n\n\n@pytest.fixture\ndef mock_labelled_thread(mocked_responses, api_url, account_id):\n base_thread = {\n \"id\": \"111\",\n \"subject\": \"Labelled Thread\",\n \"account_id\": account_id,\n \"object\": \"thread\",\n \"folders\": [{\n \"name\": \"inbox\",\n \"display_name\": \"Inbox\",\n \"id\": \"abcd\"\n }],\n \"starred\": True,\n \"unread\": False,\n \"labels\": [\n {\n \"display_name\": \"Important\",\n \"id\": \"anuep8pe5ugmxrucchrzba2o8\",\n \"name\": \"important\",\n \"account_id\": account_id,\n \"object\": \"label\"\n }, {\n \"display_name\": \"Existing\",\n \"id\": \"dfslhgy3rlijfhlsujnchefs3\",\n \"name\": \"existing\",\n \"account_id\": account_id,\n \"object\": \"label\"\n }\n ],\n \"first_message_timestamp\": 1451703845,\n \"last_message_timestamp\": 1483326245,\n \"last_message_received_timestamp\": 1483326245,\n \"last_message_sent_timestamp\": 1483232461,\n }\n response_body = json.dumps(base_thread)\n\n def request_callback(request):\n payload = json.loads(request.body)\n if 'labels' in payload:\n existing_labels = {\n label[\"id\"]: label\n for label in base_thread[\"labels\"]\n }\n new_labels = []\n for label_id in payload['labels']:\n if label_id in existing_labels:\n new_labels.append(existing_labels[label_id])\n else:\n new_labels.append({\n \"name\": \"updated\",\n \"display_name\": \"Updated\",\n \"id\": label_id,\n \"account_id\": account_id,\n \"object\": \"label\",\n })\n copied = copy.copy(base_thread)\n copied[\"labels\"] = new_labels\n return (200, {}, json.dumps(copied))\n\n endpoint = re.compile(api_url + '/threads/111')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n mocked_responses.add_callback(\n responses.PUT,\n endpoint,\n content_type='application/json',\n callback=request_callback,\n )\n\n\n@pytest.fixture\ndef mock_drafts(mocked_responses, api_url):\n response_body = json.dumps([{\n \"bcc\": [],\n \"body\": \"Cheers mate!\",\n \"cc\": [],\n \"date\": 1438684486,\n \"events\": [],\n \"files\": [],\n \"folder\": None,\n \"from\": [],\n \"id\": \"2h111aefv8pzwzfykrn7hercj\",\n \"namespace_id\": \"384uhp3aj8l7rpmv9s2y2rukn\",\n \"object\": \"draft\",\n \"reply_to\": [],\n \"reply_to_message_id\": None,\n \"snippet\": \"\",\n \"starred\": False,\n \"subject\": \"Here's an attachment\",\n \"thread_id\": \"clm33kapdxkposgltof845v9s\",\n \"to\": [\n {\n \"email\": \"helena@nylas.com\",\n \"name\": \"Helena Handbasket\"\n }\n ],\n \"unread\": False,\n \"version\": 0\n }])\n\n mocked_responses.add(\n responses.GET,\n api_url + '/drafts',\n content_type='application/json',\n status=200,\n body=response_body,\n )\n\n\n@pytest.fixture\ndef mock_draft_saved_response(mocked_responses, api_url):\n draft_json = {\n \"bcc\": [],\n \"body\": \"Cheers mate!\",\n \"cc\": [],\n \"date\": 1438684486,\n \"events\": [],\n \"files\": [],\n \"folder\": None,\n \"from\": [],\n \"id\": \"2h111aefv8pzwzfykrn7hercj\",\n \"namespace_id\": \"384uhp3aj8l7rpmv9s2y2rukn\",\n \"object\": \"draft\",\n \"reply_to\": [],\n \"reply_to_message_id\": None,\n \"snippet\": \"\",\n \"starred\": False,\n \"subject\": \"Here's an attachment\",\n \"thread_id\": \"clm33kapdxkposgltof845v9s\",\n \"to\": [\n {\n \"email\": \"helena@nylas.com\",\n \"name\": \"Helena Handbasket\"\n }\n ],\n \"unread\": False,\n \"version\": 0,\n }\n\n def create_callback(_request):\n return (200, {}, json.dumps(draft_json))\n\n def update_callback(request):\n try:\n payload = json.loads(request.body)\n except ValueError:\n return (200, {}, json.dumps(draft_json))\n\n stripped_payload = {\n key: value for key, value in payload.items() if value\n }\n updated_draft_json = copy.copy(draft_json)\n updated_draft_json.update(stripped_payload)\n updated_draft_json[\"version\"] += 1\n return (200, {}, json.dumps(updated_draft_json))\n\n mocked_responses.add_callback(\n responses.POST,\n api_url + '/drafts/',\n content_type='application/json',\n callback=create_callback,\n )\n\n mocked_responses.add_callback(\n responses.PUT,\n api_url + '/drafts/2h111aefv8pzwzfykrn7hercj',\n content_type='application/json',\n callback=update_callback,\n )\n\n\n@pytest.fixture\ndef mock_draft_deleted_response(mocked_responses, api_url):\n mocked_responses.add(\n responses.DELETE,\n api_url + '/drafts/2h111aefv8pzwzfykrn7hercj',\n content_type='application/json',\n status=200,\n body=\"\",\n )\n\n\n@pytest.fixture\ndef mock_draft_sent_response(mocked_responses, api_url):\n body = {\n \"bcc\": [],\n \"body\": \"\",\n \"cc\": [],\n \"date\": 1438684486,\n \"events\": [],\n \"files\": [],\n \"folder\": None,\n \"from\": [{'email': 'benb@nylas.com'}],\n \"id\": \"2h111aefv8pzwzfykrn7hercj\",\n \"namespace_id\": \"384uhp3aj8l7rpmv9s2y2rukn\",\n \"object\": \"draft\",\n \"reply_to\": [],\n \"reply_to_message_id\": None,\n \"snippet\": \"\",\n \"starred\": False,\n \"subject\": \"Stay polish, stay hungary\",\n \"thread_id\": \"clm33kapdxkposgltof845v9s\",\n \"to\": [\n {\n \"email\": \"helena@nylas.com\",\n \"name\": \"Helena Handbasket\"\n }\n ],\n \"unread\": False,\n \"version\": 0,\n }\n\n values = [(400, {}, \"Couldn't send email\"),\n (200, {}, json.dumps(body))]\n\n def callback(request):\n payload = json.loads(request.body)\n assert payload['draft_id'] == '2h111aefv8pzwzfykrn7hercj'\n return values.pop()\n\n mocked_responses.add_callback(\n responses.POST,\n api_url + '/send/',\n callback=callback,\n content_type='application/json'\n )\n\n\n@pytest.fixture\ndef mock_files(mocked_responses, api_url):\n body = [{\n \"content_type\": \"text/plain\",\n \"filename\": \"a.txt\",\n \"id\": \"3qfe4k3siosfjtjpfdnon8zbn\",\n \"account_id\": \"6aakaxzi4j5gn6f7kbb9e0fxs\",\n \"object\": \"file\",\n \"size\": 762878\n }]\n mocked_responses.add(\n responses.POST,\n api_url + '/files/',\n body=json.dumps(body),\n )\n mocked_responses.add(\n responses.GET,\n api_url + '/files/3qfe4k3siosfjtjpfdnon8zbn/download',\n body='test body',\n )\n\n\n@pytest.fixture\ndef mock_event_create_response(mocked_responses, api_url, message_body):\n values = [(400, {}, \"\"),\n (200, {}, json.dumps(message_body))]\n\n def callback(_request):\n return values.pop()\n\n mocked_responses.add_callback(\n responses.POST,\n api_url + '/events/',\n callback=callback,\n )\n\n put_body = {'title': 'loaded from JSON', 'ignored': 'ignored'}\n mocked_responses.add(\n responses.PUT,\n api_url + '/events/cv4ei7syx10uvsxbs21ccsezf',\n body=json.dumps(put_body)\n )\n\n\n@pytest.fixture\ndef mock_event_create_notify_response(mocked_responses, api_url, message_body):\n mocked_responses.add(\n responses.POST,\n api_url + '/events/?notify_participants=true&other_param=1',\n body=json.dumps(message_body),\n )\n\n\n\n@pytest.fixture\ndef mock_thread_search_response(mocked_responses, api_url):\n snippet = (\n \"Hey Helena, Looking forward to getting together for dinner on Friday. \"\n \"What can I bring? I have a couple bottles of wine or could put together\"\n )\n response_body = json.dumps([\n {\n \"id\": \"evh5uy0shhpm5d0le89goor17\",\n \"object\": \"thread\",\n \"account_id\": \"awa6ltos76vz5hvphkp8k17nt\",\n \"subject\": \"Dinner Party on Friday\",\n \"unread\": False,\n \"starred\": False,\n \"last_message_timestamp\": 1398229259,\n \"last_message_received_timestamp\": 1398229259,\n \"first_message_timestamp\": 1298229259,\n \"participants\": [\n {\n \"name\": \"Ben Bitdiddle\",\n \"email\": \"ben.bitdiddle@gmail.com\"\n },\n ],\n \"snippet\": snippet,\n \"folders\": [\n {\n \"name\": \"inbox\",\n \"display_name\": \"INBOX\",\n \"id\": \"f0idlvozkrpj3ihxze7obpivh\"\n },\n ],\n \"message_ids\": [\n \"251r594smznew6yhiocht2v29\",\n \"7upzl8ss738iz8xf48lm84q3e\",\n \"ah5wuphj3t83j260jqucm9a28\"\n ],\n \"draft_ids\": [\n \"251r594smznew6yhi12312saq\"\n ],\n \"version\": 2\n }\n ])\n\n mocked_responses.add(\n responses.GET,\n api_url + '/threads/search?q=Helena',\n body=response_body,\n status=200,\n content_type='application/json',\n match_querystring=True\n )\n\n@pytest.fixture\ndef mock_message_search_response(mocked_responses, api_url):\n snippet = (\n \"Sounds good--that bottle of Pinot should go well with the meal. \"\n \"I'll also bring a surprise for dessert. :) \"\n \"Do you have ice cream? Looking fo\"\n )\n response_body = json.dumps([\n {\n \"id\": \"84umizq7c4jtrew491brpa6iu\",\n \"object\": \"message\",\n \"account_id\": \"14e5bn96uizyuhidhcw5rfrb0\",\n \"thread_id\": \"5vryyrki4fqt7am31uso27t3f\",\n \"subject\": \"Re: Dinner on Friday?\",\n \"from\": [\n {\n \"name\": \"Ben Bitdiddle\",\n \"email\": \"ben.bitdiddle@gmail.com\"\n }\n ],\n \"to\": [\n {\n \"name\": \"Bill Rogers\",\n \"email\": \"wbrogers@mit.edu\"\n }\n ],\n \"cc\": [],\n \"bcc\": [],\n \"reply_to\": [],\n \"date\": 1370084645,\n \"unread\": True,\n \"starred\": False,\n \"folder\": {\n \"name\": \"inbox\",\n \"display_name\": \"INBOX\",\n \"id\": \"f0idlvozkrpj3ihxze7obpivh\"\n },\n \"snippet\": snippet,\n \"body\": \"....\",\n \"files\": [],\n \"events\": []\n },\n {\n \"id\": \"84umizq7asdf3aw491brpa6iu\",\n \"object\": \"message\",\n \"account_id\": \"14e5bakdsfljskidhcw5rfrb0\",\n \"thread_id\": \"5vryyralskdjfwlj1uso27t3f\",\n \"subject\": \"Re: Dinner on Friday?\",\n \"from\": [\n {\n \"name\": \"Ben Bitdiddle\",\n \"email\": \"ben.bitdiddle@gmail.com\"\n }\n ],\n \"to\": [\n {\n \"name\": \"Bill Rogers\",\n \"email\": \"wbrogers@mit.edu\"\n }\n ],\n \"cc\": [],\n \"bcc\": [],\n \"reply_to\": [],\n \"date\": 1370084645,\n \"unread\": True,\n \"starred\": False,\n \"folder\": {\n \"name\": \"inbox\",\n \"display_name\": \"INBOX\",\n \"id\": \"f0idlvozkrpj3ihxze7obpivh\"\n },\n \"snippet\": snippet,\n \"body\": \"....\",\n \"files\": [],\n \"events\": []\n }\n ])\n\n mocked_responses.add(\n responses.GET,\n api_url + '/messages/search?q=Pinot',\n body=response_body,\n status=200,\n content_type='application/json',\n match_querystring=True\n )\n\n\n@pytest.fixture\ndef mock_calendars(mocked_responses, api_url):\n response_body = json.dumps([\n {\n \"id\": \"8765\",\n \"events\": [\n {\n \"title\": \"Pool party\",\n \"location\": \"Local Community Pool\",\n \"participants\": [\n \"Alice\",\n \"Bob\",\n \"Claire\",\n \"Dot\",\n ]\n }\n ],\n }\n ])\n endpoint = re.compile(api_url + '/calendars')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n\n@pytest.fixture\ndef mock_events(mocked_responses, api_url):\n response_body = json.dumps([\n {\n \"title\": \"Pool party\",\n \"location\": \"Local Community Pool\",\n \"participants\": [\n {\n \"comment\": None,\n \"email\": \"kelly@nylas.com\",\n \"name\": \"Kelly Nylanaut\",\n \"status\": \"noreply\",\n }, {\n \"comment\": None,\n \"email\": \"sarah@nylas.com\",\n \"name\": \"Sarah Nylanaut\",\n \"status\": \"no\",\n },\n ]\n }\n ])\n endpoint = re.compile(api_url + '/events')\n mocked_responses.add(\n responses.GET,\n endpoint,\n content_type='application/json',\n status=200,\n body=response_body\n )\n\n\n@pytest.fixture\ndef mock_account_management(mocked_responses, api_url, account_id, app_id):\n account = {\n \"account_id\": account_id,\n \"email_address\": \"ben.bitdiddle1861@gmail.com\",\n \"id\": account_id,\n \"name\": \"Ben Bitdiddle\",\n \"object\": \"account\",\n \"provider\": \"gmail\",\n \"organization_unit\": \"label\",\n \"billing_state\": \"paid\",\n }\n paid_response = json.dumps(account)\n account[\"billing_state\"] = \"cancelled\"\n cancelled_response = json.dumps(account)\n\n upgrade_url = \"{base}/a/{app_id}/accounts/{id}/upgrade\".format(\n base=api_url, id=account_id, app_id=app_id,\n )\n downgrade_url = \"{base}/a/{app_id}/accounts/{id}/downgrade\".format(\n base=api_url, id=account_id, app_id=app_id,\n )\n mocked_responses.add(\n responses.POST,\n upgrade_url,\n content_type='application/json',\n status=200,\n body=paid_response,\n )\n mocked_responses.add(\n responses.POST,\n downgrade_url,\n content_type='application/json',\n status=200,\n body=cancelled_response,\n )\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":26508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"582338277","text":"from numpy import *\nfrom matplotlib.pyplot import *\n\nclose('all')\nn = arange(0,10)\nx = load('sig-3MHz-samp-500Hz.npz')\n\nx1 = x['arr_1']\nx1 = x1[0:10]\nsubplot(2,1,1)\nplot(n,x1,'b')\ntitle('vsig = 6000vsmpl')\nxlabel('t [us]')\nylabel('Volts')\nsubplot(2,1,2)\nn = arange(0,117600)\nn = n/6000000.\nsig = cos(2*pi*3000000*n)\nplot(sig)\n\nshow()","sub_path":"lab2/data_code/ex1.1.2/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"444116909","text":"import logging\nimport time\n\nimport docker\nimport pytest\nimport requests\n\nfrom utils import get_config, get_logs, remove_previous_container, CONTAINER_NAME\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclient = docker.from_env()\n\n\ndef verify_container(container, response_text):\n config_data = get_config(container)\n assert config_data[\"workers_per_core\"] == 1\n assert config_data[\"host\"] == \"0.0.0.0\"\n assert config_data[\"port\"] == \"8000\"\n assert config_data[\"workers\"] >= 2\n assert config_data[\"bind\"] == \"0.0.0.0:8000\"\n logs = get_logs(container)\n assert \"Checking for script in /app/prestart.sh\" in logs\n assert \"Running script /app/prestart.sh\" in logs\n prestart_echos = [\n \"postgres waiting\",\n \"postgres wait finished\",\n \"alembic magic\",\n \"prestart euri10_fastapi_base finished\",\n ]\n for prestart_echo in prestart_echos:\n assert prestart_echo in logs\n try:\n response = requests.get(f\"http://127.0.0.1:8000\")\n data = response.json()\n assert data[\"message\"] == response_text\n return True\n except Exception as e:\n logger.debug(e)\n return False\n\n\n@pytest.mark.parametrize(\n \"image,response_text\",\n [\n (\n \"registry.gitlab.com/euri10/euri10_fastapi_base:latest\",\n \"Hello euri10! From FastAPI running on Uvicorn with Gunicorn in Alpine. Using Python 3.7\",\n ),\n (\n \"registry.gitlab.com/euri10/euri10_fastapi_base:python3.7-alpine3.8\",\n \"Hello euri10! From FastAPI running on Uvicorn with Gunicorn in Alpine. Using Python 3.7\",\n ),\n ],\n)\ndef test_defaults(image, response_text):\n remove_previous_container(client, CONTAINER_NAME)\n remove_previous_container(client, \"db\")\n testnet = client.networks.create(\"testnet\")\n db = client.containers.run(\"postgres:10.6-alpine\", name=\"db\", detach=True)\n testnet.connect(db)\n time.sleep(1)\n container = client.containers.run(\n image, name=CONTAINER_NAME, ports={\"8000\": \"8000\"}, detach=True\n )\n testnet.connect(container)\n\n time.sleep(1)\n try:\n assert verify_container(container, response_text)\n except Exception as e:\n logger.debug(e)\n finally:\n container.stop()\n\n # Test that everything works after restarting too\n container.start()\n time.sleep(5)\n verify_container(container, response_text)\n container.stop()\n container.remove()\n db.stop()\n db.remove()\n testnet.remove()\n\n","sub_path":"tests/test_defaults.py","file_name":"test_defaults.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"160740224","text":"import argparse\nfrom attrdict import AttrDict\nfrom deriva.core import ErmrestCatalog, get_credential, DerivaPathError\nfrom deriva.utils.catalog.components.deriva_model import DerivaCatalog\nimport deriva.core.ermrest_model as em\nfrom deriva.core.ermrest_config import tag as chaise_tags\nfrom deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args\n\ngroups = {\n 'pdb-admin': 'https://auth.globus.org/0b98092c-3c41-11e9-a8c8-0ee7d80087ee',\n 'pdb-reader': 'https://auth.globus.org/8875a770-3c40-11e9-a8c8-0ee7d80087ee',\n 'pdb-writer': 'https://auth.globus.org/c94a1e5c-3c40-11e9-a5d1-0aacc65bfe9a',\n 'pdb-curator': 'https://auth.globus.org/eef3e02a-3c40-11e9-9276-0edc9bdd56a6',\n 'isrd-staff': 'https://auth.globus.org/176baec4-ed26-11e5-8e88-22000ab4b42b'\n}\n\ntable_name = 'chem_comp_atom'\n\nschema_name = 'PDB'\n\ncolumn_annotations = {\n 'RCT': {\n chaise_tags.display: {\n 'name': 'Creation Time'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'RMT': {\n chaise_tags.display: {\n 'name': 'Last Modified Time'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'RCB': {\n chaise_tags.display: {\n 'name': 'Created By'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'RMB': {\n chaise_tags.display: {\n 'name': 'Modified By'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'structure_id': {},\n 'alt_atom_id': {},\n 'atom_id': {},\n 'charge': {},\n 'comp_id': {},\n 'model_Cartn_x': {},\n 'model_Cartn_x_esd': {},\n 'model_Cartn_y': {},\n 'model_Cartn_y_esd': {},\n 'model_Cartn_z': {},\n 'model_Cartn_z_esd': {},\n 'partial_charge': {},\n 'pdbx_align': {},\n 'pdbx_alt_atom_id': {},\n 'pdbx_alt_comp_id': {},\n 'pdbx_aromatic_flag': {},\n 'pdbx_component_atom_id': {},\n 'pdbx_component_comp_id': {},\n 'pdbx_component_entity_id': {},\n 'pdbx_component_id': {},\n 'pdbx_leaving_atom_flag': {},\n 'pdbx_model_Cartn_x_ideal': {},\n 'pdbx_model_Cartn_y_ideal': {},\n 'pdbx_model_Cartn_z_ideal': {},\n 'pdbx_ordinal': {},\n 'pdbx_polymer_type': {},\n 'pdbx_ref_id': {},\n 'pdbx_residue_numbering': {},\n 'pdbx_stereo_config': {},\n 'pdbx_stnd_atom_id': {},\n 'substruct_code': {},\n 'type_symbol': {},\n 'Owner': {}\n}\n\ncolumn_comment = {\n 'structure_id': 'type:text\\nThe value of _entry.id identifies the data block.\\n\\n Note that this item need not be a number; it can be any unique\\n identifier.',\n 'alt_atom_id': 'type:text\\nAn alternative identifier for the atom. This data item would be\\n used in cases where alternative nomenclatures exist for labelling\\n atoms in a group.',\n 'atom_id': 'type:text\\nThe value of _chem_comp_atom.atom_id must uniquely identify\\n each atom in each monomer in the CHEM_COMP_ATOM list.\\n\\n The atom identifiers need not be unique over all atoms in the\\n data block; they need only be unique for each atom in a\\n component.\\n\\n Note that this item need not be a number; it can be any unique\\n identifier.',\n 'charge': 'type:int4\\nThe net integer charge assigned to this atom. This is the\\n formal charge assignment normally found in chemical diagrams.\\nexamples:1,-1',\n 'comp_id': 'type:text\\nThe value of _chem_comp.id must uniquely identify each item in\\n the CHEM_COMP list.\\n\\n For protein polymer entities, this is the three-letter code for\\n the amino acid.\\n\\n For nucleic acid polymer entities, this is the one-letter code\\n for the base.',\n 'model_Cartn_x': 'type:float4\\nThe x component of the coordinates for this atom in this\\n component specified as orthogonal angstroms. The choice of\\n reference axis frame for the coordinates is arbitrary.\\n\\n The set of coordinates input for the entity here is intended to\\n correspond to the atomic model used to generate restraints for\\n structure refinement, not to atom sites in the ATOM_SITE\\n list.',\n 'model_Cartn_x_esd': 'type:float4\\nThe standard uncertainty (estimated standard deviation)\\n of _chem_comp_atom.model_Cartn_x.',\n 'model_Cartn_y': 'type:float4\\nThe y component of the coordinates for this atom in this\\n component specified as orthogonal angstroms. The choice of\\n reference axis frame for the coordinates is arbitrary.\\n\\n The set of coordinates input for the entity here is intended to\\n correspond to the atomic model used to generate restraints for\\n structure refinement, not to atom sites in the ATOM_SITE\\n list.',\n 'model_Cartn_y_esd': 'type:float4\\nThe standard uncertainty (estimated standard deviation)\\n of _chem_comp_atom.model_Cartn_y.',\n 'model_Cartn_z': 'type:float4\\nThe z component of the coordinates for this atom in this\\n component specified as orthogonal angstroms. The choice of\\n reference axis frame for the coordinates is arbitrary.\\n\\n The set of coordinates input for the entity here is intended to\\n correspond to the atomic model used to generate restraints for\\n structure refinement, not to atom sites in the ATOM_SITE\\n list.',\n 'model_Cartn_z_esd': 'type:float4\\nThe standard uncertainty (estimated standard deviation)\\n of _chem_comp_atom.model_Cartn_z.',\n 'partial_charge': 'type:float4\\nThe partial charge assigned to this atom.',\n 'pdbx_align': 'type:int4\\nAtom name alignment offset in PDB atom field.',\n 'pdbx_alt_atom_id': 'type:text\\nAn alternative identifier for the atom. This data item would be\\n used in cases where alternative nomenclatures exist for labelling\\n atoms in a group.',\n 'pdbx_alt_comp_id': 'type:text\\nAn alternative identifier for the atom. This data item would be\\n used in cases where alternative nomenclatures exist for labelling\\n atoms in a group.',\n 'pdbx_aromatic_flag': 'type:text\\nA flag indicating an aromatic atom.',\n 'pdbx_component_atom_id': 'type:text\\nThe atom identifier in the subcomponent where a\\n larger component has been divided subcomponents.\\nexamples:CB,CA,CG',\n 'pdbx_component_comp_id': 'type:text\\nThe component identifier for the subcomponent where a\\n larger component has been divided subcomponents.\\nexamples:HIS,PRO',\n 'pdbx_component_entity_id': 'type:int4\\nA reference to entity identifier in data category\\n pdbx_chem_comp_subcomponent_entity_list.',\n 'pdbx_component_id': 'type:int4\\nA reference to _pdbx_reference_entity_list.component_id',\n 'pdbx_leaving_atom_flag': 'type:text\\nA flag indicating a leaving atom.',\n 'pdbx_model_Cartn_x_ideal': 'type:float4\\nAn alternative x component of the coordinates for this atom in this\\n component specified as orthogonal angstroms.',\n 'pdbx_model_Cartn_y_ideal': 'type:float4\\nAn alternative y component of the coordinates for this atom in this\\n component specified as orthogonal angstroms.',\n 'pdbx_model_Cartn_z_ideal': 'type:float4\\nAn alternative z component of the coordinates for this atom in this\\n component specified as orthogonal angstroms.',\n 'pdbx_ordinal': 'type:int4\\nOrdinal index for the component atom list.',\n 'pdbx_polymer_type': 'type:text\\nIs the atom in a polymer or non-polymer subcomponent in the BIRD definition.',\n 'pdbx_ref_id': 'type:text\\nA reference to _pdbx_reference_entity_list.ref_entity_id',\n 'pdbx_residue_numbering': 'type:int4\\nPreferred residue numbering in the BIRD definition.',\n 'pdbx_stereo_config': 'type:text\\nThe chiral configuration of the atom that is a chiral center.',\n 'pdbx_stnd_atom_id': 'type:text\\nA standard identifier for the atom. This data item is used when\\n IUPAC/IUBMB nomenclature exists for labeling atoms.',\n 'substruct_code': 'type:text\\nThis data item assigns the atom to a substructure of the\\n component, if appropriate.',\n 'type_symbol': 'type:text\\nThe code used to identify the atom species representing\\n this atom type. Normally this code is the element\\n symbol.\\nexamples:C,N,O',\n 'Owner': 'Group that can update the record.'\n}\n\ncolumn_acls = {}\n\ncolumn_acl_bindings = {}\n\ncolumn_defs = [\n em.Column.define(\n 'structure_id',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['structure_id'],\n ),\n em.Column.define(\n 'alt_atom_id', em.builtin_types['text'], comment=column_comment['alt_atom_id'],\n ),\n em.Column.define(\n 'atom_id', em.builtin_types['text'], nullok=False, comment=column_comment['atom_id'],\n ),\n em.Column.define('charge', em.builtin_types['int4'], comment=column_comment['charge'],\n ),\n em.Column.define(\n 'comp_id', em.builtin_types['text'], nullok=False, comment=column_comment['comp_id'],\n ),\n em.Column.define(\n 'model_Cartn_x', em.builtin_types['float4'], comment=column_comment['model_Cartn_x'],\n ),\n em.Column.define(\n 'model_Cartn_x_esd',\n em.builtin_types['float4'],\n comment=column_comment['model_Cartn_x_esd'],\n ),\n em.Column.define(\n 'model_Cartn_y', em.builtin_types['float4'], comment=column_comment['model_Cartn_y'],\n ),\n em.Column.define(\n 'model_Cartn_y_esd',\n em.builtin_types['float4'],\n comment=column_comment['model_Cartn_y_esd'],\n ),\n em.Column.define(\n 'model_Cartn_z', em.builtin_types['float4'], comment=column_comment['model_Cartn_z'],\n ),\n em.Column.define(\n 'model_Cartn_z_esd',\n em.builtin_types['float4'],\n comment=column_comment['model_Cartn_z_esd'],\n ),\n em.Column.define(\n 'partial_charge', em.builtin_types['float4'], comment=column_comment['partial_charge'],\n ),\n em.Column.define(\n 'pdbx_align', em.builtin_types['int4'], comment=column_comment['pdbx_align'],\n ),\n em.Column.define(\n 'pdbx_alt_atom_id', em.builtin_types['text'], comment=column_comment['pdbx_alt_atom_id'],\n ),\n em.Column.define(\n 'pdbx_alt_comp_id', em.builtin_types['text'], comment=column_comment['pdbx_alt_comp_id'],\n ),\n em.Column.define(\n 'pdbx_aromatic_flag',\n em.builtin_types['text'],\n comment=column_comment['pdbx_aromatic_flag'],\n ),\n em.Column.define(\n 'pdbx_component_atom_id',\n em.builtin_types['text'],\n comment=column_comment['pdbx_component_atom_id'],\n ),\n em.Column.define(\n 'pdbx_component_comp_id',\n em.builtin_types['text'],\n comment=column_comment['pdbx_component_comp_id'],\n ),\n em.Column.define(\n 'pdbx_component_entity_id',\n em.builtin_types['int4'],\n comment=column_comment['pdbx_component_entity_id'],\n ),\n em.Column.define(\n 'pdbx_component_id',\n em.builtin_types['int4'],\n comment=column_comment['pdbx_component_id'],\n ),\n em.Column.define(\n 'pdbx_leaving_atom_flag',\n em.builtin_types['text'],\n comment=column_comment['pdbx_leaving_atom_flag'],\n ),\n em.Column.define(\n 'pdbx_model_Cartn_x_ideal',\n em.builtin_types['float4'],\n comment=column_comment['pdbx_model_Cartn_x_ideal'],\n ),\n em.Column.define(\n 'pdbx_model_Cartn_y_ideal',\n em.builtin_types['float4'],\n comment=column_comment['pdbx_model_Cartn_y_ideal'],\n ),\n em.Column.define(\n 'pdbx_model_Cartn_z_ideal',\n em.builtin_types['float4'],\n comment=column_comment['pdbx_model_Cartn_z_ideal'],\n ),\n em.Column.define(\n 'pdbx_ordinal', em.builtin_types['int4'], comment=column_comment['pdbx_ordinal'],\n ),\n em.Column.define(\n 'pdbx_polymer_type',\n em.builtin_types['text'],\n comment=column_comment['pdbx_polymer_type'],\n ),\n em.Column.define(\n 'pdbx_ref_id', em.builtin_types['text'], comment=column_comment['pdbx_ref_id'],\n ),\n em.Column.define(\n 'pdbx_residue_numbering',\n em.builtin_types['int4'],\n comment=column_comment['pdbx_residue_numbering'],\n ),\n em.Column.define(\n 'pdbx_stereo_config',\n em.builtin_types['text'],\n comment=column_comment['pdbx_stereo_config'],\n ),\n em.Column.define(\n 'pdbx_stnd_atom_id',\n em.builtin_types['text'],\n comment=column_comment['pdbx_stnd_atom_id'],\n ),\n em.Column.define(\n 'substruct_code', em.builtin_types['text'], comment=column_comment['substruct_code'],\n ),\n em.Column.define(\n 'type_symbol',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['type_symbol'],\n ),\n em.Column.define('Owner', em.builtin_types['text'], comment=column_comment['Owner'],\n ),\n]\n\nvisible_columns = {\n '*': [\n 'RID',\n {\n 'source': [{\n 'outbound': ['PDB', 'chem_comp_atom_structure_id_fkey']\n }, 'RID'],\n 'comment': 'type:text\\nThe value of _entry.id identifies the data block.\\n\\n Note that this item need not be a number; it can be any unique\\n identifier.',\n 'markdown_name': 'structure id'\n }, 'alt_atom_id', 'atom_id', 'charge',\n {\n 'source': [{\n 'outbound': ['PDB', 'chem_comp_atom_comp_id_fkey']\n }, 'RID'],\n 'comment': 'type:text\\nThe value of _chem_comp.id must uniquely identify each item in\\n the CHEM_COMP list.\\n\\n For protein polymer entities, this is the three-letter code for\\n the amino acid.\\n\\n For nucleic acid polymer entities, this is the one-letter code\\n for the base.',\n 'markdown_name': 'comp id'\n }, 'model_Cartn_x', 'model_Cartn_x_esd', 'model_Cartn_y', 'model_Cartn_y_esd',\n 'model_Cartn_z', 'model_Cartn_z_esd', 'partial_charge', 'pdbx_align',\n 'pdbx_alt_atom_id', 'pdbx_alt_comp_id',\n ['PDB', 'chem_comp_atom_pdbx_aromatic_flag_term_fkey'], 'pdbx_component_atom_id',\n 'pdbx_component_comp_id', 'pdbx_component_entity_id', 'pdbx_component_id',\n ['PDB', 'chem_comp_atom_pdbx_leaving_atom_flag_term_fkey'], 'pdbx_model_Cartn_x_ideal',\n 'pdbx_model_Cartn_y_ideal', 'pdbx_model_Cartn_z_ideal', 'pdbx_ordinal',\n ['PDB',\n 'chem_comp_atom_pdbx_polymer_type_term_fkey'], 'pdbx_ref_id', 'pdbx_residue_numbering',\n ['PDB', 'chem_comp_atom_pdbx_stereo_config_term_fkey'], 'pdbx_stnd_atom_id',\n ['PDB', 'chem_comp_atom_substruct_code_term_fkey'], 'type_symbol',\n ['PDB', 'chem_comp_atom_RCB_fkey'], ['PDB', 'chem_comp_atom_RMB_fkey'], 'RCT', 'RMT',\n ['PDB', 'chem_comp_atom_Owner_fkey']\n ],\n 'entry': [\n {\n 'source': [{\n 'outbound': ['PDB', 'chem_comp_atom_structure_id_fkey']\n }, 'RID'],\n 'comment': 'type:text\\nThe value of _entry.id identifies the data block.\\n\\n Note that this item need not be a number; it can be any unique\\n identifier.',\n 'markdown_name': 'structure id'\n }, 'alt_atom_id', 'atom_id', 'charge',\n {\n 'source': [{\n 'outbound': ['PDB', 'chem_comp_atom_comp_id_fkey']\n }, 'RID'],\n 'comment': 'type:text\\nThe value of _chem_comp.id must uniquely identify each item in\\n the CHEM_COMP list.\\n\\n For protein polymer entities, this is the three-letter code for\\n the amino acid.\\n\\n For nucleic acid polymer entities, this is the one-letter code\\n for the base.',\n 'markdown_name': 'comp id'\n }, 'model_Cartn_x', 'model_Cartn_x_esd', 'model_Cartn_y', 'model_Cartn_y_esd',\n 'model_Cartn_z', 'model_Cartn_z_esd', 'partial_charge', 'pdbx_align',\n 'pdbx_alt_atom_id', 'pdbx_alt_comp_id',\n ['PDB', 'chem_comp_atom_pdbx_aromatic_flag_term_fkey'], 'pdbx_component_atom_id',\n 'pdbx_component_comp_id', 'pdbx_component_entity_id', 'pdbx_component_id',\n ['PDB', 'chem_comp_atom_pdbx_leaving_atom_flag_term_fkey'], 'pdbx_model_Cartn_x_ideal',\n 'pdbx_model_Cartn_y_ideal', 'pdbx_model_Cartn_z_ideal', 'pdbx_ordinal',\n ['PDB',\n 'chem_comp_atom_pdbx_polymer_type_term_fkey'], 'pdbx_ref_id', 'pdbx_residue_numbering',\n ['PDB', 'chem_comp_atom_pdbx_stereo_config_term_fkey'], 'pdbx_stnd_atom_id',\n ['PDB', 'chem_comp_atom_substruct_code_term_fkey'], 'type_symbol'\n ]\n}\n\ntable_annotations = {chaise_tags.visible_columns: visible_columns, }\n\ntable_comment = None\n\ntable_acls = {}\n\ntable_acl_bindings = {\n 'self_service_group': {\n 'types': ['update', 'delete'],\n 'scope_acl': ['*'],\n 'projection': ['Owner'],\n 'projection_type': 'acl'\n },\n 'self_service_creator': {\n 'types': ['update', 'delete'],\n 'scope_acl': ['*'],\n 'projection': ['RCB'],\n 'projection_type': 'acl'\n }\n}\n\nkey_defs = [\n em.Key.define(['RID'], constraint_names=[('PDB', 'chem_comp_atom_RIDkey1')],\n ),\n em.Key.define(\n ['structure_id', 'atom_id', 'comp_id'],\n constraint_names=[('PDB', 'chem_comp_atom_primary_key')],\n ),\n]\n\nfkey_defs = [\n em.ForeignKey.define(\n ['pdbx_aromatic_flag'],\n 'Vocab',\n 'chem_comp_atom_pdbx_aromatic_flag_term', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_pdbx_aromatic_flag_term_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['pdbx_leaving_atom_flag'],\n 'Vocab',\n 'chem_comp_atom_pdbx_leaving_atom_flag_term', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_pdbx_leaving_atom_flag_term_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['pdbx_polymer_type'],\n 'Vocab',\n 'chem_comp_atom_pdbx_polymer_type_term', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_pdbx_polymer_type_term_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['pdbx_stereo_config'],\n 'Vocab',\n 'chem_comp_atom_pdbx_stereo_config_term', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_pdbx_stereo_config_term_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['substruct_code'],\n 'Vocab',\n 'chem_comp_atom_substruct_code_term', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_substruct_code_term_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['Owner'],\n 'public',\n 'Catalog_Group', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_Owner_fkey')],\n acls={\n 'insert': [groups['pdb-curator']],\n 'update': [groups['pdb-curator']]\n },\n acl_bindings={\n 'set_owner': {\n 'types': ['update', 'insert'],\n 'scope_acl': ['*'],\n 'projection': ['ID'],\n 'projection_type': 'acl'\n }\n },\n ),\n em.ForeignKey.define(\n ['RCB'],\n 'public',\n 'ERMrest_Client', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_RCB_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n ),\n em.ForeignKey.define(\n ['RMB'],\n 'public',\n 'ERMrest_Client', ['ID'],\n constraint_names=[('PDB', 'chem_comp_atom_RMB_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n ),\n em.ForeignKey.define(\n ['structure_id'],\n 'PDB',\n 'entry', ['id'],\n constraint_names=[('PDB', 'chem_comp_atom_structure_id_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['structure_id', 'comp_id'],\n 'PDB',\n 'chem_comp', ['structure_id', 'id'],\n constraint_names=[('PDB', 'chem_comp_atom_comp_id_fkey')],\n annotations={\n chaise_tags.foreign_key: {\n 'domain_filter_pattern': 'structure_id={{structure_id}}'\n }\n },\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n]\n\ntable_def = em.Table.define(\n table_name,\n column_defs=column_defs,\n key_defs=key_defs,\n fkey_defs=fkey_defs,\n annotations=table_annotations,\n acls=table_acls,\n acl_bindings=table_acl_bindings,\n comment=table_comment,\n provide_system=True\n)\n\n\ndef main(catalog, mode, replace=False, really=False):\n updater = CatalogUpdater(catalog)\n updater.update_table(mode, schema_name, table_def, replace=replace, really=really)\n\n\nif __name__ == \"__main__\":\n host = 'pdb.isrd.isi.edu'\n catalog_id = 5\n mode, replace, host, catalog_id = parse_args(host, catalog_id, is_table=True)\n catalog = DerivaCatalog(host, catalog_id=catalog_id, validate=False)\n main(catalog, mode, replace)\n\n","sub_path":"catalog-configs/PDB/chem_comp_atom.py","file_name":"chem_comp_atom.py","file_ext":"py","file_size_in_byte":21308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"118260921","text":"\n# coding: utf-8\n\n\nimport numpy as np\n\nfrom gensim.models import KeyedVectors\nfrom gensim.models import Word2Vec\n\nfrom gensim.utils import simple_preprocess\nfrom gensim.utils import simple_tokenize\n\n\n# command line to convert glove file to word2vec file.\n# python -m gensim.scripts.glove2word2vec --input --output \n\ndef load_wv(fn='../data/word2vec/glove.twitter.27B/word2vec.50d.txt'):\n '''\n load word vector from fn\n\n Returns:\n - wv: dictionary, {key: value} corresponds to {word : vectors}\n '''\n\n wv = KeyedVectors.load_word2vec_format(fn, binary=False)\n return wv\n\ndef load_wv_from_model(fn='../data/word2vec/retrained_word2vec/reddit_word2vec'):\n return load_model_with(fn).wv\n\n\ndef preprocess(sentence):\n '''\n Inputs:\n - sentence: string\n\n Return:\n - sentence: list, separted word in each cell.\n '''\n sentence = simple_preprocess(sentence)\n return sentence\n\ndef load_corpus(fn='../data/data.csv'):\n '''\n load sentences from fn and preprocess them\n\n Return:\n - sentences: list[list[]], each sentence is preprocessed. \n '''\n\n sentences = []\n with open(fn, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n sentence = line.split('\\t')[0].strip()\n# sentence = sentence.split(' ')\n sentences.append(preprocess(sentence))\n return sentences\n\ndef retrain_model(sentences, dim, pretrain_fn='../data/word2vec/glove.twitter.27B/word2vec.50d.txt'):\n '''\n retrain model based on existing word2vector\n '''\n\n model = Word2Vec(size=dim, min_count=5)\n model.build_vocab(sentences)\n total_examples = model.corpus_count\n \n print('load pre-trained vectors...')\n glove_wv = load_wv(pretrain_fn)\n \n print('intersect glove vectors')\n model.build_vocab([list(glove_wv.vocab.keys())], update=True)\n model.intersect_word2vec_format(pretrain_fn, binary=False, lockf=1.0)\n \n print('train model...')\n model.train(sentences, total_examples=total_examples, epochs=model.iter)\n return model\n\ndef build_model(sentences, dim):\n '''\n Inputs:\n - sentences: list[list[]], training data which is tokenized.\n - dim: int, dimensions of vectors.\n\n Returns:\n - model: word2vec which contains model parameters and word2vectors\n '''\n model = Word2Vec(sentences, size=dim, min_count=2)\n model.train(sentences, total_examples=model.corpus_count, epochs=10)\n return model\n\ndef save_model_to(model, fn='../data/word2vec/retrained_word2vec/reddit_word2vec'):\n print('saving word2vec...')\n model.save(fn)\n\n\ndef load_model_with(fn='../data/word2vec/retrained_word2vec/reddit_word2vec'):\n print('loading word2vec...')\n model = Word2Vec.load(fn)\n return model\n\ndef retrain():\n sentences = load_corpus()\n model = retrain_model(sentences, 50)\n save_model_to(model)\n\n model = load_model_with()\n # print(model.wv.vocab.keys())\n\n print(model.similar_by_word('teacher', topn=10)) \n\nif __name__ == '__main__':\n # sentences = load_corpus()\n # print(sentences)\n # model = build_model(sentences, 50)\n # save_model_to(model, '../data/word2vec/retrained_word2vec/test')\n\n # model = load_model_with('../data/word2vec/retrained_word2vec/test')\n # print(model.wv.vocab.keys())\n\n # print(model.similar_by_word('teacher', topn=10))\n\n retrain()\n\n\n","sub_path":"model/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"470823265","text":"from django.contrib.auth.models import User\r\nfrom django.http import JsonResponse\r\nfrom django.shortcuts import redirect\r\nfrom django.urls import reverse\r\nfrom django.utils.deprecation import MiddlewareMixin\r\n\r\nLOGIN_REQUIRED_JSON = [\"/mm_order/addtocart/\",\"/mm_order/subfromcart/\",\"/mm_order/makeorder/\",\"/mm_order/changecartstate/\",\"/mm_order/payed/\"]\r\n\r\nLOGIN_REQUIRED = [\"/mm_order/cart/\",\"/mm_order/orderdetail/\",\"/mm_order/ordernotpay/\"]\r\n\r\n\r\nclass LoginMiddleware(MiddlewareMixin):\r\n\r\n def process_request(self,request):\r\n if request.path in LOGIN_REQUIRED_JSON:\r\n user_id = request.session.get(\"user_id\")\r\n if user_id:\r\n user = User.objects.get(pk=user_id)\r\n request.user = user\r\n else:\r\n data = {\r\n \"status\": 302,\r\n }\r\n request.session[\"error_message\"] = \"您还未登录,请先登录!\"\r\n return JsonResponse(data)\r\n\r\n\r\n if request.path in LOGIN_REQUIRED:\r\n user_id = request.session.get(\"user_id\")\r\n if user_id: # 如果已经登录\r\n user = User.objects.get(pk=user_id)\r\n request.user = user # 给request对象动态添加一个user属性\r\n else: # 未登录\r\n request.session[\"error_message\"] = \"您还未登录,请先登录!\"\r\n return redirect(reverse(\"mm_order:log\"))","sub_path":"myjob/middleware/xtqmiddleware.py","file_name":"xtqmiddleware.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"97255860","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse_lazy\nfrom django.urls import reverse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib import messages\n\nfrom galeria.forms import SingUpForm, CrearGaleria, CrearFoto\nfrom galeria.models import Usuario, Galeria, Foto\n\n# Create your views here.\ndef UsuarioCrear(request):\n template_name=''\n\n if request.method=='POST':\n form = SingUpForm(request.POST)\n if form.is_valid():\n user=form.save()\n request.session['id']=user.id\n return HttpResponseRedirect(reverse(''))\n\n else:\n form=SingUpForm()\n\n return render(request,template_name,{'form':form})\n\ndef GaleriaCrear(request):\n id_usuario=request.session.get('id')\n template_name=''\n\n if request.method=='POST':\n form = CrearGaleria(request.POST)\n if form.is_valid():\n galeria=form.save()\n Galeria.objects.filter(id=galeria.id).update(usuario=Usuario.objects.get(id=id_usuario))\n return HttpResponseRedirect(reverse(''))\n else:\n # borrar usuario\n form=CrearGaleria()\n\n return render(request,template_name,{'form':form})\n\ndef FotoCrear(request, id_galeriar):\n id_usuario=request.session.get('id')\n template_name=''\n\n if request.method=='POST':\n form = CrearFoto(request.POST)\n if form.is_valid():\n foto=form.save()\n Foto.objects.filter(id=foto.id).update(usuario=Usuario.objects.get(id=id_usuario), galeria=Galeria.objects.get(id=id_galeriar))\n return HttpResponseRedirect(reverse(''))\n else:\n # borrar usuario\n form=CrearFoto()\n\n return render(request,template_name,{'form':form})\n","sub_path":"galeria/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"649189689","text":"# Copyright (c) 2011, Enthought, Ltd.\n# Author: Pietro Berkes \n# License: Modified BSD license (2-clause)\n\n\"\"\"Standard reliability and covariation measures.\"\"\"\n\n\n\nimport numpy as np\nimport scipy.stats\nfrom pyanno.measures.helpers import all_invalid\n\nfrom pyanno.util import is_valid, MISSING_VALUE\n\nimport logging\nlogger = logging.getLogger(__name__)\n\ndef pearsons_rho(annotations1, annotations2, nclasses=None):\n \"\"\"Compute Pearson's product-moment correlation coefficient.\n\n See also :func:`~pyanno.measures.helpers.pairwise_matrix`.\n\n **References:**\n\n * `Wikipedia entry\n `_\n\n Arguments\n ---------\n annotations1 : ndarray, shape = (n_items, )\n Array of annotations for a single annotator. Missing values should be\n indicated by :attr:`pyanno.util.MISSING_VALUE`\n\n annotations2 : ndarray, shape = (n_items, )\n Array of annotations for a single annotator. Missing values should be\n indicated by :attr:`pyanno.util.MISSING_VALUE`\n\n nclasses : int\n Number of annotation classes. If None, `nclasses` is inferred from the\n values in the annotations\n\n Returns\n -------\n stat : float\n The value of the statistics\n \"\"\"\n\n valid = is_valid(annotations1) & is_valid(annotations2)\n if all(~valid):\n logger.debug('No valid annotations')\n return np.nan\n\n rho, pval = scipy.stats.pearsonr(annotations1[valid], annotations2[valid])\n return rho\n\n\ndef spearmans_rho(annotations1, annotations2, nclasses=None):\n \"\"\"Compute Spearman's rank correlation coefficient.\n\n See also :func:`~pyanno.measures.helpers.pairwise_matrix`.\n\n **References:**\n\n * `Wikipedia entry\n `_\n\n Arguments\n ---------\n annotations1 : ndarray, shape = (n_items, )\n Array of annotations for a single annotator. Missing values should be\n indicated by :attr:`pyanno.util.MISSING_VALUE`\n\n annotations2 : ndarray, shape = (n_items, )\n Array of annotations for a single annotator. Missing values should be\n indicated by :attr:`pyanno.util.MISSING_VALUE`\n\n nclasses : int\n Number of annotation classes. If None, `nclasses` is inferred from the\n values in the annotations\n\n Returns\n -------\n stat : float\n The value of the statistics\n \"\"\"\n\n valid = is_valid(annotations1) & is_valid(annotations2)\n if all(~valid):\n logger.debug('No valid annotations')\n return np.nan\n\n rho, pval = scipy.stats.spearmanr(annotations1[valid], annotations2[valid])\n return rho\n\n\ndef cronbachs_alpha(annotations, nclasses=None):\n \"\"\"Compute Cronbach's alpha.\n\n **References:**\n\n * Cronbach, L. J. (1951). \"Coefficient alpha and the internal structure\n of tests.\" Psychometrika, 16(3), 297-334.\n\n * `Wikipedia entry\n `_\n\n Arguments\n ---------\n annotations : ndarray, shape = (n_items, n_annotators)\n Array of annotations for multiple annotators. Missing values should be\n indicated by :attr:`pyanno.util.MISSING_VALUE`\n\n nclasses : int\n Number of annotation classes. If None, `nclasses` is inferred from the\n values in the annotations\n\n Returns\n -------\n stat : float\n The value of the statistics\n \"\"\"\n\n if all_invalid(annotations):\n logger.debug('No valid annotations')\n return np.nan\n\n nitems = annotations.shape[0]\n valid_anno = np.ma.masked_equal(annotations, MISSING_VALUE)\n\n item_var = valid_anno.var(1, ddof=1)\n total_var = valid_anno.sum(0).var(ddof=1)\n\n return nitems/(nitems - 1.) * (1. - item_var.sum() / total_var)\n","sub_path":"pyanno/measures/covariation.py","file_name":"covariation.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"104429064","text":"import tensorflow as tf\r\nimport numpy as np \r\n\r\nfrom Embedder import Embedder\r\nfrom Parser import Parser\r\nfrom Config import *\r\n\r\n\r\nclass RNSCN():\r\n def __init__(self, database, embedder, parser, dim_hidden, topdown = False, testMode = False):\r\n self.database = database\r\n\r\n assert isinstance(embedder, Embedder)\r\n self.embedder = embedder\r\n assert isinstance(parser, Parser)\r\n self.parser = parser\r\n\r\n if embedder.dummyMode or parser.dummyMode :\r\n self.dummyMode = True\r\n return\r\n else:\r\n self.dummyMode = False\r\n\r\n n_dependency_types = len(self.parser.parameters['dependenciesList'])\r\n dim_wordVec = self.embedder.lastNLayers * self.embedder.firstNHiddens\r\n\r\n cnt = 0\r\n self.w_wordvec_hidden = tf.Variable(initial_value = tf.random_normal_initializer()(shape = (dim_hidden, dim_wordVec), dtype = weightDType), trainable = True)\r\n cnt += 1\r\n self.b_wordvec_hidden = tf.Variable(initial_value = tf.zeros_initializer()(shape = (dim_hidden, 1), dtype = weightDType), trainable = True)\r\n cnt += 1\r\n self.w_hidden_relation = tf.Variable(initial_value = tf.random_normal_initializer()(shape = (dim_hidden, dim_hidden), dtype = weightDType), trainable = True)\r\n cnt += 1\r\n\r\n self.ws_relation_hidden = []\r\n for _ in range(n_dependency_types):\r\n w = self.w_hidden_relation = tf.Variable(initial_value = tf.random_normal_initializer()(shape = (dim_hidden, dim_hidden), dtype = weightDType), trainable = True)\r\n self.ws_relation_hidden.append(w)\r\n cnt += 1\r\n\r\n self.w_relation_probability = tf.Variable(initial_value = tf.random_normal_initializer()(shape = (n_dependency_types, dim_hidden), dtype = weightDType), trainable = True)\r\n cnt += 1 \r\n self.b_relation_probability = tf.Variable(initial_value = tf.zeros_initializer()(shape = (n_dependency_types, 1), dtype = weightDType), trainable = True)\r\n cnt += 1\r\n\r\n self.n_dependency_types = n_dependency_types\r\n self.dim_wordVec = dim_wordVec\r\n self.dim_hidden = dim_hidden\r\n\r\n self.topdown = topdown\r\n self.testMode = testMode\r\n\r\n self.nWeightTensors = cnt\r\n\r\n def Initialize(self):\r\n pass\r\n\r\n def Finalize(self):\r\n pass\r\n\r\n def SaveWeights(self):\r\n pass\r\n\r\n def LoadWeights(self):\r\n pass\r\n\r\n def RemoveCache(self):\r\n self.database.RemoveCache()\r\n self.parser.RemoveCache()\r\n self.embedder.RemoveCache()\r\n\r\n def OnStartEpoch(self, epoch):\r\n self.database.OnStartEpoch(epoch)\r\n self.parser.OnStartEpoch(epoch)\r\n self.embedder.OnStartEpoch(epoch)\r\n\r\n def OnEndEpoch(self, epoch):\r\n self.embedder.OnEndEpoch(epoch)\r\n self.parser.OnEndEpoch(epoch)\r\n self.database.OnEndEpoch(epoch)\r\n\r\n def __GetWeightsTensorList(self):\r\n list = []\r\n\r\n list.append(self.w_wordvec_hidden)\r\n list.append(self.b_wordvec_hidden)\r\n list.append(self.w_hidden_relation)\r\n \r\n for w in self.ws_relation_hidden:\r\n list.append(w)\r\n \r\n list.append(self.w_relation_probability)\r\n list.append(self.b_relation_probability)\r\n\r\n return list\r\n\r\n def __SetWeightsTensorList(self, list):\r\n cnt = 0\r\n \r\n self.w_wordvec_hidden = list[cnt]; cnt += 1\r\n self.b_wordvec_hidden = list[cnt]; cnt += 1\r\n self.w_hidden_relation = list[cnt]; cnt += 1\r\n \r\n for index in range(len(self.ws_relation_hidden)):\r\n self.ws_relation_hidden[index] = list[cnt]; cnt += 1\r\n \r\n self.w_relation_probability = list[cnt]; cnt += 1\r\n self.b_relation_probability = list[cnt]; cnt += 1\r\n\r\n self.nWeightTensors = cnt\r\n\r\n weights = property(__GetWeightsTensorList, __SetWeightsTensorList)\r\n\r\n def NWeights(self):\r\n sum = 0\r\n for tensor in self.weights:\r\n n = 1; k = 0\r\n for _ in range(len(tensor.shape)):\r\n n = n * tensor.shape[k]\r\n sum += n\r\n\r\n return sum\r\n\r\n def Predict(self, sentence):\r\n prediction = []\r\n return prediction\r\n\r\n def GenerateStatesSingleSetence(self, sentence, cacheTag, lineId):\r\n assert isinstance(cacheTag, CacheTag)\r\n\r\n compatible, parToEmbMapping, normalizedLine, _, parDepMatList, parTokenMapList, parTokenList, _, embTokenList \\\r\n = self.GetNormalizedTokenMapping(sentence, cacheTag, lineId, lineFeed = False)\r\n \r\n success = True\r\n\r\n if compatible == False:\r\n success = False\r\n print(\"Couldn't find token mapping.\")\r\n else:\r\n self.parToEmbTokenMappingSen = parToEmbMapping\r\n self.embLayersExtSen = self.embedder.GetEmbLayersExtended(normalizedLine)\r\n self.parDepMapListSen = parDepMatList\r\n self.parTokenListSen = parTokenList\r\n\r\n rootNode = self.parser.GetRootNode(self.parDepMapListSen)\r\n topNodesList = self.parser.GetDependentNodeList(rootNode, self.parDepMapListSen )\r\n if len(topNodesList) != 1:\r\n raise Exception(\"More than 1 top nodes found.\")\r\n\r\n if self.testMode:\r\n self.PrintParToEmbMapping(parTokenList, embTokenList, parToEmbMapping, topNodesList)\r\n\r\n self.hiddenListSen = [None] * len(parTokenMapList)\r\n self.relationListSen = [None] * len(parTokenMapList)\r\n\r\n if self.topdown :\r\n self.relationListSen[ 0 ] = []\r\n self.ProcessNodeTopDown(topNodesList[0], 0, tf.zeros_initializer()(shape = [self.dim_hidden, 1], dtype = weightDType ) ) # The goal is to populate self.hiddenListSen and self.relationListSen\r\n else: \r\n self.ProcessNodeBottomUp(topNodesList[0]) \r\n\r\n success = True\r\n \r\n return success, self.hiddenListSen, self.relationListSen\r\n \r\n\r\n def ProcessNodeBottomUp(self, focusDepNode):\r\n dependentNodesList = self.parser.GetDependentNodeList(focusDepNode, self.parDepMapListSen )\r\n if self.testMode and len(dependentNodesList) > 0:\r\n text = 'dependency: ' + str(focusDepNode - 1) + ' ---> '\r\n for dep in dependentNodesList: text += (str( dep-1 ) + ', ')\r\n\r\n if focusDepNode <= 0 :\r\n focusWordVec = tf.Variable( tf.zeros( shape = [self.dim_wordVec, 1], dtype = weightDType ) )\r\n else:\r\n focusWordVec = self.embedder.AverageWordVector( self.embLayersExtSen, self.parToEmbTokenMappingSen[ focusDepNode - 1 ] )\r\n assert not np.isnan(focusWordVec).any()\r\n focusWordVec = tf.convert_to_tensor([ focusWordVec ], dtype = weightDType )\r\n tf.debugging.assert_all_finite(focusWordVec, message = 'wordVec is a nan at 2.')\r\n focusWordVec = tf.transpose( focusWordVec )\r\n\r\n focusLinearPart = tf.matmul(self.w_wordvec_hidden, focusWordVec, name = 'matmul-01')\r\n focusHiddenSimple = tf.tanh ( tf.add( focusLinearPart, self.b_wordvec_hidden ) )\r\n\r\n if len(dependentNodesList) == 0: \r\n if focusDepNode > 0: \r\n focusHidden = focusHiddenSimple\r\n else:\r\n raise Exception('Root node with node dependents.')\r\n else:\r\n self.relationListSen[ focusDepNode - 1 ] = [] #\r\n\r\n sumDependentInfluence = tf.Variable( tf.zeros( shape = [self.dim_hidden, 1], dtype = weightDType ) )\r\n\r\n for dependentDepNode in dependentNodesList: \r\n dependendHidden = self.ProcessNodeBottomUp(dependentDepNode) \r\n \r\n dependentRole = tf.matmul( self.w_hidden_relation, dependendHidden, name = 'matmul-02' )\r\n focusRole = tf.matmul(self.w_wordvec_hidden, focusWordVec, name = 'matmul-03') \r\n dependentRelation = tf.tanh( tf.add( dependentRole, focusRole ) ) \r\n tf.debugging.assert_all_finite(dependentRelation, message = 'dependentRelation is a nan.')\r\n self.relationListSen[ focusDepNode - 1 ].append( (dependentDepNode - 1, dependentRelation) ) \r\n \r\n depLabel = self.parser.LookupForDependencyLabel(focusDepNode, dependentDepNode, self.parDepMapListSen, self.parTokenListSen) \r\n depId = self.parser.LookupForDependencyId(depLabel)\r\n\r\n dependentInfluence = tf.matmul( self.ws_relation_hidden[depId], dependentRelation, name = 'matmul-04')\r\n sumDependentInfluence = tf.add( sumDependentInfluence, dependentInfluence )\r\n\r\n focusHidden = tf.tanh ( tf.add( sumDependentInfluence, focusHiddenSimple ) )\r\n\r\n self.hiddenListSen[ focusDepNode - 1 ] = focusHidden \r\n tf.debugging.assert_all_finite(focusHidden, message = 'ficusHidden is a nan.')\r\n\r\n return focusHidden\r\n\r\n\r\n def ProcessNodeTopDown(self, focusDepNode, governorDepNode, governorHidden):\r\n dependentNodesList = self.parser.GetDependentNodeList(focusDepNode, self.parDepMapListSen )\r\n\r\n if self.testMode and len(dependentNodesList) > 0:\r\n text = 'dependency: ' + str(focusDepNode - 1) + ' ---> '\r\n for dep in dependentNodesList: text += (str( dep-1 ) + ', ')\r\n\r\n if focusDepNode <= 0 :\r\n focusWordVec = tf.Variable( tf.zeros( shape = [self.dim_wordVec, 1], dtype = weightDType ) )\r\n assert focusWordVec.shape == [self.dim_wordVec, 1]\r\n else:\r\n focusWordVec = self.embedder.AverageWordVector( self.embLayersExtSen, self.parToEmbTokenMappingSen[ focusDepNode - 1 ] )\r\n assert not np.isnan(focusWordVec).any()\r\n focusWordVec = tf.convert_to_tensor([ focusWordVec ], dtype = weightDType )\r\n assert focusWordVec.shape == [1, self.dim_wordVec]\r\n tf.debugging.assert_all_finite(focusWordVec, message = 'wordVec is a nan at 2.')\r\n focusWordVec = tf.transpose( focusWordVec )\r\n assert focusWordVec.shape == [self.dim_wordVec, 1]\r\n \r\n self.relationListSen[ focusDepNode - 1 ] = []\r\n\r\n focusLinearPart = tf.matmul(self.w_wordvec_hidden, focusWordVec, name = 'matmul-01')\r\n focusHiddenSimple = tf.tanh( tf.add( focusLinearPart, self.b_wordvec_hidden ) )\r\n assert focusHiddenSimple.shape == [self.dim_hidden, 1]\r\n\r\n governorRole = tf.matmul( self.w_hidden_relation, governorHidden, name = 'matmul-02' )\r\n focusRole = tf.matmul(self.w_wordvec_hidden, focusWordVec, name = 'matmul-03') \r\n governorRelation = tf.tanh( tf.add( governorRole, focusRole ) ) \r\n tf.debugging.assert_all_finite(governorRelation, message = 'governorRelation is a nan.')\r\n assert governorRelation.shape == [self.dim_hidden, 1]\r\n self.relationListSen[ focusDepNode - 1 ].append( (governorDepNode - 1, governorRelation) ) \r\n\r\n depLabel = self.parser.LookupForDependencyLabel(governorDepNode, focusDepNode, self.parDepMapListSen, self.parTokenListSen)\r\n depId = self.parser.LookupForDependencyId(depLabel)\r\n\r\n governorInfluence = tf.matmul( self.ws_relation_hidden[depId], governorRelation , name = 'matmul-04')\r\n focusHidden = tf.tanh ( tf.add( governorInfluence, focusHiddenSimple ) )\r\n assert focusHidden.shape == [self.dim_hidden, 1]\r\n\r\n tf.debugging.assert_all_finite(focusHidden, message = 'hidden is a nan.')\r\n self.hiddenListSen[ focusDepNode - 1 ] = focusHidden \r\n print(\"Node finished: \", focusDepNode - 1)\r\n\r\n for dependentDepNode in dependentNodesList:\r\n self.ProcessNodeTopDown(dependentDepNode, focusDepNode, focusHidden) \r\n\r\n\r\n def GetNormalizedTokenMapping(self, line, cacheTag, lineId, lineFeed = True):\r\n nline = self.parser.NormalizeSentence(line, cacheTag, lineId)\r\n parTokenList, parTokenString, parDepMatList, parTokenMapList = self.parser.GetTokenList(nline, True, cacheTag, lineId, lineFeed)\r\n embTokenList, embTokenString = self.embedder.GetTokenList(nline, cacheTag, lineId, lineFeed)\r\n compatible, mapping = self.embedder.GetTokenMapping(parTokenList, embTokenList, cacheTag, lineId)\r\n \r\n return compatible, mapping, nline, parTokenString, parDepMatList, parTokenMapList, parTokenList, embTokenString, embTokenList \r\n\r\n def GetTokenLabelList(self, sentence, aspectList, opinionList, cacheTag, lineId):\r\n normalizedLine = self.parser.NormalizeSentence(sentence, cacheTag, lineId)\r\n parTokenList, _, _, _ = self.parser.GetTokenList(normalizedLine, True, cacheTag, lineId, lineFeed = False)\r\n tokenLabelClassList, tokenLabelStringList = self.database.GetTokenLabelList(parTokenList, aspectList, opinionList)\r\n\r\n return tokenLabelClassList, tokenLabelStringList\r\n\r\n def PrintParToEmbMapping(self, parTokenList, embTokenList, parToEmbMapping, topNodesList):\r\n text = \"parTokens: \" \r\n for id in range(len(parTokenList)):\r\n text += ( '(' + str(id) + ' ' + parTokenList[id].lower() + ') ' )\r\n print(text)\r\n\r\n text = \"embTokens: \"\r\n for id in range(len(embTokenList)):\r\n text += ( '(' + str(id) + ' ' + embTokenList[id] + ') ' )\r\n print(text)\r\n\r\n text = 'parToEmb mapping: '\r\n for parId in range(len(parToEmbMapping)):\r\n text += (str(parId) + '-')\r\n if len(parToEmbMapping[parId]) <= 1: text += str(parToEmbMapping[parId][0]) # the length is one, not zero.\r\n else:\r\n text += '('\r\n for embId in range(len(parToEmbMapping[parId])):\r\n text += (str(parToEmbMapping[parId][embId]) + ' ')\r\n text = text[:-1]; text += ')'\r\n text += ' '\r\n print(text)\r\n\r\n print('top node = ', topNodesList[0])\r\n\r\n def DemonstrateTokenMapping(self, trainNotTest, addLastPeriod = True):\r\n if trainNotTest:\r\n pSentences = self.database.pTrainSentences\r\n pSentencesClean = self.database.pTrainSentencesClean\r\n pSentencesRemoved = self.database.pTrainSentencesRemoved\r\n else:\r\n pSentences = self.database.pTestSentences\r\n pSentencesClean = self.database.pTestSentencesClean\r\n pSentencesRemoved = self.database.pTestSentencesRemoved\r\n \r\n nRemoved = 0\r\n\r\n cleanLines = []; removedLines = []\r\n lines = self.database.GetListOfLines(pSentences, addLastPeriod)\r\n for line in lines:\r\n compatible, mapping, nline, parTokensString, parDepMatList, parTokenMapList, parTokenList, embTokensString, embTokenList = \\\r\n self.GetNormalizedTokenMapping(line, lineFeed = True)\r\n\r\n if not compatible :\r\n nRemoved += 1\r\n removedLines.append(nline)\r\n removedLines.append(parTokensString)\r\n removedLines.append(embTokensString)\r\n else:\r\n cleanLines.append(nline)\r\n\r\n cleanFile = open(pSentencesClean, 'wt+')\r\n cleanFile.writelines(cleanLines)\r\n cleanFile.close()\r\n\r\n cleanFile = open(pSentencesRemoved, 'wt+')\r\n cleanFile.writelines(removedLines)\r\n cleanFile.close()\r\n\r\n return nRemoved\r\n\r\n def GenerateLabelFile(self, trainNotTest = True):\r\n labelList = []\r\n\r\n dataset = self.database.CreateTextLinesDataset(trainNotTest, addLastPeriod = True)\r\n\r\n for dataset_record in dataset:\r\n sentence, aspect, opinion, lineId = self.database.DecodeTextLineDatasetRecord(dataset_record)\r\n\r\n consistent, aspectList, opinionList, wrongAspList, wrongOpnList = self.database.GetRefeinedLabels(sentence, aspect, opinion)\r\n \r\n normalizedLine = self.parser.NormalizeSentence(sentence)\r\n parTokenList, _, _, _ = self.parser.GetTokenList(normalizedLine, True, CacheTag.Real, lineId = -1, lineFeed = False)\r\n tokenLabelStringList, tokenLabelNumeralList = self.database.GetTokenLabelList(parTokenList, aspectList, opinionList)\r\n\r\n labelList.append(tokenLabelNumeralList)\r\n\r\n if trainNotTest: pFile = self.database.pTrainTokenLabelClass\r\n else: pFile = self.database.pTestTokenLabelClass \r\n self.database.SaveJsonData(labelList, pFile)","sub_path":"RNSCN.py","file_name":"RNSCN.py","file_ext":"py","file_size_in_byte":16386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"101990888","text":"from django.shortcuts import render\nimport os\nfrom version import VERSION\n\n\ndef get_files(path='./'):\n for top, dirs, files in os.walk(path):\n for nm in files:\n if not './.' in top and not nm.startswith('.'):\n yield os.path.join(top, nm)\n\n\n# Create your views here.\ndef home(request):\n context = {'title': 'Sample Web App',\n 'subtitle': 'Version {0}'.format(VERSION),\n 'body': list(get_files('./cloudshell-artifactory-demo'))}\n return render(request, 'main/home.html', context)\n","sub_path":"demowebapp/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"573190578","text":"import requests\n\ndef getUrl(fileName):\n\n\tWikipediaApiUrl = 'https://en.wikipedia.org/w/api.php'\n\n\treqParameters = { 'action' : 'query', \t\t\t\\\n\t\t\t\t'titles' : 'Image:' + fileName, \\\n\t\t\t\t'prop' : 'imageinfo', \t\t\\\n\t\t\t\t'iiprop' : 'url',\t\t\\\n\t\t\t\t'format' : 'json'}\n\n\trequest = requests.get(WikipediaApiUrl , \t\t\\\n\t\tparams = reqParameters, \t\t\t\\\n\t\theaders = {'Accept'\t:'application/json'})\n\n\tresult = request.json()\n\n\treturn list(result['query']['pages'].values())[0]['imageinfo'][0]['url']","sub_path":"SRC/APPLICATION-SOURCE-CODE/trivia/triviaApp/wikiImage.py","file_name":"wikiImage.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"472702539","text":"import math\nimport torch\nimport torch.nn as nn\nimport pcpr\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n'''\npoint_clouds: (num_points_1 + num_points_1 + ... + num_points_[batch_size], 3) [float]-GPU\npoint_features (k, num_points_1 + num_points_1 + ... + num_points_[batch_size]) [float]-GPU\ndefault_features (k, 1) [float]-GPU\ncam_intrinsic: (batch,3,3) [float]-GPU\ncam_extrinsic: (batch,4,4) [float]-GPU\nnear_far_max_splatting_size: (batch,3) [float]-CPU\nnum_points: (batch) [int]-CPU\ntar_image_size: (2) [int]-CPU [tar_width,tar_heigh]\n\n\n'''\n# ps_count = None\n# batch_count = 418\n# img_cnt = 0\n\nclass PCPRFunction(torch.autograd.Function):\n\n @staticmethod\n def forward(ctx, point_features, default_features,\n point_clouds,\n cam_intrinsic, cam_extrinsic, \n near_far_max_splatting_size, num_points, tar_image_size):\n \n # global ps_count #\n # if ps_count == None: #\n # ps_count = torch.zeros((num_points.int().item()+10,), dtype=torch.int32)\n\n\n batch_size = cam_intrinsic.size(0)\n dim_features = point_features.size(0)\n\n if cam_extrinsic.size(0) != batch_size or near_far_max_splatting_size.size(0)!=batch_size or\\\n num_points.size(0)!= batch_size:\n raise Exception('[PCPR] batch_sizes are not consistant.')\n\n\n _cam_extrinsic = torch.cat([cam_extrinsic[:,0:3,2], cam_extrinsic[:,0:3,0],\n cam_extrinsic[:,0:3,1],cam_extrinsic[:,0:3,3]],dim = 1)\n\n \n tar_width, tar_heigh = int(tar_image_size[0].item()), int(tar_image_size[1].item())\n\n\n out_depth = torch.zeros(batch_size,1, tar_heigh, tar_width).cuda()\n out_index = torch.zeros(batch_size, tar_heigh, tar_width, dtype=torch.int32).cuda()\n out_feature = torch.zeros(batch_size, dim_features, tar_heigh, tar_width).cuda()\n\n _num_points = num_points.int().tolist()\n\n beg = 0\n\n for i in range(batch_size):\n \n #print('Start Kernel.',flush = True)\n out_depth[i][0], out_index[i] = pcpr.forward(point_clouds[beg:beg+_num_points[i],:],\n cam_intrinsic[i], _cam_extrinsic[i], out_depth[i][0], out_index[i],\n *(near_far_max_splatting_size[i].tolist()) )\n #print('End Kernel.',flush = True)\n \n # td1 = out_depth.squeeze(0)\n # td2 = td1.squeeze(0)\n # td2 = td2.detach().cpu().numpy()\n # fig = plt.figure()\n # ax = fig.gca(projection = '3d')\n # H, W = td2.shape\n # x = np.linspace(0, H, H)\n # y = np.linspace(0, W, W)\n # X, Y = np.meshgrid(x, y)\n # ax.scatter(X, Y, td2.T)\n # plt.show()\n\n features = point_features[:,beg:beg+_num_points[i]].detach()\n \n features = torch.cat([features,default_features.detach()],dim=1)\n \n # t = torch.unique(out_index) #\n # ps_count[t.long()]+=1 #\n\n out_index[i] = out_index[i]-1\n cout_index = out_index[i].clone()\n out_index[i][out_index[i]<0] = _num_points[i]\n tmp_index = out_index[i].long()\n \n out_feature[i] = features[:,tmp_index].detach() \n \n\n beg = beg + _num_points[i]\n\n out_index = out_index.int()\n \n # global batch_count ####\n # batch_count-=1 ####\n # if batch_count%20 == 0: ####\n # statistic = ps_count.cpu().numpy() ####\n # plt.figure() ####\n # plt.hist(statistic, 25)\n # global img_cnt\n # img_cnt+=1\n # plt.savefig('./Analysis/Hist{}.png'.format(img_cnt))\n \n ctx.save_for_backward(out_index, out_feature, point_features, default_features, num_points.int())\n\n return out_feature, out_depth, cout_index\n\n @staticmethod\n def backward(ctx, grad_feature, grad_depth=None, grad_ind = None):\n out_index, out_feature, point_features, default_features, num_points = ctx.saved_tensors\n\n grad_feature = grad_feature.contiguous() \n #out_feature.backward(grad_feature)\n\n d_point_features = torch.ones_like(point_features)\n d_default_features = torch.ones_like(default_features)\n\n total_sum = torch.sum(num_points)\n\n d_point_features, d_default_features = pcpr.backward(grad_feature, out_index, num_points.cuda(),\n d_point_features, d_default_features, total_sum)\n\n #d_point_features = point_features.grad\n #d_default_features = default_features.grad\n\n return d_point_features, d_default_features,None, None, None, None, None, None \n\n\n\nclass PCPRModel(nn.Module):\n def __init__(self, tar_width, tar_heigh):\n super(PCPRModel, self).__init__()\n self.tar_image_size = torch.Tensor([tar_width, tar_heigh]).int()\n\n def forward(self, point_features, default_features,\n point_clouds,\n cam_intrinsic, cam_extrinsic, \n near_far_max_splatting_size, num_points):\n\n \n\n return PCPRFunction.apply(point_features, default_features,\n point_clouds,\n cam_intrinsic, cam_extrinsic, \n near_far_max_splatting_size, num_points, self.tar_image_size)","sub_path":"layers/pcpr_layer.py","file_name":"pcpr_layer.py","file_ext":"py","file_size_in_byte":5440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"276205110","text":"#!/usr/bin/python\n\n###\n# Copyright (2016) Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# You may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###\n\nfrom ansible.module_utils.basic import *\nfrom hpOneView.oneview_client import OneViewClient\n\n\nDOCUMENTATION = '''\n---\nmodule: oneview_enclosure\nshort_description: Manage OneView Enclosure resources.\ndescription:\n - Provides an interface to manage Enclosure resources. Can add, update, or remove.\nrequirements:\n - \"python >= 2.7.9\"\n - \"hpOneView\"\nauthor: \"Mariana Kreisig (@marikrg)\"\noptions:\n config:\n description:\n - Path to a .json configuration file containing the OneView client configuration.\n required: true\n state:\n description:\n - Indicates the desired state for the Enclosure resource.\n 'present' will ensure data properties are compliant to OneView.\n 'absent' will remove the resource from OneView, if it exists.\n choices: ['present', 'absent']\n data:\n description:\n - List with the Enclosure properties.\n required: true\nnotes:\n - A sample configuration file for the config parameter can be found at:\n https://github.hpe.com/Rainforest/oneview-ansible/blob/master/examples/oneview_config.json\n'''\n\nEXAMPLES = '''\n- name: Ensure that an Enclosure is present using the default configuration\n oneview_enclosure:\n config: \"{{ config_file_path }}\"\n state: present\n data:\n enclosureGroupUri : {{ enclosure_group_uri }},\n hostname : {{ enclosure_hostname }},\n username : {{ enclosure_username }},\n password : {{ enclosure_password }},\n name: 'Test-Enclosure'\n licensingIntent : \"OneView\"\n\n- name: Updates the enclosure to have a name of \"Test-Enclosure-Renamed\".\n oneview_enclosure:\n config: \"{{ config_file_path }}\"\n state: present\n data:\n name: 'Test-Enclosure'\n newName : \"Test-Enclosure-Renamed\n\n- name: Ensure that enclosure is absent\n oneview_enclosure:\n config: \"{{ config_file_path }}\"\n state: absent\n data:\n name: 'Test-Enclosure'\n'''\n\n\nENCLOSURE_ADDED = 'Enclosure added sucessfully.'\nENCLOSURE_REMOVED = 'Enclosure removed sucessfully.'\nENCLOSURE_UPDATED = 'Enclosure updated sucessfully.'\nENCLOSURE_ALREADY_EXIST = 'Enclosure already exists.'\nENCLOSURE_ALREADY_ABSENT = 'Nothing to do.'\n\n\nclass EnclosureModule(object):\n\n argument_spec = dict(\n config=dict(required=True, type='str'),\n state=dict(\n required=True,\n choices=['present', 'absent']\n ),\n data=dict(required=True, type='dict')\n )\n\n def __init__(self):\n self.module = AnsibleModule(argument_spec=self.argument_spec, supports_check_mode=False)\n self.oneview_client = OneViewClient.from_json_file(self.module.params['config'])\n\n def run(self):\n state = self.module.params['state']\n data = self.module.params['data']\n\n try:\n if state == 'present':\n self.__present(data)\n elif state == 'absent':\n self.__absent(data)\n\n except Exception as e:\n self.module.fail_json(msg=e.message)\n\n def __present(self, data):\n resource = self.__get_by_name(data)\n\n resource_added = False\n resource_updated = False\n\n data_without_names = data.copy()\n\n name = data_without_names.pop('newName', None)\n rack_name = data_without_names.pop('rackName', None)\n\n if not resource:\n if not name:\n name = data_without_names.pop('name', None)\n resource = self.__add(data_without_names)\n resource_added = True\n\n if self.__name_has_changes(resource, name):\n resource = self.__replace_enclosure_name(resource, name)\n resource_updated = True\n if self.__rack_name_has_changes(resource, rack_name):\n resource = self.__replace_enclosure_rack_name(resource, rack_name)\n resource_updated = True\n\n self.__exit_status_present(resource, added=resource_added, updated=resource_updated)\n\n def __absent(self, data):\n resource = self.__get_by_name(data)\n\n if resource:\n self.oneview_client.enclosures.remove(resource)\n self.module.exit_json(changed=True,\n msg=ENCLOSURE_REMOVED)\n else:\n self.module.exit_json(changed=False, msg=ENCLOSURE_ALREADY_ABSENT)\n\n def __add(self, data):\n new_enclosure = self.oneview_client.enclosures.add(data)\n return new_enclosure\n\n def __name_has_changes(self, resource, name):\n return name and resource.get('name', None) != name\n\n def __rack_name_has_changes(self, resource, rack_name):\n return rack_name and resource.get('rackName', None) != rack_name\n\n def __replace_enclosure_name(self, resource, name):\n updated_resource = self.oneview_client.enclosures.patch(resource['uri'], 'replace', '/name', name)\n return updated_resource\n\n def __replace_enclosure_rack_name(self, resource, rack_name):\n updated_resource = self.oneview_client.enclosures.patch(resource['uri'], 'replace', '/rackName', rack_name)\n return updated_resource\n\n def __exit_status_present(self, resource, added, updated):\n if added:\n message = ENCLOSURE_ADDED\n elif updated:\n message = ENCLOSURE_UPDATED\n else:\n message = ENCLOSURE_ALREADY_EXIST\n\n self.module.exit_json(changed=added or updated,\n msg=message,\n ansible_facts=dict(enclosure=resource))\n\n def __get_by_name(self, data):\n result = self.oneview_client.enclosures.get_by('name', data['name'])\n return result[0] if result else None\n\n\ndef main():\n EnclosureModule().run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/oneview_enclosure.py","file_name":"oneview_enclosure.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"572302001","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\nimport numpy as np;\nimport pandas as pd\n\n# 5个样本点之间的间距\nmat = np.array([[0, 2, 2.5, 5.3, 5], [2, 0, 1.5, 5, 5.3]\n ,[2.5, 1.5, 0, 3.5, 4], [5.3, 5, 3.5, 0, 2.3]\n , [5, 5.3, 4, 2.3, 0]])\n\n# 对每个样本点进行命名\nall_elements = ['a', 'b', 'c', 'd', 'e']\n\n# 将初始数据转换成相异矩阵\ndissimilarity_matrix = pd.DataFrame(mat\n , index=all_elements, columns=all_elements)\n\n# 计算簇中每个点计算其平均距离\ndef avg_dissim_within_group_element(ele, element_list):\n max_diameter = -np.inf\n sum_dissm = 0\n for i in element_list:\n sum_dissm += dissimilarity_matrix[ele][i]\n if (dissimilarity_matrix[ele][i] > max_diameter):\n max_diameter = dissimilarity_matrix[ele][i]\n if (len(element_list) > 1):\n avg = sum_dissm / (len(element_list) - 1)\n else:\n avg = 0\n return avg\n\n# 计算簇间每个点计算其平均距离\ndef avg_dissim_across_group_element(ele, main_list, splinter_list):\n if len(splinter_list) == 0:\n return 0\n sum_dissm = 0\n for j in splinter_list:\n sum_dissm = sum_dissm + dissimilarity_matrix[ele][j]\n avg = sum_dissm / (len(splinter_list))\n return avg\n\n# 分裂器\ndef splinter(main_list, splinter_group):\n most_dissm_object_value = -np.inf\n most_dissm_object_index = None\n for ele in main_list:\n x = avg_dissim_within_group_element(ele, main_list)\n y = avg_dissim_across_group_element(ele, main_list, splinter_group)\n diff = x - y\n if diff > most_dissm_object_value:\n most_dissm_object_value = diff\n most_dissm_object_index = ele\n if (most_dissm_object_value > 0):\n return (most_dissm_object_index, 1)\n else:\n return (-1, -1)\n\n# 将初始簇分裂成一个个簇\ndef split(element_list):\n main_list = element_list\n splinter_group = []\n (most_dissm_object_index, flag) = splinter(main_list, splinter_group)\n while (flag > 0):\n main_list.remove(most_dissm_object_index)\n splinter_group.append(most_dissm_object_index)\n (most_dissm_object_index, flag) = splinter(element_list, splinter_group)\n\n return (main_list, splinter_group)\n\n# 寻找一个直径最大的簇心编号\ndef max_diameter(cluster_list):\n max_diameter_cluster_index = None\n max_diameter_cluster_value = -np.inf\n index = 0\n for element_list in cluster_list:\n for i in element_list:\n for j in element_list:\n if dissimilarity_matrix[i][j] > max_diameter_cluster_value:\n max_diameter_cluster_value = dissimilarity_matrix[i][j]\n max_diameter_cluster_index = index\n\n index += 1\n if (max_diameter_cluster_value <= 0):\n return -1\n return max_diameter_cluster_index\n\nif __name__ == '__main__':\n current_clusters = ([all_elements])\n print('---------相异矩阵---------')\n print(mat)\n print('---------聚类结果---------')\n index, level = 0, 1\n while (index != -1):\n if level == 2:\n break\n print(level, current_clusters)\n (a_clstr, b_clstr) = split(current_clusters[index])\n del current_clusters[index]\n current_clusters.append(a_clstr)\n current_clusters.append(b_clstr)\n index = max_diameter(current_clusters)\n level += 1\n print(level, current_clusters)\n","sub_path":"src/Exp6/6.DIANA.py","file_name":"6.DIANA.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"266401692","text":"#\n# Copyright (C) 2017 Atelier Cartographique \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, version 3 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\n\nfrom . import views\nfrom .geodata import load_loaders\n\nrouter = routers.DefaultRouter(trailing_slash=False)\nrouter.register(r'maps', views.UserMapViewSet, base_name='usermap')\nrouter.register(r'messages', views.MessageViewSet)\nrouter.register(r'categories', views.CategoryViewSet)\nrouter.register(r'layerinfos', views.LayerInfoViewSet)\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'keywords', views.KeywordViewSet)\nrouter.register(r'topics', views.TopicViewSet)\nrouter.register(r'attachments', views.AttachmentViewSet)\nrouter.register(r'alias', views.AliasViewSet)\nrouter.register(r'metadatas', views.MetaDataViewSet)\nrouter.register(r'md/poc', views.PointOfContactViewSet)\nrouter.register(r'md/org', views.ResponsibleOrganisationViewSet)\n\n# for u in router.urls:\n# print(u)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^layers/(?P.+)/(?P.+)/$',\n views.LayerViewList.as_view(),\n name='api.layers_list'),\n url(r'^auth/login', views.login_view, name='api.login'),\n url(r'^auth/logout', views.logout_view, name='api.logout'),\n url(r'^wmsconfig/(?P.+)/(?P.+)$',\n views.get_wms_config,\n name='api.wms_config'),\n url(r'^wmsconfig/$', views.get_wms_layers, name='api.wms_layers'),\n]\n\nurlpatterns.extend(load_loaders())","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"318143632","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'ufian'\n\nimport config\nimport telepot\nimport time\nimport pymongo\nimport datetime\n\nimport utils as u\nimport menu as M\nfrom context import Context\nfrom calculator import CalculatorCalories\n\n\nclass CcalBot(telepot.Bot):\n def __init__(self, token, ccalories):\n super(CcalBot, self).__init__(token)\n self._answerer = telepot.helper.Answerer(self)\n self.ccalories = ccalories\n self.db = ccalories.db\n\n M.init()\n self.user_context = dict()\n\n\n\n def get_context(self, user_id):\n if user_id not in self.user_context:\n self.user_context[user_id] = Context(self, user_id)\n\n return self.user_context[user_id]\n\n def save_message(self, msg, skip_reply=False):\n user_id = u.get_user_id(msg)\n msg_copy = msg.copy()\n msg_copy['date'] = datetime.datetime.utcnow()\n self.db.messages.insert_one(msg_copy)\n if not skip_reply:\n self.sendMessage(user_id, u'Дамп из телегарма сохранен')\n\n @u.debug(config.DEBUG_MSG)\n def on_chat_message(self, msg):\n self.save_message(msg, skip_reply=True)\n\n user_id = u.get_user_id(msg)\n context = self.get_context(user_id)\n context.process(msg)\n\n @u.debug(config.DEBUG_MSG)\n def on_callback_query(self, msg):\n self.save_message(msg, skip_reply=True)\n\n user_id = u.get_user_id(msg)\n context = self.get_context(user_id)\n context.process_callback(msg)\n\n return\n\n def on_inline_query(self, msg):\n query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')\n print('Inline Query:', query_id, from_id, query_string)\n\n def compute_answer():\n # Compose your own answers\n articles = [{'type': 'article',\n 'id': 'abc', 'title': query_string, 'message_text': query_string}]\n\n return articles\n\n self._answerer.answer(msg, compute_answer)\n\n def on_chosen_inline_result(self, msg):\n result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')\n print('Chosen Inline Result:', result_id, from_id, query_string)\n\n\nif __name__ == '__main__':\n conn = pymongo.MongoClient(config.DB['host'], config.DB['port'])\n ccalories = CalculatorCalories(conn)\n bot = CcalBot(config.BOT_TOKEN, ccalories)\n bot.message_loop()\n print ('Listening ...')\n\n # Keep the program running.\n while 1:\n time.sleep(10)","sub_path":"ccal.py","file_name":"ccal.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"317681274","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\nimport os\nimport sys\nimport numpy as np\nimport argparse\nimport json\n\n\ndef sample_pos():\n\treturn np.random.rand(), np.random.rand()\n\n\ndef gen(num_samples, num_customers, capacity):\n\tnp.random.seed(None)\n\tsamples = []\n\tfor _ in range(num_samples):\n\t\tcur_sample = {}\n\t\tcur_sample['customers'] = []\n\t\tcur_sample['capacity'] = capacity\n\t\tdx, dy = sample_pos()\n\t\tcur_sample['depot'] = (dx, dy)\n\t\tfor i in range(num_customers):\n\t\t\tcx, cy = sample_pos()\n\t\t\tdemand = np.random.randint(1, 10)\n\t\t\tcur_sample['customers'].append({'position': (cx, cy), 'demand': demand})\n\t\tsamples.append(cur_sample)\n\n\tdata_size = len(samples)\n\tprint(data_size)\n# \tfout_res = open(args.res_file, 'w')\n\tfout_res = open(os.path.join('data', 'vrp', \"vrp_20_30.json\"), 'w')\n\tjson.dump(samples, fout_res)\n","sub_path":"CVRP/CVRP100/vrpDatagen.py","file_name":"vrpDatagen.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"291667241","text":"\"\"\"\r\nВ массиве случайных целых чисел поменять местами минимальный и максимальный элементы.\r\n\"\"\"\r\n\r\nimport random\r\n\r\n# Генерация массива\r\nMAS_LENGTH = 10\r\nMIN_VALUE = 0\r\nMAX_VALUE = 99\r\nmas = [random.randint(MIN_VALUE, MAX_VALUE) for _ in range(MAS_LENGTH)]\r\n\r\nprint(\"Оригинальный массив : {}\".format(mas))\r\nmin_idx = 0\r\nmax_idx = 0\r\nfor idx, item in enumerate(mas):\r\n if item < mas[min_idx]:\r\n min_idx = idx\r\n if item > mas[max_idx]:\r\n max_idx = idx\r\n\r\nmas[max_idx], mas[min_idx] = mas[min_idx], mas[max_idx]\r\n\r\nprint(\"Максимальный элемент: {}\\nМинимальный элемент : {}\\nИтоговый массив : {}\".format(mas[min_idx],\r\n mas[max_idx],\r\n mas))\r\n","sub_path":"Algorithms/Lesson03/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"528585754","text":"\"\"\"\nThe messages module provides simple Python representations of the structured\nrequest and response for the TMC CentralNode.AssignResources command.\n\"\"\"\n\nfrom .common import DishAllocation\nfrom .csp import CSPConfiguration\nfrom .mccs import MCCSAllocate\nfrom .sdp import SDPConfiguration\n\n__all__ = [\"AssignResourcesRequest\", \"AssignResourcesResponse\"]\n\n\nclass AssignResourcesRequest: # pylint: disable=too-few-public-methods\n \"\"\"\n AssignResourcesRequest is a Python representation of the structured\n argument for a TMC CentralNode.AssignResourcesRequest request.\n \"\"\"\n\n def __init__(\n self,\n subarray_id: int = None,\n dish_allocation: DishAllocation = None,\n sdp_config: SDPConfiguration = None,\n csp_config: CSPConfiguration = None,\n mccs: MCCSAllocate = None,\n interface: str = None,\n transaction_id: str = None,\n ):\n \"\"\"\n Create a new AssignResourcesRequest object.\n\n :param subarray_id: the numeric SubArray ID (1..16)\n :param dish_allocation: object holding the DISH resource allocation\n for this request.\n :param sdp_config: sdp configuration\n :param csp_config: csp configuration\n :param mccs: MCCS subarray allocation\n :param interface: url string to determine JsonSchema version\n :param transaction_id: ID for tracking requests\n\n :raises ValueError: if mccs is allocated with dish and sdp_config\n \"\"\"\n self.subarray_id = subarray_id\n self.dish = dish_allocation\n self.sdp_config = sdp_config\n self.csp_config = csp_config\n self.mccs = mccs\n self.interface = interface\n self.transaction_id = transaction_id\n\n if self.mccs is not None and self.subarray_id is None:\n raise ValueError(\"subarray_id must be defined for LOW request\")\n if self.dish is not None and self.subarray_id is None:\n raise ValueError(\"subarray_id must be defined for MID request\")\n if self.mccs is not None and self.dish is not None:\n raise ValueError(\"Can't allocate dish in the same call as mccs\")\n\n @classmethod\n def from_dish(\n cls,\n subarray_id: int,\n dish_allocation: DishAllocation,\n sdp_config: SDPConfiguration = None,\n interface: str = None,\n transaction_id: str = None,\n ):\n \"\"\"\n Create a new AssignResourcesRequest object.\n\n :param subarray_id: the numeric SubArray ID (1..16)\n :param dish_allocation: object holding the DISH resource allocation\n for this request.\n :param sdp_config: sdp configuration\n :return: AssignResourcesRequest object\n \"\"\"\n obj = cls.__new__(cls)\n obj.__init__(\n subarray_id,\n dish_allocation=dish_allocation,\n sdp_config=sdp_config,\n interface=interface,\n transaction_id=transaction_id,\n )\n return obj\n\n @classmethod\n def from_mccs(\n cls,\n subarray_id: int,\n mccs: MCCSAllocate,\n sdp_config: SDPConfiguration = None,\n csp_config: CSPConfiguration = None,\n interface: str = None,\n transaction_id: str = None,\n ):\n \"\"\"\n Create a new AssignResourcesRequest object.\n\n :param subarray_id: the numeric SubArray ID (1..16)\n :param mccs: MCCS subarray allocation\n :param sdp_config: SDP configuration\n :param csp_config: CSP configuration\n :param interface: url string to determine JsonSchema version\n\n :return: AssignResourcesRequest object\n \"\"\"\n return cls(\n subarray_id=subarray_id,\n mccs=mccs,\n sdp_config=sdp_config,\n csp_config=csp_config,\n interface=interface,\n transaction_id=transaction_id,\n )\n\n def __eq__(self, other):\n if not isinstance(other, AssignResourcesRequest):\n return False\n return (\n self.subarray_id == other.subarray_id\n and self.dish == other.dish\n and self.sdp_config == other.sdp_config\n and self.csp_config == other.csp_config\n and self.mccs == other.mccs\n and self.interface == other.interface\n and self.transaction_id == other.transaction_id\n )\n\n\nclass AssignResourcesResponse: # pylint: disable=too-few-public-methods\n \"\"\"\n AssignResourcesResponse is a Python representation of the structured\n response from a TMC CentralNode.AssignResources request.\n \"\"\"\n\n def __init__(self, dish_allocation: DishAllocation = None):\n \"\"\"\n Create a new AssignResourcesRequest response object.\n\n :param dish_allocation: a DishAllocation corresponding to the\n successfully allocated dishes\n \"\"\"\n self.dish = dish_allocation\n\n def __eq__(self, other):\n if not isinstance(other, AssignResourcesResponse):\n return False\n return self.dish == other.dish\n","sub_path":"src/ska_tmc_cdm/messages/central_node/assign_resources.py","file_name":"assign_resources.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"323404784","text":"#\n# Copyright (c) 2021 Project CHIP Authors\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom asyncio.futures import Future\nimport ctypes\nfrom dataclasses import dataclass\nfrom typing import Type, Union, List, Any\nfrom ctypes import CFUNCTYPE, c_char_p, c_size_t, c_void_p, c_uint32, c_uint16, py_object\n\nfrom .ClusterObjects import ClusterAttributeDescriptor\nimport chip.exceptions\nimport chip.interaction_model\n\n\n@dataclass\nclass AttributePath:\n EndpointId: int\n ClusterId: int\n AttributeId: int\n\n\n@dataclass\nclass AttributeStatus:\n Path: AttributePath\n Status: Union[chip.interaction_model.Status, int]\n\n\nAttributeWriteResult = AttributeStatus\n\n\n@dataclass\nclass AttributeDescriptorWithEndpoint:\n EndpointId: int\n Attribute: ClusterAttributeDescriptor\n\n\n@dataclass\nclass AttributeWriteRequest(AttributeDescriptorWithEndpoint):\n Data: Any\n\n\nAttributeReadRequest = AttributeDescriptorWithEndpoint\n\n\n@dataclass\nclass AttributeReadResult(AttributeStatus):\n Data: Any = None\n\n\nclass AsyncWriteTransaction:\n def __init__(self, future: Future, eventLoop):\n self._event_loop = eventLoop\n self._future = future\n self._res = []\n\n def _handleResponse(self, path: AttributePath, status: int):\n try:\n imStatus = chip.interaction_model.Status(status)\n self._res.append(AttributeWriteResult(Path=path, Status=imStatus))\n except:\n self._res.append(AttributeWriteResult(Path=path, Status=status))\n\n def handleResponse(self, path: AttributePath, status: int):\n self._event_loop.call_soon_threadsafe(\n self._handleResponse, path, status)\n\n def _handleError(self, chipError: int):\n self._future.set_exception(\n chip.exceptions.ChipStackError(chipError))\n\n def handleError(self, chipError: int):\n self._event_loop.call_soon_threadsafe(\n self._handleError, chipError\n )\n\n def _handleDone(self):\n if not self._future.done():\n self._future.set_result(self._res)\n\n def handleDone(self):\n self._event_loop.call_soon_threadsafe(self._handleDone)\n\n\n_OnWriteResponseCallbackFunct = CFUNCTYPE(\n None, py_object, c_uint16, c_uint32, c_uint32, c_uint16)\n_OnWriteErrorCallbackFunct = CFUNCTYPE(\n None, py_object, c_uint32)\n_OnWriteDoneCallbackFunct = CFUNCTYPE(\n None, py_object)\n\n\n@_OnWriteResponseCallbackFunct\ndef _OnWriteResponseCallback(closure, endpoint: int, cluster: int, attribute: int, status):\n closure.handleResponse(AttributePath(endpoint, cluster, attribute), status)\n\n\n@_OnWriteErrorCallbackFunct\ndef _OnWriteErrorCallback(closure, chiperror: int):\n closure.handleError(chiperror)\n\n\n@_OnWriteDoneCallbackFunct\ndef _OnWriteDoneCallback(closure):\n closure.handleDone()\n ctypes.pythonapi.Py_DecRef(ctypes.py_object(closure))\n\n\ndef WriteAttributes(future: Future, eventLoop, device, attributes: List[AttributeWriteRequest]) -> int:\n handle = chip.native.GetLibraryHandle()\n transaction = AsyncWriteTransaction(future, eventLoop)\n\n writeargs = []\n for attr in attributes:\n path = chip.interaction_model.AttributePathIBstruct.parse(\n b'\\x00' * chip.interaction_model.AttributePathIBstruct.sizeof())\n path.EndpointId = attr.EndpointId\n path.ClusterId = attr.Attribute.cluster_id\n path.AttributeId = attr.Attribute.attribute_id\n path = chip.interaction_model.AttributePathIBstruct.build(path)\n tlv = attr.Attribute.ToTLV(None, attr.Data)\n writeargs.append(ctypes.c_char_p(path))\n writeargs.append(ctypes.c_char_p(bytes(tlv)))\n writeargs.append(ctypes.c_int(len(tlv)))\n\n ctypes.pythonapi.Py_IncRef(ctypes.py_object(transaction))\n res = handle.pychip_WriteClient_WriteAttributes(\n ctypes.py_object(transaction), device, ctypes.c_size_t(len(attributes)), *writeargs)\n if res != 0:\n ctypes.pythonapi.Py_DecRef(ctypes.py_object(transaction))\n return res\n\n\ndef Init():\n handle = chip.native.GetLibraryHandle()\n\n # Uses one of the type decorators as an indicator for everything being\n # initialized.\n if not handle.pychip_WriteClient_InitCallbacks.argtypes:\n setter = chip.native.NativeLibraryHandleMethodArguments(handle)\n\n handle.pychip_WriteClient_WriteAttributes.restype = c_uint32\n setter.Set('pychip_WriteClient_InitCallbacks', None, [\n _OnWriteResponseCallbackFunct, _OnWriteErrorCallbackFunct, _OnWriteDoneCallbackFunct])\n\n handle.pychip_WriteClient_InitCallbacks(\n _OnWriteResponseCallback, _OnWriteErrorCallback, _OnWriteDoneCallback)\n","sub_path":"src/controller/python/chip/clusters/Attribute.py","file_name":"Attribute.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"419290691","text":"import pygame, sys\nfrom classes import *\nfrom path import *\nfrom stripper import *\n\npygame.init()\npygame.font.init()\nmyfont = pygame.font.SysFont(\"Arial\", 20)\n\n\nwidth = 400\nheight = 400\ngameDisplay = pygame.display.set_mode((width, height))\nfpsClock = pygame.time.Clock()\n\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nblue = (0, 0, 255)\ndarkblue = (160, 160, 255)\nred = (255, 0, 0)\ndarkred = (255, 160, 160)\ngreen = (0, 255, 0)\n\nticks = 0\n\nseconds = 0\nminutes = 0\nhours = 0\nmillliseconds = 0\n\ncurrentLayer = 0\npreviousLayer = 0\ncurrentLayerNo = 1\n\nfile_to_print = \"tf.gcode\"\nscale = 1\noffset = 0\nframerate = 120\nspeed = 10\ndebug = \"off\"\n\ndonePrinting = False\nclearance = 15 # clearance between arm areas\n\nhome1 = Point(0, 3600, 0, 0, 0, 0, False)\nhome2 = Point(0, 3600, 200, 200, 0, 0, False)\n\nmode = 1\n\n\n# this belong here?\n\n####\n\n\ndef getCurrentLayer():\n\n global currentLayer, currentLayerNo\n\n layerNo = currentLayer\n\n if mode == 1 or mode == 2:\n\n if (len(a1.path) > 1) and (len(a2.path) > 1):\n\n if not ((a1.i == len(a1.path)) or (a2.i == len(a2.path))):\n\n currentLayer = min(a1.path[a1.i].Z_value, a2.path[a2.i].Z_value)\n\n elif a1.i == len(a1.path):\n\n currentLayer = a2.path[a2.i].Z_value\n\n elif a2.i == len(a2.path):\n\n currentLayer = a1.path[a1.i].Z_value\n\n elif (len(a1.path) == 0) and (len(a2.path) > 1):\n\n currentLayer = a2.path[a2.i].Z_value\n\n elif len(a2.path) == 0 and (len(a1.path) > 1):\n\n currentLayer = a1.path[a1.i].Z_value\n\n elif not (a1.i == len(a1.path)):\n\n currentLayer = a1.path[a1.i].Z_value\n\n if currentLayer != layerNo:\n\n currentLayerNo += 1\n\n\ndef drawModel(arm):\n\n global speed\n\n if arm == a1:\n\n materialColor = darkred\n printheadColor = red\n\n elif arm == a2:\n\n materialColor = darkblue\n printheadColor = blue\n\n if arm.i == 0:\n\n arm.i += 1\n\n elif arm.i < len(arm.path):\n\n if arm.path[arm.i].Z_value == currentLayer:\n\n if arm.doneExtruding == True:\n\n arm.hypo = 0\n arm.doneExtruding = False\n arm.i += 1\n\n elif arm.doneExtruding == False:\n\n arm.extrude(speed)\n\n if arm.path[arm.i].E_value != 0:\n\n pygame.draw.aaline(\n gameDisplay, materialColor, arm.previousPoint, arm.printheadPos\n )\n\n else:\n\n arm.doneWithLayer = True\n\n else:\n\n arm.doneWithLayer = True\n\n for j, point in enumerate(arm.path):\n\n if (j < arm.i) and (arm.path[j].E_value != 0):\n\n if arm.path[j].Z_value == currentLayer:\n\n pygame.draw.aaline(\n gameDisplay,\n materialColor,\n [arm.path[j - 1].X_value + 100, 300 - arm.path[j - 1].Y_value],\n [arm.path[j].X_value + 100, 300 - arm.path[j].Y_value],\n )\n\n elif (arm.doneWithLayer == True) and (arm.path[j].Z_value == previousLayer):\n\n pygame.draw.aaline(\n gameDisplay,\n materialColor,\n [arm.path[j - 1].X_value + 100, 300 - arm.path[j - 1].Y_value],\n [arm.path[j].X_value + 100, 300 - arm.path[j].Y_value],\n )\n\n\ndef readconfig(path):\n\n global file_to_print, scale, offset, framerate, debug, mode\n\n with open(path, \"r\") as f: # open file in read mode\n\n contents = f.read()\n\n pattern = re.compile(r\"(.*)\\n\")\n\n for line in contents:\n matches = pattern.finditer(contents)\n\n for i, match in enumerate(matches):\n\n if i == 0:\n file_to_print = match.group(1)\n\n elif i == 1:\n scale = match.group(1)\n\n elif i == 2:\n offset = match.group(1)\n\n elif i == 3:\n framerate = int(match.group(1))\n\n elif i == 4:\n\n mode = int(match.group(1))\n\n elif i == 5:\n\n debug = match.group(1)\n\n\ndef writeOutput(arm):\n\n if arm == a1:\n\n f = open(\"export1.txt\", \"w+\")\n\n elif arm == a2:\n\n f = open(\"export2.txt\", \"w+\")\n\n current_Z = -696969\n\n for point in arm.path:\n\n G = \"G\" + str(point.G_value)\n F = \" F\" + str(point.F_value)\n # X = \" X\" + str(round(point.X_value, 3))\n # Y = \" Y\" + str(round(point.Y_value, 3))\n\n # using ikine\n\n t1, t2 = IKine(point.X_value, point.Y_value)\n\n X = \" T1 \" + str(round(t1, 3))\n Y = \" T2 \" + str(round(t2, 3))\n\n if point.Z_value != current_Z:\n Z = \" Z\" + str(round(point.Z_value, 1))\n current_Z = point.Z_value\n\n else:\n\n Z = \"\"\n\n E = \" E\" + str(round(point.E_value, 5))\n\n output = G + F + X + Y + Z + E + \"\\n\"\n\n f.write(output)\n f.close()\n\n\nlayers = []\n\nreadconfig(\"config.txt\")\n\nextractPointsAndLayers(file_to_print, layers, int(scale), int(offset), mode)\n\nif debug == \"on\":\n for layer in layers:\n\n layer.print_layer()\n\nfor layer in layers:\n\n layer.extract_segments()\n\n\nif debug == \"on\":\n for segment in layer.segments_in_layer:\n\n segment.print_segment()\n\n# PART 5 - Segment sorter\n\nsegment_sorting(layers, clearance, mode)\n\n# PART 6 - Path Generator\n\n\nif debug == \"on\":\n print(\"\\na1 points:\")\n\n for segment in layers[0].a1_segments:\n segment.print_segment()\n\n print(\"\\na2 points:\")\n\n for segment in layers[0].a2_segments:\n segment.print_segment()\n\n print(\"\\nlimbo\")\n\n for segment in layers[0].limbo_segments:\n segment.print_segment()\n\na1 = Arm(home1)\na2 = Arm(home2)\n\n\na1.path, a2.path = path_gen(layers, home1, home2, mode)\n\nwriteOutput(a1)\nwriteOutput(a2)\n\nif debug == \"on\":\n\n print(\"\\na1 path\")\n\n for point in a1.path:\n\n point.print_point()\n\n print(\"\\na2 path\")\n\n for point in a2.path:\n\n point.print_point()\n\n\nif (len(a1.path) > 1) and (len(a2.path) > 1):\n\n currentLayer = min(a1.path[1].Z_value, a2.path[1].Z_value)\n\nelif (len(a1.path) == 0) and (len(a2.path) > 1):\n\n currentLayer = a2.path[a2.i].Z_value\n\nelif (len(a2.path) == 0) and (len(a1.path) > 1):\n\n currentLayer = a1.path[a1.i].Z_value\n\n\n###\n\nwhile True:\n\n gameDisplay.fill(white)\n\n game_window = pygame.draw.rect(\n gameDisplay, black, ((width // 2) - 100, (height // 2) - 100, 200, 200)\n )\n\n # pygame.draw.aaline(gameDisplay, blue, [100, 100], [300, 300])\n\n ## drawSegments(0, \"a1\")\n ## drawSegments(0, \"a2\")\n ## drawSegments(0, \"limbo\")\n\n if donePrinting == False:\n\n getCurrentLayer()\n\n if len(a1.path) > 0:\n\n drawModel(a1)\n else:\n\n a1.doneWithLayer = True\n # a1.i = 1\n\n if len(a2.path) > 0:\n\n drawModel(a2)\n else:\n\n a2.doneWithLayer = True\n # a2.i = 1\n\n pygame.draw.circle(\n gameDisplay, red, [int(a1.printheadPos[0]), int(a1.printheadPos[1])], 3\n )\n pygame.draw.circle(\n gameDisplay, blue, [int(a2.printheadPos[0]), int(a2.printheadPos[1])], 3\n )\n\n if (a1.doneWithLayer == True) and (a2.doneWithLayer == True):\n\n a1.doneWithLayer = False\n a2.doneWithLayer = False\n\n if (a1.i == len(a1.path)) and (a2.i == len(a2.path)):\n\n donePrinting = True\n\n elif a1.i == len(a1.path):\n\n a1.doneWithLayer = True\n\n elif a2.i == len(a2.path):\n\n a2.doneWithLayer = True\n\n if donePrinting == False:\n\n ticks += 1\n\n seconds = ticks // framerate\n milliseconds = (ticks / framerate) * 1000\n\n seconds = seconds % (24 * 3600)\n hours = seconds // 3600\n seconds %= 3600\n minutes = seconds // 60\n seconds %= 60\n\n textsurface = myfont.render(\"h: \" + str(hours), True, black)\n text_rect = textsurface.get_rect(center=(200, 30))\n gameDisplay.blit(textsurface, text_rect)\n\n textsurface = myfont.render(\"m: \" + str(minutes), True, black)\n text_rect = textsurface.get_rect(center=(200, 50))\n gameDisplay.blit(textsurface, text_rect)\n\n textsurface = myfont.render(\"s: \" + str(seconds), True, black)\n text_rect = textsurface.get_rect(center=(200, 70))\n gameDisplay.blit(textsurface, text_rect)\n\n textsurface = myfont.render(\"Layer: \" + str(currentLayerNo), True, black)\n text_rect = textsurface.get_rect(center=(100, 50))\n gameDisplay.blit(textsurface, text_rect)\n\n # textsurface = myfont.render(\"Layer: \" + str(currentLayer), True, black)\n # text_rect = textsurface.get_rect(center=(100, 50))\n # gameDisplay.blit(textsurface, text_rect)\n\n textsurface = myfont.render(\"ms: \" + str(round(milliseconds)), True, black)\n text_rect = textsurface.get_rect(center=(300, 50))\n gameDisplay.blit(textsurface, text_rect)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n pygame.display.update()\n fpsClock.tick(framerate)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"454358666","text":"# coding: utf8\nfrom zeit.cms.i18n import MessageFactory as _\nimport datetime\nimport pytz\nimport re\nimport zope.app.container.interfaces\nimport zope.i18nmessageid\nimport zope.interface\nimport zope.interface.common.sequence\nimport zope.schema\nimport zope.security\n\n\nDOCUMENT_SCHEMA_NS = u\"http://namespaces.zeit.de/CMS/document\"\nQPS_SCHEMA_NS = u\"http://namespaces.zeit.de/QPS/attributes\"\nID_NAMESPACE = u'http://xml.zeit.de/'\nTEASER_NAMESPACE = u'http://xml.zeit.de/CMS/Teaser'\nPRINT_NAMESPACE = u\"http://namespaces.zeit.de/CMS/print\"\n\n# lovely.remotetask stores times as 32 bit leading to an overflow after 2030.\nMAX_PUBLISH_DATE = datetime.datetime(2030, 1, 1, tzinfo=pytz.UTC)\n\n# Backward compatibility imports\nfrom zeit.connector.interfaces import ( # noqa\n DeleteProperty, LockingError, IConnector, IResource,\n IWebDAVReadProperties, IWebDAVWriteProperties, IWebDAVProperties)\n\n\nclass ICMSContentType(zope.interface.interfaces.IInterface):\n \"\"\"Interface for content types.\"\"\"\n\n\nclass InvalidName(zope.schema.ValidationError):\n __doc__ = _('Name contains invalid characters')\n\n\nclass ValidationError(zope.schema.ValidationError):\n\n def doc(self):\n return self.args[0]\n\n\nvalid_name_regex = re.compile(r'^[A-Za-z0-9\\.\\,\\-_*()~]+$').match\n\n\ndef valid_name(value):\n if not valid_name_regex(value):\n raise InvalidName(value)\n return True\n\n\nclass ICMSContent(zope.interface.Interface):\n \"\"\"Interface for all CMS content being loaded from the repository.\n\n \"\"\"\n\n uniqueId = zope.interface.Attribute(\"Unique Id\")\n\n __name__ = zope.schema.TextLine(\n title=_(\"File name\"),\n readonly=True,\n constraint=valid_name)\n\n\nclass ICMSWCContent(zope.interface.Interface):\n \"\"\"Adapting to this yields ICMSContent from the workingcopy if present,\n else from the repository.\"\"\"\n\n\nclass IEditorialContent(ICMSContent):\n \"\"\"Editorial content.\n\n Editorial content is content which actually *is* content. That is in\n contrast to for example folders which are used for structuring.\n\n \"\"\"\n\n\nclass IAsset(ICMSContent):\n \"\"\"Assets are special, usually simple, content objects.\n\n Assets are useles themselves but are integrated into other objects.\n An example is the image.\n\n \"\"\"\n\n\nclass IEditPermission(zope.security.interfaces.IPermission):\n \"\"\"A permission which is always forbidden in the repository.\"\"\"\n\n\nclass ITypeDeclaration(zope.interface.Interface):\n\n type_identifier = zope.schema.TextLine(\n title=u'Unique identifier for this type')\n\n # XXX add other attributes\n\n\nclass IResult(zope.interface.common.sequence.IReadSequence):\n \"\"\"A list of dicts, with info about the total number of entries.\"\"\"\n\n hits = zope.interface.Attribute(\n 'Number of total available entries (for pagination)')\n\n\nclass Result(list):\n \"\"\"A list with additional property ``hits``.\"\"\"\n\n zope.interface.implements(IResult)\n\n hits = 0\n\n\ndef normalize_filename(filename):\n # NOTE: The master version of the algorithm is implemented in JS in\n # zeit.cms.browser.js:filename.js, keep in sync!\n f = filename\n f = f.strip().lower()\n f = f.replace(u'ä', 'ae')\n f = f.replace(u'ö', 'oe')\n f = f.replace(u'ü', 'ue')\n f = f.replace(u'ß', 'ss')\n\n # Remove special characters at beginning and end\n # XXX It's unclear why this doesn't work as a single regexp.\n f = re.sub('^([^a-z0-9]+)(.*?)$', r'\\2', f)\n f = re.sub('^(.*?)([^a-z0-9]+)$', r'\\1', f)\n\n # Replace special characters, but keep dots for special treatment\n f = re.sub('[^a-z0-9.]', '-', f)\n # Save dot of filename extensions\n f = re.sub(\n r'^(.*)\\.(jpg|jpeg|png|pdf|mp3|swf|rtf|gif|svg|bmp)$', r'\\1_\\2', f)\n # Remove all dots\n f = f.replace('.', '-')\n # Restore saved dot\n f = f.replace('_', '.')\n\n # Collapse multiple consecutive dashes\n f = re.sub('-+', '-', f)\n\n # Edge case: Remove special char before the filename extension\n f = f.replace('-.', '.')\n\n return f\n","sub_path":"src/zeit/cms/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"316113525","text":"from app.api import api\nfrom app.models import Post\nfrom flask import jsonify\n\n@api.route('articles',methods=['GET'])\ndef get_all_articles():\n results = Post.query.all()\n data = []\n for result in results:\n a = {\n 'id':result.id,\n 'title':result.title,\n 'tag':result.tag,\n 'body':result.body\n }\n data.append(a)\n return jsonify(data)","sub_path":"app/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"168558360","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'内存读写的练习'\n\n__author__ = 'Jacklee'\n\n\n# StringIO和BytesIO\n# 是file-like 对象\n# 可以像操作文件一样操作内存中的字符串和字节列表\n\n# StringIO\n# 操作的是str类型\nfrom io import StringIO\n\n# 创建一个空的对象\nf = StringIO()\n# 写入内容\nf.write('Hello')\nf.write(' ')\nf.write('world!')\n# 获得所有内容\n# 不用考虑指针的位置\nprint(f.getvalue())\n# 移动指针位置\nf.seek(0, 0)\n# 读取所有内容\nprint(f.read())\n\n# 创建一个有初始字符串的对象\nf = StringIO('Hello world!')\n# 写入内容\nf.write('Hi Jack!')\n# 当前的内容是什么呢?\n# Hi Jack!rld!\n# 创建该对象后, 读写操作的指针在开始的位置: 0\n# 如果这时候写入, 会覆盖已有的内容, 最神奇的是, 之前的内容并没有全部被覆盖(清空)\nprint(f.getvalue())\n\n# 如果有初始字符串, 需要在后面添加, 就需要一开始就移动指针位置\nf = StringIO('Hello world!')\n# 移动到结尾处\nf.seek(0, 2)\nf.write('Hi Jack!')\nprint(f.getvalue())\n\n# ByteIO\n# 操作的是二进制数据\nfrom io import BytesIO\n\n# 创建一个空对象\nf = BytesIO()\n# 写入内容\n# 如果只写入'中文',则会报错\nf.write('中文'.encode('utf-8'))\n# 读取内容\nprint(f.getvalue())\n# 初始化对象\n# b开头表示是字节, \\x表示是十六进制\nf = BytesIO(b'\\xe4\\xb8\\xad\\xe6\\x96\\x87')\n# 显示为字节对象\nprint(f.read())\n# 移动到头部\nf.seek(0, 0)\n# 显示为字符串\nprint(f.read().decode('utf-8'))\n\n\n\n","sub_path":"C09_MemoryIO.py","file_name":"C09_MemoryIO.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"192785464","text":"class Node:\n children = []\n def __init__(self,name):\n self.name = name\n self.children = []\n\nroot = 'dgoocsw'\nweights = {}\nchildren = {}\n\nwith open('in.txt') as fp:\n for line in fp:\n tokens = line.split()\n weights[tokens[0]] = int(tokens[1][1:-1])\n\n\ns = []\nwith open('in.txt') as fp:\n for line in fp:\n tokens = line.split()\n node = Node(tokens[0])\n if len(tokens) > 2:\n i = 3\n while (i < len(tokens)-1):\n node.children.append(tokens[i][0:-1])\n i = i + 1\n node.children.append(tokens[i])\n s.append(node)\n\n\nprint(len(s))\nprint(s[0].name,s[0].children)\n\nwith open('in.txt') as fp:\n for line in fp:\n tokens = line.split()\n temp = []\n if len(tokens) > 2:\n i = 3\n while (i < len(tokens)-1):\n temp.append(tokens[i][0:-1])\n i = i + 1\n temp.append(tokens[i])\n children[tokens[0]] = temp\n\n# post order traversal\n\ndef postorder(node):\n if len(children[node]) == 0:\n return weights[node]\n else:\n total = 0\n values = []\n names = []\n for child in children[node]:\n current = postorder(child)\n values.append(postorder(child))\n total = total + int(current)\n names.append(child)\n value = values[0]\n i = 1\n while (i < len(values)):\n if (values[i] != value):\n print(\"checking node\",node)\n print(\"something wrong with \",names[i], \"with weight\",values[i],i,total,\"should be \",value)\n i = i + 1\n return total + weights[node]\n\n\nprint(postorder('marnqj'))\nprint(postorder('upair'))\nprint(postorder('mkrrlbv'))\nprint(postorder('vqkwlq'))\n","sub_path":"AoC/day7/7_1.py","file_name":"7_1.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"96732705","text":"import random\nimport base64\nimport ast\nimport json\nimport time\n\nfrom google.cloud import pubsub_v1\n\nfrom google.cloud import firestore\n\n\n\n\n\ndef hello_world(request):\n \"\"\"Responds to any HTTP request.\n Args:\n request (flask.Request): HTTP request object.\n Returns:\n The response text or any set of values that can be turned into a\n Response object using\n `make_response `.\n \n \"\"\"\n global job_id\n \n global users_list\n users_list = []\n \n \n job_data = process_request(request)\n \n publish(job_data)\n \n \n timed_out = listen_for_db()\n print(timed_out)\n \n print(users_list)\n \n \n test_str = ' '.join(users_list)\n \n return test_str\n \n \n \n \n \n\n \ndef process_request(request):\n \"\"\" Responds to a GET request with \"Hello world!\". Forbids a PUT request.\n Args:\n request (flask.Request): The request object.\n \n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n .\n \"\"\"\n from flask import abort\n\n content_type = request.headers['content-type']\n request_json = request.get_json(silent=True)\n request_args = request.args\n\n if content_type == 'application/json': \n request_json = request.get_json(silent=True)\n # REFORMAT AS A FOR LOOP LATER\n \n \n \n # search_users check/set/error\n if request_json and 'search_users' in request_json:\n search_users = request_json['search_users']\n else:\n raise ValueError(\"JSON is invalid, or missing a 'search_users'\")\n \n \n \n # TWITTER_ACCESS_TOKEN check/set/error\n if request_json and 'TWITTER_ACCESS_TOKEN' in request_json:\n TWITTER_ACCESS_TOKEN = request_json['TWITTER_ACCESS_TOKEN']\n else:\n raise ValueError(\"Missing a 'TWITTER_ACCESS_TOKEN'\")\n \n \n \n \n # TWITTER_ACCESS_TOKEN_SECRET check/set/error\n if request_json and 'TWITTER_ACCESS_TOKEN_SECRET' in request_json:\n TWITTER_ACCESS_TOKEN_SECRET = request_json['TWITTER_ACCESS_TOKEN_SECRET']\n else:\n raise ValueError(\"Missing a 'TWITTER_ACCESS_TOKEN_SECRET'\")\n \n \n \n # Call the function for the POST request. \n if request.method == 'POST':\n \n \n job_data = []\n global job_id\n job_id = random.randint(100000,999999)\n job_data.extend(search_users)\n job_data.append(TWITTER_ACCESS_TOKEN)\n job_data.append(TWITTER_ACCESS_TOKEN_SECRET)\n job_data.append(job_id)\n \n \n \n return job_data\n else:\n return abort(405)\n \n \n \n \n \n \n \n \ndef publish(job_details):\n \"\"\"Publishes a message to a Pub/Sub topic.\"\"\"\n client = pubsub_v1.PublisherClient()\n \n \n # `projects/{project_id}/topics/{topic_name}`\n topic_path = client.topic_path('bert-optimization-testing', 'tweet_gather')\n \n #encode to send message to workers\n data = json.dumps(job_details, ensure_ascii=False).encode('utf8')\n \n \n \n # When you publish a message, the client returns a future.\n api_future = client.publish(topic_path, data=data)\n api_future.add_done_callback(get_callback(api_future, data))\n\n # Keep the main thread from exiting until background message\n # is processed.\n while api_future.running():\n time.sleep(0.1)\n \n \n \ndef get_callback(api_future, data):\n \"\"\"Wrap message data in the context of the callback function.\"\"\"\n\n def callback(api_future):\n try:\n print(\"Published message {} now has message ID {}\".format(\n data, api_future.result()))\n except Exception:\n print(\"A problem occurred when publishing {}: {}\\n\".format(\n data, api_future.exception()))\n raise\n return callback\n\n\n\ndef listen_for_db():\n \n global num_recieved\n num_recieved = 0\n \n \n start = time.time()\n \n timed_out = False\n \n subscriber = pubsub_v1.SubscriberClient()\n subscription_path = subscriber.subscription_path('bert-optimization-testing', 'listen_for_job')\n \n \n \n subscriber.subscribe(subscription_path, callback=process_data)\n print('Listening for messages on {}'.format(subscription_path))\n \n while num_recieved < 1:\n time.sleep(1)\n now = time.time()\n print(\"has been running for: \", now)\n if now - start > 30:\n timed_out = True\n print(\"timed out!\")\n return\n \n return timed_out\n \n \n \n \n \n \ndef process_data(message):\n message.ack()\n global job_id\n message_num = job_id\n message_data = message.data.decode('utf-8')\n message_data = ast.literal_eval(message_data)\n message_id = int(message_data[0])\n print(message_id)\n if message_id == message_num:\n \n #print('Received message: {}'.format(message))\n users_in_job = message_data[1]\n users_list.extend(users_in_job)\n \n \n \n print('finished processing')\n \n \n \n global num_recieved\n num_recieved = num_recieved + 1\n else:\n print(\"recieved message id: \", message_id)\n print(\"expected message id: \", message_num)\n \n\n \n \n","sub_path":"event-based-funcs/recommend/recommend_list.py","file_name":"recommend_list.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"19240748","text":"import gzip\r\nimport cPickle as pickle\r\n\r\n\r\n\r\nfrom loader import *\r\nfrom models import *\r\n\r\n\r\n\r\nsrc = 'svhn'\r\ntgt = 'mnist'\r\n\r\n# RESFILE = 'results/'+src+'-'+tgt+'_drcn_results_drop0.5_aug0_denoise0.3.pkl.gz'\r\n# PARAMFILE = 'results/'+src+'-'+tgt+'_drcn_weights_drop0.5_aug0_denoise0.3.pkl.gz'\r\n\r\nRESFILE = 'results/'+src+'-'+tgt+'_convae_results_denoising0.pkl.gz'\r\nPARAMFILE = 'results/'+src+'-'+tgt+'_convae_weights_denoising0.pkl.gz'\r\n\r\n\r\nprint('Load data...')\r\ninds = pickle.load(gzip.open('data_indices100.pkl.gz','rb'))\r\n\r\nif src == 'svhn':\r\n\t(X_train, Y_train), (X_test, Y_test) = load_svhn()\r\n\t(_, _), (_, _), (X_tgt_test, Y_tgt_test) = load_mnist32x32()\r\n\tidx_src = inds['svhn_train']\r\n\tidx_tgt = inds['mnist_test']\r\nelif src == 'mnist':\r\n\t(X_train, Y_train), (_, _), (X_test, Y_test) = load_mnist32x32()\r\n\t(_, _), (X_tgt_test, Y_tgt_test) = load_svhn()\r\n\tidx_src = inds['mnist_train']\r\n\tidx_tgt = inds['svhn_test']\r\n\r\n[n, c, d1, d2] = X_train.shape\r\n\r\nprint('Load config and params...')\r\nres = pickle.load(gzip.open(RESFILE,'rb'))\r\n\r\nmodel = DRCN((c, d1, d2), 10, res['net_config'], res['ae_config'])\r\nmodel.load_weights(PARAMFILE)\r\n\r\n\r\n\r\nshow_filter(X_train[idx_src], grayscale=True, filename='viz/'+src+'_'+tgt+'_convae_X100-src-orig.png')\r\nshow_filter(model.convae_.predict(X_train[idx_src]), grayscale=True, filename='viz/'+src+'_'+tgt+'_convae_X100-src-pred.png')\r\nshow_filter(X_tgt_test[idx_tgt], grayscale=True, filename='viz/'+src+'_'+tgt+'_convae_X100-tgt-orig.png')\r\nshow_filter(model.convae_.predict(X_tgt_test[idx_tgt]), grayscale=True, filename='viz/'+src+'_'+tgt+'_convae_X100-tgt-pred.png')","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"444364332","text":"import os\n\nfrom datetime import timedelta\nfrom typing import List\n\nfrom celery import Celery\nfrom celery.schedules import crontab\nfrom sqlalchemy.orm import with_polymorphic\n\nfrom pycroft.helpers.task import DBTask\nfrom pycroft.lib.finance import get_negative_members\nfrom pycroft.lib.logging import log_task_event\nfrom pycroft.lib.mail import send_mails, Mail, RetryableException, TaskFailedTemplate, \\\n MemberNegativeBalance\nfrom pycroft.lib.task import task_type_to_impl\nfrom pycroft.model import session\nfrom pycroft.model.finance import BankAccountActivity\nfrom pycroft.model.session import with_transaction\nfrom pycroft.model.swdd import swdd_vo, swdd_import, swdd_vv\nfrom pycroft.model.task import Task, TaskStatus\nfrom pycroft.model.traffic import TrafficVolume\n\napp = Celery('tasks', backend=os.environ['PYCROFT_CELERY_RESULT_BACKEND_URI'],\n broker=os.environ['PYCROFT_CELERY_BROKER_URI'])\n\n\n@with_transaction\ndef write_task_message(task, message, log=False):\n message = str(message)\n\n if log:\n log_task_event(message, task.creator, task)\n\n print(message)\n\n\ndef repair_session():\n if not session.session.is_active:\n session.session.rollback()\n print(\"Repaired session (rollback).\")\n\n\n@app.task(base=DBTask)\ndef execute_scheduled_tasks():\n tasks = (session.session.query(with_polymorphic(Task, \"*\"))\n .filter(Task.status == TaskStatus.OPEN,\n Task.due <= session.utcnow())\n .all())\n\n print(\"executing {} scheduled tasks\".format(len(tasks)))\n\n for task in tasks:\n repair_session()\n\n task_impl = task_type_to_impl.get(task.type)()\n\n try:\n task_impl.execute(task)\n except Exception as e:\n task_impl.errors.append(str(e))\n\n repair_session()\n\n if task_impl.new_status is not None:\n task.status = task_impl.new_status\n\n if task_impl.errors:\n task.errors = task_impl.errors\n\n for error in task.errors:\n print(\"Error while executing task: {}\".format(error))\n\n write_task_message(task, \"Processed {} task. Status: {}\".format(\n task.type.name, task.status.name), log=True)\n\n session.session.commit()\n\n if task.status == TaskStatus.FAILED:\n from pycroft.lib.user import user_send_mail\n\n user_send_mail(task.creator, TaskFailedTemplate(), True)\n\n\n@app.task(base=DBTask)\ndef remove_old_traffic_data():\n TrafficVolume.q.filter(\n TrafficVolume.timestamp < (session.utcnow() - timedelta(7))).delete()\n\n session.session.commit()\n\n print(\"Deleted old traffic data\")\n\n\n@app.task(base=DBTask)\ndef refresh_swdd_views():\n swdd_vo.refresh()\n swdd_vv.refresh()\n swdd_import.refresh()\n\n session.session.commit()\n\n print(\"Refreshed swdd views\")\n\n\n@app.task(base=DBTask)\ndef mail_negative_members():\n from pycroft.lib.user import user_send_mails\n\n activity = BankAccountActivity.q.order_by(BankAccountActivity.imported_at.desc()).first()\n if activity.imported_at.date() >= session.utcnow().date() - timedelta(days=2):\n negative_users = get_negative_members()\n user_send_mails(negative_users, MemberNegativeBalance())\n else:\n mail = Mail(\"Finanzen\",\n \"finanzen@lists.agdsn.de\",\n \"Automatische Zahlungsrückstands-Mail fehlgeschlagen\",\n body_plain=\"Der Import ist nicht aktuell genug.\")\n send_mails_async.delay([mail])\n\n\n@app.task(ignore_result=True, rate_limit=1, bind=True)\ndef send_mails_async(self, mails: List[Mail]):\n success = False\n failures = len(mails)\n\n try:\n success, failures = send_mails(mails)\n except RetryableException:\n self.retry(countdown=1800, max_retries=96)\n print(\"Retrying mail task in 30min\")\n except RuntimeError:\n pass\n\n if not success:\n print(\"Could not send all mails! ({}/{} failed)\".format(failures, len(mails)))\n\n\napp.conf.update(\n CELERYBEAT_SCHEDULE={\n 'execute-scheduled-tasks': {\n 'task': 'pycroft.task.execute_scheduled_tasks',\n 'schedule': timedelta(hours=1)\n },\n 'remove-old-traffic-data': {\n 'task': 'pycroft.task.remove_old_traffic_data',\n 'schedule': timedelta(days=1)\n },\n 'refresh-swdd-views':{\n 'task': 'pycroft.task.refresh_swdd_views',\n 'schedule': timedelta(hours=3)\n },\n 'mail-negative-members': {\n 'task': 'pycroft.task.mail_negative_members',\n 'schedule': crontab(0, 0, day_of_month=5)\n }\n },\n CELERY_ENABLE_UTC=True,\n CELERY_TIMEZONE='Europe/Berlin')\n","sub_path":"pycroft/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"435227534","text":"from django.shortcuts import render\n\n# Create your views here.\n# Views.py controls what is being seen in the browser\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.core.mail import send_mail, get_connection\nfrom django.contrib import messages\nimport requests\nimport urllib\nimport json\n\nfrom . forms import urlForm, ContactForm\n\ndef documentation(request):\n return render(request, \"dbdex/documentation.html\")\n\ndef feedback(request):\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n fullname = cd['fullname']\n email_from = cd['email']\n reciepient_email = ['akubosylvernus@gmail.com']\n comment = cd['comment']\n con = get_connection('django.core.mail.backends.console.EmailBackend')\n \n send_mail(\n fullname,\n comment,\n email_from,\n reciepient_email,\n connection=con,\n )\n messages.success(request, 'Successfully sent!') \n else:\n messages.warning(request, 'Not sent!')\n else:\n form = ContactForm() \n return render(request, 'dbdex/feedback.html', {'form': form})\n\n\ndef home_page(request):\n context = {\n \"feedback\":\"Feedback\",\n }\n \n return render(request, \"dbdex/index.html\", context)\n\n# The sql function below contain all about the sql injection page\ndef sql(request):\n form = urlForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n cd = form.cleaned_data\n search_id = cd['url']\n #This line tests the url for sql injection vulnurability\n response = f'{search_id}%27'\n printout = ' is vulnerable to SQL injection'\n\n url = search_id\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n \n if 'You have an error in your SQL syntax;' in response:\n \n if 'MsSQL' in response:\n form = urlForm(request.POST or None)\n resp= 'Found database type: MSSQL'\n context ={\n \"form\": form,\n \"resp\": resp,\n \"MsSQL\": True,\n \"result\": printout,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n }\n return render (request, \"dbdex/sql.html\", context)\n\n elif 'MySQL' in response:\n resp ='Found database type: MYSQL'\n context ={\n \"form\": form,\n \"resp\": resp,\n \"MySQL\": True,\n \"result\": printout,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n }\n return render (request, \"dbdex/sql.html\", context)\n\n elif 'MariaDB' in response:\n resp ='Found database type: MariaDB'\n context ={\n \"form\": form,\n \"resp\": resp,\n \"MariaDB\": True,\n \"result\": printout,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n }\n return render (request, \"dbdex/sql.html\", context)\n\n else:\n resp ='can not find the type of database used'\n context ={\n \"form\": form,\n \"resp\": resp,\n \"notvulnerable\": True,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n }\n \n return render(request, \"dbdex/sql.html\", context)\n \n else:\n printout =\" is NOT vulnerable to SQL injection\"\n \n context = {\n \"form\": form,\n 'notvulnerable': True,\n \"feedback\":\"Feedback\",\n \"link\": str1,\n \"result\": printout\n }\n return render(request, \"dbdex/sql.html\", context)\n context ={\n \"form\": form,\n \"feedback\":\"Feedback\",\n }\n return render(request, \"dbdex/sql.html\", context)\n\n\n# this method check for the form parameter\ndef formparameter(request): \n form = urlForm(request.POST or None)\n context = {\n \"feedback\":\"Feedback\",\n \"form\": form,\n }\n \n if request.method == 'POST':\n search_id = request.POST.get('url', None)\n url = search_id\n\n if form.is_valid():\n from requests.auth import HTTPBasicAuth\n url = search_id\n req1 = requests.get(url)\n req = requests.get(url,auth=HTTPBasicAuth('1\\'or\\'1\\'=\\'1', '1\\'or\\'1\\'=\\'1')) # sql query is been sent to the login form\n \n\n \n if req1.text != req.text:\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n\n getresult = ' is NOT vulnerable'\n context ={\n \"form\": form,\n \"notvulnerable\": True,\n \"getresult\": getresult,\n \"feedback\":\"Feedback\",\n \"link\": str1,\n } \n print('Not vulnerable')\n return render(request, \"dbdex/formparameter.html\", context)\n \n\n elif \"invalid\" in req.text :\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n\n getresult = ' is not vulnerable'\n context ={\n \"form\": form,\n \"notvulnerable\": True,\n \"getresult\": getresult,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n } \n return render(request, \"dbdex/formparameter.html\", context)\n \n\n elif \"incorrect\" in req.text :\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n\n getresult = ' is not vulnerable'\n context ={\n \"form\": form,\n \"notvulnerable\": True,\n \"getresult\": getresult,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n } \n return render(request, \"dbdex/formparameter.html\", context)\n \n\n elif \"Wrong\" in req.text :\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n\n getresult = ' is not vulnerable'\n context ={\n \"form\": form,\n \"notvulnerable\": True,\n \"getresult\": getresult,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n } \n return render(request, \"dbdex/formparameter.html\", context)\n \n\n elif \"error login\" in req.text :\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n\n getresult = ' is not vulnerable'\n context ={\n \"form\": form,\n \"notvulnerable\": True,\n \"getresult\": getresult,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n } \n return render(request, \"dbdex/formparameter.html\", context)\n \n else:\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n\n getresult = ' is vulnerable'\n context ={\n \"form\": form,\n \"vulnerable\": True,\n \"getresult\": getresult,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n } \n return render(request, \"dbdex/formparameter.html\", context)\n \n return render(request, \"dbdex/formparameter.html\", context)\n\n# the method for printing http header\ndef header(request):\n form = urlForm(request.POST or None)\n context ={\n \"form\": form,\n \"feedback\":\"Feedback\",\n }\n if request.method == 'POST':\n search_id = request.POST.get('url', None)\n \n if form.is_valid():\n # the request module is been use to get the header flag\n head = requests.get(search_id).headers\n\n context = {\n \"form\": form,\n \"head\": head,\n 'httpheader': True, \n \"feedback\":\"Feedback\",\n }\n return render (request, \"dbdex/header.html\", context)\n\n return render (request, \"dbdex/header.html\", context)\n \n# the method for xss\ndef xss(request):\n form = urlForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n cd = form.cleaned_data\n search_id = cd['url']\n url = search_id\n url.split(\"/\")[2:]\n array = url.split(\"/\")[0:3]\n str1 = '/'.join(array)\n print(str1)\n # javascript code is been supply\n payloads = ['', '']\n for payload in payloads:\n req_data = f'{url}{payload}'\n req = requests.post(req_data)\n print(req.text)\n if payload in req_data:\n resp = \" is vulnerable\\r\\n\"\n context ={\n \"form\": form,\n \"getresult\": resp,\n \"vulnerable\": True,\n \"link\": str1,\n }\n return render(request, \"dbdex/xss.html\", context)\n\n else:\n resp = \" is not vulnerable\\r\\n\"\n context ={\n \"form\": form,\n \"getresult\": resp,\n \"notvulnerable\": True,\n \"link\": str1,\n \"feedback\":\"Feedback\",\n }\n \n return render(request, \"dbdex/xss.html\", context)\n context ={\n \"form\": form,\n \"feedback\":\"Feedback\",\n }\n return render(request, \"dbdex/xss.html\", context)\n","sub_path":"dbdex/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510169034","text":"\n\"\"\"\nAuthor: Raul Novelo\n raul.novelo@aaaimx.org\n\n Intermediate code classes and 3-Address Code table generation\n\"\"\"\n\nfrom .constants import *\nfrom .helpers import *\n\n\nclass TR(object):\n \"\"\"\n Conditional reference for jumps (JR)\n \"\"\"\n\n def __init__(self, obj, size, start, body):\n self.obj = obj\n self.jmpTrue = start + size\n self.jmpFalse = start + size + body + 1\n\n\nclass IntermediateCode(object):\n \"\"\"\n 3-Address Code class representation\n \"\"\"\n\n def aritmetic(self, postfix, var=None):\n \"\"\"\n Intermediate code for an aritmetic expression\n\n :list postfix: a postfix array expression\n :str var: a name to be asigned for default None\n :returns: a lsit of dicts that contains 3-Address Code\n \"\"\"\n # reverse the list to use as stack\n string = list(reversed(postfix))\n aux = list() # auxiliar stack\n taddc = list() # Three Addres Code (EDD)\n tmpCont = 0 # temporals counter\n lastPrecedence = None\n el = string.pop() # get the first operand\n while el is not None:\n # Recorrer la expresión hasta encontrar el primer operador\n if el in OPAR:\n # Asignar a una variable auxiliar, el operador y los operandos previos\n # Asignar a una segunda variable auxiliar, el operador y los 2 operandos previos.\n op2 = aux.pop()\n op1 = aux.pop()\n\n # En la primera iteración\n if not lastPrecedence == PRECEDENCE[el] or lastPrecedence is None:\n tmpCont += 1\n # Se agrega un renglón en la triplo : variable temporal, primer operando y la operación (=)\n taddc.append({\n 'obj': f'T{tmpCont}',\n 'fuente': op1,\n 'op': '='\n })\n lastPrecedence = PRECEDENCE[el]\n\n # Se agregar otro renglón en la triplo : variable temporal, segundo operando y operador\n # A partir de la segunda iteración:\n # Se agrega un renglón en la triplo : variable temporal, operando y operador\n taddc.append({\n 'obj': f'T{tmpCont}',\n 'fuente': op2,\n 'op': el\n })\n # Se sustituye el operador y los 2 operandos de la variable auxiliar por la variable temporal.\n aux.append(f'T{tmpCont}')\n else:\n # agregar operando a la pila\n aux.append(el)\n\n # Se verifica el fin de cadena original\n if len(string) == 0:\n break\n # Se regresa al paso 2\n # se lee el siguiente operando\n el = string.pop()\n\n # Se asigna la cadena auxiliar a la cadena original\n string = aux\n tmp = string.pop()\n\n # si es una asignación simple\n if not lastPrecedence:\n taddc.append({\n 'obj': 'T1',\n 'fuente': tmp,\n 'op': '='\n })\n tmp = 'T1'\n # final step, asign last temporal to variable\n taddc.append({\n 'obj': var,\n 'fuente': tmp,\n 'op': '='\n })\n return taddc\n\n def iterative(self, postfix, start=0, body=0):\n \"\"\"\n Intermediate Code for `while` instruction\n \"\"\"\n # reverse the list to use as stack\n\n string = list(reversed(postfix))\n aux = list() # auxiliar stack\n taddc = list() # Three Addres Code (EDD)\n tmpCont = 0 # temporals counter\n trCont = trSize = 0 # TR counter\n lastPrecedence = lastOpLo = None\n lastTr = None\n el = string.pop() # get the first operand\n while el is not None:\n # Recorrer la expresión hasta encontrar el primer operador\n if el in OPAR:\n # Asignar a una variable auxiliar, el operador y los operandos previos\n # Asignar a una segunda variable auxiliar, el operador y los 2 operandos previos.\n op2 = aux.pop()\n op1 = aux.pop()\n if type(op1) is not str:\n op1 = f'T{tmpCont}'\n taddc.append({\n 'obj': op1,\n 'fuente': op2,\n 'op': el\n })\n trSize += 1\n aux.append(op1)\n\n elif el in OPRE:\n op2 = aux.pop()\n op1 = aux.pop()\n taddc.append({\n 'obj': op1,\n 'fuente': op2,\n 'op': el\n })\n trSize += 3\n trCont += 1\n tmpCont = 0\n obj = f'TR{trCont}'\n if not lastTr:\n lastTr = TR(obj, trSize, start, body)\n taddc.append(lastTr)\n else:\n trN = TR(obj, trSize, start, body)\n lastTr.jmpFalse = trN.jmpFalse\n taddc.append(trN)\n lastTr = trN\n aux.append(obj)\n lastPrecedence = None\n elif el in OPLO:\n band = False\n for i in range(len(taddc)):\n if type(taddc[i]) is not dict:\n if not band and el == '||':\n taddc[i].jmpFalse = taddc[i].jmpTrue\n taddc[i].jmpTrue = lastTr.jmpTrue\n band = True\n taddc[i] = [{\n 'obj': taddc[i].obj,\n 'fuente': 'TRUE',\n 'op': taddc[i].jmpTrue\n }, {\n 'obj': taddc[i].obj,\n 'fuente': 'FALSE',\n 'op': taddc[i].jmpFalse\n }]\n lastOpLo = el\n else:\n if type(el) is str:\n tmpCont += 1\n trSize += 1\n taddc.append({\n 'obj': f'T{tmpCont}',\n 'fuente': el,\n 'op': '='\n })\n aux.append(f'T{tmpCont}')\n else:\n aux.append(el)\n\n # Se verifica el fin de cadena original\n if len(string) == 0:\n break\n # Se regresa al paso P2\n # se lee el siguiente operando\n el = string.pop()\n if not lastOpLo:\n band = False\n for i in range(len(taddc)):\n if type(taddc[i]) is not dict:\n taddc[i] = [{\n 'obj': taddc[i].obj,\n 'fuente': 'TRUE',\n 'op': taddc[i].jmpTrue\n }, {\n 'obj': taddc[i].obj,\n 'fuente': 'FALSE',\n 'op': taddc[i].jmpFalse\n }]\n return taddc\n\n def generate_objcode(self, triplo):\n aux = None\n asm = []\n labels = []\n acc = []\n i = 0\n for el in triplo:\n obj = el['obj']\n fuente = el['fuente']\n op = el['op']\n\n if re.match(r'T\\d', obj):\n obj = REGISTERS[obj]\n if re.match(r'T\\d', str(fuente)):\n fuente = REGISTERS[fuente]\n try:\n if op == 'JR':\n asm.append('JMP label%d' % fuente)\n labels.append(fuente)\n elif op in OPRE:\n aux = el\n if triplo[i - 1]['op'] == '%':\n obj = 'AH'\n asm.append('CMP %s, %s' % (obj, fuente))\n else:\n if ASSEMBLY[op] in ['MUL', 'DIV']:\n tmp = 'BL'\n acc.append([i, 'MOV %s, %s' % (tmp, fuente)])\n asm.append('%s %s' % (ASSEMBLY[op], tmp))\n else:\n if triplo[i + 1]['op'] in ['%', '/']:\n obj = 'AX'\n if triplo[i - 1]['op'] == '%':\n fuente = 'AH'\n asm.append('%s %s, %s' % (ASSEMBLY[op], obj, fuente))\n except:\n if fuente == 'TRUE':\n asm.append('%s label%d' % (ASSEMBLY[aux['op']], op))\n labels.append(op)\n elif obj:\n asm.append('JMP label' + str(op))\n labels.append(op)\n i += 1\n asm.append('')\n \n # set labels\n for label in set(labels):\n asm[label - 1] = 'label%d: %s' % (label, asm[label - 1])\n\n # set mul and div compensation\n for i in range(len(acc)):\n asm.insert(acc[i][0] + i, acc[i][1])\n \n return asm\n\n\nif __name__ == \"__main__\":\n while_case = ['a', 2, '%', 0, '==', 'a', 20, '<', '||']\n data = IntermediateCode.iterative(\n while_case, isWhile=True, start=3, body=6)\n print(data)\n","sub_path":"compiler/three_add_code.py","file_name":"three_add_code.py","file_ext":"py","file_size_in_byte":9311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"614590066","text":"import matplotlib.pyplot as plt\nimport codecs\nimport re\n\ndef main(cipher_data):\n #計算するやつを用意\n char = [chr(i) for i in range(97, 97+26)]\n cnt = [0 for i in range(26)]\n\n #正規化\n cipher_data_norm = cipher_data.lower()\n cipher_data_norm = re.sub('\\n', ' ', cipher_data_norm)\n\n #カウント\n for i in range(26):\n cnt[i] = cipher_data_norm.count(char[i])\n\n #表へプロット\n x = [i for i in range(1,27)]\n y = cnt\n plt.bar(x, y, align='center')\n plt.xticks(x, char)\n plt.show()\n\n\nif __name__ == '__main__':\n\n #'sample.txt'から文章の読み込み\n f = open('sample.txt')\n text = f.read()\n f.close()\n\n #暗号化\n encrypt_data = codecs.encode(text, 'rot13')\n\n #実行\n main(encrypt_data)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"62586493","text":"import re\n\nMyRegex = [\n r'blk_(|-)[0-9]+' , # block id\n r'(/|)([0-9]+\\.){3}[0-9]+(:[0-9]+|)(:|)', # IP\n r'(?<=[^A-Za-z0-9])(\\-?\\+?\\d+)(?=[^A-Za-z0-9])|[0-9]+$', # Numbers\n]\n\ndef preprocess(logLine):\n for regex in MyRegex:\n line = re.sub(regex, '<*>', ' ' + logLine)\n return line\n\ndef tokenSpliter(logLine, regex, specialRegex):\n match = regex.search(logLine.strip())\n # print(match)\n if match == None:\n tokens = None\n pass;\n else:\n message = match.group('Content')\n # print(message)\n line = preprocess(message)\n tokens = line.strip().split()\n # print(tokens)\n return tokens\n\ndef regexGenerator(logformat):\n headers = []\n splitters = re.split(r'(<[^<>]+>)', logformat)\n regex = ''\n for k in range(len(splitters)):\n if k % 2 == 0:\n splitter = re.sub(' +', '\\\\\\s+', splitters[k])\n regex += splitter\n else:\n header = splitters[k].strip('<').strip('>')\n regex += '(?P<%s>.*?)' % header\n headers.append(header)\n regex = re.compile('^' + regex + '$')\n return regex\n\ndef dictionaryTransformation(keys, values):\n Dict = dict()\n for i in range(len(keys)):\n Dict[keys[i]] = values[i]\n return Dict","sub_path":"LogAbstractionOnline/Common.py","file_name":"Common.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"68902610","text":"import numpy as np\n\ndef inv_aprox(matrixA):\n length = len(matrixA[0])\n x = np.ones((length,1))\n y = np.ones((length,1))\n y[0] = 1/matrixA[0][0]\n for j in range(1,length):\n s = 0\n for k in range(j):\n s += matrixA[j][k]*y[k]\n sign_s = s/np.abs(s)\n y[j] = -(s + sign_s)/matrixA[j][j]\n y_norm = np.sqrt(np.sum(np.multiply(y,y)))\n norm_A = y_norm/np.sqrt(length)\n return norm_A\nmatA = np.array([[2,0,0],[5,4,0],[3,1,6]])\nnorm = inv_aprox(matA)\nprint(norm)\n","sub_path":"ainv_aprox.py","file_name":"ainv_aprox.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"337243269","text":"# -*- coding: UTF-8 -*-\n#!/usr/bin/env python\n############################################################\n#\n# FILE NAME : luci.sh\n# VERSION : 1.0\n# DESCRIPTION: K2P旧UI升级到新UI时,etc/config/luci文件配置适配\n# AUTHOR : LiuLu \n# CREATE DATE: 04/06/2017\n#\n##############################################################\nimport time\nimport adapter, log\nclass dmzClass(object):\n\t\"\"\"docstring for dmzClass\"\"\"\n\tdef __init__(self, arg):\n\t\tself.ip = arg['ip']\n\n\tdef setDmz(self):\n\t\tadapter.clickApp()\n\t\ttime.sleep(1)\n\n\t\tadapter.srcollAction('bottom')\n\t\tadapter.waitandClick('//*[@id=\"AppList\"]/ul[5]/a[1]/li')\n\t\tadapter.alwaysOpenSwitch('//*[@id=\"Switch\"]', 'data-value')\n\t\tadapter.waitandSendkeys('//*[@id=\"DmzIp\"]', self.ip)\n\t\tadapter.waitandClick('//*[@id=\"Save\"]')\n\ndef main(data):\n\tlog.writeLog(data, 'dmz', 1)\n\tdmzObj = dmzClass(data)\n\n\tdmzObj.setDmz()\n\tlog.writeLog(data, 'dmz', 2)\n","sub_path":"src/dmz.py","file_name":"dmz.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"72940204","text":"import numpy as np\nimport talib\n\nfrom typing import Union\n\n\ndef smma(candles: np.ndarray, period=5, sequential=False) -> Union[float, np.ndarray]:\n \"\"\"\n SMMA - Smoothed Moving Average\n\n :param candles: np.ndarray\n :param period: int - default: 5\n :param sequential: bool - default=False\n\n :return: float | np.ndarray\n \"\"\"\n if not sequential and len(candles) > 240:\n candles = candles[-240:]\n\n # calculate the smoothed moving average\n res = numpy_ewma(candles[:, 2], period)\n\n return res if sequential else res[-1]\n\n\ndef numpy_ewma(data, window):\n alpha = 1 / window\n scale = 1/(1-alpha)\n n = data.shape[0]\n scale_arr = (1-alpha)**(-1*np.arange(n))\n weights = (1-alpha)**np.arange(n)\n pw0 = (1-alpha)**(n-1)\n mult = data*pw0*scale_arr\n cumsums = mult.cumsum()\n out = cumsums*scale_arr[::-1] / weights.cumsum()\n\n return out","sub_path":"jesse/indicators/smma.py","file_name":"smma.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"198685131","text":"import argparse\nimport glob\n\n\ndef main(args):\n\n inputs = glob.glob(args.input_files)\n print('Found %s input files.' % len(inputs))\n num_words = 0\n word_counter = {}\n for filename in inputs:\n print('Processing file %s' % filename)\n with open(filename, 'r', encoding='utf-8') as f:\n sentences = f.readlines()\n for sentence in sentences:\n for word in sentence.split():\n num_words += 1\n if word in word_counter.keys():\n word_counter[word] += 1\n else:\n word_counter[word] = 1\n \n print('Total words: %s' % num_words)\n print('Total unique words: %s' % len(word_counter))\n\n cutoff = args.freq_cutoff\n if cutoff > 0:\n word_counter = { k : v for k, v in word_counter.items() if v > cutoff }\n \n if args.add_special_symbols:\n word_counter.pop('', None)\n word_counter.pop('', None)\n word_counter.pop('', None)\n word_list = [k for k, v in sorted(word_counter.items(), key=lambda kv : kv[1], reverse=True)]\n if args.max_vocab_size is not None and args.max_vocab_size < len(word_list):\n word_list = word_list[0:args.max_vocab_size]\n if args.add_special_symbols:\n print('Add special symbols')\n word_list = ['', '', ''] + word_list\n\n print('Final vocab size: %s' % len(word_list))\n\n with open(args.output_file, 'w', encoding='utf-8') as f:\n for w in word_list:\n f.write('%s\\n' % w)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Collect vocabulary file')\n parser.add_argument('--input_files', help='Input file patterns')\n parser.add_argument('--max_vocab_size', type=int, help='Max vocab size')\n parser.add_argument('--freq_cutoff', type=int, default=1,\n help='Frequency cutoff, only save words with frequency larger than this value')\n parser.add_argument('--output_file', help='Output vocab file')\n parser.add_argument('--add_special_symbols', action='store_true',\n help='If set, will add into the vocabulary')\n\n args = parser.parse_args()\n main(args)\n","sub_path":"tfmlm/bin/create_vocab.py","file_name":"create_vocab.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"309983860","text":"import json\nimport cv2\nimport numpy as np\nimport os\nimport argparse\nimport sys\nsys.path.append('../')\nimport Rect\nfrom pythonRLSA import rlsa\nfrom scipy import signal\nfrom joblib import Parallel, delayed\n\ndef SymbolDetection(mask):\n '''\n :param mask: 1*W mask which denotes if symbol appears on correspondent column of original row_img (H*W)\n :return: intervals of symbols, remove len(symbols)<20\n '''\n list=mask.tolist()\n intervals=[]\n N=len(list)\n for i in range(N):\n if list[i]==0:\n if list[max(i-1,0)]>0:\n intervals.append([i])\n if list[i]>0:\n if list[max(i-1,0)]==0 and intervals:\n intervals[-1].append(i)\n if intervals: #remove very narrow symbols, which are not characters or numbers\n if len(intervals[-1])==1:\n intervals.pop(-1)\n\n for i in range(len(intervals)-1,-1,-1):\n if intervals[i][1]-intervals[i][0]<20:\n intervals.pop(i)\n return intervals\n\ndef Binarization(img,patchSize=15,threshold=12):\n if len(img.shape)==3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # local binarization\n img_b = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, patchSize, threshold)\n return img_b\n\ndef ExpandRect(rect,threshold=12):\n rect = [list(rect[0]), list(rect[1]), rect[2]]\n\n if rect[1][0] > rect[1][1]:\n rect[1][1] = rect[1][1] +threshold\n else:\n rect[1][0] = rect[1][0] +threshold\n\n return tuple(rect)\n\n\ndef main(page,args=None):\n print(\"processing \"+page)\n #read in data\n col_rect_file=os.path.join(args.colrectdir,page+'.json')\n row_rect_file=os.path.join(args.rowrectdir,page+'.json')\n\n bg_img = cv2.imread('/home/ubuntu/results/personnel-records/1956/seg/background.png')\n\n with open(col_rect_file) as file:\n col_rects = json.load(file)\n\n with open(row_rect_file) as file:\n row_rects = json.load(file)\n\n for key in row_rects.keys():\n row_rects_col = row_rects[key]\n col_img=cv2.imread(os.path.join(args.imgdir,page,page+'_'+key+'.png'))\n\n col_img_b=Binarization(col_img)\n RLSA_thr=10\n\n _ , M_col = Rect.CropRect(col_img_b, col_rects[int(key)])\n for i in range(len(row_rects_col)):\n\n #detect symbols\n row_img_b , _ =Rect.CropRect(col_img_b, Rect.RectOnDstImg(row_rects_col[i],M_col))\n #cv2.imwrite(\"row_img.png\", row_img_b)\n\n #import pdb;pdb.set_trace()\n count=np.sum(row_img_b/255,axis=0)\n count=signal.medfilt(count, 5)\n\n _, count=cv2.threshold(count, 5, 255, cv2.THRESH_BINARY_INV)\n #cv2.imwrite(\"beforeRSLA.png\", count)\n count=rlsa.rlsa(count.T, True, False, RLSA_thr)\n #cv2.imwrite(\"afterRSLA.png\", count)\n\n symbol_intervals=SymbolDetection(count[-1])\n\n #decide if we need to move symbols closer\n if symbol_intervals:\n if symbol_intervals[-1][0]>0.7*row_img_b.shape[1] and len(symbol_intervals)>1:\n #expend some area as margin for PIE\n symbol_intervals[0][0]=max(0,symbol_intervals[0][0]-10)\n symbol_intervals[-2][1] = symbol_intervals[-2][1] + 10\n symbol_intervals[-1][0] = symbol_intervals[-1][0] - 10\n\n #copy the region of FName (src)\n row_img, M_col2row = Rect.CropRect(col_img, Rect.RectOnDstImg(ExpandRect(row_rects_col[i]),M_col))\n src_img=row_img[:,symbol_intervals[0][0]:symbol_intervals[-2][1]].copy()\n\n # t is the distance between first and last name\n t = symbol_intervals[-1][0] - symbol_intervals[-2][1]\n M_row2col = np.linalg.inv(M_col2row)\n\n # manually setup mask, for better performance we should automatically find a mask (binarization,DP,etc)\n roi_pts = np.array([[0, 0],\n [src_img.shape[1], 0],\n [src_img.shape[1], src_img.shape[0]],\n [0, src_img.shape[0]]], dtype=\"float32\")\n\n # mask w.r.t M_row2col\n roi_pts = Rect.PtsOnDstImg(roi_pts, M_row2col)\n roi_pts = roi_pts - np.min(roi_pts,axis=0)\n height,width = np.max(roi_pts, axis=0)[::-1]\n mask = np.zeros([min(height,src_img.shape[0]),min(width,src_img.shape[1])])\n roi_mask=cv2.fillConvexPoly(mask, roi_pts, 255)\n\n # fill the region of FName with random sampled background\n center = [[(symbol_intervals[0][0]+symbol_intervals[-2][1]) / 2, row_img.shape[0] / 2]]\n center = tuple(Rect.PtsOnDstImg(center,M_row2col,False)[-1])\n x , y = np.random.randint(bg_img.shape[0]-roi_mask.shape[0],size=1)[0], np.random.randint(bg_img.shape[1]-roi_mask.shape[1],size=1)[0]\n try:\n #import pdb;pdb.set_trace()\n col_img_tmp = cv2.seamlessClone(bg_img[x:x+roi_mask.shape[0],y:y+roi_mask.shape[1]], col_img, roi_mask.astype(np.uint8), center, cv2.NORMAL_CLONE)\n\n #paste the src region to target region\n center = [[center[0] + t, row_img.shape[0] / 2]]\n center = tuple(Rect.PtsOnDstImg(center, M_row2col, False)[-1])\n col_img = cv2.seamlessClone(src_img, col_img_tmp, roi_mask.astype(np.uint8), center, cv2.NORMAL_CLONE)\n except:\n\n # get error if part of src img is out of dst image\n # compute on original image can avoid this problem, but this is much faster and there is no big difference\n print(\"skip PIE for row \"+page+'_'+key +'_'+str(i))\n\n if not os.path.isdir(os.path.join(args.outputdir,page)):\n os.mkdir(os.path.join(args.outputdir,page))\n print('creating directory ' + os.path.join(args.outputdir,page))\n cv2.imwrite(os.path.join(args.outputdir,page,page+'_'+key+'.png'),col_img)\n\nif __name__ == '__main__':\n # construct the argument parse and parse the arguments\n parser = argparse.ArgumentParser(description='Page Detection')\n parser.add_argument('--imgdir', type=str)\n parser.add_argument('--colrectdir', type=str)\n parser.add_argument('--rowrectdir', type=str)\n parser.add_argument('--outputdir', type=str)\n args = parser.parse_args()\n\n #create output file\n if not os.path.isdir(args.outputdir):\n os.mkdir(args.outputdir)\n print('creating directory ' + args.outputdir)\n\n clean_names = lambda x: [i for i in x if i[0] != '.']\n\n pages = sorted(clean_names(os.listdir(args.imgdir)))\n #import pdb;pdb.set_trace()\n Parallel(n_jobs=1)(map(delayed(main), pages,[args]*len(pages)))\n","sub_path":"Postprocessing/MovingNums_index.py","file_name":"MovingNums_index.py","file_ext":"py","file_size_in_byte":6952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"217071932","text":"# coding=utf-8\nfrom __future__ import unicode_literals\n\nfrom mock import patch\n\nfrom snips_nlu.constants import (\n INTENTS, LANGUAGE_EN, RES_INTENT_NAME, UTTERANCES)\nfrom snips_nlu.dataset import validate_and_format_dataset\nfrom snips_nlu.entity_parser import BuiltinEntityParser, CustomEntityParser\nfrom snips_nlu.entity_parser.custom_entity_parser_usage import (\n CustomEntityParserUsage)\nfrom snips_nlu.intent_classifier import LogRegIntentClassifier\nfrom snips_nlu.intent_classifier.featurizer import Featurizer\nfrom snips_nlu.intent_classifier.log_reg_classifier_utils import (\n text_to_utterance)\nfrom snips_nlu.pipeline.configs import (\n LogRegIntentClassifierConfig)\nfrom snips_nlu.tests.utils import (\n BEVERAGE_DATASET, FixtureTest, SAMPLE_DATASET, get_empty_dataset)\nfrom snips_nlu.utils import NotTrained\n\n\n# pylint: disable=unused-argument\ndef get_mocked_augment_utterances(dataset, intent_name, language,\n min_utterances, capitalization_ratio,\n add_builtin_entities_examples,\n random_state):\n return dataset[INTENTS][intent_name][UTTERANCES]\n\n\nclass TestLogRegIntentClassifier(FixtureTest):\n def test_intent_classifier_should_get_intent(self):\n # Given\n dataset = validate_and_format_dataset(SAMPLE_DATASET)\n classifier = LogRegIntentClassifier().fit(dataset)\n text = \"This is a dummy_3 query from another intent\"\n\n # When\n res = classifier.get_intent(text)\n intent = res[RES_INTENT_NAME]\n\n # Then\n expected_intent = \"dummy_intent_2\"\n\n self.assertEqual(intent, expected_intent)\n\n def test_intent_classifier_should_get_intent_when_filter(self):\n # Given\n dataset = validate_and_format_dataset(BEVERAGE_DATASET)\n classifier = LogRegIntentClassifier().fit(dataset)\n\n # When\n text1 = \"Make me two cups of tea\"\n res1 = classifier.get_intent(text1, [\"MakeCoffee\", \"MakeTea\"])\n\n text2 = \"Make me two cups of tea\"\n res2 = classifier.get_intent(text2, [\"MakeCoffee\"])\n\n text3 = \"bla bla bla\"\n res3 = classifier.get_intent(text3, [\"MakeCoffee\"])\n\n # Then\n self.assertEqual(\"MakeTea\", res1[RES_INTENT_NAME])\n self.assertEqual(\"MakeCoffee\", res2[RES_INTENT_NAME])\n self.assertEqual(None, res3)\n\n def test_should_not_get_intent_when_not_fitted(self):\n # Given\n intent_classifier = LogRegIntentClassifier()\n\n # When / Then\n self.assertFalse(intent_classifier.fitted)\n with self.assertRaises(NotTrained):\n intent_classifier.get_intent(\"foobar\")\n\n def test_should_get_none_if_empty_dataset(self):\n # Given\n dataset = validate_and_format_dataset(get_empty_dataset(LANGUAGE_EN))\n classifier = LogRegIntentClassifier().fit(dataset)\n text = \"this is a dummy query\"\n\n # When\n intent = classifier.get_intent(text)\n\n # Then\n expected_intent = None\n self.assertEqual(intent, expected_intent)\n\n @patch('snips_nlu.intent_classifier.featurizer.Featurizer.to_dict')\n def test_should_be_serializable(self, mock_to_dict):\n # Given\n mocked_dict = {\"mocked_featurizer_key\": \"mocked_featurizer_value\"}\n\n mock_to_dict.return_value = mocked_dict\n\n dataset = validate_and_format_dataset(SAMPLE_DATASET)\n\n intent_classifier = LogRegIntentClassifier().fit(dataset)\n coeffs = intent_classifier.classifier.coef_.tolist()\n intercept = intent_classifier.classifier.intercept_.tolist()\n\n # When\n intent_classifier.persist(self.tmp_file_path)\n\n # Then\n intent_list = sorted(SAMPLE_DATASET[INTENTS])\n intent_list.append(None)\n expected_dict = {\n \"config\": LogRegIntentClassifierConfig().to_dict(),\n \"coeffs\": coeffs,\n \"intercept\": intercept,\n \"t_\": 701.0,\n \"intent_list\": intent_list,\n \"featurizer\": mocked_dict\n }\n metadata = {\"unit_name\": \"log_reg_intent_classifier\"}\n self.assertJsonContent(self.tmp_file_path / \"metadata.json\", metadata)\n self.assertJsonContent(self.tmp_file_path / \"intent_classifier.json\",\n expected_dict)\n\n @patch('snips_nlu.intent_classifier.featurizer.Featurizer.from_dict')\n def test_should_be_deserializable(self, mock_from_dict):\n # Given\n mocked_featurizer = Featurizer(LANGUAGE_EN, None)\n mock_from_dict.return_value = mocked_featurizer\n\n intent_list = [\"MakeCoffee\", \"MakeTea\", None]\n\n coeffs = [\n [1.23, 4.5],\n [6.7, 8.90],\n [1.01, 2.345],\n ]\n\n intercept = [\n 0.34,\n 0.41,\n -0.98\n ]\n\n t_ = 701.\n\n config = LogRegIntentClassifierConfig().to_dict()\n\n classifier_dict = {\n \"coeffs\": coeffs,\n \"intercept\": intercept,\n \"t_\": t_,\n \"intent_list\": intent_list,\n \"config\": config,\n \"featurizer\": mocked_featurizer.to_dict(),\n }\n self.tmp_file_path.mkdir()\n metadata = {\"unit_name\": \"log_reg_intent_classifier\"}\n self.writeJsonContent(self.tmp_file_path / \"metadata.json\", metadata)\n self.writeJsonContent(self.tmp_file_path / \"intent_classifier.json\",\n classifier_dict)\n\n # When\n classifier = LogRegIntentClassifier.from_path(self.tmp_file_path)\n\n # Then\n self.assertEqual(classifier.intent_list, intent_list)\n self.assertIsNotNone(classifier.featurizer)\n self.assertListEqual(classifier.classifier.coef_.tolist(), coeffs)\n self.assertListEqual(classifier.classifier.intercept_.tolist(),\n intercept)\n self.assertDictEqual(classifier.config.to_dict(), config)\n\n def test_should_get_intent_after_deserialization(self):\n # Given\n dataset = validate_and_format_dataset(BEVERAGE_DATASET)\n classifier = LogRegIntentClassifier().fit(dataset)\n classifier.persist(self.tmp_file_path)\n\n # When\n builtin_entity_parser = BuiltinEntityParser.build(language=\"en\")\n custom_entity_parser = CustomEntityParser.build(\n dataset, CustomEntityParserUsage.WITHOUT_STEMS)\n loaded_classifier = LogRegIntentClassifier.from_path(\n self.tmp_file_path,\n builtin_entity_parser=builtin_entity_parser,\n custom_entity_parser=custom_entity_parser)\n result = loaded_classifier.get_intent(\"Make me two cups of tea\")\n\n # Then\n expected_intent = \"MakeTea\"\n self.assertEqual(expected_intent, result[RES_INTENT_NAME])\n\n def test_should_be_serializable_into_bytearray(self):\n # Given\n dataset = validate_and_format_dataset(BEVERAGE_DATASET)\n intent_classifier = LogRegIntentClassifier().fit(dataset)\n\n # When\n intent_classifier_bytes = intent_classifier.to_byte_array()\n custom_entity_parser = CustomEntityParser.build(\n dataset, CustomEntityParserUsage.WITHOUT_STEMS)\n builtin_entity_parser = BuiltinEntityParser.build(language=\"en\")\n loaded_classifier = LogRegIntentClassifier.from_byte_array(\n intent_classifier_bytes,\n builtin_entity_parser=builtin_entity_parser,\n custom_entity_parser=custom_entity_parser)\n result = loaded_classifier.get_intent(\"make me two cups of tea\")\n\n # Then\n expected_intent = \"MakeTea\"\n self.assertEqual(expected_intent, result[RES_INTENT_NAME])\n\n @patch(\"snips_nlu.intent_classifier.log_reg_classifier\"\n \".build_training_data\")\n def test_empty_vocabulary_should_fit_and_return_none_intent(\n self, mocked_build_training):\n # Given\n language = LANGUAGE_EN\n dataset = {\n \"entities\": {\n \"dummy_entity_1\": {\n \"automatically_extensible\": True,\n \"use_synonyms\": False,\n \"data\": [\n {\n \"value\": \"...\",\n \"synonyms\": [],\n }\n ],\n \"matching_strictness\": 1.0\n }\n },\n \"intents\": {\n \"dummy_intent_1\": {\n \"utterances\": [\n {\n \"data\": [\n {\n \"text\": \"...\",\n \"slot_name\": \"dummy_slot_name\",\n \"entity\": \"dummy_entity_1\"\n }\n ]\n }\n ]\n }\n },\n \"language\": language\n }\n dataset = validate_and_format_dataset(dataset)\n\n text = \" \"\n noise_size = 6\n utterances = [text] + [text] * noise_size\n utterances = [text_to_utterance(t) for t in utterances]\n labels = [0] + [1] * noise_size\n intent_list = [\"dummy_intent_1\", None]\n mocked_build_training.return_value = utterances, labels, intent_list\n\n # When / Then\n intent_classifier = LogRegIntentClassifier().fit(dataset)\n intent = intent_classifier.get_intent(\"no intent there\")\n self.assertEqual(None, intent)\n","sub_path":"snips_nlu/tests/test_log_reg_intent_classifier.py","file_name":"test_log_reg_intent_classifier.py","file_ext":"py","file_size_in_byte":9517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"483624253","text":"# -*- coding:utf-8 -*-\n\"\"\"\nA subclass that provides special behavior for particular cases.\n\"\"\"\nfrom abc import ABCMeta\nfrom uuid import uuid4\n\n\nclass Data(metaclass=ABCMeta):\n \"\"\" Data holding container base class. \"\"\"\n pass\n\n\nclass PersonData(Data):\n \"\"\" Holds person data in python object. \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.id = str(uuid4())\n\n def __repr__(self):\n return f\"Person: name = {self.name}\"\n\n def __bool__(self):\n return True\n\n\nclass InvalidPersonData(Data):\n \"\"\"\n Represent an invalid person record.\n This is the \"Special Case\".\n \"\"\"\n\n def __init__(self, name=None):\n self.name = False # indicate there is no name\n self.id = None\n\n def __repr__(self):\n return \"INVALID DATA\"\n\n def __bool__(self):\n return False\n\n\nif __name__ == \"__main__\":\n # fake record_set with bad records\n record_set = (\n {'name': \"John\"},\n {'name': \"Laura\"},\n {'name': \"Alex\"},\n {'name': \"Adele\"},\n {'name': \"\"},\n {'name': 34},\n )\n\n def load_persons(record_set):\n \"\"\"\n Load persons data into python objects.\n This function includes validation which is not good example,\n validating should be done in another ways.\n \"\"\"\n for record in record_set:\n if record['name']:\n if isinstance(record['name'], (str,)):\n if len(record['name']) > 2:\n yield PersonData(name=record['name'])\n else:\n yield InvalidPersonData(name=record['name'])\n\n print(\"All data:\")\n for p in load_persons(record_set):\n print(p)\n\n # filter out valid records\n valid_persons = filter(lambda valid: valid, load_persons(record_set))\n # filter out invalid records\n invalid_persons = filter(lambda valid: not valid, load_persons(record_set))\n print(\"\\nValid person data:\")\n for vp in valid_persons:\n print(vp)\n print(\"\\nInvalid person data:\")\n for ip in invalid_persons:\n print(ip)\n","sub_path":"python/application-architecture/base/special_case/special_case.py","file_name":"special_case.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"150912876","text":"import csv\nimport random\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n#code to read a csv and convert into dictionary\nOCCUPATIONS = {}\nwith open('./static/occupations.csv') as csv_file: # open CSV file\n # instantiate CSV reader object\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0 # make sure header isn't included in dictionary\n for row in csv_reader: # populate dictionary with keys and values\n if(line_count == 0):\n line_count += 1\n else:\n OCCUPATIONS[row[0]] = float(row[1])\n\n\ndef selector(): # function to randomly select an occupation\n randomValue = random.random() * 99.8 # Pick a random number from 0 to 99.8\n threshold = 0 # establish a counter\n for x, y in OCCUPATIONS.items(): # for every entry in the dictionary (key, value)\n if(randomValue < threshold): # if the random number is less than the threshold\n return(x, y) # return that entry\n else:\n threshold += y # otherwise add this value to the threshold\n\n@app.route(\"/\")\ndef hello_world():\n print(__name__)\n return \"no hablo queso!\"\n\n\n@app.route(\"/index\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/occupyflaskst\") # route traffic to http://localhost:5000/occupyflaskst\ndef test_tmplt():\n selected = selector() # select a weighted random occupation\n\n # Render the template with the entire ictionary to be printed, and the chosen value\n return render_template(\"index.html\", OCCUPATIONS=OCCUPATIONS, selected=selected) \n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n\n","sub_path":"fall/10_occ/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"470586520","text":"#Danijel Klarin, 24.12.2018.\r\n#Vježba6_zd01\r\n\r\n'''Napišite program vjezba6_zd01.py koji za zadani decimalni broj a\r\n (broj a > 0 trebate sami zadati unutar programa) koji predstavlja\r\n duljinu stranice jednakostraničnog trokuta, računa površinu\r\n pripadnog jednakostraničnog trokuta čija je stranica duljine a,\r\n prema formuli:\r\n\r\n P = (a ** 2 * sqrt(3)) / 4'''\r\n\r\nfrom math import sqrt\r\n\r\na = float(input(\"Unesi decimalan broj: \"))\r\n\r\nif a > 0:\r\n\r\n P = (a ** 2 * sqrt(3)) / 4\r\n print(\"Površina trokuta iznosi {:.2f}\".format(P))\r\n\r\nelif a == 0:\r\n\r\n print(\"Uneseni broj je 0!\")\r\n\r\nelse:\r\n\r\n print(\"Uneseni broj je manji od 0!\")\r\n\r\n \r\n \r\n","sub_path":"Vjezba 06 - Priprema za kolokvij I - 1. dio/vjezba6_zd01.py","file_name":"vjezba6_zd01.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"257429580","text":"import ctypes ## For message box\r\nimport re ## For searching for letters in input\r\nfrom math import sqrt ## For the sqrt calculation\r\nprint (\"Note: This checker only finds factors upto the square root of the number\")\r\nprint ()\r\n\r\ndef func(): ## Function for checking input for letters, finding square root (root), and using modulo, finding numbers to be added to the list\r\n\tglobal answer\r\n\tanswer = input(\"Enter number: \")\r\n\tif re.search('[a-zA-Z]', str(answer)): ## Searches for letters in 'answer' if detected repeats question\r\n\t\tprint (\"This contains letters\")\r\n\t\tanswer = input(\"Enter number: \")\r\n\t\tfunc(answer)\r\n\telse: ## Uses sqrt to find the square root of 'answer' then saves it as 'root'\r\n\t\troot = sqrt(int(answer))\r\n\t\tcount = 1 ## Default value\r\n\t\twhile (count <= root): ## While loop, which incraments by 1 from 1 until it reaches 'root'\r\n\t\t\trem = int(answer) % int(count) ## Using modulo, divides 'answer' by 'count' and returns remainder \r\n\t\t\tif rem == 0: ## If remainder 'rem' is equal to zero, the 'count' value is added to the 'factors' array and adds 1 to 'count', otherwise it just adds 1 to 'count'\r\n\t\t\t\tfactors.append(count)\r\n\t\t\t\tcount = count + 1\r\n\t\t\telse:\r\n\t\t\t\tcount = count + 1\r\n\t\t\t\t\r\ndef init():\r\n\tglobal factors\r\n\tfactors = [] ## List which contains the numbers which have no remainder when the input is divided by it\r\n\tcon = 1 ## Used to create an infinite loop so that numbers can be checked up until this value is changed to 0\r\n\twhile (con != 0):\t## Infinite loop to trigger 'exit' after every calculation\r\n\t\tprint ()\r\n\t\texit = input(\"Do you want to test a number? (Y/N) \").lower() ## If \"Y\", the function is called, the array displayed and wiped\r\n\t\tif exit == \"y\":\r\n\t\t\tfunc()\r\n\t\t\tif len(factors) != 1: ## If function to determine what to output to user\r\n\t\t\t\tprint (answer + \" is not prime, these are the factors: \" + str(factors).strip('[]'))\r\n\t\t\telse:\r\n\t\t\t\tprint (answer + \" is prime\")\r\n\t\t\tfactors = []\r\n\t\telif exit == \"n\": ## If \"N\", 'con' is set to 0 stopping loop and ending script\r\n\t\t\tcon = 0\r\n\t\t\tprint (\"Goodbye!\") ## Cya!\r\n\t\telse:\r\n\t\t\tprint (\"Try Again\")\r\n\t\t\tinit()\r\n\t\r\ninit()\r\n\r\n","sub_path":"prime/prime_sqrt.py","file_name":"prime_sqrt.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"543129171","text":"from urllib2 import unquote\nfrom openmtc.exc import OpenMTCNetworkError\nfrom openmtc_etsi.model import FilterCriteria\n\nfrom openmtc_server.transportdomain import (RequestMethod, ErrorResponse,\n Response, Request, ResponseCode)\nfrom openmtc_etsi.scl import (\n CreateRequestIndication, RetrieveRequestIndication, DeleteRequestIndication,\n UpdateRequestIndication, NotifyRequestIndication)\nfrom openmtc_etsi.response import (\n CreateResponseConfirmation, NotifyResponseConfirmation,\n DeleteResponseConfirmation, UpdateResponseConfirmation,\n RetrieveResponseConfirmation, ErrorResponseConfirmation)\nfrom openmtc_etsi.exc import (SCLError, STATUS_ACCEPTED, SCLNotAcceptable,\n OpenMTCError)\nfrom openmtc_scl.transportdomain.util import (encode_result, encode_error,\n encode_request_indication_payload)\nfrom futile.logging import get_logger\nfrom openmtc_etsi.client.util import decode_result\nimport openmtc_scl.api as api\nfrom openmtc_scl import ETSIEndpoint\nfrom openmtc.model import ListAttribute\nfrom openmtc_server.util import log_error\n\n_logger = get_logger(__name__)\n\n\netsi_version_2 = api.config[\"etsi\"][\"etsi_version\"] >= \"2.0\"\n\nif etsi_version_2:\n etsi_compat = api.config[\"etsi\"][\"etsi_compatibility\"] < \"2.0\"\n if etsi_compat:\n def get_requesting_entity(request):\n req_entity = request.originator\n _logger.debug(\"Originator: %s - Username: %s\", req_entity,\n request.username)\n if not req_entity:\n req_entity = request.username\n if req_entity:\n req_entity = unquote(req_entity)\n return req_entity\n else:\n def get_requesting_entity(request):\n _logger.debug(\"originator: %s\", request.originator)\n return request.originator\nelse:\n etsi_compat = api.config[\"etsi\"][\"etsi_compatibility\"] >= \"2.0\"\n if etsi_compat:\n def get_requesting_entity(request):\n req_entity = request.username\n _logger.debug(\"Username: %s - Originator: %s\", req_entity,\n request.originator)\n if req_entity:\n return unquote(req_entity)\n return request.originator\n else:\n def get_requesting_entity(request):\n req_entity = request.username\n _logger.debug(\"Username: %s\", req_entity)\n if req_entity:\n return unquote(req_entity)\n\n\ndef map_request_to_request_indication(request):\n path = request.path\n method = request.method\n if method == RequestMethod.create:\n req_ind = CreateRequestIndication(path=path, resource=request.payload,\n content_type=request.content_type)\n elif method == RequestMethod.retrieve:\n req_ind = RetrieveRequestIndication(path)\n if path.endswith((\"/contentInstances\", \"/discovery\")):\n args = request.params\n filter_criteria = {k: v for k, v in args.items() if\n k not in (\"ifNoneMatch\", \"searchString\",\n \"contentType\", \"searchPrefix\",\n \"maxSize\")}\n filter_criteria = FilterCriteria(**filter_criteria)\n if_none_match = args.getlist(\"ifNoneMatch\")\n if if_none_match:\n filter_criteria.ifNoneMatch = if_none_match\n search_string = args.getlist(\"searchString\")\n if search_string:\n filter_criteria.searchString = search_string\n content_type = args.getlist(\"contentType\")\n if content_type:\n filter_criteria.contentType = content_type\n req_ind.filterCriteria = filter_criteria\n if path.endswith(\"/discovery\"):\n req_ind.searchPrefix = args.get(\"searchPrefix\")\n req_ind.maxSize = args.get(\"maxSize\")\n # obtain some filter-criteria from HTTP headers, where appropriate\n # TODO: kca: not sure if this is actually standard compliant, but it\n # seems like common sense. Check if its in the standard, if not,\n # allow to turn it off via config\n # TODO: use generic format\n environ = request.metadata\n for n in (\"if_None_Match\", \"if_Unmodified_Since\",\n \"if_Modified_Since\"):\n try:\n header = environ[\"HTTP_\" + n.upper()]\n except KeyError:\n pass\n else:\n filter_criteria.setdefault(n.replace(\"_\", \"\"), header)\n\n elif method == RequestMethod.update:\n req_ind = UpdateRequestIndication(path=path,\n resource=request.payload,\n content_type=request.content_type)\n elif method == RequestMethod.delete:\n req_ind = DeleteRequestIndication(path)\n elif method == RequestMethod.notify:\n req_ind = NotifyRequestIndication(path=path,\n resource=request.payload,\n content_type=request.content_type)\n else:\n raise ErrorResponse(ResponseCode.method_not_allowed)\n# TODO: set correlationID, rcat, trpdt\n req_ind.requestingEntity = get_requesting_entity(request)\n via = request.via\n if via:\n req_ind.via = request.via\n return req_ind\n\n\ndef get_etsi_request_mapper(handle_request_indication, reference_point):\n def etsi_request_mapper(request):\n # TODO: unify so that thjs is not needed\n req_ind = map_request_to_request_indication(request)\n\n endpoint = ETSIEndpoint(reference_point, request.connector.base_uri)\n\n try:\n return handle_request_indication(req_ind, endpoint) \\\n .then(lambda response: map_response_confirmation_to_response(\n request, response),\n lambda response: map_error_response_confirmation_to_response(\n request, response))\n except SCLError as exc:\n raise ErrorResponse(status_code=exc.StatusCode,\n payload=str(exc))\n except Exception as exc:\n raise ErrorResponse(payload=repr(exc))\n return etsi_request_mapper\n\n\ndef map_response_confirmation_to_response(request, response):\n try:\n primitiveType = response.primitiveType\n except AttributeError:\n if isinstance(response, Response):\n return response\n raise\n\n config = api.config\n status_code = response.statusCode\n\n if status_code == STATUS_ACCEPTED:\n return Response(ResponseCode.accepted)\n\n pretty = config[\"global\"].get(\"pretty_print\")\n if pretty is None:\n user_agent = request.user_agent\n pretty = user_agent and (\"opera\" in user_agent or\n \"mozilla\" in user_agent)\n\n location = None\n if primitiveType in (\"create\", \"retrieve\"):\n try:\n content_type, data = encode_result(response, accept=request.accept,\n pretty=pretty)\n except SCLNotAcceptable as exc:\n status_code = exc.statusCode\n data = str(exc)\n content_type = \"text/plain\"\n else:\n if primitiveType == \"create\":\n location = response.resourceURI\n else:\n data = content_type = None\n\n if data is None:\n return Response(ResponseCode.no_content)\n\n return Response(\n status_code=status_code,\n payload=data,\n content_type=content_type,\n location=location\n )\n\n\ndef map_error_response_confirmation_to_response(request, response):\n if log_error(response):\n _logger.exception(\"Caught Exception in request handling\")\n else:\n _logger.debug(\"Caught Exception in request handling: %s\",\n repr(response))\n\n if isinstance(response, ErrorResponse):\n return response\n\n try:\n statuscode = response.statusCode\n except AttributeError:\n statuscode = ResponseCode.internal_error\n\n config = api.config\n pretty = config[\"global\"].get(\"pretty_print\")\n if pretty is None:\n user_agent = request.user_agent\n pretty = user_agent and (\"opera\" in user_agent or\n \"mozilla\" in user_agent)\n\n content_type, data = encode_error(response, accept=request.accept,\n pretty=pretty)\n\n return ErrorResponse(\n payload=data,\n status_code=statuscode,\n content_type=content_type)\n\n\ndef map_request_indication_to_request(request_indication):\n try:\n request_indication.content_type\n except AttributeError:\n content_type = data = None\n else:\n content_type, data = encode_request_indication_payload(\n request_indication)\n\n method = method_map[request_indication.method]\n\n if method == RequestMethod.retrieve:\n # params\n try:\n params = {k: v for k, v in\n request_indication.filterCriteria.values.items() if\n v is not None}\n except AttributeError:\n params = {}\n if request_indication.searchPrefix:\n params['searchPrefix'] = request_indication.searchPrefix\n if request_indication.maxSize:\n params['maxSize'] = request_indication.maxSize\n else:\n params = {}\n\n # TODO: Via handling\n return Request(method=method,\n path=request_indication.path,\n originator=request_indication.requestingEntity,\n content_type=content_type,\n payload=data,\n params=params)\n\n\ndef map_response_to_response_confirmation(method, path, response):\n\n try:\n content_type = response.content_type\n except AttributeError:\n content_type = None\n\n if method in (\"create\", \"retrieve\", \"update\"):\n try:\n payload = response.payload\n except AttributeError:\n payload = None\n pass\n d, ct = decode_result(path, payload, content_type)\n else:\n d, ct = None, None\n\n if method == \"create\":\n # try to detect fields when response from retargeted create response\n # returned. i.e. expirationTime\n fields = [a.name for a in d.attributes if\n (getattr(d, a.name) is not None) and\n not (a.default and getattr(d, a.name) == a.default) and\n not (isinstance(a, ListAttribute) and not getattr(d, a.name))]\n return CreateResponseConfirmation(resourceURI=response.location,\n resource=d, content_type=ct,\n fields=fields)\n if method == \"notify\":\n return NotifyResponseConfirmation()\n if method == \"retrieve\":\n return RetrieveResponseConfirmation(resource=d, content_type=ct)\n if method == \"update\":\n return UpdateResponseConfirmation(resource=d, content_type=ct)\n if method == \"delete\":\n return DeleteResponseConfirmation()\n raise OpenMTCError(\"Unhandled method: %s\", method)\n\n\ndef map_error_response_to_error_response_confirmation(request_indication,\n request, response):\n if log_error(response):\n _logger.exception(\"Caught Exception in request handling\")\n else:\n _logger.debug(\"Caught Exception in request handling: %s\",\n repr(response))\n\n if isinstance(response, OpenMTCNetworkError):\n return response\n\n if isinstance(response, ErrorResponseConfirmation):\n return response\n\n try:\n status_code = response.statusCode\n except AttributeError:\n status_code = ResponseCode.internal_error\n\n config = api.config\n pretty = config[\"global\"].get(\"pretty_print\")\n if pretty is None:\n user_agent = request.user_agent\n pretty = user_agent and (\"opera\" in user_agent or\n \"mozilla\" in user_agent)\n\n content_type, data = encode_error(response, accept=request.accept,\n pretty=pretty)\n\n return ErrorResponseConfirmation(status_code, request_indication.method,\n data)\n\n\nmethod_map = {\n \"create\": RequestMethod.create,\n \"retrieve\": RequestMethod.retrieve,\n \"notify\": RequestMethod.create,\n \"update\": RequestMethod.update,\n \"delete\": RequestMethod.delete,\n \"execute\": RequestMethod.update\n}\n\n\ndef get_request_method(request_indication_method):\n try:\n return method_map[request_indication_method]\n except KeyError:\n raise ValueError(\"Invalid request indication method: %s\",\n request_indication_method)\n","sub_path":"eds/openmtc-gevent/server/openmtc-scl/src/openmtc_scl/mappingfunction.py","file_name":"mappingfunction.py","file_ext":"py","file_size_in_byte":12959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"430247101","text":"#!/usr/bin/env python3.4\n#file admin.py\n\nfrom django.contrib.admin import autodiscover, site\nfrom debates.models import (\n Teacher, Judge, Debater,\n Topic, Location, Score, Subscore,\n Deduction, Debate, Team\n )\nfrom debates.resources import DebaterResource, TeacherResource\nfrom import_export.admin import ImportExportModelAdmin\n#from logging import getLogger\n\n#logger = getLogger('logview.debugger')\n\nautodiscover()\n\nclass DebaterAdmin(ImportExportModelAdmin):\n resource_class = DebaterResource\n\nclass TeacherAdmin(ImportExportModelAdmin):\n resource_class = TeacherResource\n\nsite.register(Teacher, TeacherAdmin)\nsite.register(Judge)\nsite.register(Debater, DebaterAdmin)\nsite.register(Topic)\nsite.register(Location)\nsite.register(Score)\nsite.register(Subscore)\nsite.register(Deduction)\nsite.register(Debate)\nsite.register(Team)#, TeamAdmin)\n","sub_path":"AHS-Freshman-Debates/debates/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"460151505","text":"from setuptools import setup, find_packages\n\nrequirements = [\n 'flask==1.1.1',\n 'flask-api==1.1',\n]\n\ndevelop_requirements = [\n 'coverage',\n 'autopep8',\n 'flake8',\n 'mypy',\n 'autoflake',\n 'isort',\n]\n\nextras_require = {\n 'dev': develop_requirements,\n}\n\nsetup(\n name='api',\n version='0.1.0',\n description='',\n author='',\n author_email='',\n url='',\n install_requires=requirements,\n extras_require=extras_require,\n packages=find_packages(exclude=[])\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"339312233","text":"from voximplant.apiclient import VoximplantAPI, VoximplantException\nimport pytz\nimport datetime\n\nif __name__ == \"__main__\":\n voxapi = VoximplantAPI(\"credentials.json\")\n\n # Get the first call session history record from the 2012-01-01 00:00:00 UTC to the 2014-01-01 00:00:00 UTC\n\n FROM_DATE = datetime.datetime(2012, 1, 1, 0, 0, 0, pytz.utc)\n TO_DATE = datetime.datetime(2014, 1, 1, 0, 0, 0, pytz.utc)\n COUNT = 1\n \n try:\n res = voxapi.get_call_history(FROM_DATE, TO_DATE, count=COUNT)\n except VoximplantException as e:\n print(\"Error: {}\".format(e.message))\n print(res)\n","sub_path":"samples/get_call_history.py","file_name":"get_call_history.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"45079904","text":"input_ = input('')\nvalidInputs = '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\nvalidIsbn = False\nchecker = 0\n\n\nif len(input_) != 10:\n print('INPUT ERROR')\nelse:\n while validIsbn == False:\n digits = []\n itterator = 0\n end = 2\n checkDigits = 10\n multiplier = 10\n controlNumber = 0\n Remainder = 0\n checkDigit = 0\n controlNumberAdder = 0\n isthereI = False\n for i in input_:\n if i in validInputs:\n digits.append(i)\n elif i == 'X':\n i = 10\n digits.append(i)\n elif i == '.':\n i = checker\n digits.append(i)\n isthereI = True\n elif i not in validInputs:\n print('INPUT ERROR')\n quit()\n while checkDigits >= end:\n controlNumberAdder = int(digits[itterator]) * multiplier\n controlNumber = controlNumber + controlNumberAdder\n multiplier = multiplier - 1\n checkDigits = checkDigits - 1\n itterator = itterator + 1\n Remainder = controlNumber % 11 \n checkDigit = int(digits[9])\n if isthereI == True:\n if (controlNumber + checkDigit) % 11 == 0:\n if checker == 10:\n print('X')\n validIsbn = True\n else:\n print(str(checker))\n validIsbn = True\n else:\n checker = checker + 1\n elif (controlNumber + checkDigit) % 11 == 0:\n print('VALID')\n validIsbn = True\n elif (controlNumber + checkDigit) % 11 != 0:\n print('INVALID')\n validIsbn = True","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"218282353","text":"import json\nimport openpyxl\n\n\ndef main():\n print('start program')\n\n filename = './template.xlsx'\n book = openpyxl.load_workbook(filename)\n\n # get the first sheet\n sheet = book.worksheets[0]\n data = {}\n\n creators = []\n videos = []\n gifs = []\n photos = []\n\n # parse excel file and generate a json\n for row in sheet.rows:\n colname = row[0].value\n if colname == \"title\":\n title = row[1].value\n data.update({\"title\": title})\n\n elif colname == \"subtitle\":\n subtitle = row[1].value\n data.update({\"subtitle\": subtitle})\n\n elif colname == \"link\":\n link = row[1].value\n data.update({\"link\": link})\n\n elif colname == \"creators\":\n name = row[1].value\n portfolio = row[2].value\n email = row[3].value\n twitter = row[4].value\n tmp = {\n 'name': name,\n 'portfolio': portfolio,\n 'email': email,\n 'twitter': twitter\n }\n creators.append(tmp)\n\n elif colname == \"about\":\n para1 = row[1].value\n para2 = row[2].value\n\n data.update({\n 'about': [\n para1,\n para2\n ]\n })\n\n elif colname == \"videos\":\n embed = row[1].value\n page = row[2].value\n tmp = {\n 'embedUrl': embed,\n 'videoPage': page\n }\n videos.append(tmp)\n\n elif colname == \"gifs\":\n url = row[1].value\n tmp = {\n \"gifUrl\": url\n }\n gifs.append(tmp)\n\n elif colname == \"photos\":\n url = row[1].value\n tmp = {\n \"photoUrl\": url\n }\n photos.append(tmp)\n\n elif colname == \"footer\":\n text = row[1].value\n link = row[2].value\n data.update({\n 'footer': [\n {\n 'footerText': text,\n 'footerLink': link\n }\n ]\n })\n\n else:\n print(\"you may put a wrong item in your sheet. Please check your sheet\")\n\n data.update({\n \"creators\":\n creators\n })\n\n data.update({\n 'videos':\n videos\n })\n\n data.update({\n 'gifs':\n gifs\n })\n\n data.update({\n 'photos':\n photos\n })\n\n # generate json\n f = open(\"data.json\", \"w\")\n json.dump(data, f, ensure_ascii=False, indent=4,\n sort_keys=True, separators=(',', ': '))\n print('generated data.json')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"e2j.py","file_name":"e2j.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"382096522","text":"import pandas as pd \nimport pickle\nimport gensim.corpora as corpora\n\nfrom src.features.tokenize import tokenize\nfrom src.features.dictionary import create_dictionary\nfrom src.features.clean import clean_up_text\n\n\ndef load_model():\n with open(r\"models/model.pkl\", \"rb\") as input_file:\n model = pickle.load(input_file)\n return(model)\n\ndef test(model,text:str):\n text = pd.DataFrame(data={'content':[text]}, columns=['content'])\n doc = clean_up_text(text)\n lemma = tokenize(doc)\n id2word, corpus = create_dictionary(lemma)\n prediction = model[corpus]\n\n topics = list()\n for prob in prediction[0][1]:\n for topic in prob[1]:\n topics.append(topic)\n moda = max(set(topics), key=topics.count)\n topics = model.print_topics()[moda]\n return topics","sub_path":"src/models/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"156729189","text":"#! /usr/bin/env python3\n#\n# This file is part of Toboggan, https://github.com/TheoryInPractice/Toboggan/,\n# and is Copyright (C) North Carolina State University, 2017. It is licensed\n# under the three-clause BSD license; see LICENSE.\n#\n# -*- coding: utf-8 -*-\n# python libs\nimport sys\nimport itertools\n# local imports\nfrom toboggan.dp import solve as solve_dp\n\n\n# Print iterations progress\ndef print_progress(iteration, total, prefix='', suffix='', decimals=1,\n bar_length=100):\n \"\"\"\n Call in a loop to create terminal progress bar.\n\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent\n complete (Int)\n bar_length - Optional : character length of bar (Int)\n \"\"\"\n str_format = \"{0:.\" + str(decimals) + \"f}\"\n percents = str_format.format(100 * (iteration / float(total)))\n filled_length = int(round(bar_length * iteration / float(total)))\n bar = '█' * filled_length + '-' * (bar_length - filled_length)\n\n sys.stdout.write('\\r%s |%s| %s%s %s' % (prefix, bar, percents, '%',\n suffix)),\n\n if iteration == total:\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n\ndef is_feasible(weights, flow, max_weight):\n \"\"\"Test whether set of guessed weights is feasible.\"\"\"\n # In the following, we replace very occurenve of 'None' in the\n # weight-array by the minimum/maximum possible value (given by the\n # last/the first\n # non-None value next to it).\n min_weights = [1] + weights\n max_weights = [max_weight] + list(reversed(weights))\n for i in range(1, len(min_weights)):\n min_weights[i] = min_weights[i] if min_weights[i] else min_weights[i-1]\n max_weights[i] = max_weights[i] if max_weights[i] else max_weights[i-1]\n min_weights = min_weights[1:]\n max_weights = list(reversed(max_weights[1:]))\n\n # If the flow value lies outside of the sum-of-weight estimates,\n # the current guessed set of weights is infeasible.\n return sum(min_weights) <= flow and sum(max_weights) >= flow\n\n\ndef solve(instance, silent=True, max_weight_lower=1,\n max_weight_upper=float('inf'), scoring=\"sink distance\"):\n \"\"\"Solve the provided instance of path-flow decomposition.\"\"\"\n flow = instance.flow\n k = instance.k\n\n # quit right away if the instance has weight bounds that can't be satisfied\n if instance.has_bad_bounds():\n return set()\n\n # if k equals the size of the largest edge cut, the weights are\n # predetermined\n if instance.k == max(len(C) for C in instance.edge_cuts):\n largest_cut = max(instance.edge_cuts, key=len)\n # Important: path weights must be sorted, otherwise our\n # subsequent optimizations will remove this constraint.\n weights = list(sorted(w for _, w in largest_cut))\n return solve_dp(instance, silent=True, guessed_weights=weights)\n\n max_weight = instance.max_weight_bounds[1]\n feasible_weights = list(filter(lambda w: w <= max_weight,\n instance.weights))\n\n if not silent:\n print(instance.weights, feasible_weights)\n\n # figure out whether we get the first or last positions for free\n largest_free = False\n smallest_free = False\n # check largest weight first\n if instance.max_weight_bounds[0] == instance.max_weight_bounds[1]:\n largest_free = True\n largest = instance.max_weight_bounds[0]\n if min(instance.weights) == 1:\n smallest_free = True\n smallest = 1\n\n positions = list(range(int(smallest_free), k-int(largest_free)))\n\n # iterate over the number of unguessed weights\n for diff in range(k+1):\n if not silent:\n print(\"Diff =\", diff)\n # iterate over positions of guessed weights. We want them to be\n # ordered, but choose the smallest first to be removed\n for rev_indices in itertools.combinations(reversed(positions), k-diff):\n indices = list(reversed(rev_indices))\n p = len(indices)\n # when k-1 values are determined, it also determines the kth value\n if p == k-1:\n continue\n # iterate over choices for those guessed weights\n for chosen_weights in itertools.combinations(feasible_weights, p):\n weights = [None] * k\n\n # assign the chosen weights to the guessed positions\n for p, w in zip(indices, chosen_weights):\n weights[p] = w\n\n # add in free values\n if smallest_free:\n weights[0] = smallest\n if largest_free:\n weights[k-1] = largest\n\n # quit if this didn't work\n if not is_feasible(weights, flow, max_weight):\n continue\n\n if not silent:\n print(\"Trying weights\", weights)\n sol = solve_dp(instance, silent=True, guessed_weights=weights)\n if len(sol) > 0:\n if not silent:\n try:\n for s in sol:\n print(s, sum(s.path_weights), flow)\n except AttributeError:\n print(\"Unterdetermined solution\")\n return sol\n","sub_path":"toboggan/guess_weight.py","file_name":"guess_weight.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"171583346","text":"import re\nfrom io import BytesIO\nfrom typing import Callable, Dict, List, IO, Iterator, Union\n\nimport attr\n\nfrom lxml import etree\n\n\ndef _string_to_valid_classname(name: str):\n return re.sub('[^a-zA-Z_]', '_', name)\n\n\n@attr.s(slots=True)\nclass Annotation():\n type: str = attr.ib()\n begin: int = attr.ib()\n end: int = attr.ib()\n xmiID: int = attr.ib(default=None)\n sofa: int = attr.ib(default=None)\n\n\n@attr.s(slots=True)\nclass Feature():\n name = attr.ib()\n description = attr.ib()\n rangeTypeName = attr.ib()\n\n\n@attr.s(slots=True)\nclass Type():\n name: str = attr.ib()\n description: str = attr.ib()\n supertypeName: str = attr.ib()\n features: List[Feature] = attr.ib()\n constructor: Callable[[Dict], Annotation] = attr.ib(init=False, cmp=False, repr=False)\n\n def __attrs_post_init__(self):\n \"\"\" Build the constructor that can create annotations of this type \"\"\"\n name = _string_to_valid_classname(self.name)\n fields = {feature.name: attr.ib(default=None) for feature in self.features}\n fields['type'] = attr.ib(default=self.name)\n self.constructor = attr.make_class(name, fields, bases=(Annotation,), slots=True)\n\n def __call__(self, **kwargs) -> Annotation:\n \"\"\" Creates an annotation of this type \"\"\"\n return self.constructor(**kwargs)\n\n\nclass FallbackType():\n def __init__(self, **kwargs):\n self._fields = kwargs\n\n def __getattr__(self, item):\n return self._fields.get(item, None)\n\n\nclass TypeSystem():\n\n def __init__(self, types: List[Type] = None):\n if types is None:\n types = []\n\n self._types = {}\n for type in types:\n self._types[type.name] = type\n\n def has_type(self, typename: str):\n \"\"\"\n\n Args:\n typename (str):\n\n Returns:\n\n \"\"\"\n return typename in self._types\n\n def get_type(self, typename: str) -> Type:\n \"\"\"\n\n Args:\n typename (str):\n\n Returns:\n\n \"\"\"\n if self.has_type(typename):\n return self._types[typename]\n else:\n # TODO: Fix fallback for lenient parsing\n return FallbackType\n\n def get_types(self) -> Iterator[Type]:\n \"\"\" Returns all types of this type system \"\"\"\n return iter(self._types.values())\n\n def to_xml(self, path_or_buf: Union[IO, str] = None):\n \"\"\" Creates a string representation of this type system\n\n Args:\n path_or_buf: File path or file-like object, if None is provided the result is returned as a string.\n\n Returns:\n\n \"\"\"\n serializer = TypeSystemSerializer()\n\n if path_or_buf is None:\n sink = BytesIO()\n serializer.serialize(sink, self)\n return sink.getvalue().decode('utf-8')\n else:\n serializer.serialize(path_or_buf, self)\n\n def __len__(self) -> int:\n return len(self._types)\n\n\n# Deserializing\n\ndef load_typesystem(source: Union[IO, str]) -> TypeSystem:\n deserializer = TypeSystemDeserializer()\n if isinstance(source, str):\n return deserializer.deserialize(BytesIO(source.encode('utf-8')))\n else:\n return deserializer.deserialize(source)\n\n\nclass TypeSystemDeserializer():\n\n def deserialize(self, source: Union[IO, str]) -> TypeSystem:\n \"\"\"\n\n Args:\n source: a filename or file object containing XML data\n\n Returns:\n typesystem (TypeSystem):\n \"\"\"\n types = []\n\n context = etree.iterparse(source, events=('end',), tag=('{*}typeDescription',))\n for event, elem in context:\n name = elem.find('{*}name').text or ''\n description = elem.find('{*}description').text or ''\n supertypeName = elem.find('{*}supertypeName').text or ''\n features = []\n\n for feature_description in elem.iterfind('{*}features/{*}featureDescription'):\n feature = self._parse_feature(feature_description)\n features.append(feature)\n\n type = Type(name, description, supertypeName, features)\n types.append(type)\n\n elem.clear()\n while elem.getprevious() is not None:\n del elem.getparent()[0]\n del context\n\n return TypeSystem(types)\n\n def _parse_feature(self, elem) -> Feature:\n name = elem.find('{*}name').text or ''\n description = elem.find('{*}description').text or ''\n rangeTypeName = elem.find('{*}rangeTypeName').text or ''\n return Feature(name, description, rangeTypeName)\n\n\n# Serializing\n\nclass TypeSystemSerializer():\n\n def serialize(self, sink: Union[IO, str], typesystem: TypeSystem):\n nsmap = {None: 'http://uima.apache.org/resourceSpecifier'}\n with etree.xmlfile(sink) as xf:\n with xf.element('typeSystemDescription', nsmap=nsmap):\n with xf.element('types'):\n for type in typesystem.get_types():\n self._serialize_type(xf, type)\n\n def _serialize_type(self, xf: IO, type: Type):\n typeDescription = etree.Element('typeDescription')\n\n name = etree.SubElement(typeDescription, 'name')\n name.text = type.name\n\n description = etree.SubElement(typeDescription, 'description')\n description.text = type.description\n\n supertypeName = etree.SubElement(typeDescription, 'supertypeName')\n supertypeName.text = type.supertypeName\n\n features = etree.SubElement(typeDescription, 'features')\n for feature in type.features:\n self._serialize_feature(features, feature)\n\n xf.write(typeDescription)\n\n def _serialize_feature(self, features: etree.Element, feature: Feature):\n featureDescription = etree.SubElement(features, 'featureDescription')\n\n name = etree.SubElement(featureDescription, 'name')\n name.text = feature.name\n\n description = etree.SubElement(featureDescription, 'description')\n description.text = feature.description\n\n rangeTypeName = etree.SubElement(featureDescription, 'rangeTypeName')\n rangeTypeName.text = feature.rangeTypeName\n","sub_path":"cassis/typesystem.py","file_name":"typesystem.py","file_ext":"py","file_size_in_byte":6170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"477346090","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 6 19:43:08 2017\n\n@author: m75380\n\nScript to add SIRENE to API\n\"\"\"\nfrom datetime import datetime\nimport json\nimport os\n\nfrom api_helpers import APIConnection\n\n# Project id or display name to delete\ndisplay_name = 'RNSR'\nproject_id = None\n\n# Path to configuration\nconnection_config_path = os.path.join('conf', 'local_connection_parameters.json')\nlogs_path = 'logs.json'\n\n# =============================================================================\n# Check that we are selecting either by project_id or by display name\n# =============================================================================\nassert int(display_name is None) + int(project_id is None) == 1\n\n# =============================================================================\n# Define how to connect to API\n# =============================================================================\nconn_params = json.load(open(connection_config_path))\nPROTOCOL = conn_params['PROTOCOL']\nHOST = conn_params['HOST']\nPRINT = conn_params['PRINT']\nPRINT_CHAR_LIMIT = conn_params['PRINT_CHAR_LIMIT']\n\nc = APIConnection(PROTOCOL, HOST, PRINT, PRINT_CHAR_LIMIT)\n\n# =============================================================================\n# Load logs\n# =============================================================================\nif os.path.isfile(logs_path):\n logs = json.load(open(logs_path))\nelse:\n logs = dict()\n\n# =============================================================================\n# Delete project with same display_name or project id\n# =============================================================================\nif display_name is not None:\n project_id = logs[display_name]\n \nurl_to_append = '/api/delete/normalize/{0}'.format(project_id)\nresp = c.get_resp(url_to_append)\n \n# =============================================================================\n# Remove old project from logs if present\n# =============================================================================\nif display_name is None:\n display_name = [key for key, value in logs.items() if value==project_id]\n if display_name:\n assert len(display_name) == 1\n display_name = display_name[0]\n\nif display_name:\n del logs[display_name]\n with open(logs_path, 'w') as w:\n json.dump(logs, w)","sub_path":"merge_machine/scripts/delete_referential.py","file_name":"delete_referential.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"381571239","text":"import sys\ninput = sys.stdin.readline\n\n\ndef DFS(si):\n global answer\n\n if len(stack) > 0:\n if sum(stack) == S:\n answer += 1\n\n for i in range(si, N):\n if not visit[i]:\n visit[i] = True\n stack.append(seq[i])\n DFS(i + 1)\n visit[i] = False\n stack.pop()\n\n\nN, S = map(int, input().split())\nseq = list(map(int, input().split()))\nvisit = [False] * N\nstack = []\nanswer = 0\n\nDFS(0)\n\nprint(answer)\n","sub_path":"BaekjoonOnlineJudge/1182/1182.py","file_name":"1182.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"578489573","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Transmission Error Fix\n# (fixtransmission.py)\n# \n# Copyright 2017 Ruslan Rotaru \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\nimport time\nimport subprocess\n\ndef listTorrents():\n try:\n commandResult = subprocess.check_output([\"transmission-remote\",\"--auth\", \"transmission:transmission\", \"-l\"])\n except CalledProcessError:\n dateAndTime = time.strftime(\"%H:%M:%S\") + \" \" + time.strftime(\"%d/%m/%Y\")\n print(dateAndTime + \" ERROR: something went wrong checking the torrents listing.\") \n return -1\n return commandResult\n\ndef getTorrentInfo(item):\n try:\n commandResult = subprocess.check_output([\"transmission-remote\",\"--auth\", \"transmission:transmission\", \"-t\", item, \"-i\"])\n except CalledProcessError:\n dateAndTime = time.strftime(\"%H:%M:%S\") + \" \" + time.strftime(\"%d/%m/%Y\")\n print(dateAndTime + \" ERROR: something went wrong checking the torrent info.\") \n return -1\n return commandResult\n\ndef removeTorrent(item):\n try:\n commandResult = subprocess.check_output([\"transmission-remote\",\"--auth\", \"transmission:transmission\", \"-t\", item, \"--remove\"])\n except CalledProcessError:\n dateAndTime = time.strftime(\"%H:%M:%S\") + \" \" + time.strftime(\"%d/%m/%Y\")\n print(dateAndTime + \" ERROR: something went wrong removing torrent.\") \n return -1\n return commandResult\n\ndef addTorrent(magnet):\n try:\n commandResult = subprocess.check_output([\"transmission-remote\",\"--auth\", \"transmission:transmission\", \"--add\", magnet])\n except CalledProcessError:\n dateAndTime = time.strftime(\"%H:%M:%S\") + \" \" + time.strftime(\"%d/%m/%Y\")\n print(dateAndTime + \" ERROR: something went wrong adding torrent.\") \n return -1\n return commandResult\n\n\ndef sendEmail(msg):\n try:\n ps = subprocess.Popen(('echo', msg), stdout=subprocess.PIPE)\n output = subprocess.check_output(('mail', '-s', 'Torrents Fixed', \"rotarur.adverts@gmail.com\"), stdin=ps.stdout)\n ps.wait()\n except OSError:\n dateAndTime = time.strftime(\"%H:%M:%S\") + \" \" + time.strftime(\"%d/%m/%Y\")\n print(dateAndTime + \" ERROR: something went wrong with 'mail'. \" + output)\n return -1\n \ndef main():\n\n splitResult = listTorrents().split(\"\\n\")\n\n # Remove items which are just empty strings\n while True:\n try:\n splitResult.remove(\"\")\n except ValueError:\n # Insert error message here\n break\n\n # Remove first and last items so the list only contains torrent info.\n # If the length of the list is smaller than 2, just exit.\n if len(splitResult) > 2:\n splitResult.pop(0)\n splitResult.pop()\n else:\n return 0\n\n # For the remaining items, check if any of them does not contain '100%',\n # if there is an error string add them to a error torrents list.\n errorTorrents = []\n for item in splitResult:\n if not \"100%\" in item:\n torrentId = item.split()[0].rstrip(\"*\")\n torrent = getTorrentInfo(torrentId)\n if \"Error\" in torrent:\n torrent = torrent.split()\n for item in torrent:\n if \"magnet\" in item:\n errorTorrents.append((torrentId, item))\n\n # For each torrentId in the Torrents list, save the magnet link\n # remove the torrent and readd it from magnet link\n emailMessage = \"The following torrents were readded: \\n\"\n torrentsFixed = False\n \n for item in errorTorrents:\n commandResultRemove = removeTorrent(item[0])\n commandAdd = addTorrent(item[1])\n emailMessage += commandResultRemove.rstrip() + \", Id = \" + item[0] + \", Torrent Name = \" + item[1] + \"\\n\" \n if \"success\" in commandResultRemove:\n torrentsFixed = True\n\n if torrentsFixed == True:\n sendEmail(emailMessage)\n \n return 0\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"fixtransmission.py","file_name":"fixtransmission.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"392558320","text":"def template(model):\n # include model simulations\n rel = EmptyLine()\n rel += Header(\"Model simulations\", 2)\n #if reservoir_model and model.model_runs:\n\n fontsize = 20\n\n model_runs = model.model_runs\n for i, mr in enumerate(model_runs):\n n = mr.nr_pools\n\n comb = model.model_run_combinations[i]\n if comb['par_set'] is not None:\n par_set_names = comb['par_set']['values']\n par_set = {model.symbols_by_type[name]: value for name, value in par_set_names.items()}\n else:\n par_set=dict()\n\n run_data_str_basis = \"Initial values: \" + comb['IV']['table_head']\n \n if comb['par_set'] is not None:\n run_data_str_basis += \", Parameter set: \" + comb['par_set']['table_head']\n\n # plot solutions\n fig = plt.figure(figsize=(7,3*len(model.state_vector[\"expr\"])), tight_layout=True) \n #time_unit = model.df.get_by_cond('unit', 'name', model.time_symbol['name'])\n #units = [model.df.get_by_cond('unit', 'name', sv.name) for sv in model.state_vector['expr']]\n #mr.plot_sols(fig, time_unit, units)\n mr.plot_solutions(fig, fontsize=fontsize)\n# fimm-30.01.2018 mr.plot_sols(fig)\n\n label = \"Model run \" + str(i+1) + \" - solutions\"\n run_data_str = run_data_str_basis + \", Time step: \" + str(comb['run_time']['step_size'])\n rel += MatplotlibFigure(fig, label, run_data_str)\n \n return rel\n","sub_path":"bgc_md/report_templates/single_model/StatevariablesAsFunctionsOfTime.py","file_name":"StatevariablesAsFunctionsOfTime.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"556855407","text":"from django.contrib.auth.forms import UserCreationForm\nfrom django import forms\nfrom user.models import User\n\nclass UserRegisterForm(UserCreationForm):\n username = forms.CharField(label = \"Username\", required = True)\n email = forms.EmailField(label = \"Email\",required = True)\n first_name = forms.CharField(label = \"First name\",required = False)\n last_name = forms.CharField(label = \"Last name\",required = False)\n gender = forms.CharField(label = \"Gender\", required = True)\n avatar = forms.ImageField(label = \"Avatar\", required = False)\n tracking_id = forms.CharField(label = \"Traffic Id\", required = False)\n utm_source = forms.CharField(label = \"UTM SRC\", required = False)\n\n class Meta:\n model = User\n fields = ( \"email\", )\n\n def save(self, commit = True):\n user = super(UserRegisterForm, self).save(commit = False)\n user.first_name = self.cleaned_data[\"first_name\"]\n user.last_name = self.cleaned_data[\"last_name\"]\n user.email = self.cleaned_data[\"email\"].lower()\n user.username = self.cleaned_data[\"username\"].lower()\n user.gender = self.cleaned_data[\"gender\"]\n user.avatar = self.cleaned_data[\"avatar\"]\n user.tracking_id = self.cleaned_data[\"tracking_id\"]\n user.utm_source = self.cleaned_data[\"utm_source\"]\n\n\n if commit:\n user.save()\n return user\n\n def clean_email(self):\n data = self.cleaned_data['email'].lower()\n if User.objects.filter(email=data).exists():\n raise forms.ValidationError(\"This email already used\")\n return data\n\n\n def clean_username(self):\n data = self.cleaned_data['username'].lower()\n print(data)\n if not data :\n raise forms.ValidationError(\"Username cannot be empty\")\n\n if data.find(\" \") != -1 :\n raise forms.ValidationError(\"Username cannot contain spaces\")\n\n if User.objects.filter(username=data).exists():\n raise forms.ValidationError(\"This username already used\")\n return data\n\n\n\nclass ImageUploadForm(forms.Form):\n image = forms.ImageField()","sub_path":"user/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"4308049","text":"import sqlite3\nconn = sqlite3.connect(\"bmtc.db\")\nc = conn.cursor()\n\nc.execute(\"SELECT * FROM fares\")\ndata = c.fetchall()\nprint(\"Stage, Adults, Child, Senior\")\nfor row in data:\n print(row)\n\nconn.commit()\n\nc.close()\nconn.close()\n","sub_path":"fare_db.py","file_name":"fare_db.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"341899018","text":"##########################################################################\n# This is a class definition for a z_Slice\n# Author: Chris McCormick\n# Date: Summer 2016\n##########################################################################\nfrom copy import deepcopy\nfrom classes.atom_Type import atom_Type\nfrom global_Vars import *\n\nclass z_Slice(object):\n slice_Depth = SLICE_SIZE # defined in global_Vars.py\n \n def __init__(self, slice_ID, bottom, x_Len, y_Len, type_List, atom_Groups):\n self.slice_ID = slice_ID\n self.bottom_Bound = bottom # bottom bound of slice in nm\n self.volume = self.slice_Depth * x_Len * y_Len # nm Cubed\n self.atom_Types = []\n self.atom_Groups = deepcopy(atom_Groups) # each slice gets it's own list of atom groups \n \n # goes through all of the atoms in a frame, and builds a list of atom types that exist in that slice.\n # As it does this, it also keeps a running total of the mass of that atom type in that slice.\n def load_Slice_Masses(self, my_Frame):\n frame = my_Frame\n \n for molecule in frame.molecules:\n for atom in molecule.atoms:\n if atom.position[Z] >= self.bottom_Bound and atom.position[Z] < self.bottom_Bound + self.slice_Depth:\n add_Me = True\n if not self.atom_Types:\n new_A_Type = atom_Type()\n new_A_Type.molecule_Name = molecule.molecule_Name\n new_A_Type.type_Name = molecule.molecule_Name\n new_A_Type.atom_Name = atom.atom_Name\n new_A_Type.type_Name = new_A_Type.type_Name + '-' + atom.atom_Name\n self.atom_Types.append(new_A_Type)\n self.atom_Types[-1].tot_Mass_In_Slice = self.atom_Types[-1].tot_Mass_In_Slice + atom.atom_Mass\n add_Me = False\n else:\n for i in range(len(self.atom_Types)):\n if molecule.molecule_Name == self.atom_Types[i].molecule_Name and atom.atom_Name == self.atom_Types[i].atom_Name:\n self.atom_Types[i].tot_Mass_In_Slice = self.atom_Types[i].tot_Mass_In_Slice + atom.atom_Mass\n add_Me = False\n if add_Me == True:\n new_A_Type = atom_Type()\n new_A_Type.molecule_Name = molecule.molecule_Name\n new_A_Type.type_Name = molecule.molecule_Name\n new_A_Type.atom_Name = atom.atom_Name\n new_A_Type.type_Name = new_A_Type.type_Name + '-' + atom.atom_Name\n self.atom_Types.append(new_A_Type)\n self.atom_Types[-1].tot_Mass_In_Slice = self.atom_Types[-1].tot_Mass_In_Slice + atom.atom_Mass\n\n # calls the calculate density function for each atom type that exists in a given slice\n def calculate_Densities(self):\n for a_Type in self.atom_Types:\n a_Type.calculate_Density(self.volume)\n\n # returns the density in this slice of the atom type passed in. If the atom type does not exist in this\n # slice, return 0.\n def get_Density_Or_Zero(self, check_Type):\n check_Type_Name = check_Type\n if not self.atom_Types:\n return 0\n for each_Type in self.atom_Types:\n if check_Type_Name == each_Type.type_Name:\n return each_Type.density_In_Slice\n return 0","sub_path":"classes/z_Slice.py","file_name":"z_Slice.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"23761953","text":"\"\"\"\r\nProspective employers please read:\r\n\r\nThis code was written to test different depths of artificial neural\r\nnetworks and different sizes for the weight matrices. It was originally\r\nrun on a Google Cloud virtual machine and will not run locally unless\r\nPyTorch is installed. Also, the data is local to my computer so it will\r\nnot load properly.\r\n\r\nThe purpose of this neural network was to classify grayscale images of\r\nclothing.\r\n\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom random import randint\r\n\r\n# Load datasets. Training set is 50,000 labeled images; test set is 10,000 images\r\ntrain_data=torch.load('./Data/train_data.pt')\r\ntrain_label=torch.load('./Data/train_label.pt')\r\ntest_data=torch.load('./Data/test_data.pt')\r\ntest_label=torch.load('./Data/test_label.pt')\r\nprint(train_data.size())\r\n\r\n# Define a two layer, three layer, and four layer neural net\r\nclass two_layer_net(nn.Module):\r\n def __init__(self, input_size, hidden1, output_size):\r\n super().__init__()\r\n self.linear1 = nn.Linear(input_size, hidden1, bias=True)\r\n self.linear2 = nn.Linear(hidden1, output_size, bias=True)\r\n\r\n def forward(self, x):\r\n a = self.linear1(x)\r\n b = F.relu(a)\r\n scores = self.linear2(b)\r\n return scores\r\n\r\nclass three_layer_net(nn.Module):\r\n def __init__(self, input_size, hidden1, hidden2, output_size):\r\n super().__init__()\r\n self.linear1 = nn.Linear(input_size, hidden1, bias=True)\r\n self.linear2 = nn.Linear(hidden1, hidden2, bias=True)\r\n self.linear3 = nn.Linear(hidden2, output_size, bias=True)\r\n\r\n def forward(self, x):\r\n a = self.linear1(x)\r\n b = F.relu(a)\r\n c = self.linear2(b)\r\n d = F.relu(c)\r\n scores = self.linear3(d)\r\n return scores\r\n\r\nclass four_layer_net(nn.Module):\r\n def __init__(self, input_size, hidden1, hidden2, hidden3, output_size):\r\n super().__init__()\r\n self.linear1 = nn.Linear(input_size, hidden1, bias=True)\r\n self.linear2 = nn.Linear(hidden1, hidden2, bias=True)\r\n self.linear3 = nn.Linear(hidden2, hidden3, bias=True)\r\n self.linear4 = nn.Linear(hidden3, output_size, bias=True)\r\n\r\n def forward(self, x):\r\n a = self.linear1(x)\r\n b = F.relu(a)\r\n c = self.linear2(b)\r\n d = F.relu(c)\r\n e = self.linear3(d)\r\n f = F.relu(e)\r\n scores = self.linear4(f)\r\n return scores\r\n\r\nprint(train_data.size())\r\n\r\n# Define function for tracking error of network\r\ndef get_error(scores, labels):\r\n \"\"\"\r\n Will take the output of the network (scores; a tensor) and what\r\n the network should have output (labels; also a tensor) and compute\r\n the error for a specific batch.\r\n \"\"\"\r\n bs = scores.size(0) # 'bs' stands for 'batch size'\r\n predicted_labels = scores.argmax(dim = 1) # Tensor with 'bs' entries\r\n indicator = (predicted_labels == labels) # Tensor containing 'True' for each success\r\n num_matches = indicator.sum().item()\r\n return 1 - (num_matches / bs)\r\n\r\n# Now we will train the neural net and test different weights\r\nbs = 50\r\nlearning_rates = [0.05, 0.1, 0.15, 0.2]\r\nweights = [50, 100, 150, 200]\r\ncriterion = nn.CrossEntropyLoss()\r\n\r\nfor lr in learning_rates:\r\n for weight in weights:\r\n\r\n # Initialize all networks\r\n net_2 = two_layer_net(784, weight, 10)\r\n net_3 = three_layer_net(784, weight, weight, 10)\r\n net_4 = four_layer_net(784, weight, weight, weight, 10)\r\n two_layer_optimizer = optim.SGD(net_2.parameters(), lr=lr)\r\n three_layer_optimizer = optim.SGD(net_3.parameters(), lr=lr)\r\n four_layer_optimizer = optim.SGD(net_4.parameters(), lr=lr)\r\n\r\n # Print current setup as a header\r\n print('==========')\r\n print('Weights: ', weight, '\\t Learning Rate: ', lr)\r\n print('==========')\r\n print('')\r\n\r\n for epoch in range(30):\r\n\r\n # Initialize empty variables for tracking purposes\r\n num_batches = 0\r\n running_loss_2 = 0\r\n running_loss_3 = 0\r\n running_loss_4 = 0\r\n running_error_2 = 0\r\n running_error_3 = 0\r\n running_error_4 = 0\r\n\r\n # Randomly choose the order to pull images for training\r\n shuffled_indices = torch.randperm(60000)\r\n\r\n # Loop through entire training set in batches\r\n for count in range(0, 60000, bs):\r\n\r\n # Clear optimizer gradient before each iteration\r\n two_layer_optimizer.zero_grad()\r\n three_layer_optimizer.zero_grad()\r\n four_layer_optimizer.zero_grad()\r\n\r\n # Pull batch of images from training data\r\n indices = shuffled_indices[count : count + bs]\r\n batch_data = train_data[indices]\r\n batch_label = train_label[indices]\r\n\r\n # Shape the batch properly for processing\r\n inputs = batch_data.view(bs, 784)\r\n\r\n # Track all operations on inputs (so gradients\r\n # can be computed backwards later)\r\n inputs.requires_grad_(True)\r\n\r\n # Put batch through net\r\n two_layer_scores = net_2(inputs)\r\n three_layer_scores = net_3(inputs)\r\n four_layer_scores = net_4(inputs)\r\n\r\n # Compute the loss of the network on the batch\r\n two_layer_loss = criterion(two_layer_scores, batch_label)\r\n three_layer_loss = criterion(three_layer_scores, batch_label)\r\n four_layer_loss = criterion(four_layer_scores, batch_label)\r\n\r\n # Compute gradients backward\r\n two_layer_loss.backward()\r\n three_layer_loss.backward()\r\n four_layer_loss.backward()\r\n\r\n # Do one step of stochastic gradient descent\r\n two_layer_optimizer.step()\r\n three_layer_optimizer.step()\r\n four_layer_optimizer.step()\r\n\r\n # Now let's check the error and loss\r\n num_batches += 1\r\n\r\n\r\n\r\n with torch.no_grad():\r\n running_loss_2 += two_layer_loss.item()\r\n running_loss_3 += three_layer_loss.item()\r\n running_loss_4 += four_layer_loss.item()\r\n error_2 = get_error(two_layer_scores, batch_label)\r\n error_3 = get_error(three_layer_scores, batch_label)\r\n error_4 = get_error(four_layer_scores, batch_label)\r\n running_error_2 += error_2\r\n running_error_3 += error_3\r\n running_error_4 += error_4\r\n\r\n # At the end of 1 epoch, print error and loss\r\n total_loss_2 = running_loss_2 / num_batches\r\n total_loss_3 = running_loss_3 / num_batches\r\n total_loss_4 = running_loss_4 / num_batches\r\n total_error_2 = running_error_2 / num_batches\r\n total_error_3 = running_error_3 / num_batches\r\n total_error_4 = running_error_4 / num_batches\r\n\r\n print('Epoch: ', epoch)\r\n print('|Two Layer Net|', '\\t Loss: ', total_loss_2, '\\t Error (%): ', total_error_2*100)\r\n print('|Three Layer Net|', '\\t Loss: ', total_loss_3, '\\t Error (%): ', total_error_3*100)\r\n print('|Four Layer Net|', '\\t Loss: ', total_loss_4, '\\t Error (%): ', total_error_4*100)\r\n print('')\r\n","sub_path":"code_sample.py","file_name":"code_sample.py","file_ext":"py","file_size_in_byte":7538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"610526288","text":"\"\"\"\nCreated on Tue Aug 10 15:02:57 2021\n@author: Andres Sandino\ne-mail: asandino@unal.edu.co\n\n\"\"\"\n\nimport tensorflow as tf\n#import tensorflow.keras as keras\n\nimport os\nfrom os import listdir\nimport math\nimport numpy as np\n\nimport pandas as pd\n\nfrom tensorflow.keras.metrics import BinaryAccuracy\nfrom tensorflow.keras.metrics import FalseNegatives\n\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import Sequential,datasets, layers, models\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint,LearningRateScheduler\nfrom tensorflow.keras.optimizers import Adam\n\nprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n\n#%%\n#\n#./data/datainfo.csv\n\n\ndataframe = pd.read_csv(\"/home/usuario/Documentos/GitHub/DL_Project/ChexNet/data/datainfo.csv\") \n\ndataframetest = pd.read_csv(\"/home/usuario/Descargas/chexnet-master/experiments/DenseNet121/DenseNet121/train.csv\")\n\ntraindata = dataframe.iloc[0:1000][:]\nvaliddata = dataframe.iloc[10000:12000][:]\ntestdata = dataframe.iloc[100000:101000][:]\n\ntestindex = dataframetest.iloc[:,0]\ntestdata2 = dataframetest.iloc[:,3:]\n\nfin=pd.concat([testindex,testdata2],axis=1)\n\n#partir en train-val\n#%%\ndef transformar():\n def transform_batch_images(batch_x):\n batch_x = np.asarray(batch_x/255)\n imagenet_mean = np.array([0.485, 0.456, 0.406])\n imagenet_std = np.array([0.229, 0.224, 0.225])\n batch_x = (batch_x - imagenet_mean) / imagenet_std\n return batch_x\n return transform_batch_images\n\n#%%\n#classes = dataframe.columns[1:].values.tolist()\n\nthoraxlabels = [\"Atelectasis\",\"Cardiomegaly\",\n \"Effusion\",\"Infiltration\",\n \"Mass\",\"Nodule\",\"Pneumonia\",\n \"Pneumothorax\",\"Consolidation\",\n \"Edema\",\"Emphysema\",\"Fibrosis\",\n \"Pleural_Thickening\",\"Hernia\"]\n\nclasses = ['A1','A2','A3','A4','A5','A6','A7','A8','A9','A10','A11','A12','A13','A14']\n\nbatch_size = 32\ncolor_mode = 'rgb' # \"grayscale\", \"rgb\", \"rgba\"\nimg_directory_path = \"/home/usuario/Descargas/images/\"\n\ntarget_size = (224, 224)\n\n#train_datagen = ImageDataGenerator(rescale=1./255,validation_split=validation_split)\n#valid_datagen = ImageDataGenerator(rescale=1./255,validation_split=validation_split)\ntrain_datagen = ImageDataGenerator(preprocessing_function=transformar(),\n horizontal_flip=True\n )\n #featurewise_std_normalization=True,\n #horizontal_flip=True)\nvalid_datagen = ImageDataGenerator(preprocessing_function=transformar(),\n \n \n )\n #featurewise_center=True, \n #featurewise_std_normalization=True\n \n\n\ntest_datagen = ImageDataGenerator(preprocessing_function=transformar())\n #featurewise_center=True, \n # featurewise_std_normalization=True,\n # horizontal_flip=True)\n\n# test_datagen = ImageDataGenerator(\n# featurewise_center=True, \n# featurewise_std_normalization=True,\n \n# )\n\n#train_datagen = ImageDataGenerator(rescale=1./255,horizontal_flip=True)\n#valid_datagen = ImageDataGenerator(rescale=1./255)\n\n\n\ntrain_set = train_datagen.flow_from_dataframe(\n traindata,\n directory=img_directory_path,\n x_col=\"filename\",\n y_col=classes,\n class_mode=\"raw\",\n target_size=target_size,\n color_mode=color_mode,\n batch_size=batch_size,\n #subset='training',\n shuffle='False',\n seed=1,\n validate_filenames=True,\n )\n\n\nvalid_set = valid_datagen.flow_from_dataframe(\n validdata,\n directory=img_directory_path,\n x_col=\"filename\",\n y_col=classes,\n class_mode=\"raw\",\n target_size=target_size,\n color_mode=color_mode,\n batch_size=batch_size,\n #subset='validation',\n shuffle='False',\n seed=1,\n validate_filenames=True,\n )\n\n\ntest_set = test_datagen.flow_from_dataframe(\n fin,\n directory=img_directory_path,\n x_col=\"Image Index\",\n y_col=thoraxlabels,\n class_mode=\"raw\",\n target_size=target_size,\n color_mode=color_mode,\n batch_size=batch_size,\n #subset='training',\n shuffle='False',\n seed=1,\n validate_filenames=True,\n )\n\n\ntrain_steps=np.int16(train_set.samples//train_set.batch_size)\nvalid_steps=np.int16(valid_set.samples//test_set.batch_size)\ntest_steps=np.int16(test_set.samples//test_set.batch_size)\n\n#%%\n\n# def createmodel():\n\n# model = Sequential()\n \n# input_shape=(224,224,3)\n \n# model.add(tf.keras.applications.DenseNet121(include_top=True,\n# weights='/home/usuario/Descargas/weight.h5',\n# #weights='imagenet',\n# #weights=None,\n# input_tensor=None,\n# input_shape=(224, 224, 3),\n# pooling='avg',\n# classes=14,))\n \n# #model.add(Dense(14,activation='sigmoid'))\n# model.summary()\n# return model\n\n# model = createmodel()\n\n#%%\n\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input\n\n\ninput_shape = (224, 224, 3)\n\nimg_input = Input(shape=input_shape)\n\nmdl = tf.keras.applications.DenseNet121(include_top=False,\n #weights=None,\n weights='imagenet',\n #weights=None,\n input_tensor=img_input,\n input_shape=(224,224,3),\n pooling='avg',\n classes=14,)\n\n\nx = mdl.output\n # Last output layer is a dense connected layer with sigmoid activation according to the CheXNet paper\n#predictions = Dense(len(class_names), activation=\"sigmoid\", name=\"predictions\")(x)\npredictions = Dense(14, activation=\"sigmoid\", name=\"predictions\")(x)\n\nmodel = Model(inputs=img_input, outputs=predictions)\n#weights_path='/home/usuario/Descargas/weight_func.h5'\nweights_path='/home/usuario/Descargas/weight_func.h5'\nmodel.load_weights(weights_path)\n\n\n#%%\n#%%# from tensorflow.keras import Model\n# mdl = model.layers[0]\n# numlayers = len(mdl.layers)\n\n# SplitModel = Model(inputs=mdl.input,outputs=mdl.layers[numlayers-2].output)\n# input_img = Input(shape=(224,224,3))\n# SplitModelOut = SplitModel(input_img)\n\n# output = Dense(14,activation='sigmoid')(SplitModelOut)\n\n# model2 = Model(input_img,output)\n\n# model2.layers[1].trainable=False\n\n# model2.summary()\n\n\n#%%\n\n#model.load_weights('/home/usuario/Descargas/mymodel.h5')\n\n\n#%%\n\ndef step_decay(epoch):\n\tinitial_lrate = 1e-5\n\tdrop = 0.1\n\tepochs_drop = 20\n\tlrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))\n\treturn lrate\n\n#%%\n\noptimizer = Adam(1e-4) # 1e-5\n\nBinaryCrossEnt=tf.keras.metrics.BinaryCrossentropy()\n\n\n# tf.keras.metrics.(\n# name=\"binary_accuracy\", dtype=None, threshold=0.5\n# )\n\n#nn=BinaryAccuracy(name=\"binary_accuracy\", dtype=None, threshold=0.5)\n#mm=FalseNegatives(name=\"fn_accuracy\",thresholds=0.5)\n\n\nmodel.compile(optimizer=optimizer, \n loss = 'binary_crossentropy', \n metrics=['accuracy'])\n#BinaryCrossEnt,\n\ncheckpoint_path = '/home/usuario/Descargas/modelo.h5'\nlr = LearningRateScheduler(step_decay)\nes = EarlyStopping(patience=20,mode='min', verbose=1)\nmc = ModelCheckpoint(checkpoint_path, \n monitor='val_loss', \n verbose=2 , \n save_best_only=True, \n mode='min')\n\n#%%\n\nhistory = model.fit(train_set,steps_per_epoch=train_steps, validation_data=valid_set,\n validation_steps=valid_steps,\n epochs=100,verbose=1,callbacks=[mc,lr])\n#callbacks=[mc,lr]\n\n#%%\n#model.save_weights('/home/usuario/Descargas/mymodel.h5')\n#model.save_weights('mymodel13082021.h5')\n\n#%%\n\nkk=[]\n\nimport matplotlib.pyplot as plt\n\nfor i in range(3,10):\n caso=i\n batch=2\n \n imgbatch = train_set[batch][0]\n \n truelabelbatch=train_set[batch][1]\n truelabel = truelabelbatch[caso]\n kk.append(truelabel)\n \n im = imgbatch[caso,:,:,:]\n\n # imagenet_mean = np.array([0.485,0.456,0.406])\n # imagenet_std = np.array([0.229,0.224,0.225])\n \n # im2 = (im-imagenet_mean)/imagenet_std\n\n #im = im2\n plt.show()\n plt.imshow(im[:,:,0],cmap='gray')\n \n im3=np.expand_dims(im,axis=0)\n \n prediction = model.predict(im3)\n prediction2 = np.squeeze(prediction,axis=0)\n #pre = np.round(prediction>0.5)\n \n \n print(\"case: \"+np.str(i))\n print(\"true\")\n print(truelabel)\n print(\"pred\")\n print(np.int16(np.round(prediction2)))\n \n \n \n#%%\n\nthoraxlabels = [\"Atelectasis\",\"Cardiomegaly\",\n \"Effusion\",\"Infiltration\",\n \"Mass\",\"Nodule\",\"Pneumonia\",\n \"Pneumothorax\",\"Consolidation\",\n \"Edema\",\"Emphysema\",\"Fibrosis\",\n \"Pleural_Thickening\",\"Hernia\"]\n\n\n\n#%%\n# kk=[]\n\n# for i in range(10):\n# zz=test_set[i][1]\n# kk.append(zz)\n\n#%%\n\npredictions=model.predict(test_set,test_steps,verbose=1)\n\n#%%\n\n\nprediction_mat=predictions\n\ntruelabel=testdata2.iloc[:,2:]\ntruelabel_mat=truelabel.to_numpy()\n\n\n#%%\nfrom sklearn.metrics import roc_curve, confusion_matrix, roc_auc_score, f1_score\n\n\ntruevector=truelabel_mat[:,2]\npredictvector=prediction_mat[:,2]\n\nauc = roc_auc_score(truevector,predictvector)\n\nfpr,tpr,thresholds = roc_curve(truevector,predictvector)\n\nplt.plot(fpr,tpr)\n\nss=f1_score(truevector, np.round(predictvector>0.5), average='weighted')\n\ntn, fp, fn, tp=confusion_matrix(truevector, np.round(predictvector>0.5)).ravel()\n\n\n\n#%%\n\n# from tensorflow.keras.models import Model\n# from tensorflow.keras.layers import Input\n\n\n# input_shape = (224, 224, 3)\n\n# img_input = Input(shape=input_shape)\n\n# mdl = tf.keras.applications.DenseNet121(include_top=False,\n# weights=None,\n# #weights='imagenet',\n# #weights=None,\n# input_tensor=img_input,\n# input_shape=(224,224,3),\n# pooling='avg',\n# classes=14,)\n\n\n# x = mdl.output\n# # Last output layer is a dense connected layer with sigmoid activation according to the CheXNet paper\n# predictions = Dense(len(class_names), activation=\"sigmoid\", name=\"predictions\")(x)\n\n# model = Model(inputs=img_input, outputs=predictions)\n# weights_path='/home/usuario/Descargas/weight.h5'\n# model.load_weights(weights_path)\n\n\n#%%\n# p=10\n# aa=train_set[p][0]\n# bb=train_set[p][1]\n\n\n# #%%\n# aa=test_set[p][0]\n# bb=test_set[p][1]\n# truelabel=bb[0]\n\n\n\n# jj=aa[0,:,:,:]\n# plt.imshow(jj)\n\n\n\n\n#print(ll)\n\na=0;\n","sub_path":"ChexNet/ChexNet.py","file_name":"ChexNet.py","file_ext":"py","file_size_in_byte":11523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"597437161","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport socket\r\nimport threading\r\n\r\n\r\n# 创建socket\tAF_INET指定使用IPv4协议,SOCK_STREAM指定使用面向流的TCP协议\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \r\ns.bind(('192.168.83.130', 8000))\t # 绑定地址和端口\r\ns.listen(5)\t#最多监听5个客户端\r\n\r\ndef fun(sock, addr):\r\n\tprint('Accept new connection from {}'.format(addr))\r\n\tsock.send('Hello!'.encode())\t# 向客户端发送数据\r\n\twhile True:\r\n\t\tdata = sock.recv(1024)\t\t# 每次最多接收1024b(1kb)\r\n\t\tif data == 'exit' or not data:\r\n\t\t\tbreak\r\n\t\tsock.send('hello,{}'.format(data).encode())\t# 向客户端发送数据\r\n\tsock.close()\r\n\tprint('Connection closed {}'.format(addr))\r\n\r\nprint('Waiting for connection...')\r\nwhile True:\r\n\tsock, addr = s.accept()\t# 等待连接,返回socket对象和请求连接的客户端地址\r\n\t# 创建新线程(或进程)来处理TCP连接\r\n\tt = threading.Thread(target=fun, args=(sock, addr))\r\n\tt.start()# 启动线程\r\n\r\n\r\n\r\n\r\n","sub_path":"10_socket/tcp/tcpserver.py","file_name":"tcpserver.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"256364715","text":"# ========================================================================\n# Copyright (c) 2015 The University of Washington\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========================================================================\n#\n\n#\n# IAM messaging tools - DAO impl - AWS interface\n#\n\nimport re\n\n\n# AWS interface classes \n#from boto3.data.sqs.message import RawMessage\n#import boto3\n#from boto3 import Session\nimport boto\nfrom boto.sqs.message import RawMessage\n\nimport json\n\n# import datetime\n# import dateutil.parser\n# import base64\n# import string\n# import time\n# import re\n# import os.path\nfrom sys import exit\n# import signal\nfrom copy import deepcopy\n\nfrom messagetools.iam_message import encode_message\nfrom messagetools.iam_message import decode_message\nfrom messagetools.dao_implementation.mock import get_mockdata_message\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass File(object):\n\n def __init__(self, conf):\n self._conf = conf\n self._event_no = 0\n\n def recv_message(self):\n message = get_mockdata_message('aws', self._conf, self._event_no)\n self._event_no += 1\n return message\n \n def recv_and_process(self, handler, max=1):\n ntot = 0\n nvalid = 0\n logger = logging.getLogger(__name__)\n\n logger.debug('recv and proc: no=%d, max=%d' % (self._event_no, max))\n for n in range(0,max):\n message = get_mockdata_message('aws', self._conf, self._event_no)\n \n if message==None: \n break\n self._event_no += 1\n ret = handler(message)\n if ret:\n nvalid += 1\n ntot += 1\n return (ntot, nvalid)\n \n \n\nclass Live(object):\n\n def __init__(self, conf):\n self._conf = conf\n #boto3 testing\n #self.session = Session(aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'], region_name=self._conf['REGION_NAME'])\n \n def send_message(self, msg, context, cryptid, signid):\n sns_connection = boto3.connect_sns(aws_access_key_id=self._conf['SNS_KEYID'], aws_secret_access_key=self._conf['SNS_KEY'])\n b64msg = encode_message(msg, context, cryptid, signid)\n sns_connection.publish(self._conf['SNS_ARN'], b64msg, 'iam-message')\n\n\n def get_all_queues(self):\n sqs_connection = boto.connect_sqs(aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'])\n queues = sqs_connection.get_all_queues()\n return queues\n \n def get_queue(self):\n #boto2\n #sqs_connection = boto3.connect_sqs(aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'])\n #boto3\n #sqs_connection = boto3.client('sqs', aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'])\n #sqs_connection = self.session.client('sqs')\n # sqs_connection = self.session.resource('aws/sqs')\n #queue_url = sqs_connection.get_queue_url(QueueName=self._conf['SQS_QUEUE'])\n #queue = sqs_connection.receive_message(QueueUrl=queue_url['QueueUrl'])\n sqs_connection = boto.connect_sqs(aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'])\n queue = sqs_connection.get_queue(self._conf['SQS_QUEUE'])\n if queue==None:\n logger.critical(\"Could not connect to '%s'!\" % (self._conf['SQS_QUEUE']))\n return queue\n #queue.set_message_class(RawMessage)\n logger.debug('%r messages in the queue' % (queue.count()))\n return queue\n \n \n def create_topic(self, topic_name):\n sns_connection = boto.connect_sns(aws_access_key_id=self._conf['SNS_KEYID'], aws_secret_access_key=self._conf['SNS_KEY'])\n if sns_connection==None:\n loger.error('AWS sns connect failed')\n return none\n ret = sns_connection.create_topic(topic_name)\n if ret==None:\n log.error('AWS topic create failed for %s' % topic_name)\n return none\n return ret\n\n\n def create_queue(self, queue_name):\n sqs_connection = boto.connect_sqs(aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'])\n if sqs_connection==None:\n loger.error('AWS sqs connect failed')\n return none\n ret = sqs_connection.create_queue(queue_name)\n if ret==None:\n logger.error('AWS queue create failed for %s' % queue_name)\n return ret\n\n\n def recv_message(self):\n sqs_queue = self.get_queue()\n sqs_msg = sqs_queue.read()\n if sqs_msg == None:\n return None\n #no implicit byte/string conversions in python3\n sqsmsg = json.loads(sqs_msg.get_body().encode('utf8','ignore').decode('utf-8','ignore'))\n msg = decode_message(sqsmsg['Message'])\n logger.debug('live recv: [%s]' % json.dumps(msg))\n if msg != None:\n sqs_queue.delete_message(sqs_msg)\n return msg\n \n def recv_and_process(self, handler, max=1):\n sqs_queue = self.get_queue()\n msgs = sqs_queue.get_messages(max)\n nmsg = len(msgs)\n logger.info('live recv-proc: %d msg, max=%d' % (nmsg, max))\n nvalid = 0\n for m in msgs:\n \n #no implicit byte/string conversions in python3\n sqsmsg = json.loads(m.get_body().encode('utf8','ignore').decode('utf-8','ignore'))\n msg = decode_message(sqsmsg['Message'])\n \n if msg==None:\n sqs_queue.delete_message(m)\n continue\n nvalid += 1\n ret = handler(msg)\n if ret:\n sqs_queue.delete_message(m)\n return (nmsg, nvalid)\n \n def subscribe_queue(self, topic_name, queue_name):\n sns_connection = boto.connect_sns(aws_access_key_id=self._conf['SNS_KEYID'], aws_secret_access_key=self._conf['SNS_KEY'])\n sqs_connection = boto.connect_sqs(aws_access_key_id=self._conf['SQS_KEYID'], aws_secret_access_key=self._conf['SQS_KEY'])\n queue = sqs_connection.get_queue(queue_name)\n arn = self._conf['SNS_ARNROOT'] + topic_name\n sns_connection.subscribe_sqs_queue(arn, queue)\n\n def purge_queue(self):\n sqs_queue = self.get_queue()\n sqs_queue.purge()\n return\n\n \n\n","sub_path":"messagetools/dao_implementation/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"497077113","text":"import streamlit as st\nfrom tflite_runtime.interpreter import Interpreter \nfrom PIL import Image, ImageOps\nimport numpy as np\nimport requests\nimport os\nfrom io import BytesIO\nimport wget\n\n\ndef download_model():\n model_path = 'mymodel-2.tflite'\n if not os.path.exists(model_path):\n url = 'https://frenzy86.s3.eu-west-2.amazonaws.com/python/models/mymodel-2.tflite'\n filename = wget.download(url)\n else:\n print(\"Model is here.\")\n\ndef file_selector(folder_path='.'):\n filenames = os.listdir(folder_path)\n selected_filename = st.selectbox('Select a file inside images collections: ', filenames)\n return os.path.join(folder_path, selected_filename)\n\ndef main():\n #st.title(\"Eye Detection\")\n image_file = st.file_uploader(\"Upload Image\", type = ['jpg','png','jpeg'])\n download_model()\n model_path = 'mymodel-2.tflite'\n\n if image_file != None:\n image1 = Image.open(image_file)\n rgb_im = image1.convert('RGB') \n image = rgb_im.save(\"saved_image.jpg\")\n image_path = \"saved_image.jpg\"\n st.image(image1, width = 450)\n\n else:\n folder_path = './images/'\n filename = file_selector(folder_path=folder_path)\n st.write('You selected `%s`' % filename)\n image = Image.open(filename)\n image_path = filename\n print(image_path)\n st.image(image,width = 450)\n #st.image(image,use_column_width=True)\n\n if st.button(\"Make Prediction\"):\n download_model()\n img = Image.open(image_path)\n ## Load model\n interpreter = Interpreter(model_path)\n print(\"Model Loaded Successfully.\")\n ## Prepare the image\n #img = Image.open(\"img/test.jpg\")\n image = ImageOps.fit(img, (128,128),Image.ANTIALIAS)\n image = image.convert('RGB')\n image = np.asarray(image)\n image = (image.astype(np.float32) / 255.0)\n input_data = image[np.newaxis,...]\n\n ## run inference\n interpreter.allocate_tensors()\n inputdets = interpreter.get_input_details()\n outputdets = interpreter.get_output_details()\n interpreter.set_tensor(inputdets[0]['index'], input_data)\n interpreter.invoke()\n prediction = interpreter.get_tensor(outputdets[0]['index']) \n pred = prediction[0][0]\n print(pred) \n if(pred > 0.54):\n st.write(\"\"\"\n ## **Prediction:** Seems ok!!\n \"\"\"\n )\n else:\n st.write(\"\"\"\n ## **Prediction:** You have an high probability to be affected by Melanoma. Please consult a doctor as soon as possible.\n \"\"\"\n )\nif __name__ == '__main__':\n main()\n","sub_path":"pag1.py","file_name":"pag1.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"633359553","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\ntry:\n import cupy as xp\n\n gpu_available = True\nexcept ModuleNotFoundError:\n import numpy as xp\n\n gpu_available = False\n\nfrom eryn.moves import ReversibleJump\nfrom eryn.prior import PriorContainer\nfrom eryn.utils.utility import groups_from_inds\n\n__all__ = [\"PriorGenerate\"]\n\n\nclass BruteRejection(ReversibleJump):\n \"\"\"Generate Revesible-Jump proposals for GBs with brute-force rejection\n\n Will use gpu if template generator uses GPU.\n\n Args:\n priors (object): :class:`PriorContainer` object that has ``logpdf``\n and ``rvs`` methods.\n\n \"\"\"\n\n def __init__(\n self,\n gb,\n priors,\n num_brute,\n start_freq_ind,\n data_length,\n data,\n noise_factors,\n *args,\n waveform_kwargs={},\n parameter_transforms=None,\n search=False,\n **kwargs\n ):\n\n for key in priors:\n if not isinstance(priors[key], PriorContainer):\n raise ValueError(\"Priors need to be eryn.priors.PriorContainer object.\")\n self.priors = priors\n self.gb = gb\n\n # use gpu from template generator\n self.use_gpu = gb.use_gpu\n if self.use_gpu:\n self.xp = xp\n else:\n self.xp = np\n\n self.num_brute = num_brute\n self.start_freq_ind = start_freq_ind\n self.data_length = data_length\n self.waveform_kwargs = waveform_kwargs\n self.parameter_transforms = parameter_transforms\n self.noise_factors = self.xp.asarray(noise_factors).copy()\n self.noise_factors_list = [\n self.xp.asarray(noise_factors_i) for noise_factors_i in noise_factors\n ]\n self.data = self.xp.asarray(data).copy()\n self.data_list = [self.xp.asarray(data_i) for data_i in data]\n self.search = search\n\n super(BruteRejection, self).__init__(*args, **kwargs)\n\n def get_proposal(self, all_coords, all_inds, all_inds_for_change, random):\n \"\"\"Make a proposal\n\n Args:\n all_coords (dict): Keys are ``branch_names``. Values are\n np.ndarray[ntemps, nwalkers, nleaves_max, ndim]. These are the curent\n coordinates for all the walkers.\n all_inds (dict): Keys are ``branch_names``. Values are\n np.ndarray[ntemps, nwalkers, nleaves_max]. These are the boolean\n arrays marking which leaves are currently used within each walker.\n all_inds_for_change (dict): Keys are ``branch_names``. Values are\n dictionaries. These dictionaries have keys ``\"+1\"`` and ``\"-1\"``,\n indicating waklkers that are adding or removing a leafm respectively.\n The values for these dicts are ``int`` np.ndarray[..., 3]. The \"...\" indicates\n the number of walkers in all temperatures that fall under either adding\n or removing a leaf. The second dimension, 3, is the indexes into\n the three-dimensional arrays within ``all_inds`` of the specific leaf\n that is being added or removed from those leaves currently considered.\n random (object): Current random state of the sampler.\n\n Returns:\n tuple: Tuple containing proposal information.\n First entry is the new coordinates as a dictionary with keys\n as ``branch_names`` and values as\n ``double `` np.ndarray[ntemps, nwalkers, nleaves_max, ndim] containing\n proposed coordinates. Second entry is the new ``inds`` array with\n boolean values flipped for added or removed sources. Third entry\n is the factors associated with the\n proposal necessary for detailed balance. This is effectively\n any term in the detailed balance fraction. +log of factors if\n in the numerator. -log of factors if in the denominator.\n\n \"\"\"\n q = {}\n new_inds = {}\n factors = {}\n\n for i, (name, coords, inds, inds_for_change) in enumerate(\n zip(\n all_coords.keys(),\n all_coords.values(),\n all_inds.values(),\n all_inds_for_change.values(),\n )\n ):\n ntemps, nwalkers, nleaves_max, ndim = coords.shape\n new_inds[name] = inds.copy()\n q[name] = coords.copy()\n\n if i == 0:\n factors = np.zeros((ntemps, nwalkers))\n\n # adjust inds\n\n # adjust deaths from True -> False\n inds_here = tuple(inds_for_change[\"-1\"].T)\n new_inds[name][inds_here] = False\n\n # factor is -log q()\n current_priors = self.priors[name]\n factors[inds_here[:2]] += -1 * current_priors.logpdf(q[name][inds_here])\n\n # adjust births from False -> True\n inds_here = tuple(inds_for_change[\"+1\"].T)\n new_inds[name][inds_here] = True\n\n # add coordinates for new leaves\n current_priors = self.priors[name]\n inds_here = tuple(inds_for_change[\"+1\"].T)\n num_inds_change = len(inds_here[0])\n\n # group everything\n groups = groups_from_inds({name: inds[inds_here[:2]][None, :, :]})[name]\n # TODO: adjust to cupy\n\n templates = self.xp.zeros(\n (num_inds_change, 2, self.data_length), dtype=self.xp.complex128\n ) # 2 is channels\n\n params = coords[inds_here[:2]][inds[inds_here[:2]]]\n\n if self.parameter_transforms is not None:\n params_in = self.parameter_transforms.both_transforms(\n params.copy(), return_transpose=False\n )\n\n # TODO fix error with buffer\n self.gb.generate_global_template(\n params_in,\n groups,\n templates,\n # start_freq_ind=self.start_freq_ind,\n **{\n **self.waveform_kwargs,\n **{\"start_freq_ind\": self.start_freq_ind - self.gb.shift_ind},\n },\n )\n\n # data should not be whitened\n in_vals = (templates - self.data[None, :, :]) * self.noise_factors[\n None, :, :\n ]\n d_h_d_h = 4 * np.sum((in_vals.conj() * in_vals), axis=(1, 2))\n\n out_temp = np.zeros((num_inds_change, ndim))\n ll_out = np.zeros((num_inds_change,))\n log_prob_factors = np.zeros((num_inds_change,))\n # TODO: take out of loop later?\n for j in range(num_inds_change):\n prior_generated_points = current_priors.rvs(size=self.num_brute)\n data = [\n (\n (self.data_list[0] - templates[j, 0].copy())\n * self.noise_factors[0]\n ).copy(),\n (\n (self.data_list[1] - templates[j, 1].copy())\n * self.noise_factors[1]\n ).copy(),\n ]\n\n if self.parameter_transforms is not None:\n prior_generated_points_in = self.parameter_transforms.both_transforms(\n prior_generated_points.copy(), return_transpose=True\n )\n\n self.gb.d_d = d_h_d_h[j]\n\n ll = self.gb.get_ll(\n prior_generated_points_in,\n data,\n self.noise_factors_list,\n calc_d_d=False,\n phase_marginalize=False,\n **{\n **self.waveform_kwargs,\n **{\"start_freq_ind\": self.start_freq_ind - self.gb.shift_ind},\n },\n )\n\n if self.use_gpu:\n try:\n ll = ll.get()\n except AttributeError:\n pass\n\n probs = np.exp(ll - ll.max()) / np.sum(np.exp(ll - ll.max()))\n if self.search:\n # get max\n ind_keep = np.argmax(ll)\n\n else:\n # draw based on likelihood\n ind_keep = np.random.choice(np.arange(self.num_brute), p=probs,)\n\n ll_out[j] = ll[ind_keep]\n out_temp[j] = prior_generated_points[ind_keep].copy()\n log_prob_factors[j] = np.log(probs[ind_keep])\n\n q[name][inds_here] = out_temp\n\n # factor is +log q() for prior\n factors[inds_here[:2]] += +1 * current_priors.logpdf(q[name][inds_here])\n # add factor from likelihood draw\n factors[inds_here[:2]] += +1 * log_prob_factors\n return q, new_inds, factors\n","sub_path":"lisatools/sampling/moves/bruterejection.py","file_name":"bruterejection.py","file_ext":"py","file_size_in_byte":8865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"652595925","text":"import csv\nimport os\nimport json\nimport pickle\n\nos.chdir(\"d:\\\\PYTHON-IT-AK\\\\GitHub\\\\M-PT1-37-21\\\\Tasks\\\\Lappo_Tasks\\\\Class_task4\\\\\")\nprint(os.getcwd())\n\n\nwith open(\"d:\\\\PYTHON-IT-AK\\\\GitHub\\\\M-PT1-37-21\\\\Tasks\\\\Lappo_Tasks\\\\Class_task4\\\\cars.csv\", \"w\", newline='') as f:\n writer = csv.writer(f, delimiter=';')\n writer.writerow([\"Model\", \"Year\", \"Horsepower\", \"Engine size\"])\n writer.writerow([\"80 1.6 Specs\", \"1989\", \"69\", \"1595 cm3 (97.3 cu-in)\"])\n writer.writerow([\"80 1.9 E Specs\", \"1986\", \"113\", \"1847 cm3 (112.7 cu-in)\"])\n writer.writerow([\"80 2.0 16v Quatro Specs\", \"1990\", \"140\", \"1984 cm3 (121.1 cu-in)\"])\n\ncount=0\ncsv_rows=list()\ncsv_header=list()\n\n# with open(\"cars.csv\", \"r\", newline='') as f:\n# reader = csv.reader(f, delimiter=';')\n# for x in reader:\n# if count == 0:\n# csv_header=x\n# #csv_header.append(x)\n# else:\n# csv_rows.append(x)\n# count += 1\n\nsuper_dic=dict()\n\nwith open('cars.csv', newline='') as f:\n reader = csv.DictReader(f, delimiter=';')\n for x in reader: \n for key in x: \n try:\n super_dic[key] = super_dic[key] + ', '+ x[key] \n except KeyError: \n super_dic[key] = x[key] \n\nprint(super_dic)\n\n\nwith open('cars.json', 'w') as f:\n json.dump(super_dic, f)\n\n\nwith open('cars.json', \"r\") as f:\n json_load=json.load(f)\n\nwith open(\"pickle_file.txt\", \"wb\") as f:\n pickle.dump(json_load, f)","sub_path":"Tasks/Lappo_Tasks/Class_task4/CSV-JSON-PICKLE.py","file_name":"CSV-JSON-PICKLE.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"440490107","text":"import bpy\n\nobject = bpy.data.objects['Suzanne']\nradius = 2.0\nresolution = 30\nfile = open(\"/home/anon/Desktop/test.txt\", 'w')\n\nimport mathutils\nfrom mathutils import Vector\ndef pointInsideMesh(point,ob):\n axes = [ mathutils.Vector((1,0,0)) ]\n outside = False\n for axis in axes:\n mat = ob.matrix_world\n mat.invert()\n orig = mat*point\n count = 0\n while True:\n dd,location,normal,index = ob.ray_cast(orig,orig+axis*10000.0)\n if index == -1: break\n count += 1\n orig = location + axis*0.00001\n if count%2 == 0:\n outside = True\n break\n return not outside\n\nbla = radius/resolution\n\nout = \"\"\n\nfor z in range(-resolution, resolution):\n for y in range(-resolution, resolution):\n for x in range(-resolution, resolution):\n loc = Vector((x*bla, y*bla, z*bla))\n print(loc)\n if(pointInsideMesh(loc, object) == True):\n out += '1'\n else:\n out += '0'\n out += '\\n'\n out += '\\n'\nfile.write(out)\nfile.close()\n","sub_path":"src/blender_scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"67203634","text":"# -*- coding:utf-8 -*-\n# 定时器实例\nimport sched\nimport time\nschedule = sched.scheduler(time.time, time.sleep)\n\n\ndef func(inc=5):\n print(\"定时器执行......\")\n schedule.enter(inc, 0, func)\n schedule.run()\n\nif __name__ == '__main__':\n func(6)","sub_path":"Python/tasktest.py","file_name":"tasktest.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"369855578","text":"from __future__ import division\nfrom scipy import stats\nimport pymongo, pandas\n\n\nconnection = pymongo.MongoClient('localhost', 27017)\ncommunities = connection.database_names()\n\nfor db in [\"gender\", \"admin\", \"local\", \"visualizations\", \"results\"]:\n\tif db in communities:communities.remove(db)\n\nresults_db = connection['results']['question_1']\n\nfor community in communities:\n\n\tcommunity_db = connection[community]['statistics']\n\tcursor = community_db.find({'contributions_total': {'$gt':0} }, \n \t\t\t{u'_id': False, u'comments_total':True, u'gender':True,\n \t\t\t\tu'questions_total':True,u'answers_total':True, u'contributions_total':True})\n\n\tdf = pandas.DataFrame(list(cursor))\n\n\tmales = df[df['gender']=='Male']\n\tfemales = df[df['gender']=='Female']\n\n\tcommunity_stats = {\n\t\t'community': community,\n\t\t'size': females.count()[0] + males.count()[0],\n\n\t\t'women_comments_mean' : females['comments_total'].mean(),\n\t\t'men_comments_mean' : males['comments_total'].mean(),\n\t\t'comments_difference_mean': females['comments_total'].mean() - males['comments_total'].mean(),\n\t\t'women_comments_median' : females['comments_total'].median(),\n\t\t'men_comments_median' : males['comments_total'].median(),\n\t\t'comments_difference_median': females['comments_total'].median() - males['comments_total'].median(),\n\t\t'comments_pvalue': 2* stats.mannwhitneyu(females['comments_total'], males['comments_total'])[1],\n\n\t\t'women_questions_mean' : females['questions_total'].mean(),\n\t\t'men_questions_mean' : males['questions_total'].mean(),\n\t\t'questions_difference_mean': females['questions_total'].mean() - males['questions_total'].mean(),\n\t\t'women_questions_median' : females['questions_total'].median(),\n\t\t'men_questions_median' : males['questions_total'].median(),\n\t\t'questions_difference_median': females['questions_total'].median() - males['questions_total'].median(),\n\t\t'questions_pvalue': 2* stats.mannwhitneyu(females['questions_total'], males['questions_total'])[1],\n\n\t\t'women_answers_mean' : females['answers_total'].mean(),\n\t\t'men_answers_mean' : males['answers_total'].mean(),\n\t\t'answers_difference_mean': females['answers_total'].mean() - males['answers_total'].mean(),\n\t\t'women_answers_median' : females['answers_total'].median(),\n\t\t'men_answers_median' : males['answers_total'].median(),\n\t\t'answers_difference_median': females['answers_total'].median() - males['answers_total'].median(),\n\t\t'answers_pvalue': 2* stats.mannwhitneyu(females['answers_total'], males['answers_total'])[1],\n\n\t\t'women_contributions_mean' : females['contributions_total'].mean(),\n\t\t'men_contributions_mean' : males['contributions_total'].mean(),\n\t\t'contributions_difference_mean': females['contributions_total'].mean() - males['contributions_total'].mean(),\n\t\t'women_contributions_median' : females['contributions_total'].median(),\n\t\t'men_contributions_median' : males['contributions_total'].median(),\n\t\t'contributions_difference_median': females['contributions_total'].median() - males['contributions_total'].median(),\n\t\t'contributions_pvalue': 2* stats.mannwhitneyu(females['contributions_total'], males['contributions_total'])[1]\n\t}\n\n\tresults_db.insert( community_stats )\n","sub_path":"results/question_one.py","file_name":"question_one.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"212197772","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n# enable debugging\nimport cgitb\nimport subprocess\nimport json\ncmd = \"python3 /var/www/mini-hoen/service_request.py request -j\"\nproc = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\ncgitb.enable()\na = proc.stdout.decode('utf-8')\n# d = str(a).replace(\"'\", '\"')\n# Json = json.dumps(a)\n\n\n\nprint('Content-Type: text/html')\nprint()\n# a=json.dumps(proc.stdout.decode('utf-8'),indent=3)\nprint(a)\n# print(proc.stderr)","sub_path":"cgi-bin/getJSON.py","file_name":"getJSON.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"516911704","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# wallpaper manager script\n\nfrom pathlib import Path, PurePath\nimport json\nimport os\nimport shutil\nimport argparse\nimport urllib.request\nimport random\n\nMAX_KEEP = 100\nXDG_DATA_HOME = os.environ.get(\"XDG_DATA_HOME\", \"~/.local/share\")\nBASE_PATH = Path(XDG_DATA_HOME) / \"wpm\"\nDOWNLOADS_PATH = BASE_PATH / \"downloads\"\nCOLLECTIONS_PATH = BASE_PATH / \"collections\"\nos.makedirs(DOWNLOADS_PATH, exist_ok=True)\nos.makedirs(COLLECTIONS_PATH, exist_ok=True)\n\n\ndef keep_latest_files(path: Path, keep_count):\n # 获取所有文件的列表\n files = list(path.iterdir())\n\n # 对文件列表按照修改时间排序\n files.sort(key=lambda f: f.stat().st_mtime)\n\n # 删除最早的文件\n for file in files[:-keep_count]:\n file.unlink(missing_ok=True)\n\n\ndef _pull_once():\n response = urllib.request.urlopen(\n \"http://api.btstu.cn/sjbz/api.php?lx=dongman&format=json\")\n json_data = json.loads(response.read().decode(\"utf-8\"))\n wallpaper_url = json_data[\"imgurl\"]\n wallpaper_path = DOWNLOADS_PATH / PurePath(wallpaper_url).name\n response = urllib.request.urlopen(wallpaper_url)\n wallpaper_path.write_bytes(response.read())\n return wallpaper_path\n\n\ndef pull_wallpaper(n=1):\n paths = [_pull_once() for _ in range(n)]\n keep_latest_files(DOWNLOADS_PATH, MAX_KEEP)\n return paths\n\n\ndef apply_wallpaper(path):\n os.system(f\"feh --bg-scale {path}\")\n\n\ndef get_current_wallpaper_path():\n fehbg_text = Path(\"~/.fehbg\").expanduser().read_text()\n wallpaper_path = fehbg_text.split(\"'\")[1]\n return wallpaper_path\n\n\ndef command_collect(*args, **kwargs):\n target_path = COLLECTIONS_PATH\n sub_path = kwargs['sub_path']\n if sub_path is not None:\n target_path = target_path / sub_path\n wallpaper_path = get_current_wallpaper_path()\n shutil.copy(wallpaper_path, target_path)\n\n\ndef command_current(**kwargs):\n print(get_current_wallpaper_path())\n\n\ndef command_pull(**kwargs):\n print(str(pull_wallpaper()[0]))\n\n\ndef command_apply_next(**kwargs):\n path = str(pull_wallpaper()[-1])\n apply_wallpaper(path)\n\n\ndef command_apply_collections(**kwargs):\n target_path = COLLECTIONS_PATH\n sub_path = kwargs['sub_path']\n if sub_path is not None:\n target_path = target_path / sub_path\n image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']\n files = [\n f for f in target_path.iterdir()\n if f.is_file() and f.suffix in image_extensions\n ]\n wallpaper = random.choice(files)\n apply_wallpaper(str(wallpaper))\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Process some commands')\n\n # Add a top-level parser for the \"command\" argument\n subparsers = parser.add_subparsers(title='Commands', dest='command')\n\n # Create a parser for the \"collect\" command\n parser_collect = subparsers.add_parser('collect', help='Collect')\n parser_collect.add_argument('sub_path',\n type=str,\n nargs='?',\n help='The sub path from COLLECTIONS_PATH')\n parser_collect.set_defaults(func=command_collect)\n\n # Create a parser for the \"current\" command\n parser_current = subparsers.add_parser('current',\n help='Show current wallpaper path')\n parser_current.set_defaults(func=command_current)\n\n # Create a parser for the \"pull\" command\n parser_pull = subparsers.add_parser('pull', help='Pull wallpapers')\n parser_pull.set_defaults(func=command_pull)\n\n # Create a parser for the \"apply_next\" command\n parser_apply_next = subparsers.add_parser(\n 'apply_next', help='Pull next wallpaper and apply')\n parser_apply_next.set_defaults(func=command_apply_next)\n\n # Create a parser for the \"apply_collection\" command\n parser_apply_collections = subparsers.add_parser(\n 'apply_collections',\n help='Choose wallpaper from collections, and apply')\n parser_apply_collections.set_defaults(func=command_apply_collections)\n parser_apply_collections.add_argument(\n 'sub_path',\n type=str,\n nargs='?',\n help='The sub path from COLLECTIONS_PATH')\n\n # Parse the command-line arguments\n args = parser.parse_args()\n if hasattr(args, \"func\"):\n args.func(**vars(args))\n else:\n command_apply_next()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/wpm.py","file_name":"wpm.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"515173613","text":"import pandas as pd\nimport os\nimport requests\nfrom pathlib import Path\nfrom PIL import Image\nfrom pandarallel import pandarallel\npandarallel.initialize()\nfrom tqdm import tqdm\n\n# https://github.com/google-research-datasets/conceptual-12m\ncc_url = 'https://storage.googleapis.com/conceptual_12m/cc12m.tsv'\n\ndef download(url: str, fname: str):\n resp = requests.get(url, stream=True)\n total = int(resp.headers.get('content-length', 0))\n with open(fname, 'wb') as file, tqdm(\n desc=fname,\n total=total,\n unit='iB',\n unit_scale=True,\n unit_divisor=1024,\n ) as bar:\n for data in resp.iter_content(chunk_size=1024):\n size = file.write(data)\n bar.update(size)\n\nif not os.path.isfile('cc12m.tsv'):\n print('Missing cc12m url-caption-dataset. Downloading...')\nelse:\n print('cc12m.tsv already downloaded. Proceeding with downloading images!')\n\ndfc = pd.read_csv(\"cc12m.tsv\", sep='\\t', names=[\"url\", \"caption\"])\n\nimage_folder = 'images'\ntext_folder = 'texts'\noutput_folder = 'output'\nskip_folder = 'skip'\npaths = [image_folder, text_folder, output_folder, skip_folder]\nfor path in paths:\n os.makedirs(path, exist_ok=True)\nimageformats = ['jpg', 'jpeg', 'bmp', 'png']\nskips = os.listdir(skip_folder) + [x[:-4] for x in os.listdir(text_folder)]\ntotal = 12423374\nskiplist = [int(x) for x in skips]\nremaining = total - len(skiplist)\npercent_remaining = 100 * (total - remaining) / total\nmaxwidth = 256\nmaxheight = 256\n\ndf = dfc.loc[~dfc.index.isin(skiplist)]\nprint('Remaining {} images to be downloaded - {} ({:.5f} %) already downloaded.'.format(remaining, len(skiplist), percent_remaining))\n\ndef load_image_and_caption(x):\n id = \"0\"*(9-len(str(x.name))) + str(x.name)\n suffix = ''\n ending = x.url.split('.')[-1].lower()\n if ending.lower() in imageformats:\n suffix = '.' + ending\n try:\n foo = Image.open(requests.get(x.url, stream=True, timeout=3).raw)\n a = max(maxwidth/foo.size[0], maxheight/foo.size[1])\n foo = foo.resize((int(foo.size[0] * a), int(foo.size[1] * a)), Image.ANTIALIAS)\n foo.save(Path(image_folder + \"/\" + id + '.jpg'), optimize=True, quality=85)\n except Exception:\n open(Path(skip_folder + '/' + id), 'a').close\n pass\n else:\n with open(Path(text_folder + '/' + id + '.txt'), 'w') as f:\n f.write(x.caption)\n\ndf.parallel_apply(lambda x: load_image_and_caption(x), axis=1)\nprint('Finished downloading available images from conceptual images!')\n","sub_path":"general/cc12m.py","file_name":"cc12m.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"182937343","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Input, BatchNormalization\nfrom keras.optimizers import SGD, Adam\nimport numpy\nimport os\nimport cv2\nimport time\n\n\ndef predict_model():\n # lrelu = LeakyReLU(alpha=0.1)\n SRCNN = Sequential()\n SRCNN.add(Conv2D(nb_filter=128, nb_row=9, nb_col=9, init='glorot_uniform',\n activation='relu', border_mode='valid', bias=True, input_shape=(None, None, 1)))\n SRCNN.add(Conv2D(nb_filter=64, nb_row=3, nb_col=3, init='glorot_uniform',\n activation='relu', border_mode='same', bias=True))\n # SRCNN.add(BatchNormalization())\n SRCNN.add(Conv2D(nb_filter=1, nb_row=5, nb_col=5, init='glorot_uniform',\n activation='linear', border_mode='valid', bias=True))\n adam = Adam(lr=0.0003)\n SRCNN.compile(optimizer=adam, loss='mean_squared_error', metrics=['mean_squared_error'])\n return SRCNN\n\n\nclass ImgSuperReso(object):\n def __init__(self, weight_path='model_data/model_weight.h5'):\n self.srcnn_model = predict_model()\n self.srcnn_model.load_weights(weight_path)\n\n def processImg(self, raw_file, processed_file):\n img = cv2.imread(raw_file, cv2.IMREAD_COLOR)\n (filepath, tempfilename) = os.path.split(raw_file);\n (shortname, extension) = os.path.splitext(tempfilename);\n img = cv2.resize(img, None, fx=2, fy=2)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n Y_img = img[:, :, 0]\n Y = numpy.zeros((1, img.shape[0], img.shape[1], 1), dtype=float)\n Y[0, :, :, 0] = Y_img.astype(float) / 255.\n # t1 = time.time()\n pre = self.srcnn_model.predict(Y, batch_size=1) * 255.\n # t2 = time.time()\n # print(t2 - t1)\n pre[pre[:] > 255] = 255\n pre[pre[:] < 0] = 0\n pre = pre.astype(numpy.uint8)\n img[6: -6, 6: -6, 0] = pre[0, :, :, 0]\n img = cv2.cvtColor(img, cv2.COLOR_YCrCb2BGR)\n cv2.imwrite(processed_file, img)\n\n\nif __name__ == \"__main__\":\n t1 = time.time()\n imgSuperReso = ImgSuperReso()\n t2 = time.time()\n imgSuperReso.processImg('temp/flowers.bmp', 'temp/new.bmp')\n t3 = time.time()\n\n print(t2 - t1)\n print(t3 - t2)\n","sub_path":"improve_image.py","file_name":"improve_image.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"369883712","text":"# encoding:gbk\r\nimport requests\r\nimport time\r\nimport threading\r\nimport psutil\r\nimport os\r\nfrom fake_useragent import UserAgent\r\nfrom lxml import etree\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nfrom concurrent.futures import ProcessPoolExecutor\r\n\r\ndef head():\r\n headers = {\r\n 'User-Agent': str(UserAgent().random)\r\n }\r\n return headers\r\n\r\ndef stripText(textlist):\r\n \"\"\"\r\n 将文本转为字符串,并去掉其中的\\n,\\t,\\r,/等字符\r\n\r\n :param textlist:\r\n :return:\r\n \"\"\"\r\n star_list = \"\"\r\n for item in textlist:\r\n item_str = item.strip().replace('\\n','').replace('\\t', '').replace('\\r','').replace('-','')\r\n # item_str = item.strip() 当参数为空时,默认删除字符串两端的空白符(包括'\\n','\\t','\\r','')\r\n if item_str != '':\r\n if star_list != '':\r\n star_list = star_list + ',' + item_str\r\n else:\r\n star_list = item_str\r\n return star_list\r\n\r\ndef tishi():\r\n choices = input(\"请按照序号顺序进行:1.单线程 2.多线程 3.多进程:\")\r\n return choices\r\n\r\ndef downMP4(item):\r\n # 开始时间\r\n start_time = time.time()\r\n\r\n # 详细页url\r\n video_page_url = 'http://699pic.com' + item\r\n video_page_response = requests.get(url=video_page_url, headers=head())\r\n video_page_response.encoding = video_page_response.apparent_encoding\r\n video_page_rep = video_page_response.text\r\n\r\n tree_video = etree.HTML(video_page_rep)\r\n video_xapth_src = \"//div/video/source/@src\"\r\n\r\n # 视频的url\r\n video_url = 'http:'+ stripText(tree_video.xpath(video_xapth_src))\r\n print(video_url)\r\n\r\n # 视频名称\r\n video_name_xpath = '//div/div/div/h1/text()'\r\n video_name = stripText(tree_video.xpath(video_name_xpath))\r\n\r\n # 获得当前线程\r\n thred = threading.current_thread()\r\n # 获得当前进程\r\n process = psutil.Process(os.getpid())\r\n print('当前线程名称为:%s, ID���:%s, 进程名称为:%s, ID为%s'\r\n % (thred.getName(), thred.ident, process.name(), process.pid))\r\n\r\n # 发起请求,获得视频文件\r\n video_response = requests.get(url=video_url, headers=head())\r\n MP4_rep = video_response.content\r\n\r\n # 存储视频文件\r\n with open(video_name+'.MP4', 'wb') as f:\r\n f.write(MP4_rep)\r\n # 完成时间\r\n finshTime = time.time() - start_time\r\n return video_name+'.MP4 用时为:' + str(finshTime) + '秒'\r\n\r\ndef main():\r\n url = 'http://699pic.com/media/video-1142643.html'\r\n response = requests.get(url, headers=head())\r\n response.encoding = response.apparent_encoding\r\n rep = response.text\r\n\r\n with open('英雄.html', 'w', encoding='utf-8') as f:\r\n f.write(rep)\r\n\r\n # 构建xpath解析对象\r\n tree = etree.HTML(rep)\r\n video_xpath_page = \"//div[@class='search-video-wrap']/div[@class='video-list clearfix']/ul/li/a[1]/@href\"\r\n # 所有的视频信息\r\n item_list = tree.xpath(video_xpath_page)[:6]\r\n\r\n start_time = time.time()\r\n\r\n while True:\r\n choises = tishi()\r\n if choises == '1':\r\n print('正在使用单线程')\r\n print('*'*80)\r\n for item in item_list:\r\n result = downMP4(item)\r\n print(result)\r\n\r\n # 总的完成时间\r\n finshTime = time.time() - start_time\r\n print( '下载总时长为:' + str(finshTime) + '秒')\r\n print('单线程爬取完毕!')\r\n print('*'*80)\r\n choises = tishi()\r\n\r\n if choises == '2':\r\n print('正在使用多线程')\r\n print('-'*80)\r\n with ThreadPoolExecutor(max_workers=4) as excutor:\r\n # 提交线程\r\n futures = excutor.map(downMP4, item_list)\r\n for future in futures:\r\n print(future)\r\n\r\n # 总的完成时间\r\n finshTime = time.time() - start_time\r\n print( '下载总时长为:' + str(finshTime) + '秒')\r\n print('多线程爬取完毕!')\r\n print('-'*80)\r\n choises = tishi()\r\n\r\n if choises == '3':\r\n print('正在使用多进程')\r\n print('='*80)\r\n with ProcessPoolExecutor(max_workers=4) as excutor:\r\n # 提交进程\r\n futures = excutor.map(downMP4, item_list)\r\n for future in futures:\r\n print(future)\r\n\r\n # 总的完成时间\r\n finshTime = time.time() - start_time\r\n print( '下载总时长为:' + str(finshTime) + '秒')\r\n print('多进程爬取完毕!')\r\n print('='*80)\r\n print('三种线程爬取完毕!')\r\n\r\n break\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"线程与进程/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"18020054","text":"import unittest\nfrom VSTSInfo import VstsInfo\n\nclass TestVstsInfo(unittest.TestCase):\n\n def test_can_get_url_from_config(self):\n info = VstsInfo(None, None)\n base = info.instance_base\n self.assertNotEqual(base, None)\n\n def test_has_cash_prefix(self):\n info = VstsInfo(None, None)\n base = info.cash_prefix\n self.assertNotEqual(base, None)\n\n def test_can_get_filename_for_cache(self):\n info = VstsInfo(None, None)\n info.config['DEFAULT']['vsts_instance_base'] = \"company.visualstudio.com\"\n info.config['DEFAULT']['cash_prefix'] = \"vsts\"\n url = \"https://\" + info.instance_base + \"/my_project\"+ \"?foo=bar&foofoo=barbar\"\n expected = info.cache_folder + \"\\\\\" + info.cash_prefix +\".my_project\" + \"(qm)\" + \"foo=bar&foofoo=barbar\" +\".json\"\n cache_file_name = info.build_file_name(url)\n self.assertEqual(cache_file_name, expected)\n\n def test_get_request_settings(self):\n info = VstsInfo(None, None)\n settings = info.get_request_settings()\n self.assertEqual(settings['instance'], info.instance )\n\n def test_personal_access_token_starts_with_colon(self):\n info = VstsInfo(None, None)\n actual = info.personal_access_token\n self.assertTrue(actual.startswith(':'))\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"code/test_vsts_info.py","file_name":"test_vsts_info.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"612596633","text":"\n# KNAP SACK - W\n# n items {p[i], w[i]}\n# many items of each type\n# one item of each type\n# max( sum(p[i] for i in S), sum(w[i] for i in S) <= W\n\n# Greedy\nI[i] = p[i] / w[i]\nW - w[i]\n\n# DP - one item\np[i]\nw[i]\n\nmemo[W+1][n+1]\n\ndef solve(w, n):\n\tif n == 0:\n\t\tif w[0] < w:\n\t\t\treturn p[0]\n\t\telse:\n\t\t\treturn 0\n\n\tif memo[w][n] == -1:\n\t\tmemo[w][n] = max(solve(w-w[n], n-1) + p[n], solve(w, n-1))\n\t\treturn memo[w][n]\n\telse:\n\t\treturn memo[w][n]\n","sub_path":"DP-problems/knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"63020543","text":"from time import strftime\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Date\nfrom sqlalchemy.orm import sessionmaker\nfrom datetime import datetime\nfrom datetime import timedelta\n\nengine = create_engine('sqlite:///todo.db?check_same_thread=False')\nBase = declarative_base()\n\n\nclass Task(Base):\n __tablename__ = 'task'\n id = Column(Integer, primary_key=True)\n task = Column(String)\n deadline = Column(Date, default=datetime.today())\n\n def __repr__(self):\n return self.string_field\n\n\nBase.metadata.create_all(engine)\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nmenu_item = None\nnow = datetime.now().date()\nnext_week = now + timedelta(days=6)\nwhile menu_item != \"0\":\n print(\"1) Today's tasks\")\n print(\"2) Week's tasks\")\n print(\"3) All tasks\")\n print(\"4) Missed tasks\")\n print(\"5) Add task\")\n print(\"6) Delete task\")\n print(\"0) Exit\")\n\n menu_item = input()\n\n if menu_item == \"1\":\n tasks = session.query(Task).all()\n print(f\"Today {now.strftime('%d')} {now.strftime('%b')}:\")\n if not tasks:\n print(\"Nothing to do!\")\n else:\n for task in tasks:\n print(task.task)\n\n elif menu_item == \"2\":\n weekday = now\n while weekday <= next_week:\n tasks = session.query(Task).filter(Task.deadline == weekday)\n print(weekday.strftime('%A %d %b:'))\n i = 0\n if tasks.count() == 0:\n print('Nothing to do!')\n print(\"\")\n else:\n for task in tasks:\n i += 1\n print(f'{i}. {task.task}')\n print(\"\")\n weekday += timedelta(days=1)\n\n elif menu_item == \"3\":\n print(\"All tasks:\")\n tasks = session.query(Task).order_by(Task.deadline).all()\n i = 0\n for task in tasks:\n i += 1\n print(f'{i}. {task.task}. {task.deadline.strftime(\"%#d %b\")}')\n print(\"\")\n\n elif menu_item == \"4\":\n print(\"Missed tasks:\")\n tasks = session.query(Task).filter(Task.deadline < now)\n i = 0\n if tasks.count() == 0:\n print('Nothing is missed!')\n print(\"\")\n else:\n for task in tasks:\n i += 1\n print(f'{i}. {task.task}. {task.deadline.strftime(\"%#d %b\")}')\n print(\"\")\n\n elif menu_item == \"5\":\n print(\"Enter task\")\n new_task_name = input()\n print(\"Enter deadline\")\n new_task_deadline = datetime.strptime(input(), '%Y-%m-%d')\n new_task = Task(task=new_task_name, deadline=new_task_deadline)\n session.add(new_task)\n session.commit()\n\n elif menu_item == \"6\":\n print(\"Choose the number of the task you want to delete:\")\n tasks = session.query(Task).order_by(Task.deadline).all()\n i = 0\n for task in tasks:\n i += 1\n print(f'{i}. {task.task}. {task.deadline.strftime(\"%#d %b\")}')\n option = int(input())\n task_to_del = session.query(Task).filter(Task.id == tasks[option-1].id).delete()\n session.commit()\n\n\n print(\"\")\n\n elif menu_item == \"0\":\n print(\"Bye!\")\n","sub_path":"ToDoList/todolist.py","file_name":"todolist.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"417248920","text":"import os.path\n# Get all regular files\nnames = [name for name in os.listdir('.')\n if os.path.isfile(os.path.join('.', name))]\n# Get all dirs\ndirnames = [name for name in os.listdir('.')\n if os.path.isdir(os.path.join('.', name))]\n\nimport glob\npyfiles = glob.glob('somedir/*.py')\n\nfrom fnmatch import fnmatch\npyfiles = [name for name in os.listdir('somedir')\n if fnmatch(name, '*.py')] ","sub_path":"python/cookbook/files_io/files_in_dir.py","file_name":"files_in_dir.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"458822093","text":"import mysql.connector\n\nclass trafficSeeder:\n def __init__(self, db_client, traffic_status):\n self.db_client = db_client\n self.cursor = db_client.cursor\n self._traffic_status = traffic_status\n\n def seed(self):\n for index, status in enumerate(self._traffic_status):\n insert_statement = (\"\"\n \"INSERT INTO traffic \"\n \"(id, status) \"\n \"VALUES (%(id)s, %(status)s);\")\n data = {\n 'id': index + 1,\n 'status': status\n }\n\n try:\n self.cursor.execute(insert_statement, data)\n except mysql.connector.Error as err:\n print(\"Error: {}\".format(err))\n exit(1)\n\n self.db_client.commit()\n","sub_path":"python/seeder/trafficSeeder.py","file_name":"trafficSeeder.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"392499627","text":"# coding: utf-8\n# 生成器函数,函数里只要有yield关键字\n\n\ndef gen_func():\n yield 1\n yield 2\n yield 3\n\n\n# 惰性求值,延迟求值\ndef fib(index):\n if index == 0:\n return 0\n elif index <= 2:\n return 1\n else:\n return fib(index - 1) + fib(index - 2)\n\n\n# print(fib(5))\n\ndef gen_fib(index):\n n, a, b = 0, 0, 1\n while n < index:\n yield b\n a, b = b, a + b\n n += 1\n\nfor data in gen_fib(10):\n print(data)\n\n\n\n\ndef func():\n return 1\n\n\nif __name__ == \"__main__\":\n gen = gen_func()\n re = func()\n pass\n","sub_path":"chapter09/gen_func.py","file_name":"gen_func.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"432459522","text":"\"\"\"\r\nName: Reddit Bot\r\nMade By: Mads Hermansen\r\nGithub: https://github.com/KarlofKuwait\r\n\"\"\"\r\nimport PySimpleGUI as sg\r\n\r\ndef RedditBot():\r\n layout = [\r\n [sg.Text('Username', size=(15, 1)), sg.InputText('')],\r\n [sg.Text('Password', size=(15, 1)), sg.InputText('')],\r\n [sg.Text('Client ID', size=(15, 1)), sg.InputText('')],\r\n [sg.Text('Client Secret', size=(15, 1)), sg.InputText('')],\r\n [sg.Text('User Agent', size=(15, 1)), sg.InputText('')],\r\n [sg.Submit(\"Log In\", size=(15, 1)), sg.Exit()]\r\n\r\n ]\r\n\r\n Login = sg.Window('RedditBot Login', icon='Logo/Logo.ico').Layout(layout)\r\n \r\n while True:\r\n event, values = Login.Read()\r\n if event is None or event == 'Exit':\r\n break\r\n if event == \"Log In\":\r\n Login.Hide()\r\n break\r\n return event, values;\r\n\r\ndef Start():\r\n Bot = sg.Window(\"RedditBot\").Layout(layout2)\r\n Bot.SetIcon(icon=\"Logo/Logo.ico\")\r\n while True:\r\n event, values = Bot.Read()\r\n if event is None or event == 'Exit':\r\n break\r\n if event == \"Turn On\":\r\n Bot.Hide()\r\n break\r\n return event, values;\r\n","sub_path":"Reddit Bot/RedditBotGUI.py","file_name":"RedditBotGUI.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"45291557","text":"class Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n\n if height == None or len(height) < 3:\n return 0\n\n ans = 0\n\n n = len(height)\n\n max_left = [0] * n\n max_right = [0] * n\n\n # 每个节点,包括自身在内的,左边最大的点\n i = 1\n max_left[0] = height[0]\n while i <= n - 2:\n max_left[i] = max(max_left[i - 1], height[i])\n i += 1\n\n # 每个节点,包括自身在内的,右边最大的点\n j = n - 2\n max_right[n-1] = height[n-1]\n while j >= 0:\n max_right[j] = max(max_right[j + 1], height[j])\n j -= 1\n\n k = 1\n while k <= n - 2:\n left = max_left[k]\n right = max_right[k]\n if min(left, right) > height[k]:\n ans += min(left, right) - height[k]\n k += 1\n \n return ans\n\n# 4\n","sub_path":"Week_01/trapping-rain-water.py","file_name":"trapping-rain-water.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"106781454","text":"import math\nfrom typing import Any, AsyncIterator, ClassVar, Dict, Optional, Tuple\n\nimport aiohttp\n\nfrom .. import command, module, util\n\n\nclass HerokuManager(module.Module):\n name: ClassVar[str] = \"Heroku\"\n\n api_key: str\n app_name: str\n\n apps: Dict[str, Any]\n account: Dict[str, Any]\n http: aiohttp.ClientSession\n\n uri: str\n useragent: str\n\n async def on_load(self) -> None:\n self.api_key = self.bot.getConfig[\"heroku_api_key\"]\n self.app_name = self.bot.getConfig[\"heroku_app_name\"]\n if self.api_key is None or self.app_name is None:\n self.log.warning(\"Heroku module credential not satisfy.\")\n self.bot.unload_module(self)\n return\n\n self.http = self.bot.http\n\n self.uri = \"https://api.heroku.com\"\n self.useragent = (\n \"Mozilla/5.0 (Linux; Android 11; SM-G975F) \"\n \"AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/90.0.4430.210 Mobile Safari/537.36\"\n )\n self.account = await self.get_account()\n\n self.apps = {}\n async for app_name, app_id in self.get_account_apps():\n self.apps[app_name] = app_id\n\n async def request(\n self, path: str,\n options: Optional[Dict[str, Any]] = None\n ) -> Dict[Any, Any]:\n headers = {\n \"User-Agent\": self.useragent,\n \"Authorization\": f\"Bearer {self.api_key}\",\n \"Accept\": \"application/vnd.heroku+json; version=3\",\n }\n\n if options is not None:\n headers.update(options)\n\n async with self.http.get(path, headers=headers) as resp:\n if resp.status != 200:\n ret = {\"status\": resp.status, \"error\": {\"reason\": resp.reason}}\n self.log.info(util.tg.pretty_print_entity(ret))\n return ret\n\n return await resp.json()\n\n async def get_account(self) -> Dict[Any, Any]:\n path = self.uri + \"/account\"\n return await self.request(path)\n\n async def get_account_quota(self) -> Dict[str, Any]:\n options = {\n \"Accept\": \"application/vnd.heroku+json; version=3.account-quotas\"\n }\n path = self.uri + f\"/accounts/{self.account['id']}/actions/get-quota\"\n\n return await self.request(path, options)\n\n async def get_account_apps(self) -> AsyncIterator[Tuple[str, int]]:\n path = self.uri + \"/apps\"\n apps = await self.request(path)\n for app in apps:\n yield app[\"name\"], app[\"id\"]\n\n @command.desc(\"Check your Free Dyno hours quota you've used this month.\")\n @command.alias(\"dyno\")\n async def cmd_dynousage(self, ctx: command.Context) -> Optional[str]:\n await ctx.respond(\"Pulling information...\")\n\n ret = await self.get_account_quota()\n\n quota = ret[\"account_quota\"]\n quota_used = ret[\"quota_used\"]\n\n # Account quota remaining this month\n remaining_quota = quota - quota_used\n percentage = math.floor(remaining_quota / quota * 100)\n minutes_remaining = remaining_quota / 60\n hours = math.floor(minutes_remaining / 60)\n minutes = math.floor(minutes_remaining % 60)\n\n # Account apps quota used this month\n apps = ret[\"apps\"]\n for app in apps:\n if app[\"app_uuid\"] == self.apps.get(self.app_name):\n appQuota = app.get(\"quota_used\")\n appQuotaUsed = appQuota / 60\n appPercentage = math.floor(appQuota * 100 / quota)\n break\n else:\n appQuotaUsed = 0\n appPercentage = 0\n\n appHours = math.floor(appQuotaUsed / 60)\n appMinutes = math.floor(appQuotaUsed % 60)\n\n head = util.text.join_map(\n {\n \"Hours\": f\"{hours}h\",\n \"Minutes\": f\"{minutes}m\"\n },\n heading=f\"Account remaining ({percentage}%) this month\"\n )\n body = util.text.join_map(\n {\n \"Hours\": f\"{appHours}h\",\n \"Minutes\": f\"{appMinutes}m\",\n },\n heading=f\"App[{self.app_name}] usage ({appPercentage}%) this month\"\n )\n\n return head + \"\\n\\n\" + body\n","sub_path":"caligo/modules/heroku.py","file_name":"heroku.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"602138910","text":"import sys\nimport redis\n\ndef get_redis(db):\n r = redis.Redis(host='localhost', port=6379, db=db)\n return r\n\ndef write_to(fname,db):\n r = get_redis(db)\n pipe = r.pipeline()\n n=0\n batchsize = 100000\n with open(fname,'r') as inf:\n for line in inf:\n x = line.strip().split('\\t')\n pipe.set(x[0],x[1])\n n += 1\n if n >= batchsize:\n pipe.execute()\n n = 0\n pipe.execute()\n\ndef go():\n write_to('src/graph_coalescence/links.txt',0)\n write_to('src/graph_coalescence/nodelabels.txt',1)\n write_to('src/graph_coalescence/backlinks.txt',2)\n\ndef go_test():\n #Is going to run from ac root\n write_to('tests/test_links.txt',0)\n write_to('tests/test_nodelabels.txt',1)\n write_to('tests/test_backlinks.txt',2)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'test':\n go_test()\n else:\n go()\n\n","sub_path":"src/graph_coalescence/load_redis.py","file_name":"load_redis.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"580808434","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom django.core.paginator import Paginator\nfrom django.core.cache import cache\nfrom django.conf import settings\nfrom django.db.models import Count\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth import login, authenticate\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\n\nfrom Home.models import BlogType, Blog\nfrom read_statistics.utils import read_statistics_one_read\nfrom read_statistics.utils import get_seven_days_read_data, get_7_days_hot_blogs, get_today_hot_data, \\\n get_yesterday_hot_data\nfrom comment.models import Comment\nfrom comment.forms import CommentForms\nfrom .forms import LoginFrom, RegForm\n\nimport json\n\n\n\n# Create your views here.\ndef get_blog_list_common_data(request, blogs_all_list):\n paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER) # 每10页进行分页\n page_num = request.GET.get('page', 1) # 获取url的页面参数(GET请求)\n page_of_blogs = paginator.get_page(page_num)\n page_range = paginator.page_range\n\n # 获取博客分类对应的博客数量 BlogType.objects.annotation(blog_count=Count('blog'))\n # or\n # blog_types = BlogType.objects.all()\n # blog_type_list = []\n # for blog_type in blog_types:\n # blog_type.blog_count = Blog.objects.filter(blog_type=blog_type).count()\n # blog_type_list.append(blog_type)\n\n # 获取日期归档对应的博客数量\n blog_dates = Blog.objects.dates('created_time', 'month', order='DESC')\n blog_dates_dict = {}\n for blog_date in blog_dates:\n blog_count = Blog.objects.filter(created_time__year=blog_date.year,\n created_time__month=blog_date.month).count()\n blog_dates_dict[blog_date] = blog_count\n\n content = {}\n content['blogs'] = page_of_blogs.object_list\n content['page_of_blogs'] = page_of_blogs\n content['page_range'] = page_range\n content['blog_types'] = BlogType.objects.annotate(blog_count=Count('blog')) # blog_type_list\n content['blog_dates'] = blog_dates_dict\n\n return content\n\n\ndef home(request):\n blogs_all_list = Blog.objects.all()\n content = get_blog_list_common_data(request, blogs_all_list)\n\n blog_content_type = ContentType.objects.get_for_model(Blog)\n dates, read_nums = get_seven_days_read_data(blog_content_type)\n\n # 获取7天热门博客的缓存数据\n hot_blogs_for_7_days = cache.get('hot_blogs_for_7_days')\n if hot_blogs_for_7_days is None:\n hot_blogs_for_7_days = get_7_days_hot_blogs()\n cache.set('hot_blogs_for_7_days', hot_blogs_for_7_days, 3600)\n print('calc')\n else:\n print('use cache')\n\n content['blogs'] = Blog.objects.all()[:settings.EACH_PAGE_BLOGS_NUMBER]\n content['dates'] = json.dumps(dates)\n content['read_nums'] = json.dumps(read_nums)\n content['hot_blogs_for_7_days'] = get_7_days_hot_blogs()\n content['today_hot_data'] = get_today_hot_data(blog_content_type)\n content['yesterday_hot_data'] = get_yesterday_hot_data(blog_content_type)\n\n return render(request, 'home.html', content)\n\n\ndef blog_detail(request, blog_pk):\n blog = get_object_or_404(Blog, pk=blog_pk)\n read_cookie_key = read_statistics_one_read(request, blog)\n blog_content_type = ContentType.objects.get_for_model(blog)\n comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk)\n\n content = {}\n content['blog'] = get_object_or_404(Blog, pk=blog_pk)\n content['user'] = request.user\n content['previous_blog'] = Blog.objects.filter(created_time__gt=blog.created_time).last()\n content['next_blog'] = Blog.objects.filter(created_time__lt=blog.created_time).first()\n content['comments'] = comments\n content['comment_form'] = CommentForms(initial={'content_type': blog_content_type.model, 'object_id': blog_pk}) # 实例化CommentForms类\n response = render(request, 'blog_detail.html', content) # 响应\n response.set_cookie(read_cookie_key, 'true', max_age=60) # 阅读cookie标记\n return response\n\n\ndef blogs_with_type(request, blog_type_pk):\n blog_type = get_object_or_404(BlogType, pk=blog_type_pk)\n blogs_all_list = Blog.objects.filter(blog_type=blog_type)\n content = get_blog_list_common_data(request, blogs_all_list)\n content['blog_type'] = blog_type\n\n return render(request, 'blogs_with_type.html', content)\n\n\ndef aboutAuthor(request):\n content = {}\n return render(request, 'aboutAuthor.html', content)\n\n\ndef blogs_with_date(request, year, month):\n blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)\n content = get_blog_list_common_data(request, blogs_all_list)\n content['blogs_with_date'] = '%s年%s月' % (year, month)\n\n return render(request, 'blogs_with_date.html', content)\n\n\ndef login_(request):\n if request.method == 'POST':\n login_form = LoginFrom(request.POST)\n if login_form.is_valid():\n user = login_form.cleaned_data['user']\n login(request, user)\n return redirect(request.GET.get('from', reverse('home')))\n else:\n login_form = LoginFrom()\n\n content = {}\n content['login_form'] = login_form\n return render(request, 'login.html', content)\n\ndef register(request):\n if request.method == 'POST':\n reg_form = RegForm(request.POST)\n if reg_form.is_valid():\n username = reg_form.cleaned_data['username']\n password = reg_form.cleaned_data['password']\n email = reg_form.cleaned_data['email']\n # 创建用户\n user = User.objects.create_user(username, email, password)\n user.save()\n # 登录用户\n user = authenticate(username=username, password=password)\n login(request, user)\n return redirect(request.GET.get('from', reverse('home')))\n else:\n reg_form = RegForm()\n\n content = {}\n content['reg_form'] = reg_form\n return render(request, 'register.html', content)","sub_path":"blog/Home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"605408709","text":"\"\"\"Projector test app\n=====================\n\nApp to test the projector - MCS hardware data link.\n\n\"\"\"\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.factory import Factory\nfrom kivy.properties import BooleanProperty, StringProperty, ObjectProperty\nfrom kivy.graphics.opengl import glEnable, GL_DITHER, glDisable\nfrom kivy.graphics.texture import Texture\nif __name__ == '__main__':\n from kivy.core.window import Window\ntry:\n from pypixxlib import _libdpx as libdpx\n from pypixxlib.propixx import PROPixx\n from pypixxlib.propixx import PROPixxCTRL\nexcept ImportError:\n libdpx = PROPixx = PROPixxCTRL = None\n\n__all__ = ('IOApp', )\n\nkv = '''\nBoxLayout:\n orientation: 'vertical'\n padding: '25dp'\n bits: bits\n canvas:\n Color:\n rgba: 1, 1, 1, 1\n Rectangle:\n texture: app.bits_texture\n pos: 0, self.height - 1\n size: 1, 1\n Widget:\n size_hint_y: None\n height: '2dp'\n BoxLayout:\n spacing: '5dp'\n size_hint: None, None\n size: self.minimum_width, '25dp'\n Label:\n padding_x: '5dp'\n text: 'Video Mode'\n size_hint_x: None\n width: self.texture_size[0]\n Spinner:\n values: app.video_modes\n on_text: app.set_video_mode(self.text)\n text: 'RGB'\n size_hint_x: None\n width: '100dp'\n Label:\n padding_x: '5dp'\n text: 'LED Mode'\n size_hint_x: None\n width: self.texture_size[0]\n Spinner:\n values: list(app.led_modes.keys())\n on_text: app.set_led_mode(self.text)\n text: 'RGB'\n size_hint_x: None\n width: '100dp'\n GridLayout:\n id: bits\n cols: 8\n spacing: '5dp'\n size_hint: None, None\n size: self.minimum_size\n Widget\n\n\n:\n padding: '5dp', '5dp'\n size_hint: None, None\n size: '45dp', self.texture_size[1]\n on_state: app.update_bits()\n'''\n\n\nclass IOApp(App):\n\n led_mode = StringProperty('RGB')\n\n video_mode = StringProperty('RGB')\n\n led_modes = {'RGB': 0, 'GB': 1, 'RB': 2, 'B': 3, 'RG': 4, 'G': 5, 'R': 6,\n 'none': 7}\n\n video_modes = ['RGB', 'RB3D', 'RGB240', 'RGB180', 'QUAD4X', 'QUAD12X',\n 'GREY3X']\n\n screen_size = (1920, 1080)\n\n bits_texture = ObjectProperty(None)\n\n def build(self):\n tex = self.bits_texture = Texture.create(size=(1, 1))\n tex.mag_filter = 'nearest'\n tex.min_filter = 'nearest'\n\n root = Builder.load_string(kv)\n grid = root.bits\n for i in range(23, -1, -1):\n grid.add_widget(Factory.BitToggleButton(text=str(i)))\n return root\n\n def on_start(self):\n glDisable(GL_DITHER)\n Window.clearcolor = (0, 0, 0, 1)\n Window.size = self.screen_size\n Window.left = 0\n Window.fullscreen = True\n self.set_led_mode(self.led_mode)\n self.set_video_mode(self.video_mode)\n self.update_bits()\n self.set_pixel_mode(True)\n\n def set_pixel_mode(self, state):\n if PROPixxCTRL is None:\n raise ImportError('Cannot open PROPixx library')\n\n ctrl = PROPixxCTRL()\n if state:\n ctrl.dout.enablePixelMode()\n else:\n ctrl.dout.disablePixelMode()\n ctrl.updateRegisterCache()\n ctrl.close()\n\n def set_led_mode(self, mode):\n '''Sets the projector's LED mode. ``mode`` can be one of\n led_modes.\n '''\n if libdpx is None:\n raise ImportError('Cannot open PROPixx library')\n\n self.led_mode = mode\n libdpx.DPxOpen()\n libdpx.DPxSelectDevice('PROPixx')\n libdpx.DPxSetPPxLedMask(self.led_modes[mode])\n libdpx.DPxUpdateRegCache()\n libdpx.DPxClose()\n\n def set_video_mode(self, mode):\n '''Sets the projector's video mode. ``mode`` can be one of\n video_modes.\n '''\n if PROPixx is None:\n raise ImportError('Cannot open PROPixx library')\n\n self.video_mode = mode\n dev = PROPixx()\n dev.setDlpSequencerProgram(mode)\n dev.updateRegisterCache()\n dev.close()\n\n def update_bits(self):\n value = 0\n for i, button in enumerate(self.root.bits.children):\n if button.state == 'down':\n value |= 1 << i\n r, g, b = value & 0xFF, (value & 0xFF00) >> 8, \\\n (value & 0xFF0000) >> 16\n self.bits_texture.blit_buffer(\n bytes([r, g, b]), colorfmt='rgb', bufferfmt='ubyte')\n\n\nif __name__ == '__main__':\n app = IOApp()\n try:\n app.run()\n finally:\n app.bits_texture.blit_buffer(\n b'000', colorfmt='rgb', bufferfmt='ubyte')\n app.set_pixel_mode(False)\n app.set_led_mode('RGB')\n app.set_video_mode('RGB')\n","sub_path":"ceed/tools/projector_io.py","file_name":"projector_io.py","file_ext":"py","file_size_in_byte":4915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"316598347","text":"from .library import *\nfrom ctypes import *\nfrom .util import (safe_call, to_str)\n\ndef info():\n safe_call(clib.af_info())\n\ndef device_info():\n c_char_256 = c_char * 256\n device_name = c_char_256()\n backend_name = c_char_256()\n toolkit = c_char_256()\n compute = c_char_256()\n\n safe_call(clib.af_device_info(pointer(device_name), pointer(backend_name), \\\n pointer(toolkit), pointer(compute)))\n dev_info = {}\n dev_info['device'] = to_str(device_name)\n dev_info['backend'] = to_str(backend_name)\n dev_info['toolkit'] = to_str(toolkit)\n dev_info['compute'] = to_str(compute)\n\n return dev_info\n\ndef get_device_count():\n c_num = c_int(0)\n safe_call(clib.af_get_device_count(pointer(c_num)))\n return c_num.value\n\ndef get_device():\n c_dev = c_int(0)\n safe_call(clib.af_get_device(pointer(c_dev)))\n return c_dev.value\n\ndef set_device(num):\n safe_call(clib.af_set_device(num))\n\ndef is_dbl_supported(device=None):\n dev = device if device is not None else get_device()\n res = c_bool(False)\n safe_call(clib.af_get_dbl_support(pointer(res), dev))\n return res.value\n\ndef sync(device=None):\n dev = device if device is not None else get_device()\n safe_call(clib.af_sync(dev))\n\ndef device_mem_info():\n alloc_bytes = c_size_t(0)\n alloc_buffers = c_size_t(0)\n lock_bytes = c_size_t(0)\n lock_buffers = c_size_t(0)\n safe_call(clib.af_device_mem_info(pointer(alloc_bytes), pointer(alloc_buffers),\\\n pointer(lock_bytes), pointer(lock_buffers)))\n mem_info = {}\n mem_info['alloc'] = {'buffers' : alloc_buffers.value, 'bytes' : alloc_bytes.value}\n mem_info['lock'] = {'buffers' : lock_buffers.value, 'bytes' : lock_bytes.value}\n return mem_info\n","sub_path":"arrayfire/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"611790836","text":"\"\"\"empty message\n\nRevision ID: a436ba516b8b\nRevises: 6852908252e7\nCreate Date: 2019-03-20 13:50:12.542996\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlalchemy_utils\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a436ba516b8b'\ndown_revision = '6852908252e7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('test',\n sa.Column('processor_name', sa.String(), nullable=False,\n server_default=\"default\"))\n\n\ndef downgrade():\n op.drop_column('test', 'processor_name')\n","sub_path":"migrations/versions/a436ba516b8b_.py","file_name":"a436ba516b8b_.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"643009755","text":"#!/usr/bin/python3\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, you can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport json\nimport sys\n\nkeys = {\n \"extensions.{e2fda1a4-762b-4020-b5ad-a41df1933103}.name\": \"extensionName\",\n \"extensions.{e2fda1a4-762b-4020-b5ad-a41df1933103}.description\": \"extensionDescription\",\n \"extensions.{e2fda1a4-762b-4020-b5ad-a41df1933103}.creator\": \"extensionAuthor\",\n}\ndata = {}\n\nwith open(sys.argv[1], encoding=\"utf-8\") as fp:\n for line in fp.readlines():\n for key, new_key in keys.items():\n if line.startswith(key):\n data[new_key] = {\n \"message\": line[line.index(\"=\") + 1:].strip(),\n }\n\nwith open(sys.argv[2], \"w\", encoding=\"utf-8\") as fp:\n json.dump(data, fp, ensure_ascii=False, indent=2, sort_keys=True)\n fp.write(\"\\n\")\n","sub_path":"calendar/lightning/repack/webextify.py","file_name":"webextify.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"457644305","text":"from sys import stdin, setrecursionlimit\nfrom collections import deque\n\ninput = stdin.readline\nsetrecursionlimit(10 ** 6)\n\n# K만큼의 depth만\nN, M, K, X = map(int, input().split())\ngrpah = [[] for _ in range(N + 1)]\ncheck = [-1 for _ in range(N + 1)]\nfor _ in range(M):\n u, v = map(int, input().split())\n grpah[u].append(v)\n\n\ndq = deque()\ndq.append(X)\ncheck[X] = 0\nans = []\nwhile dq:\n now = dq.popleft()\n for nxt in grpah[now]:\n if check[nxt] == -1:\n check[nxt] = check[now] + 1\n if check[nxt] == K:\n ans.append(nxt)\n elif check[nxt] < K:\n dq.append(nxt)\n\nans.sort()\nif len(ans) == 0:\n print(-1)\nelse:\n for a in ans:\n print(a)","sub_path":"BOJ_Silver/Graph/18352.py","file_name":"18352.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"217898299","text":"#!/usr/bin/env python3\n#https://codeforces.com/group/H9K9zY8tcT/contest/297264/problem/B\n#利用奇偶性?\n#每次移除奇数个节点..所以就看原来n是奇数还是偶数\n\n\nq = int(input()) #5e4\nfor _ in range(q):\n n = int(input()) #5e4 (summed)\n l = [input() for _ in range(n-1)]\n print('Alice' if n%2>0 else 'Bob')\n","sub_path":"bnu/team_201006/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"366405733","text":"#!/usr/bin/python\n\nimport sys\nimport subprocess\n\ndef main(argc, argv):\n\ttarget = argv[1]\n\tlabel = argv[2]\n\trevision = argv[3]\n\t\n\tsed_str = '\\'/^XBCS-LABEL/{h;s/=.*/: SHA/};${x;/^$/{s//XBCS-LABEL: SHA/;H};x}\\''\n\tsed_str = sed_str.replace('LABEL', label).replace('SHA', revision)\n\tsed_str = 'sed -i ' + sed_str + ' ' + target\n\t\n\tprint(sed_str)\n\n\tp = subprocess.Popen(sed_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\nif __name__ == \"__main__\":\n\tmain(len(sys.argv), sys.argv)\n","sub_path":"scripts/insert_commit.py","file_name":"insert_commit.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"566593283","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nfrom __future__ import print_function\n\ndef load_kernel(fn, name):\n\n from pycuda.compiler import SourceModule\n\n with open(fn, 'r') as f:\n k = f.read()\n\n mod = SourceModule(k)\n return mod.get_function(name)\n\n return k\n\n","sub_path":"modules/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"303559002","text":"import matplotlib.pyplot as plt \n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\"\"\"\n##Colors:\n'r' - Red\n'g' - Green\n'b' - Blue\n'c' - Cyan\n'm' - Magenta\n'y' - Yellow\n'k' - Black\n'w' - White\n\"\"\"\nshow = 1##Init\nwhile ( show > 0 ):\n show = int(input(\"Show? (0 to exit): \"))\n try:\n if( show == 1 ):\n xpoints = np.array([0, 6])\n ypoints = np.array([0, 250])\n\n plt.plot(xpoints, ypoints)\n\n if( show == 2 ):\n ypoints = np.array([3, 8, 1, 10])\n\n plt.plot(ypoints, marker = 'o')\n\n if( show == 3 ):\n x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])\n y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])\n\n if( show == 4 ):\n x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])\n y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])\n\n plt.title(\"Sports Watch Data\")\n plt.xlabel(\"Average Pulse\")\n plt.ylabel(\"Calorie Burnage\")\n\n plt.plot(x, y)\n\n #plt.grid(axis = 'y') ##or x\n plt.grid(color = 'green', linestyle = '--', linewidth = 0.5) \n\n plt.plot(x, y)\n\n plt.xlabel(\"Average Pulse\")\n plt.ylabel(\"Calorie Burnage\")\n\n if( show == 5 ):\n x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])\n y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])\n\n plt.scatter(x, y)\n ##plt.scatter(x, y, color = '#88c999') ##Color\n\n if( show == 6 ):\n ##Subset 1\n x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])\n y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])\n plt.scatter(x, y)\n\n ##Subset 2\n x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])\n y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])\n plt.scatter(x, y) \n\n if( show == 7 ):\n x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])\n y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])\n colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])\n\n plt.scatter(x, y, c=colors, cmap='viridis')\n\n plt.colorbar()\n\n if( show == 8 ):\n x = np.array([\"A\", \"B\", \"C\", \"D\"])\n y = np.array([3, 8, 1, 10])\n\n ##plt.bar(x, y, color = \"#4CAF50\") ##Color\n plt.bar(x, y, width = 0.1) \n\n if( show == 9 ):\n y = np.array([35, 25, 25, 15])\n mylabels = [\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"]\n myexplode = [0.2, 0, 0, 0]\n\n plt.pie(y, labels = mylabels, explode = myexplode, shadow = True)\n\n \"\"\"\n ##Colors\n y = np.array([35, 25, 25, 15])\n mylabels = [\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"]\n myexplode = [0.2, 0, 0, 0]\n\n plt.pie(y, labels = mylabels, explode = myexplode, shadow = True) \n \"\"\"\n\n plt.show() \n except:\n print(\"There was a problem\")","sub_path":"ej_plot.py","file_name":"ej_plot.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"469910049","text":"import os\nimport numpy as np\n\ndef mkdirs(paths):\n \"\"\"create empty directories if they don't exist\n\n Parameters:\n paths (str list) -- a list of directory paths\n \"\"\"\n if isinstance(paths, list) and not isinstance(paths, str):\n for path in paths:\n mkdir(path)\n else:\n mkdir(paths)\n\n\ndef mkdir(path):\n \"\"\"create a single empty directory if it didn't exist\n\n Parameters:\n path (str) -- a single directory path\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef mkdir_given_options(opt):\n for k, v in sorted(vars(opt).items()):\n if (str(k).endswith(\"_dir\", len(str(k)) - 4, len(str(k)))): # for those dirs # convert to absolution path\n mkdir(str(v)) \n return opt \n\ndef print_options(opt):\n \"\"\"Print and save options\n\n It will print both current options and default values(if different).\n It will save options into a text file / [checkpoints_dir] / opt.txt\n \"\"\"\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n \n \n message += '----------------- End -------------------'\n print(message)\n \ndef print_current_loss(log_file, epoch, epoch_step, steps_per_epoch, total_time, \n epoch_time, remain_time, images_per_sec, lr, report):\n # basic print message \n message = '|epoch: %d| progress: %d/%d| image/sec %0.1f | total_time: %.3f m | epoch_time: %.3f m| remain: %.3f m| lr: %.7f\\n' % (epoch, epoch_step, \\\n steps_per_epoch, images_per_sec, total_time/60, epoch_time/60, remain_time/60, lr)\n # other message saved in report\n for k, v in report.items():\n if isinstance(v, tuple):\n message += '%s: %.6f, %.3f ' % (k, v[0], v[1])\n elif isinstance(v, np.float32):\n message +='%s: %.6f ' % (k, v)\n else:\n raise NotImplementedError(\"value has unsupport type:\", type(v))\n print(message)\n\n with open(log_file, \"a\") as log_file:\n log_file.write('%s\\n' % message) # save the message\n\ndef save_images(seq, save_dir, epoch, count, prefix):\n prefix_dir = os.path.join(save_dir, prefix)\n if not os.path.exists(prefix_dir):\n os.makedirs(prefix_dir)\n \n file_name = \"%d_v%04d.npy\" % (epoch, count)\n np.save(os.path.join(prefix_dir, file_name), seq)\n","sub_path":"video_prediction/utils/general_ops.py","file_name":"general_ops.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"284516655","text":"import engine\r\nimport random\r\nimport time\r\nimport multiprocessing\r\n\r\nengine.SetSeed(random.randint(0, 100))\r\nhyper_param = 2\r\n\r\ndef WrapSearch(args):\r\n\r\n child = args[0]\r\n param = args[1]\r\n trial = args[2]\r\n\r\n return engine.Search(child['m'], child['y'], param, trial)\r\n\r\ndef Search(m, y, param, trial, cores):\r\n\r\n movable = engine.GetMovablePy(m, y)\r\n children = []\r\n while movable:\r\n move = movable ^ (movable & (movable - 1))\r\n reversable = engine.GetReversablePy(m, y, move)\r\n m_child = m | move | reversable\r\n y_child = y ^ reversable\r\n children.append({'m': y_child, 'y': m_child})\r\n movable ^= move\r\n\r\n trial_p = trial // len(children)\r\n time_before = time.time()\r\n\r\n # プレイアウト進捗とノード数を共有メモリしたい\r\n with multiprocessing.Pool(cores) as p:\r\n\r\n winrates = p.map(WrapSearch, [(child, param, trial_p) for child in children])\r\n\r\n choiced_winrate = min(winrates)\r\n choiced_child = children[winrates.index(choiced_winrate)]\r\n\r\n info = {\r\n 'time': time.time() - time_before,\r\n 'winrate': 1 - choiced_winrate\r\n }\r\n\r\n return choiced_child['y'], choiced_child['m'], info\r\n\r\ndef Move(m, y, move):\r\n\r\n movable = engine.GetMovablePy(m, y)\r\n\r\n if move & movable:\r\n\r\n reversable = engine.GetReversablePy(m, y, move)\r\n m |= move | reversable\r\n y ^= reversable\r\n\r\n return m, y\r\n\r\ndef CheckEnd(m, y):\r\n\r\n return engine.GetMovablePy(m, y) | engine.GetMovablePy(y, m)\r\n","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"299443756","text":"import tensorflow as tf\nimport os\n\ndef picread(file_list):\n \"\"\"\n 狗图片读取,转换成数据张量\n :param file_list:\n :return:\n \"\"\"\n #构造文件队列\n file_queue=tf.train.string_input_producer(file_list)\n\n # 构造一个图片读取器,去对垒当中读取数据\n # 返回reader实例,调用read方法读取内容,key,value\n reader=tf.WholeFileReader()\n key,value=reader.read(file_queue)\n print(value)\n\n # 对样本内容进行解码\n image=tf.image.decode_jpeg(value)\n print(image)\n\n # 处理图片大小,形状,经过该函数处理图片数据类型编程float类型\n resize_image=tf.image.resize_images(image, [200, 200])\n print(resize_image)\n\n # 设置固定形状,使用静态api修改\n resize_image.set_shape([200,200,3])\n print(resize_image)\n\n # 批处理图片数据\n # 每个样本的形状必须全部定义 否则报错\n image_batch=tf.train.batch([resize_image],batch_size=1,num_threads=1,capacity=100)\n print(image_batch)\n return image_batch\n\n\nif __name__ == '__main__':\n file_name=os.listdir(\"./data/dog/\")\n # 路径拼接\n file_list=[os.path.join(\"./data/dog/\",file) for file in file_name]\n\n print(file_list)\n image_batch=picread(file_list)\n with tf.Session() as sess:\n\n # 创建线程回收的协调员\n coord=tf.train.Coordinator()\n\n # 需手动开启子线程进行批处理读取到队列操作\n threads=tf.train.start_queue_runners(sess=sess,coord=coord)\n\n print(sess.run(image_batch))\n\n coord.request_stop()\n coord.join(threads)","sub_path":"狗图片读取.py","file_name":"狗图片读取.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"268002992","text":"#!/usr/bin/python2\nimport requests\nimport csv\nimport pprint\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n#######\n\nimport sys \nimport importlib\nimport imp\nimport json\nimport time\ncities =[]\nwith open('cities.json') as json_file: \n data = json.load(json_file)\n for p in data:\n x = p['country']\n if x == 'JP':\n ###print('Country: ' + p['country'])\n ###print('City: ' + p['name'])\n #print('From: ' + p['from'])\n print('')\n xname = p['name']\n print(xname)\n\n xname = xname.encode('ascii', 'ignore').decode('ascii')\n ###cities.append(p['name'])\n cities.append(xname)\n#######\n\n\n\ncities = sorted(cities)\natts = [\"hotels\", \"restaurants\"]\n\nfor att in atts:\n print('Now working on the attraction of: ' + att)\n for city in cities:\n print('Writing user reviews for City: ' + city)\n \n ###city = \"Tokyo\"\n\n #att = \"hotels or restaurants\"\n ###attraction_string = \"restaurants, \" + city\n attraction_string = att + \", \" + city\n\n file_name = \"Hotels_Restaurants_in_Japan_by_no_name.csv\"\n ###file_name = att + \"_in_Japan.csv\"\n \n #sending get request.\n main_api = \"https://maps.googleapis.com/maps/api/place/textsearch/json?\"\n parameters = {\"query\":attraction_string,\n \"key\":\"\"} #enter api key here.\n resp = requests.get(main_api, parameters).json()\n \n #it selects the places with at least one rating, and puts their place id in place_id.\n place_id = [result['place_id'] for result in resp['results'] if 'rating' in result]\n \n #creating a csv file and with headings.\n with open(file_name, \"a+\") as toWrite:\n writer=csv.writer(toWrite)\n ###writer.writerow(['Date Collected', 'Health Care Provider', 'HCP location', 'Website Review is From', 'Specialty', 'Reviewer Name',\\\n ###'Date of Review', 'Reviewer Demographics(gender/race)', 'Star Rating', 'How Many Stars', 'Other Meta-Data', 'Review', 'URL'])\n #getting responses using place ids collected in place_id.\n for ids in place_id:\n details_api = \"https://maps.googleapis.com/maps/api/place/details/json?\"\n parameters = {\"placeid\": ids,\n \"key\":\"AIzaSyCPFtscQTpvKikFNUfZGOWeZFLe2jt39HE\" } #api key here.\n detail_resp = requests.get(details_api, parameters)\n result = detail_resp.json()['result']\n try:\n reviewss = result['reviews']\n doc_name=result['name']\n doc_url = result['url']\n city_state = result['formatted_address']\n website = 'GOOGLE'\n specialty = 'Urologists'\n date_collected = 'June 15 2017'\n total_poss = '5'\n #gets multiple reviews of the physician(if any).\n for review in reviewss:\n ###rating = review['rating']\n ###revname = review['author_name']\n rev = review['text']\n ###date_review = review['relative_time_description']\n ###rev_url = review.get('author_url', '')\n \n ##yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')\n rev = rev.encode('ascii', 'ignore').decode('ascii')\n ###revname = revname.encode('ascii', 'ignore').decode('ascii')\n ###date_review = date_review.encode('ascii', 'ignore').decode('ascii')\n ###rev_url = rev_url.encode('ascii', 'ignore').decode('ascii')\n\n \n\n\n ###writer.writerow([date_collected, doc_name, city_state, website, specialty, revname, date_review, rev_url, rating, total_poss, '', rev, doc_url])\n\n ###writer.writerow([city,att,doc_name,rev, '.'])\n writer.writerow([rev, '.'])\n\n\n except:\n print('******** WARNING: No reviews are found for this city: ' + city)\n","sub_path":"get_att_comments_by_no_name.py","file_name":"get_att_comments_by_no_name.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"40531148","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 10 17:55:25 2021\n\n@author: kevin\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n# import json\nimport os\n\nfrom datetime import timedelta\nfrom sklearn.preprocessing import OneHotEncoder\n\ndef read_file():\n start_date = pd.to_datetime('2020-01-01')\n end_date = pd.to_datetime('2021-03-21')\n freq = 'D'\n index_name = '日期'\n\n data_fp = os.getcwd() + os.sep + 'dataset' + os.sep\n file_list = os.listdir(data_fp)\n \n date = pd.date_range(start=start_date, end=end_date, freq=freq)\n data_df = pd.DataFrame(index=date)\n data_df.index.name = index_name\n for file in file_list:\n if file.endswith('.csv'):\n try:\n df = pd.read_csv(data_fp+file, encoding='utf-8')\n except:\n try:\n df = pd.read_csv(data_fp+file, encoding='Big5')\n except:\n raise Exception\n \n else:\n continue\n \n if file=='MODIFIED.csv':\n df.set_index(df.columns[0], inplace=True)\n \n # if file in ['台灣電力公司_過去電力供需資訊.csv', \n # '本年度每日尖峰備轉容量率.csv', \n # '近三年每日尖峰備轉容量率.csv']:\n # df.set_index(df.columns[0], inplace=True)\n \n # elif file in ['經濟部能源局_電力供需表.csv']:\n # df.iloc[:, 0] += 191100\n # df.set_index(df.columns[0], inplace=True)\n # df.index = pd.to_datetime(df.index, format='%Y%m') + timedelta(days=14)\n # df = df.iloc[:, 1:]\n \n # elif file in ['經濟部能源局_未來電力供需預測.csv']:\n # df.iloc[:, 0] += 1911\n # df.set_index(df.columns[0], inplace=True)\n # df.index = pd.to_datetime(df.index, format='%Y') + timedelta(days=183)\n \n # elif file in ['經濟部能源局_國內歷次調整之電價.csv']:\n # continue\n # # df.set_index(df.columns[0], inplace=True)\n # # df.index = pd.to_datetime(df.index, format='%Y%m%d')\n # # df = df[(df.index>=start_date) & (df.index<=end_date)]\n \n # # temp_df = pd.DataFrame(index=date)\n # # for col, temp in df.groupby('項目'):\n # # if col not in temp_df:\n # # temp_df[col] = np.nan\n \n # # temp_df.loc[temp.index, col] = temp.values\n \n # elif file in ['科技部科學園區用電負載量.csv']:\n # df = df.transpose()\n # df = df.iloc[1: , 2: 118]\n # df.set_index(df.columns[0], inplace=True)\n # df.set_axis(pd.MultiIndex.from_frame(df.iloc[0: 2, : ].transpose()), axis=1, inplace=True)\n # df = df[2: ]\n \n # temp_df = pd.DataFrame(index=date)\n # for (c, y), ser in df.items():\n # if c==c:\n # col = c\n # elif col!=col:\n # raise ValueError\n \n # if col not in temp_df:\n # temp_df[col] = np.nan\n \n # sd = f'{int(y[: -1])+1911}-01-01'\n # ed = f'{int(y[: -1])+1911}-12-31'\n # if sd not in date or ed not in date:\n # continue\n # d = pd.date_range(start=sd, end=ed, freq='MS') + timedelta(days=14)\n \n # temp_df.loc[d, col] = ser.values\n \n # df = temp_df\n \n \n # Weather data\n \n \n else:\n print(file, 'skipped')\n continue\n \n \n try:\n df.index = pd.to_datetime(df.index, format='%Y%m%d')\n except:\n try:\n df.index = pd.to_datetime(df.index)\n except:\n raise Exception\n \n df.columns = [f'{col} - {file}' for col in df.columns]\n data_df = data_df.merge(df, left_index=True, right_index=True, how='left')\n \n # # Add additional date columns and do one-hot-encoding\n\n # data_df['Weekday'] = data_df.index.dayofweek # Monday=0, Sunday=6\n # data_df['Month'] = data_df.index.month # January=1, December=12\n \n # temp = np.array(list(data_df.index.strftime('%A'))).reshape(-1, 1)\n # weekday_ohe = OneHotEncoder().fit(temp)\n # data_df[weekday_ohe.get_feature_names(['Weekday'])] \\\n # = weekday_ohe.transform(temp).toarray()\n\n # temp = np.array(list(data_df.index.month_name())).reshape(-1, 1)\n # month_ohe = OneHotEncoder().fit(temp)\n # data_df[month_ohe.get_feature_names(['Month'])] \\\n # = month_ohe.fit_transform(temp).toarray()\n\n # Transform into numercal data\n for col, ser in data_df.items():\n if np.any(ser==ser):\n if not np.issubdtype(ser, np.number):\n data_df[col] = ser.astype(float).values\n # print(col)\n # # Replace string with nan\n # df[col].replace(str_to_nan_list, np.nan, inplace=True)\n \n else:\n data_df.drop(col, axis=1, inplace=True)\n \n return data_df\n \n# Read file\ndata_df = read_file()\n\n\nroot_fp = os.getcwd() + os.sep\ndata_df.to_csv(root_fp+'training_data.csv', encoding='big5')\n\n","sub_path":"data_regulator.py","file_name":"data_regulator.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"258021346","text":"from bs4 import BeautifulSoup\nimport requests\n\nclass Product():\n\ttitle = ''\n\tphotoLink = ''\n\tprice = 9999\n\tcurency = ' MDL'\n\tlink = ''\n\tdef __init__(self, title , price, curency, link):\n\t\tself.title = title\n\t\tself.price = price\n\t\tself.curency = curency\n\t\tself.link = link\n\tdef __str__(self):\n\t\treturn ('Title:\\t'+self.title+'\\nLink:\\t'+self.link+'\\nPrice:\\t'+str(self.price)+ '\\nCurency:\\t'+self.curency+'\\n')\n\ndef getHTML(url):\n\treturn requests.get(url).text\ndef Parse(html,keyword,min,max,relevance):\n\tproducts = []\n\tsoup = BeautifulSoup(html,'lxml')\n\titems = soup.find('div', id = 'js-ads-container').find('ul', class_ = 'ads-list-photo').find_all('li', class_ = 'ads-list-photo-item')\n\tfor item in items:\n\t\ttry:\n\t\t\tpriceWithCurency = item.find('div',class_ = 'ads-list-photo-item-price').text\n\t\t\tprice = ''.join(priceWithCurency.split()[:-1])\n\t\t\tcurency = ''.join(priceWithCurency.split()[-1:])\n\t\t\ttitle = item.find('div',class_ = 'ads-list-photo-item-title').text\n\t\t\tlink = 'https://999.md' + item.find('div',class_ = 'ads-list-photo-item-title').find('a')['href']\n\t\t\tif curency == '$':\n\t\t\t\tcurency = 'MDL'\n\t\t\t\tprice = str(int(price) * 17)\n\t\t\telif curency == '€':\n\t\t\t\tcurency = 'MDL'\n\t\t\t\tprice = str(int(price) * 20)\n\t\t\telse:\n\t\t\t\tprice = str(int(price))\n\t\t\t\tcurency = 'MDL'\t\t\t\n\t\t\tif price and int(price) > min and int(price) < max:\n\t\t\t\t\tif relevance:\n\t\t\t\t\t\t\tif keyword in title or keyword.lower in title.lower() or keyword.upper in title.upper():\n\t\t\t\t\t\t\t\t\tproducts.append(Product(title, price, curency, link))\n\t\t\t\t\telse:\n\t\t\t\t\t\tproducts.append(Product(title, price, curency, link))\n\n\t\texcept:\n\t\t\tcontinue\n\treturn products\n\n# def ParseCurency():\n# \turl = 'https://www.curs.md/ru'\n# \thtml = getHTML(url)\n# \tsoup = BeautifulSoup(html,'lxml')\n# \tallCurency = soup.find('div', id = 'cursBox').find('table', class_ = 'table').find_all('tr')\n# \tusd = allCurency.find.(text='USD').parent\n# \tprint(usd)\n\ndef main():\n\tkeyword = 'macbook'\n\tParseCurency()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"_parser.py","file_name":"_parser.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"225382774","text":"from abc import ABC\n\nfrom tensorflow.python.keras.engine import data_adapter\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.applications import DenseNet121\nimport tensorflow as tf\n\nfrom dmv import settings\n\n\nclass MultiEvalModel(Model, ABC):\n def dlf(self, x):\n x_mask = tf.expand_dims(tf.cast(\n tf.math.greater(\n tf.math.count_nonzero(x, axis=[2, 3, 4]),\n tf.constant([0], dtype=tf.int64)\n ),\n tf.keras.backend.floatx()), axis=-1)\n\n x = tf.transpose(x, perm=[1, 0, 2, 3, 4])\n y_preds = tf.map_fn(fn=lambda t: self(t, training=False), elems=x)\n y_preds = tf.transpose(y_preds, perm=[1, 0, 2])\n\n y_pred = tf.math.divide(\n tf.math.reduce_sum(tf.math.multiply(y_preds, x_mask), axis=1),\n tf.math.reduce_sum(x_mask, axis=1)\n )\n\n return y_pred\n\n def test_step(self, data):\n data = data_adapter.expand_1d(data)\n x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)\n\n y_pred = self.dlf(x)\n\n # Updates stateful loss metrics.\n self.compiled_loss(y, y_pred, sample_weight, regularization_losses=self.losses)\n\n self.compiled_metrics.update_state(y, y_pred, sample_weight)\n return {m.name: m.result() for m in self.metrics}\n\n def predict_step(self, data):\n data = data_adapter.expand_1d(data)\n x, _, _ = data_adapter.unpack_x_y_sample_weight(data)\n return self.dlf(x)\n\n\nclass Mura(MultiEvalModel):\n def __init__(self, num_classes, input_shape):\n super().__init__()\n self.num_classes = num_classes\n self.my_input_shape = input_shape\n\n self.base = DenseNet121(include_top=False, input_shape=input_shape, pooling='avg', weights=settings.DENSENET_INIT)\n for index, layer in enumerate(self.base.layers):\n layer.trainable = True\n\n self.classify = Dense(num_classes, activation='sigmoid', name='classify')\n\n def get_config(self):\n config = super().get_config().copy()\n config.update({\n 'num_classes': self.num_classes,\n 'input_shape': self.my_input_shape\n })\n\n def call(self, inputs, **kwargs):\n x = self.base(inputs)\n x = self.classify(x)\n\n return x\n\n @staticmethod\n def folder_id():\n return 'single'\n","sub_path":"src/main/python/dmv/models/single.py","file_name":"single.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"540360732","text":"from cassandra import ConsistencyLevel\r\nfrom cassandra.cluster import Cluster\r\nfrom cassandra.query import SimpleStatement, tuple_factory\r\n\r\nif name == \"main\":\r\n cluster = Cluster(['127.0.0.1'], port=9042)\r\n session = cluster.connect('Client_queue', wait_for_all_pools=True)\r\n session.row_factory = tuple_factory\r\n\r\n query1 = SimpleStatement(\r\n \"SELECT client_fullname,client_document,queue_number FROM \\\"Client_queue\\\"\",\r\n consistency_level=ConsistencyLevel.LOCAL_ONE)\r\n executive1 = session.execute(query1)\r\n\r\n session = cluster.connect('Schedule_queue', wait_for_all_pools=True)\r\n session.row_factory = tuple_factory\r\n\r\n query2 = SimpleStatement(\r\n \"SELECT date,time_in_queue,queue_name FROM \\\"Schedule_queue\\\"\",\r\n consistency_level=ConsistencyLevel.LOCAL_ONE)\r\n executive2 = session.execute(query2)\r\n\r\n session = cluster.connect('Place_queue', wait_for_all_pools=True)\r\n session.row_factory = tuple_factory\r\n\r\n query3 = SimpleStatement(\r\n \"SELECT type_of_service, waiting_time,number_of_people FROM \\\"Place_queue\\\"\",\r\n consistency_level=ConsistencyLevel.LOCAL_ONE)\r\n executive3 = session.execute(query3)\r\n\r\n session = cluster.connect('Client_place', wait_for_all_pools=True)\r\n session.row_factory = tuple_factory\r\n\r\n query4 = SimpleStatement(\r\n \"SELECT client_fullname,client_document,type_of_service FROM \\\"Client_place\\\"\",\r\n consistency_level=ConsistencyLevel.LOCAL_ONE)\r\n executive4 = session.execute(query4)\r\n\r\n for Rows in executive1:\r\n print(Rows)\r\n for Rows in executive2:\r\n print(Rows)\r\n for Rows in executive3:\r\n print(Rows)\r\n for Rows in executive4:\r\n print(Rows)","sub_path":"Lab1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"649528076","text":"import os\nimport cv2 as cv\nimport numpy as np\n\npeople = ['Ben Afflek','Elton John',\"Jerry Seinfield\",'Madonna','Mindy Kaling','santosh']\n#people = ['']\nDIR = r'E:\\hangman\\clock\\opencv\\train'\np = []\nhaar_cascade = cv.CascadeClassifier('har_face.xml')\nfeatures = []\nlabels = []\n\ndef create_train():\n for person in people:\n path = os.path.join(DIR,person)\n label = people.index(person)\n \n for img in os.listdir(path):\n img_path = os.path.join(path,img)\n img_array = cv.imread(img_path)\n gray = cv.cvtColor(img_array,cv.COLOR_BGR2GRAY)\n print(img_path) \n\n faces_rect = haar_cascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=4)\n \n for (x,y,w,h) in faces_rect:\n faces_roi = gray[y:y+h,x:x+w]\n features.append(faces_roi)\n labels.append(label)\n\n\ncreate_train()\n\nfeatures = np.array(features,dtype=\"object\")\nlabels = np.array(labels)\n\nface_recognizer = cv.face.LBPHFaceRecognizer_create()\n\"\"\"training\"\"\"\n\nface_recognizer.train(features,labels)\nface_recognizer.save('face_trained.yml')\nnp.save('features.npy',features)\nnp.save('labels.npy',labels)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"16 face recognizer.py","file_name":"16 face recognizer.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"398275399","text":"#!/usr/bin/env python3\n\nimport os\nimport base64\nimport pickle\nimport boto.utils\nimport logging\nimport sys\nimport textwrap\n\nfrom jinja2 import Template\n\nAWSLOGS_CONFIG_TEMPLATE = textwrap.dedent(\"\"\"\n [general]\n state_file = /var/awslogs/state/agent-state\n buffer_duration = 5000\n initial_position = start_of_file\n encoding = utf-8\n {% for log_mapping in observed_log_files %}\n [{{log_mapping['file']}}]\n datetime_format = {{log_mapping['datetime_format']}}\n multi_line_start_pattern = {datetime_format}\n file = {{log_mapping['file']}}\n log_group_name = {{log_mapping['group_name']}}\n log_stream_name = {{instance_id}}\n {% endfor %}\n\"\"\")\n\n\ndef render_template(template, environment):\n \"\"\"\n Render a template with given params\n :param template: Jinja2 template string\n :param environment: dict of vars to render in template\n :return: rendered template string\n \"\"\"\n template = Template(template, trim_blocks=True)\n return str(template.render(environment)).strip()\n\n\ndef write_file(path, content):\n with open(path, 'w') as file:\n file.write(content)\n\n\ndef main(pickled_logs):\n logging.basicConfig(level=logging.INFO)\n\n logging.info('Configuring Cloudwatch Logs Agent')\n\n identity = boto.utils.get_instance_identity()['document']\n logs_str = base64.b64decode(pickled_logs)\n observed_log_files = pickle.loads(logs_str)\n\n logging.info('Watching logs:')\n for log_file in observed_log_files:\n logging.info(' %s', log_file['file'])\n\n # Create any log directories that don't already exist. This is a convenience so that\n # if you're mounting a docker volume for logs as part of your deployment you don't need to\n # worry about creating it first.\n for log_file in observed_log_files:\n file_path = log_file['file']\n last_slash = file_path.rfind('/')\n if last_slash > 0:\n directory = file_path[:last_slash]\n if not os.path.isdir(directory):\n logging.info('Creating log directory: %s', directory)\n os.makedirs(directory)\n os.chmod(directory, 0o777)\n\n environment = {\n 'observed_log_files': observed_log_files,\n 'region': identity['region'],\n 'account_id': identity['accountId'],\n 'instance_id': identity['instanceId']\n }\n\n try:\n write_file('/tmp/awslogs.conf', render_template(AWSLOGS_CONFIG_TEMPLATE, environment))\n os.system('sudo mv /tmp/awslogs.conf /var/awslogs/etc/awslogs.conf')\n\n logging.info('Successfully configured Cloudwatch Logs Agent')\n logging.info('Restarting Cloudwatch Logs Agent')\n os.system('service awslogs restart')\n except Exception as e:\n logging.error('Failed to configure Cloudwatch Logs Agent')\n logging.exception(e)\n sys.exit(1)\n\nif __name__ == '__main__':\n main(sys.argv[1])\n","sub_path":"runtime/opt/nova/configure-cloudwatch-logs-agent.py","file_name":"configure-cloudwatch-logs-agent.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"190864948","text":"\"\"\"\nauthor: mikaeld\n\"\"\"\n\n\ndef longest_substring(input_string: str, k: int):\n result_substring = ''\n\n for index in range(len(input_string)):\n\n for reader_position in range(index, len(input_string)):\n substring = input_string[index:reader_position+1]\n unique_characters = set(substring)\n\n if len(unique_characters) <= k:\n if len(substring) > len(result_substring):\n result_substring = substring\n\n else:\n break\n\n return result_substring\n\n\nif __name__ == '__main__':\n assert longest_substring('abcba', 2) == 'bcb'\n assert longest_substring('aasdqwwwss', 2) == 'wwwss'\n","sub_path":"2020-04-05/mducharme.py","file_name":"mducharme.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"96574403","text":"import torch\r\nimport torchvision\r\nfrom torch import nn\r\nfrom torch.autograd import Variable\r\nimport torch.nn.functional as F\r\nfrom torchvision.utils import save_image\r\nfrom torchvision.models import vgg16\r\nimport math\r\ndef weights_init_normal(m):\r\n classname = m.__class__.__name__\r\n if classname.find('Conv') != -1:\r\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\r\n elif classname.find('BatchNorm') != -1:\r\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\r\n torch.nn.init.constant_(m.bias.data, 0.0)\r\n\r\nclass Generator(nn.Module):\r\n def __init__(self, scale_factor):\r\n upsample_block_num = int(math.log(scale_factor, 2))\r\n\r\n super(Generator, self).__init__()\r\n self.block1 = nn.Sequential(\r\n nn.Conv2d(3, 64, kernel_size=9, padding=4),\r\n nn.PReLU()\r\n )\r\n self.block2 = ResidualBlock(64)\r\n self.block3 = ResidualBlock(64)\r\n self.block4 = ResidualBlock(64)\r\n self.block5 = ResidualBlock(64)\r\n self.block6 = ResidualBlock(64)\r\n self.block7 = nn.Sequential(\r\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(64)\r\n )\r\n block8 = [UpsampleBLock(64, 2) for _ in range(upsample_block_num)]\r\n block8.append(nn.Conv2d(64, 3, kernel_size=9, padding=4))\r\n self.block8 = nn.Sequential(*block8)\r\n\r\n def forward(self, x):\r\n block1 = self.block1(x)\r\n block2 = self.block2(block1)\r\n block3 = self.block3(block2)\r\n block4 = self.block4(block3)\r\n block5 = self.block5(block4)\r\n block6 = self.block6(block5)\r\n block7 = self.block7(block6)\r\n block8 = self.block8(block1 + block7)\r\n\r\n return (F.tanh(block8) + 1) / 2\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self):\r\n super(Discriminator, self).__init__()\r\n self.net = nn.Sequential(\r\n nn.Conv2d(3, 64, kernel_size=3, padding=1),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(64),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(64, 128, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(128),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(128),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(128, 256, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(256),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(256),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(256, 512, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(512),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(512),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Conv2d(512, 1024, kernel_size=1),\r\n nn.LeakyReLU(0.2),\r\n nn.Conv2d(1024, 1, kernel_size=1)\r\n )\r\n\r\n def forward(self, x):\r\n batch_size = x.size(0)\r\n return F.sigmoid(self.net(x).view(batch_size))\r\n\r\n\r\nclass ResidualBlock(nn.Module):\r\n def __init__(self, channels):\r\n super(ResidualBlock, self).__init__()\r\n self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)\r\n self.bn1 = nn.BatchNorm2d(channels)\r\n self.prelu = nn.PReLU()\r\n self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)\r\n self.bn2 = nn.BatchNorm2d(channels)\r\n\r\n def forward(self, x):\r\n residual = self.conv1(x)\r\n residual = self.bn1(residual)\r\n residual = self.prelu(residual)\r\n residual = self.conv2(residual)\r\n residual = self.bn2(residual)\r\n\r\n return x + residual\r\n\r\n\r\nclass UpsampleBLock(nn.Module):\r\n def __init__(self, in_channels, up_scale):\r\n super(UpsampleBLock, self).__init__()\r\n self.conv = nn.Conv2d(in_channels, in_channels * up_scale ** 2, kernel_size=3, padding=1)\r\n self.pixel_shuffle = nn.PixelShuffle(up_scale)\r\n self.prelu = nn.PReLU()\r\n\r\n def forward(self, x):\r\n x = self.conv(x)\r\n x = self.pixel_shuffle(x)\r\n x = self.prelu(x)\r\n return x\r\n# WGAN\r\n\r\nimport os\r\nimport pickle\r\nimport glob\r\nimport numpy as np\r\nimport torch\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\nfrom PIL import Image\r\nfrom torch.utils.data import Dataset\r\n# HR_train_data_path = 'C:/Users/User/Desktop/GAN_data_set/imagenet64_train/Imagenet64_train'\r\nHR_train_data_path = './SRGAN_training_data/*'\r\ntest_data_path = './SRGAN_test_data/*'\r\n\r\nbatch_size = 64\r\ninput_channels = 3\r\nhr_height = 128\r\nlr_height = 32\r\nn_critic = 1\r\nn_critic_D = 1\r\nclip_value = 0.02\r\nepochs = 100\r\nnum_epochs = 201\r\ndef unpickle(file):\r\n with open(file, 'rb') as fo:\r\n dict = pickle.load(fo)\r\n return dict\r\n\r\nclass ImageDataset(Dataset):\r\n def __init__(self, imgs, lr_transforms=None, hr_transforms=None):\r\n self.lr_transform = transforms.Compose(lr_transforms)\r\n self.hr_transform = transforms.Compose(hr_transforms)\r\n\r\n self.files = imgs\r\n\r\n def __getitem__(self, index):\r\n img = Image.fromarray(self.files[index].astype('uint8'), 'RGB')\r\n img_lr = self.lr_transform(img)\r\n img_hr = self.hr_transform(img)\r\n\r\n return {'lr': img_lr, 'hr': img_hr}\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\nclass TestImageDataset(Dataset):\r\n def __init__(self, imgs, lr_transforms=None, hr_transforms=None):\r\n self.lr_transform = transforms.Compose(lr_transforms)\r\n self.hr_transform = transforms.Compose(hr_transforms)\r\n\r\n self.files = imgs\r\n\r\n def __getitem__(self, index):\r\n img = Image.fromarray(self.files[index].astype('uint8'), 'RGB')\r\n img_lr = self.lr_transform(img)\r\n img_hr = self.hr_transform(img)\r\n\r\n return {'lr': img_lr, 'hr': img_hr}\r\n\r\n def __len__(self):\r\n return len(self.files)\r\ndef load_databatch(data_folder, idx):\r\n data_file_HR = os.path.join(HR_train_data_path, 'train_data_batch_')\r\n d_HR = unpickle(data_file_HR + str(idx))\r\n x_HR = d_HR['data'][:4000]\r\n\r\n data_size = x_HR.shape[0]\r\n\r\n hr_height2 = hr_height * hr_height\r\n x_HR = np.dstack((x_HR[:, :hr_height2], x_HR[:, hr_height2:2*hr_height2], x_HR[:, 2*hr_height2:]))\r\n x_HR = x_HR.reshape((x_HR.shape[0], hr_height, hr_height, 3))\r\n\r\n lr_transforms = [\r\n transforms.Resize((hr_height//4, hr_height//4), Image.BICUBIC),\r\n transforms.ToTensor() ]\r\n\r\n hr_transforms = [\r\n transforms.Resize((hr_height, hr_height), Image.BICUBIC),\r\n transforms.ToTensor() ]\r\n\r\n train_loader = torch.utils.data.DataLoader(ImageDataset(x_HR, lr_transforms=lr_transforms, hr_transforms=hr_transforms),\r\n batch_size=batch_size, shuffle=True)\r\n return train_loader\r\n\r\ndef load_jpg(data_folder,batch_size = batch_size, shuffle=True):\r\n# print(data_folder)\r\n image_list = []\r\n print(\"start loading\")\r\n for filename in glob.glob(data_folder): #assuming gif\r\n im = Image.open(filename)\r\n im = im.resize((hr_height, hr_height), Image.BICUBIC)\r\n im = np.array(im)\r\n if im.shape == (hr_height ,hr_height ,3):\r\n image_list.append(im)\r\n\r\n image = np.asarray(image_list)\r\n\r\n lr_transforms = [\r\n transforms.Resize((lr_height, lr_height), Image.BICUBIC),\r\n transforms.ToTensor()\r\n ]\r\n\r\n hr_transforms = [\r\n transforms.Resize((hr_height, hr_height), Image.BICUBIC),\r\n transforms.ToTensor()\r\n ]\r\n\r\n train_loader = torch.utils.data.DataLoader(TestImageDataset(image, lr_transforms=lr_transforms, hr_transforms=hr_transforms),\r\n batch_size=batch_size, shuffle=shuffle)\r\n\r\n return train_loader\r\n\r\ndataloader = load_jpg(HR_train_data_path)\r\ntest_data_set = load_jpg(test_data_path,shuffle = False)\r\n# print(dataloader)\r\nprint(\"end\")\r\n\r\n# Loss function\r\nclass GeneratorLoss(nn.Module):\r\n def __init__(self):\r\n super(GeneratorLoss, self).__init__()\r\n vgg = vgg16(pretrained=True)\r\n loss_network = nn.Sequential(*list(vgg.features)[:31]).eval()\r\n for param in loss_network.parameters():\r\n param.requires_grad = False\r\n self.loss_network = loss_network\r\n self.mse_loss = nn.MSELoss()\r\n self.tv_loss = TVLoss()\r\n\r\n def forward(self, out_labels, out_images, target_images):\r\n # Adversarial Loss\r\n adversarial_loss = torch.mean(1 - out_labels)\r\n # Perception Loss\r\n perception_loss = self.mse_loss(self.loss_network(out_images), self.loss_network(target_images))\r\n # Image Loss\r\n image_loss = self.mse_loss(out_images, target_images)\r\n # TV Loss\r\n tv_loss = self.tv_loss(out_images)\r\n return image_loss + 0.001 * adversarial_loss + 0.006 * perception_loss + 2e-8 * tv_loss\r\nclass TVLoss(nn.Module):\r\n def __init__(self, tv_loss_weight=1):\r\n super(TVLoss, self).__init__()\r\n self.tv_loss_weight = tv_loss_weight\r\n\r\n def forward(self, x):\r\n batch_size = x.size()[0]\r\n h_x = x.size()[2]\r\n w_x = x.size()[3]\r\n count_h = self.tensor_size(x[:, :, 1:, :])\r\n count_w = self.tensor_size(x[:, :, :, 1:])\r\n h_tv = torch.pow((x[:, :, 1:, :] - x[:, :, :h_x - 1, :]), 2).sum()\r\n w_tv = torch.pow((x[:, :, :, 1:] - x[:, :, :, :w_x - 1]), 2).sum()\r\n return self.tv_loss_weight * 2 * (h_tv / count_h + w_tv / count_w) / batch_size\r\n\r\n @staticmethod\r\n def tensor_size(t):\r\n return t.size()[1] * t.size()[2] * t.size()[3]\r\n# def generator_loss(logits_fake):\r\n# size = logits_fake.shape[0]\r\n# true_labels = Variable(torch.ones(size, 1)).float().cuda()\r\n# loss = torch.mean(logits_fake)\r\n# return loss\r\n# def adversarial_loss(logits_real, logits_fake): # 判别器的 loss\r\n# size = logits_real.shape[0]\r\n# true_labels = Variable(torch.ones(size, 1)).float().cuda()\r\n# false_labels = Variable(torch.zeros(size, 1)).float().cuda()\r\n# loss = torch.nn.L1Loss(logits_real, true_labels) + torch.nn.L1Loss(logits_fake, false_labels)\r\n# return loss\r\n\r\ngenerator_loss = GeneratorLoss().cuda()\r\ndiscriminator_loss = torch.nn.MSELoss()\r\ncontent_loss = nn.MSELoss(size_average = True)\r\n\r\n\r\n\r\n#Optimizer\r\n\r\n\r\n\r\ndef psnr_cal(img1, img2):\r\n mse = np.mean( (img1 - img2) ** 2 )\r\n\r\n PIXEL_MAX = 1.0\r\n return 20 * np.log10(PIXEL_MAX / np.sqrt(mse))\r\n\r\ncuda = True if torch.cuda.is_available() else False\r\nTensor = torch.cuda.FloatTensor if cuda else torch.Tensor\r\ninput_lr = Tensor(batch_size, input_channels, lr_height, lr_height).cuda()\r\ninput_hr = Tensor(batch_size, input_channels, hr_height, hr_height).cuda()\r\nvalid = Variable(torch.ones(batch_size, 1)).float().cuda()\r\nfake = Variable(torch.zeros(batch_size, 1)).float().cuda()\r\n\r\n# def debug_memory():\r\n# import collections, gc, torch\r\n# tensors = collections.Counter((str(o.device), o.dtype, tuple(o.shape))\r\n# for o in gc.get_objects()\r\n# if torch.is_tensor(o))\r\n# for line in sorted(tensors.items()):\r\n# print('{}\\t{}'.format(*line))\r\n# debug_memory()\r\n\r\ndef train_a_gan(D_net, G_net, D_optimizer, G_optimizer, generator_loss, sample_interval = 50, checkpoint_interval = 10):\r\n iter_count = 0\r\n current_batch = 0\r\n index = 0\r\n torch.cuda.empty_cache()\r\n for epoch in range(epochs, num_epochs):\r\n for i, img in enumerate(dataloader):\r\n if i == len(dataloader)-1:\r\n break;\r\n # model input\r\n imgs_lr = Variable(input_lr.copy_(img['lr'])).cuda()\r\n imgs_hr = Variable(input_hr.copy_(img['hr'])).cuda()\r\n# print(imgs_lr.size())\r\n\r\n fake_images = G_net(imgs_lr).detach()\r\n # Train Discriminator\r\n# if i % n_critic_D == 0 :\r\n D_optimizer.zero_grad()\r\n\r\n #loss of real and fake image\r\n # Total loss\r\n\r\n # GAN\r\n\r\n # loss_D = discriminator_loss(D_net(imgs_hr), valid) + discriminator_loss(D_net(fake_images), fake)\r\n\r\n # WGAN\r\n loss_D = 1 - D_net(imgs_hr).mean() + D_net(fake_images).mean() # 判别器的 loss\r\n\r\n # RGAN\r\n # loss_D = -torch.mean(torch.log(torch.sigmoid(-Relative))) # 判别器的 loss\r\n\r\n loss_D.backward()\r\n D_optimizer.step()\r\n\r\n\r\n\r\n # train generators\r\n# if i % n_critic == 0:\r\n G_optimizer.zero_grad()\r\n # Generate Hr from low resolution input\r\n # adversarial loss\r\n gen_img = G_net(imgs_lr)\r\n # GAN\r\n # gen_error = generator_loss(D_net(fake_images), valid)\r\n # WGAN\r\n# gen_error = -torch.mean(D_net(gen_img))\r\n# content_error = content_loss(gen_img , imgs_hr)\r\n\r\n\r\n # VGG_feature_loss\r\n# gen_features = feature_extractor(fake_images)\r\n# real_features = Variable(feature_extractor(imgs_hr).data, requires_grad=False)\r\n# VGG_loss = content_loss(real_features , gen_features)\r\n # print(imgs_hr.size())\r\n\r\n\r\n #Total loss\r\n # GAN\r\n real_out = D_net(imgs_hr).mean()\r\n fake_out = D_net(fake_images).mean()\r\n loss_G = generator_loss(fake_out, gen_img, imgs_hr)\r\n\r\n # WGAN\r\n # loss_G = 1e-2*gen_error + content_error\r\n\r\n # RGAN\r\n # Relative = D_net(fake_images)-D_net(imgs_hr)\r\n\r\n loss_G.backward()\r\n G_optimizer.step()\r\n\r\n print(\"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]\" %\r\n (epoch, num_epochs, i, len(dataloader),\r\n loss_D.item(), loss_G.item()))\r\n\r\n\r\n# print(fake_images.data.cpu().numpy())\r\n # Save image sample turn to next batch\r\n if i % sample_interval == 0 :\r\n index = index+1\r\n psnr_val = 0\r\n for i , test_img in enumerate(test_data_set):\r\n if i >= 1:\r\n break;\r\n# print(test_img)\r\n test_imgs_lr = Variable(input_lr.copy_(test_img['lr'])).detach()\r\n test_imgs_hr = Variable(input_hr.copy_(test_img['hr'])).detach()\r\n test_fake_images = G_net(test_imgs_lr)\r\n\r\n psnr_val += psnr_cal(test_fake_images.data.cpu().numpy(),test_imgs_hr.data.cpu().numpy())\r\n print(\"[PSNR: %f]\"%psnr_val)\r\n# save_image(test_imgs_lr,\"C:/Users/User/Desktop/Deep_Learning/GAN_images/TESTIMAGE'{0}'.png\".format(i+(epoch)*batch_size), normalize=True)\r\n save_image(torch.cat((test_fake_images.data, test_imgs_hr.data), -2),\r\n \"./SRGAN_save_image/'{0}'.png\".format(i+(epoch)*len(dataloader)), normalize=True)\r\n\r\n# if i == (len(dataloader)-1) :\r\n# break;\r\n\r\n if checkpoint_interval != -1 and epoch % checkpoint_interval == 0:\r\n # Save model checkpoints\r\n torch.save(G_net.state_dict(), './SRGAN_save_model/generator_%d-RGAN.pth' % epoch)\r\n torch.save(D_net.state_dict(), './SRGAN_save_model/discriminator_%d-RGAN.pth' % epoch)\r\n\r\nD = Discriminator().cuda()\r\nG = Generator(4).cuda()\r\ndef get_optimizer_G(net):\r\n optimizer = torch.optim.Adam(net.parameters(), lr = 1e-4)\r\n return optimizer\r\ndef get_optimizer_D(net):\r\n optimizer = torch.optim.Adam(net.parameters(), lr = 1e-4)\r\n return optimizer\r\nD_optim = get_optimizer_D(D)\r\nG_optim = get_optimizer_G(G)\r\n\r\nif epochs != 0:\r\n # Load pretrained models\r\n D.apply(weights_init_normal)\r\n# D.load_state_dict(torch.load('./SRGAN_save_model/discriminator_%d-RGAN.pth'% epochs))\r\n G.load_state_dict(torch.load('./SRGAN_save_model/generator_%d-RGAN.pth'% epochs))\r\nelse:\r\n # Initialize weights\r\n D.apply(weights_init_normal)\r\n G.apply(weights_init_normal)\r\ntrain_a_gan(D, G, D_optim, G_optim, generator_loss)\r\n","sub_path":"SRGAN.py","file_name":"SRGAN.py","file_ext":"py","file_size_in_byte":16478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"472246356","text":"import json, config\nfrom requests_oauthlib import OAuth1Session\n\n#認証までは同じ\nCK = config.CONSUMER_KEY\nCS = config.CONSUMER_SECRET\nAT = config.ACCESS_TOKEN\nATS = config.ACCESS_TOKEN_SECRET\n#OAuth認証処理\ntwitter = OAuth1Session(CK,CS,AT,ATS)\n\n#エンドポイントは前回のタイムラインと異なる\n#ツイートポストエンドポイント\nurl = \"https://api.twitter.com/1.1/statuses/update.json\"\n\nprint(\"ツイートする内容の入力フォーム\")\n#input()でキーボード入力\ntweet = input(\">> \")\nprint('*******************************************')\n\n#辞書型で保存\nparams = {\"status\" : tweet}\n\n#post送信\nres = twitter.post(url, params = params)\n\n#status_code = 200だと正常に動作した\nif res.status_code == 200:\n print(\"Success.\")\n#正常投稿出来なかった場合\nelse:\n print(\"Failed. : %d\"% res.status_code)\n","sub_path":"python_Twitter/postTweet.py","file_name":"postTweet.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27613241","text":"import pandas as pd\nimport numpy as np\nimport random\nimport math\nimport os\nfrom tqdm import tqdm\nfrom pathlib import Path\n\n\ndef change_docker_cwd(target_dir):\n \"\"\"Change the current working dir if in docker\"\"\"\n if f\"{os.getenv('BASE_DIR')}\" == str(Path.cwd()):\n os.chdir(Path(target_dir))\n print(f\"Running in docker -> Change cwd to {target_dir}\")\n\n\n# read csv file as data frame\ndef readCSV(path):\n return pd.read_csv(path)\n\n\n# get random gender distribution\ndef getRandomDistribution(df, N):\n idx_list = [None] * N\n for i in np.arange(N):\n idx_list[i] = random.choice(list(df.index))\n return idx_list\n\n\n# get requested gender distribution\ndef getGenderDistribution(df, ratio, N):\n # Get female idxs\n idx_female = df.index[df[\"Gender\"] == \"female\"]\n # females = df.iloc[idx_female]\n # Get male idxs\n idx_male = df.index[df[\"Gender\"] == \"male\"]\n # males = df.iloc[idx_male]\n\n female_num = int(ratio * N)\n male_num = N - female_num\n\n idx_list = random.choices(idx_female, k=female_num)\n idx_list = idx_list + random.choices(idx_male, k=male_num)\n\n # idx_list = random.shuffle(idx_list)\n return idx_list\n\n\n# get female lists\ndef getFemaleList(df, N):\n idx_list = [None] * N\n # Get female idxs\n idx_female = df.index[df[\"Gender\"] == \"female\"]\n\n for i in np.arange(N):\n # print(np.mod(i, len(df)))\n idx_list[i] = df.index[idx_female[np.mod(i, len(idx_female))]]\n\n # idx_list = random.shuffle(idx_list)\n return idx_list\n\n\n# get male lists\ndef getMaleList(df, N):\n idx_list = [None] * N\n # Get female idxs\n idx_male = df.index[df[\"Gender\"] == \"male\"]\n\n for i in np.arange(N):\n # print(np.mod(i, len(df)))\n idx_list[i] = df.index[idx_male[np.mod(i, len(idx_male))]]\n\n # idx_list = random.shuffle(idx_list)\n return idx_list\n\n\n# create chunks with sliding window\ndef slidingWindow(x, window, stride):\n # Warning: this function changes the view of the array but the locations in memory is the same!\n shape = x.shape[:-1] + (math.floor((x.shape[-1] - window) / stride) + 1, window)\n strides = x.strides[:-1] + (\n x.strides[-1] * stride,\n x.strides[-1],\n )\n return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)\n\n\n# load precomputed feature vectors\ndef loadFeatureDatabase(path):\n files = os.listdir(path)\n feat_database = []\n for f in tqdm(files):\n feat_database.append(np.load(PATH + \"features/\" + f))\n return np.asarray(feat_database)\n","sub_path":"utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"299083973","text":"#!/usr/bin/env python\nimport cv2\nimport numpy as np\n\nwindowName = \"Bean\";\nh = np.array([1, 4, 6, 4, 1],float);\nsum = np.sum(h)\nh = h/sum\n\ndef display(window, im):\n\twhile True:\n\t\n\t\tcv2.imshow(window, im)\n\t\tkey = cv2.waitKey(1) & 0xFF\n\t\t# if the 'c' key is pressed, break from the loop\n\t\tif key == ord(\"n\"):\n\t\t\tbreak\n\tcv2.destroyAllWindows()\n\ndef getGaussian(im, fil):\n\theight, width = im.shape[:2]\n\ttemp = np.zeros((height, width,3), np.uint8)\n\tcv2.filter2D(im, -1, fil, temp)\n\ttemp =cv2.resize(temp,(height/2,width/2))\n\n\treturn temp\n\ndef getLaplacian(im, fil):\n\theight, width = im.shape[:2]\n\ttemp = np.zeros((height/2,width/2,3), np.uint8)\n\ttemp = getGaussian(im, fil)\n\tim = cv2.resize(im,(height/2,width/2))\n\tLap = im - temp\n\n\treturn Lap, temp\n\n\n\ndef main():\n\timage = cv2.imread('tstimg.jpg',1);\n\tG = cv2.resize(image,(500,500))\n\timage = cv2.resize(image,(500,500))\n\tdisplay(windowName, image)\n\ttmp = np.zeros((500, 500, 3), np.uint8)\n\n\t# Problem 1: 4 levels of a guassian pyramid\n\t# Press N to cycle through images\n\tprint('Press N to advance through images')\n\tfor x in range(1,5):\n\t\tG = getGaussian(G,h)\n\t\tdisplay('Guassian', G)\n\n\t\t\n\t# Problem 2: 4 levels of a laplacian pyramid\n\t# Press N to cycle through images\n\ttmp = np.zeros((500/2, 500/2, 3), np.uint8)\n\tG = cv2.resize(image,(500,500))\n\tfor x in range(1,5):\n\t\tL, G = getLaplacian(G,h)\n\t\tdisplay('laplacian', L)\n\n\n\n\n# Standard boilerplate to call the main() function to begin\n# the program.\nif __name__ == '__main__':\n main()","sub_path":"Homework/Hw4/Hw4.py","file_name":"Hw4.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"513561137","text":"import threading\n\nimport transaction\n\nimport sheraf\nimport tests\n\n\nclass Child(sheraf.InlineModel):\n nom = sheraf.SimpleAttribute()\n a1 = sheraf.SimpleAttribute()\n a2 = sheraf.SimpleAttribute()\n a3 = sheraf.SimpleAttribute()\n\n @classmethod\n def create(cls, val):\n model = super().create()\n model.nom = val\n model.a1 = val\n model.a2 = val\n model.a3 = val\n model.check(val)\n return model\n\n def check(self, key):\n assert key == self.nom == self.a1 == self.a2 == self.a3\n\n def __eq__(self, other):\n return (\n self.nom == other.nom\n and self.a1 == other.a1\n and self.a2 == other.a2\n and self.a3 == other.a3\n )\n\n\nclass Parent(tests.UUIDAutoModel):\n sons = sheraf.LargeDictAttribute(sheraf.InlineModelAttribute(Child))\n daughters = sheraf.SmallListAttribute(sheraf.InlineModelAttribute(Child))\n\n\nLENGTH = 10000\nNUMBER_OF_THREADS = 4\n\n\nclass TestIterations:\n def test_inline_model_dict(self, sheraf_database):\n with sheraf.connection():\n _parent = Parent.create()\n for i in range(LENGTH):\n _parent.sons[i] = Child.create(i)\n transaction.commit()\n\n class Reader(threading.Thread):\n def __init__(self):\n super().__init__()\n self.failed = False\n\n def run(self):\n with sheraf.connection():\n _parent = next(Parent.all())\n for key, son in _parent.sons:\n try:\n son.check(key)\n except:\n self.failed = True\n\n readers = [Reader() for i in range(NUMBER_OF_THREADS)]\n [r.start() for r in readers]\n\n [r.join() for r in readers]\n assert not any(r.failed for r in readers)\n\n\nclass TestZip:\n def test(self, sheraf_database):\n with sheraf.connection():\n _p1 = Parent.create()\n _p2 = Parent.create()\n for i in range(LENGTH):\n _p1.daughters.append(Child.create(i))\n _p2.daughters.append(Child.create(i))\n transaction.commit()\n\n class Reader(threading.Thread):\n def __init__(self):\n super().__init__()\n self.failed = False\n\n def run(self):\n with sheraf.connection():\n [_p1, _p2] = Parent.all()\n for _d1, _d2 in zip(_p1.daughters, _p2.daughters):\n if not _d1 == _d2:\n self.failed = True\n\n readers = [Reader() for i in range(NUMBER_OF_THREADS)]\n [r.start() for r in readers]\n\n [r.join() for r in readers]\n assert not any(r.failed for r in readers)\n","sub_path":"tests/perf/test_threading.py","file_name":"test_threading.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"155675435","text":"import keras\nimport pandas as pd\nfrom glob import glob\nimport cv2\nimport numpy as np\nfrom keras.models import load_model\n\npreprocess_path = \"pure_test/\"\ntrain_files = glob(os.path.join(preprocess_path, \"*jpeg\"))\ndf = pd.read_csv(\"trainLabels.csv\")\n\n\ndef load_data_label(train_files, df):\n dataset = []\n labels_all=[]\n healthy = 0\n disease = 0\n for f in train_files:\n img_data=cv2.imread(f)\n basename = os.path.basename(f)\n image_id = basename.split(\".\")[0]\n mini_df = df[df['image'] == image_id]\n if len(mini_df) < 1:\n continue\n label = mini_df.values[0][1]\n\n if label == 0:\n healthy += 1\n if healthy > 220:\n healthy = 220\n continue\n else:\n disease += 1\n labels_all.append(label)\n dataset.append(img_data)\n labels_all = keras.utils.to_categorical(labels_all, num_classes=5).astype(np.float16)\n dataset = np.array(dataset).astype(np.float16)\n return dataset, labels_all, healthy, disease\n\n\nif __name__ == '__main__':\n model = load_model(\"final_model_inv3.hdf5\")\n model.summary()\n\n dataSet, labelSet , positive, negative = load_data_label(train_files, df)\n# divide_number = len(train_files) // 8\n data_test = dataSet\n label_test = labelSet\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0, 1, 2, 3\"\n\n score = model.evaluate(data_test, label_test, verbose=1)\n rate = 100*positive/(positive + negative)\n print(\"Positive rate is: \" + str(round(rate,4)) + \"%\")\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])\n","sub_path":"diabetic/preliminary_test.py","file_name":"preliminary_test.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"249972647","text":"from typing import List\n\nfrom superscreen import Layer\n\n\ndef ibm_squid_layers(\n align: str = \"middle\",\n london_lambda: float = 0.08,\n z0: float = 0.0,\n d_BE: float = 0.16,\n d_I1: float = 0.15,\n d_W1: float = 0.10,\n d_I2: float = 0.13,\n d_W2: float = 0.20,\n) -> List[Layer]:\n \"\"\"Return a list of superscreen.Layers representing the superconducting layers\n in IBM SQUID susceptometers.\n\n See https://arxiv.org/pdf/1605.09483.pdf, Figure 8.\n\n Args:\n align: Whether to position the 2D model layer at the top, middle, or bottom\n of the phyical 3D metal layer.\n london_lambda: The London penetration depth for the superconducting films,\n in microns.\n z0: The vertical position of the bottom of W2, i.e. the surface of the\n SQUID chip.\n d_BE, d_I1, d_W1, d_I2, d_W2: Layer thicknesses in microns.\n\n Returns:\n A list a Layer objects representing the SQUID wiring layers.\n\n \"\"\"\n assert align in (\"top\", \"middle\", \"bottom\")\n\n # Metal layer vertical positions in microns.\n if align == \"bottom\":\n z0_W2 = z0\n z0_W1 = z0 + d_W2 + d_I2\n z0_BE = z0 + d_W2 + d_I2 + d_W1 + d_I1\n elif align == \"middle\":\n z0_W2 = z0 + d_W2 / 2\n z0_W1 = z0 + d_W2 / 2 + d_I2 + d_W1 / 2\n z0_BE = z0 + d_W2 / 2 + d_I2 + d_W1 / 2 + d_I1 + d_BE / 2\n else:\n z0_W2 = z0 + d_W2\n z0_W1 = z0 + d_W2 + d_I2 + d_W1\n z0_BE = z0 + d_W2 + d_I2 + d_W1 + d_I1 + d_BE\n\n return [\n Layer(\"W2\", london_lambda=london_lambda, thickness=d_W2, z0=z0_W2),\n Layer(\"W1\", london_lambda=london_lambda, thickness=d_W1, z0=z0_W1),\n Layer(\"BE\", london_lambda=london_lambda, thickness=d_BE, z0=z0_BE),\n ]\n","sub_path":"docs/notebooks/squids/ibm/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"110852807","text":"from mezzanine.pages.models import Page\nfrom django.http import Http404, HttpResponse\nfrom .models import Event, EventContainer, _get_current_domain\nfrom icalendar import Calendar as ICalendar, Event as IEvent\nfrom datetime import datetime\nfrom . import __version__\n\ndef _make_icalendar():\n ical = ICalendar()\n ical.add('prodid',\n '-//St Barnabas Theological College/mezzanine-events//NONSGML V{}//EN'.format(__version__))\n ical.add('version', '2.0') # version of the format, not the product!\n return ical\n\ndef _make_ievent(ev):\n iev = IEvent()\n iev.add('summary', ev.title)\n iev.add('url', 'http://{domain}{url}'.format(\n domain=_get_current_domain(),\n url=ev.get_absolute_url(),\n ))\n iev.add('location', ev.location)\n iev.add('dtstamp', datetime.combine(ev.date, ev.start_time))\n iev.add('dtstart', datetime.combine(ev.date, ev.start_time))\n iev.add('dtend', datetime.combine(ev.end_date, ev.end_time))\n iev['uid'] = \"event-{id}@{domain}\".format(\n id=ev.id,\n domain=_get_current_domain(),\n )\n return iev\n\ndef icalendar(request, slug):\n try:\n page = Page.objects.published(request.user).get(slug=slug)\n except Page.DoesNotExist:\n raise Http404()\n\n if not isinstance(page.get_content_model(), Event):\n raise Http404()\n\n ev = page.get_content_model()\n ical = _make_icalendar()\n iev = _make_ievent(ev)\n ical.add_component(iev)\n\n return HttpResponse(ical.to_ical(), content_type=\"text/calendar\")\n\ndef icalendar_container(request, slug):\n try:\n page = Page.objects.published(request.user).get(slug=slug)\n except Page.DoesNotExist:\n raise Http404()\n\n if not isinstance(page.get_content_model(), EventContainer):\n raise Http404()\n\n ical = _make_icalendar()\n\n for child in page.children.all():\n if isinstance(child.get_content_model(), Event):\n ev = child.get_content_model()\n iev = _make_ievent(ev)\n ical.add_component(iev)\n\n return HttpResponse(ical.to_ical(), content_type=\"text/calendar\")\n","sub_path":"mezzanine_events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"254260177","text":"#-*- coding: utf-8 -*-\n\n\"\"\"\nabstraction for video processor\n\"\"\"\n\nimport numpy as np\n\nimport config\nimport utils\n\n\nclass VideoProcessor(object):\n\n def __init__(self, classifier):\n self.classifier = classifier\n self.n_frames = 0\n self.time_per_frame = []\n self.past_frames = []\n\n def process_frame(self, image):\n \"\"\"process current frame and returns image with detections drawn\"\"\"\n\n self.past_frames.append(image)\n if len(self.past_frames) > config.video_lookback_frame_count:\n self.past_frames.pop(0)\n\n heatmap = np.zeros_like(image.original[:, :, 0]).astype(np.float)\n for img in self.past_frames:\n heatmap = utils.add_heat(heatmap, img.hot_windows)\n thresholded_heatmap = utils.apply_threshold(\n heatmap,\n config.video_heatmap_threshold\n )\n labels = utils.create_labels(thresholded_heatmap)\n final_detection = utils.draw_labeled_bboxes(image.original, labels)\n\n image.heatmap = heatmap\n image.thresholded_heatmap = thresholded_heatmap\n image.drawn_vehicle_detections = final_detection\n","sub_path":"video_processor.py","file_name":"video_processor.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"393439029","text":"\"\"\"\nMeta-experiments which involves training and testing the model with multiple\nhyperparamter settings.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\nimport numpy as np\nimport random\nimport sys\nif sys.version_info > (3, 0):\n from six.moves import xrange\n\nimport tensorflow as tf\nfrom tensorflow.python.util import nest\n\nfrom encoder_decoder import graph_utils\n\n\nhyperparam_range = {\n \"attention_input_keep\": [0.4, 0.6, 0.8, 1.0],\n \"attention_output_keep\": [0.4, 0.6, 0.8, 1.0],\n \"universal_keep\": [0.6, 0.7, 0.75, 0.8, 0.5],\n \"sc_input_keep\": [0.6, 0.7, 0.8],\n \"sc_output_keep\": [0.6, 0.7, 0.8],\n \"tg_input_keep\": [0.6, 0.7, 0.8],\n \"tg_output_keep\": [0.5, 0.6, 0.7, 0.8],\n \"adam_epsilon\": [1e-8, 1e-7, 1e-5, 1e-3, 1e-1],\n \"learning_rate\": [0.0001, 0.001, 0.01, 0.1],\n \"sc_token_dim\": [300, 400, 500, 600],\n \"num_layers\": [2, 4, 8],\n \"num_samples\": [1024, 512],\n \"beta\": [0.8,0.9,1.0,1.1,1.2]\n}\n\n\ndef grid_search(train_fun, decode_fun, eval_fun, train_set, dev_set, FLAGS):\n \"\"\"\n Perform hyperparameter tuning of a model using grid-search.\n\n :param train_fun: Function to train the model.\n :param decode_fun: Function to decode from the trained model.\n :param eval_fun: Function to evaluate the decoding results.\n :param train_set: Training dataset.\n :param dev_set: Development dataset.\n :param FLAGS: General model hyperparameters.\n \"\"\"\n FLAGS.create_fresh_params = True\n\n hyperparameters = FLAGS.tuning.split(',')\n num_hps = len(hyperparameters)\n hp_range = hyperparam_range\n\n print(\"======== Grid Search ========\")\n print(\"%d hyperparameter(s): \" % num_hps)\n for i in xrange(num_hps):\n print(\"{}: {}\".format(\n hyperparameters[i], hp_range[hyperparameters[i]]))\n print()\n\n param_grid = [v for v in hp_range[hyperparameters[0]]]\n for i in xrange(1, num_hps):\n param_grid = itertools.product(param_grid, hp_range[hyperparameters[i]])\n\n best_hp_set = [-1] * num_hps\n best_seed = -1\n best_metrics_value = 0\n\n for row in param_grid:\n row = nest.flatten(row)\n for i in xrange(num_hps):\n setattr(FLAGS, hyperparameters[i], row[i])\n if hyperparameters[i] == 'universal_keep':\n setattr(FLAGS, 'sc_input_keep', row[i])\n setattr(FLAGS, 'sc_output_keep', row[i])\n setattr(FLAGS, 'tg_input_keep', row[i])\n setattr(FLAGS, 'tg_output_keep', row[i])\n setattr(FLAGS, 'attention_input_keep', row[i])\n setattr(FLAGS, 'attention_output_keep', row[i])\n\n print(\"Trying parameter set: \")\n for i in xrange(num_hps):\n print(\"* {}: {}\".format(hyperparameters[i], row[i]))\n\n # Try different random seed if tuning initialization\n num_trials = 5 if FLAGS.initialization else 1\n\n if FLAGS.dataset.startswith('bash'):\n metrics = [\"top1_temp_ms\", \"top1_cms\", \"top3_temp_ms\", \"top3_cms\"]\n metrics_weights = [0.4, 0.4, 0.1, 0.1]\n else:\n metrics = [\"top1_temp_ms\"]\n metrics_weights = [1]\n metrics_signature = '+'.join(\n ['{}x{}'.format(m, mw) for m, mw in zip(metrics, metrics_weights)])\n\n for t in xrange(num_trials):\n seed = random.getrandbits(32)\n tf.set_random_seed(seed)\n metrics_value = single_round_model_eval(train_fun, decode_fun,\n eval_fun, train_set, dev_set, metrics, metrics_weights)\n print(\"Parameter set: \")\n for i in xrange(num_hps):\n print(\"* {}: {}\".format(hyperparameters[i], row[i]))\n print(\"random seed: {}\".format(seed))\n print(\"{} = {}\".format(metrics_signature, metrics_value))\n print(\"Best parameter set so far: \")\n for i in xrange(num_hps):\n print(\"* {}: {}\".format(hyperparameters[i], best_hp_set[i]))\n print(\"Best random seed so far: {}\".format(best_seed))\n print(\"Best evaluation metrics so far = {}\".format(best_metrics_value))\n if metrics_value > best_metrics_value:\n best_hp_set = row\n best_seed = seed\n best_metrics_value = metrics_value\n print(\"☺ New best parameter setting found\")\n\n print()\n print(\"*****************************\")\n print(\"Best parameter set: \")\n for i in xrange(num_hps):\n print(\"* {}: {}\".format(hyperparameters[i], best_hp_set[i]))\n print(\"Best seed = {}\".format(best_seed))\n print(\"Best {} = {}\".format(metrics, best_metrics_value))\n print(\"*****************************\")\n\n\ndef schedule_experiments(train_fun, decode_fun, eval_fun, train_set, dev_set,\n hyperparam_sets, FLAGS):\n \"\"\"\n Run multiple experiments with different sets of hyperparameters.\n \"\"\"\n\n print(\"===== Scheduled Experiments =====\")\n for hyperparam_set in hyperparam_sets:\n for hp in hyperparam_set:\n setattr(FLAGS, hp, hyperparam_set[hp])\n if hp == 'universal_keep':\n setattr(FLAGS, 'sc_input_keep', hyperparam_set[hp])\n setattr(FLAGS, 'sc_output_keep', hyperparam_set[hp])\n setattr(FLAGS, 'tg_input_keep', hyperparam_set[hp])\n setattr(FLAGS, 'tg_output_keep', hyperparam_set[hp])\n setattr(FLAGS, 'attention_input_keep', hyperparam_set[hp])\n setattr(FLAGS, 'attention_output_keep', hyperparam_set[hp])\n\n print(\"Trying parameter set: \")\n for hp in hyperparam_set:\n print(\"* {}: {}\".format(hp, hyperparam_set[hp]))\n metrics = \"top1_temp_ms\"\n\n metrics_value = single_round_model_eval(\n train_fun, decode_fun, eval_fun, train_set, dev_set, metrics)\n print(\"Parameter set: \")\n for hp in hyperparam_set:\n print(\"* {}: {}\".format(hp, hyperparam_set[hp]))\n print(\"{} = {}\".format(metrics, metrics_value))\n\n\ndef single_round_model_eval(train_fun, decode_fun, eval_fun, train_set,\n dev_set, metrics, metrics_weights):\n \"\"\"\n Train the model with a certain set of hyperparameters and evaluate on the\n development set.\n\n :param train_fun: Function to train the model.\n :param decode_fun: Function to decode from the trained model.\n :param eval_fun: Function to evaluate the decoding results.\n :param train_set: Training dataset.\n :param dev_set: Development dataset.\n :param metrics: List of evaluation metrics used for tuning.\n :param metrics_weights: List of evaluation metrics weights used for tuning.\n\n :return: The weighted evaluation metrics.\n \"\"\"\n assert(len(metrics) > 0)\n assert(len(metrics) == len(metrics_weights))\n tf.reset_default_graph()\n try:\n train_fun(train_set, dev_set)\n \n tf.reset_default_graph()\n model_dir, decode_sig = decode_fun(dev_set, verbose=False)\n\n M = eval_fun(dev_set, model_dir, decode_sig, verbose=False)\n\n metrics_value = 0\n for m, m_w in zip(metrics, metrics_weights):\n metrics_value += m_w * M[m]\n except graph_utils.InfPerplexityError:\n metrics_value = -np.inf\n\n return metrics_value\n","sub_path":"encoder_decoder/meta_experiments.py","file_name":"meta_experiments.py","file_ext":"py","file_size_in_byte":7329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"408338300","text":"test = {\n\t\"name\": \"q1_5\",\n\t\"points\": 0,\n\t\"hidden\": False,\n\t\"suites\": [ \n\t\t{\n\t\t\t\"cases\": [ \n\t\t\t\t{\n\t\t\t\t\t\"code\": r\"\"\"\n\t\t\t\t\t>>> q1_5 in [1, 2, 3, 4]\n\t\t\t\t\tTrue\n\t\t\t\t\t\"\"\",\n\t\t\t\t\t\"hidden\": False,\n\t\t\t\t\t\"locked\": False,\n\t\t\t\t}, \n\t\t\t],\n\t\t\t\"scored\": False,\n\t\t\t\"setup\": \"\",\n\t\t\t\"teardown\": \"\",\n\t\t\t\"type\": \"doctest\"\n\t\t}, \n\t]\n}","sub_path":"hw/hw03/tests/q1_5.py","file_name":"q1_5.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"476137717","text":"from timeit import default_timer as timer\nimport data as dt\nimport torch\nimport datetime\nimport copy\nimport random as rndm\nimport Bnet as net_opt\nimport Pnet as net_sol\n\n\ndef initialize(path, name):\n ##\n # Function that initialize output file\n ##\n f = open(path + name, 'w')\n f.write(str(datetime.datetime.now()) + '\\n')\n f.close()\n\n\ndef usage(err):\n ##\n # Function that write parameters\n ##\n if err:\n print('Error in --path. Use:')\n print(' --help | --path path | --v')\n\n\ndef write_sol(data, tp, path, file, tp_heu):\n ##\n # Function that write greedy and heuristic solutions\n ##\n if path == '':\n print('Wrong path for write sol tp %d' % tp)\n else:\n f_out = open(path + file, 'a')\n # GREEDY\n if tp == 0:\n f_out.write('GREEDY SOLUTION\\n')\n for j in range(len(data)):\n for i in range(len(data[j])):\n if i != len(data[j]) - 1:\n f_out.write(str(data[j][i]) + ' ')\n else:\n f_out.write(str(data[j][i]))\n f_out.write('\\n')\n # HEURISTIC BASE\n elif tp == 1:\n if tp_heu == 'base':\n f_out.write('HEURISTIC BASE SOLUTION\\n')\n elif tp_heu == 'incumbent':\n f_out.write('HEURISTIC INCUMBENT SOLUTION\\n')\n elif tp_heu == 'best_incumbent':\n f_out.write('HEURISTIC BEST INCUMBENT SOLUTION\\n')\n elif tp_heu == 'inv_greedy':\n f_out.write('INVERSE GREEDY SOLUTION\\n')\n elif tp_heu == 'heu_rand':\n f_out.write('HEURISTIC BEST INCUMBENT SOLUTION --- RANDOM ITEMS ---\\n')\n elif tp_heu == 'heu_prob':\n f_out.write('HEURISTIC BEST INCUMBENT SOLUTION --- PROBABILITY ITEMS ---\\n')\n for j in range(len(data)):\n for i in range(len(data[j])):\n if i != len(data[j]) - 1:\n f_out.write(str(data[j][i]) + ' ')\n else:\n f_out.write(str(data[j][i]))\n f_out.write('\\n')\n f_out.close()\n\n\ndef read_sol(path, file, n):\n ##\n # Function that read greedy and heuristic solutions\n ##\n gr = []\n heu_base = []\n heu_inc = []\n heu_b_inc = []\n heu_rand = []\n heu_prob = []\n inv_gr = []\n lines = open(path + file, 'r').read().split('\\n')\n for i in range(len(lines)):\n if lines[i] == 'GREEDY SOLUTION':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n gr.append(tmp)\n i += n\n elif lines[i] == 'HEURISTIC BASE SOLUTION':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n heu_base.append(tmp)\n i += n\n elif lines[i] == 'HEURISTIC INCUMBENT SOLUTION':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n heu_inc.append(tmp)\n i += n\n elif lines[i] == 'HEURISTIC BEST INCUMBENT SOLUTION':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n heu_b_inc.append(tmp)\n i += n\n elif lines[i] == 'INVERSE GREEDY SOLUTION':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n inv_gr.append(tmp)\n i += n\n elif lines[i] == 'HEURISTIC BEST INCUMBENT SOLUTION --- RANDOM ITEMS ---':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n heu_rand.append(tmp)\n i += n\n elif lines[i] == 'HEURISTIC BEST INCUMBENT SOLUTION --- PROBABILITY ITEMS ---':\n for j in range(i + 1, i + 1 + n):\n line = lines[j].split(' ')\n tmp = []\n for k in range(len(line)):\n tmp.append((int(line[k])))\n heu_prob.append(tmp)\n i += n\n return gr, heu_base, heu_inc, heu_b_inc, inv_gr, heu_rand, heu_prob\n\n\ndef write_all(data, path, file, measure, tp, flag, neg, pos):\n ##\n # Function that write error and accuracy\n ##\n f_out = open(path + file, 'a')\n if measure == 'loss':\n f_out.write('LOSS FUNCTION\\n')\n for i in range(len(data)):\n f_out.write(str(data[i]) + ' ')\n f_out.write('\\n')\n f_out.close()\n elif measure == 'accuracy':\n if tp == 'val':\n f_out.write('ACCURACY VALIDATION\\n')\n elif tp == 'test':\n f_out.write('ACCURACY TEST\\n')\n elif tp == 'heu_base_solver':\n f_out.write('ACCURACY HEURISTIC BASE vs SOLVER\\n')\n elif tp == 'heu_base_greedy':\n f_out.write('ACCURACY HEURISTIC BASE vs GREEDY\\n')\n elif tp == 'heu_inc_solver':\n f_out.write('ACCURACY HEURISTIC INCUMBENT vs SOLVER\\n')\n elif tp == 'heu_inc_greedy':\n f_out.write('ACCURACY HEURISTIC INCUMBENT vs GREEDY\\n')\n elif tp == 'heu_b_inc_solver':\n f_out.write('ACCURACY HEURISTIC BEST INCUMBENT vs SOLVER\\n')\n elif tp == 'heu_b_inc_greedy':\n f_out.write('ACCURACY HEURISTIC BEST INCUMBENT vs GREEDY\\n')\n elif tp == 'heu_rand_solver':\n f_out.write('ACCURACY HEURISTIC BEST INCUMBENT vs SOLVER --- RANDOM ITEMS ---\\n')\n elif tp == 'heu_rand_greedy':\n f_out.write('ACCURACY HEURISTIC BEST INCUMBENT vs GREEDY --- RANDOM ITEMS ---\\n')\n elif tp == 'heu_prob_solver':\n f_out.write('ACCURACY HEURISTIC BEST INCUMBENT vs SOLVER --- PROBABILITY ITEMS ---\\n')\n elif tp == 'heu_prob_greedy':\n f_out.write('ACCURACY HEURISTIC BEST INCUMBENT vs GREEDY --- PROBABILITY ITEMS ---\\n')\n elif tp == 'inv_solver':\n f_out.write('ACCURACY INVERSE GREEDY vs SOLVER\\n')\n elif tp == 'inv_greedy':\n f_out.write('ACCURACY INVERSE vs GREEDY\\n')\n f_out.write(str(data))\n f_out.write('\\n')\n f_out.close()\n elif measure == 'error':\n if flag:\n if tp == 'heu_base_solver':\n f_out.write('ERROR HEURISTIC BASE vs SOLVER\\n')\n elif tp == 'heu_base_greedy':\n f_out.write('ERROR HEURISTIC BASE vs GREEDY\\n')\n elif tp == 'heu_inc_solver':\n f_out.write('ERROR HEURISTIC INCUMBENT vs SOLVER\\n')\n elif tp == 'heu_inc_greedy':\n f_out.write('ERROR HEURISTIC INCUMBENT vs GREEDY\\n')\n elif tp == 'heu_b_inc_solver':\n f_out.write('ERROR HEURISTIC BEST INCUMBENT vs SOLVER\\n')\n elif tp == 'heu_b_inc_greedy':\n f_out.write('ERROR HEURISTIC BEST INCUMBENT vs GREEDY\\n')\n elif tp == 'heu_rand_solver':\n f_out.write('ERROR HEURISTIC BEST INCUMBENT vs SOLVER --- RANDOM ITEMS ---\\n')\n elif tp == 'heu_rand_greedy':\n f_out.write('ERROR HEURISTIC BEST INCUMBENT vs GREEDY --- RANDOM ITEMS ---\\n')\n elif tp == 'heu_prob_solver':\n f_out.write('ERROR HEURISTIC BEST INCUMBENT vs SOLVER --- PROBABILITY ITEMS ---\\n')\n elif tp == 'heu_prob_greedy':\n f_out.write('ERROR HEURISTIC BEST INCUMBENT vs GREEDY --- PROBABILITY ITEMS ---\\n')\n elif tp == 'inv_solver':\n f_out.write('ERROR INVERSE vs SOLVER\\n')\n elif tp == 'inv_greedy':\n f_out.write('ERROR INVERSE GREEDY vs GREEDY\\n')\n f_out.write('MIN: %f\\n' % data[0])\n f_out.write('MAX: %f\\n' % data[1])\n f_out.write('AVG: %f\\n' % data[2])\n f_out.write('AVG_NEG: %f %d\\n' % (data[3], neg))\n f_out.write('AVG_POS: %f %d\\n' % (data[4], pos))\n else:\n if tp == 'val':\n f_out.write('ERROR VALIDATION\\n')\n elif tp == 'test':\n f_out.write('ERROR TEST\\n')\n for j in range(len(data)):\n f_out.write(str(data[j]))\n f_out.write('\\n')\n f_out.close()\n\n\ndef read_all(path, file):\n ##\n # Function that read error, accuracy\n ##\n lines = open(path + file, 'r').read().split('\\n')\n accuracy = [-1.0, -1.0, -1.0]\n error = [[-10.0, -10.0, -10.0], [-10.0, -10.0, -10.0], [-10.0, -10.0, -10.0]]\n z_opt = []\n loss = []\n for i in range(len(lines)):\n if lines[i] == 'LOSS FUNCTION':\n i = i + 1\n losses = lines[i].split(' ')\n for j in range(len(losses)-1):\n loss.append(float(losses[j]))\n elif lines[i] == 'ACCURACY VALIDATION':\n i = i + 1\n accuracy[0] = float(lines[i])\n elif lines[i] == 'ACCURACY TEST':\n i = i + 1\n accuracy[1] = float(lines[i])\n elif lines[i] == 'ERROR VALIDATION':\n i = i + 1\n error[0][0] = float(lines[i])\n i = i + 1\n error[0][1] = float(lines[i])\n i = i + 1\n error[0][2] = float(lines[i])\n elif lines[i] == 'ERROR TEST':\n i = i + 1\n error[1][0] = float(lines[i])\n i = i + 1\n error[1][1] = float(lines[i])\n i = i + 1\n error[1][2] = float(lines[i])\n elif lines[i] == 'Z_OPT':\n for j in range(i+1, len(lines)-1):\n line = lines[j].split(' ')\n sol = []\n for k in range(len(line)):\n sol.append(int(line[k]))\n z_opt.append(sol)\n break\n return loss, accuracy, error, z_opt\n\n\ndef plot_loss(loss, show, path):\n ##\n # Function that plot loss function\n ##\n import matplotlib as mpl\n mpl.use('tkagg')\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots()\n it = []\n for i in range(len(loss)):\n it.append(i)\n ax.plot(it, loss)\n ax.set(xlabel='itation', ylabel='Loss function',\n title='Loss function during training network')\n ax.grid()\n fig.savefig(path)\n if show:\n plt.show()\n\n\ndef save_model(model, path):\n ##\n # Function that save the model\n ##\n torch.save(model.state_dict(), path)\n\n\ndef load_model(path_model, input_size, output_size, gpu, mod):\n ##\n # Function that load the model\n ##\n model = []\n if mod == 'opt':\n if gpu:\n model = net_opt.Network(input_size, output_size, gpu)\n model.load_state_dict(torch.load(path_model))\n else:\n model = net_opt.Network(input_size, output_size, gpu)\n model.load_state_dict(torch.load(path_model, map_location='cpu'))\n elif mod == 'solution':\n if gpu:\n model = net_sol.Network(input_size, output_size, gpu)\n model.load_state_dict(torch.load(path_model))\n else:\n model = net_sol.Network(input_size, output_size, gpu)\n model.load_state_dict(torch.load(path_model, map_location='cpu'))\n return model\n\n\n'''\ndef read_params():\n ##\n # Function that read input parameters\n ##\n path = './sorted/unfix/'\n params = sys.argv\n if len(params) > 1:\n for i in range(len(params)):\n if params[i] == \"--path\":\n if len(params) > i+1:\n path = params[i+1]\n else:\n usage(True)\n sys.exit()\n elif params[i] == \"--help\" or params[i] == \"-h\":\n usage(False)\n sys.exit()\n return path\n'''\n\n\ndef main(verbose, path):\n ##\n # Function that read all data\n ##\n # read all arguments\n if verbose:\n print('###\\tStart reading data')\n start = timer()\n train, validation, test = dt.read_data(path)\n end = timer()\n if verbose:\n print('###\\tTime for reading data: %.2f sec' % (end - start))\n return train, validation, test, path\n\n\ndef sorting_item(items, dec):\n ##\n # Function that sort items\n ##\n idx = []\n for i in range(len(items)):\n idx.append(i)\n\n for k in range(len(items)):\n # sorting profit / weight ratio\n\n for j in range(k + 1, len(items)):\n if dec:\n if items[k][0] < items[j][0]:\n idx[j] = k\n idx[k] = j\n tmp_w = items[k][0]\n tmp_p = items[k][1]\n items[k][0] = items[j][0]\n items[k][1] = items[j][1]\n items[j][0] = tmp_w\n items[j][1] = tmp_p\n else:\n if items[k][0] > items[j][0]:\n tmp = idx[k]\n idx[k] = idx[j]\n idx[j] = tmp\n tmp_w = items[k][0]\n tmp_p = items[k][1]\n items[k][0] = items[j][0]\n items[k][1] = items[j][1]\n items[j][0] = tmp_w\n items[j][1] = tmp_p\n return items, idx\n\n\ndef sort_weight(test, it, dec):\n ##\n # Function that sort items based on profit / weight ratio\n ##\n\n # BRUTE FORCE SORTING -> OPTIMIZE!\n idx = []\n for i in range(test[it].n_item):\n idx.append(i)\n items = copy.deepcopy(test[it].items)\n\n for k in range(len(items)):\n # sorting profit / weight ratio\n for j in range(k + 1, len(items)):\n if dec:\n if items[k][0] < items[j][0]:\n idx[j] = k\n idx[k] = j\n tmp_w = items[k][0]\n tmp_p = items[k][1]\n items[k][0] = items[j][0]\n items[k][1] = items[j][1]\n items[j][0] = tmp_w\n items[j][1] = tmp_p\n else:\n if items[k][0] > items[j][0]:\n\n tmp = idx[k]\n idx[k] = idx[j]\n idx[j] = tmp\n tmp_w = items[k][0]\n tmp_p = items[k][1]\n items[k][0] = items[j][0]\n items[k][1] = items[j][1]\n items[j][0] = tmp_w\n items[j][1] = tmp_p\n return items, idx\n\n\ndef sort(test, it, dec):\n ##\n # Function that sort items based on profit / weight ratio\n ##\n\n # BRUTE FORCE SORTING -> OPTIMIZE!\n items = []\n for k in range(test[it].n_item):\n # sorting profit / weight ratio\n items = test[it].items\n for j in range(k + 1, test[it].n_item):\n if dec:\n if items[k][1] / items[k][0] < items[j][1] / items[j][0]:\n tmp_w = items[k][0]\n tmp_p = items[k][1]\n items[k][0] = items[j][0]\n items[k][1] = items[j][1]\n items[j][0] = tmp_w\n items[j][1] = tmp_p\n else:\n if items[k][1] / items[k][0] > items[j][1] / items[j][0]:\n tmp_w = items[k][0]\n tmp_p = items[k][1]\n items[k][0] = items[j][0]\n items[k][1] = items[j][1]\n items[j][0] = tmp_w\n items[j][1] = tmp_p\n return items\n\n\ndef partial_greedy(capacity, items):\n ##\n # Function that compute partial greedy solution\n ##\n opt_sol = []\n total_w = 0\n for j in range(len(items)):\n if total_w + items[j][0] <= capacity:\n opt_sol.append(j)\n total_w += items[j][0]\n return opt_sol\n\n\ndef greedy(data, it):\n ##\n # Function that compute greedy solutions\n ##\n items = sort(data, it, True)\n opt_sol = []\n total_w = 0\n for j in range(data[it].n_item):\n if total_w + items[j][0] <= data[it].capacity:\n opt_sol.append(j)\n total_w += items[j][0]\n return opt_sol\n\n\ndef inv_greedy(data, it):\n ##\n # Function that compute inverse greedy solutions\n ##\n items, idx = sort_weight(data, it, False)\n opt_sol = []\n total_w = 0\n for j in range(data[it].n_item):\n if total_w + items[j][0] <= data[it].capacity:\n opt_sol.append(j)\n total_w += items[j][0]\n for k in range(len(opt_sol)):\n opt_sol[k] = idx[opt_sol[k]]\n return opt_sol\n\n\ndef compute_z(test, sol, it):\n ##\n # Function that compute value of z\n ##\n z = 0\n for i in range(len(sol)):\n z += test[it].items[sol[i]][1]\n return z\n\n\ndef create_items(data, it, maybe, start, inv):\n ##\n # Function that create separate items for computing solutions\n ##\n items = []\n idx = []\n for i in range(start, len(maybe)):\n items.append(data[it].items[maybe[i]].copy())\n if inv:\n items, idx = sorting_item(items, False)\n return items, idx\n\n\ndef heuristic_base(data, epoch, input_size, network):\n ##\n # Function that compute heuristic solutions\n ##\n maybe = []\n # compute total of weights\n total_w = 0\n for i in range(data[epoch].n_item):\n total_w = total_w + data[epoch].items[i][0]\n\n # compute partial weights\n partial_w = 0\n opt_sol = []\n\n for j in range(data[epoch].n_item):\n partial_w = partial_w + data[epoch].items[j][0]\n\n # input_in & input_out\n input_in = [0] * input_size\n input_out = [0] * input_size\n # prepare input for NN\n for i in range(len(opt_sol)):\n item_w = data[epoch].items[opt_sol[i]][0] * (partial_w/total_w) / data[epoch].capacity\n input_in[opt_sol[i] * 2 + 1] = data[epoch].items[opt_sol[i]][1] / data[epoch].ub_dan\n input_in[opt_sol[i] * 2] = item_w\n input_out[opt_sol[i] * 2 + 1] = data[epoch].items[opt_sol[i]][1] / data[epoch].ub_dan\n input_out[opt_sol[i] * 2] = item_w\n item_w = data[epoch].items[j][0] * (partial_w / total_w)\n input_in[j * 2 + 1] = data[epoch].items[j][1] / data[epoch].ub_dan\n input_in[j * 2] = item_w\n\n if network.gpu:\n inputs_in = torch.cuda.FloatTensor([input_in])\n inputs_out = torch.cuda.FloatTensor([input_out])\n else:\n inputs_in = torch.Tensor([input_in])\n inputs_out = torch.Tensor([input_out])\n # output of NN\n output_in = network(inputs_in)\n output_out = network(inputs_out)\n # chose item\n if float(output_in) > float(output_out):\n maybe.append(j)\n # compute greedy solution\n items, _ = create_items(data, epoch, maybe, 0, False)\n opt_sol = partial_greedy(data[epoch].capacity, items)\n for i in range(len(opt_sol)):\n opt_sol[i] = maybe[opt_sol[i]]\n\n return opt_sol, maybe\n\n\ndef heuristic_inc(data, epoch, input_size, network, maybe):\n ##\n # Function that compute heuristic solutions with greedy incumbent\n ##\n\n # compute greedy solution and NN items\n if len(maybe) == 0:\n _, maybe = heuristic_base(data, epoch, input_size, network)\n\n # initialize incumbent solution\n items, _ = create_items(data, epoch, maybe, 0, False)\n incumbent_sol = partial_greedy(data[epoch].capacity, items)\n for i in range(len(incumbent_sol)):\n incumbent_sol[i] = maybe[incumbent_sol[i]]\n incumbent = compute_z(data, incumbent_sol, epoch)\n\n for i in range(1, len(maybe)):\n # compute actual solution for NN items\n items, _ = create_items(data, epoch, maybe, i, False)\n tmp_sol = copy.deepcopy(partial_greedy(data[epoch].capacity, items))\n for j in range(len(tmp_sol)):\n tmp_sol[j] += i\n tmp_sol[j] = maybe[tmp_sol[j]]\n z_tmp = compute_z(data, tmp_sol, epoch)\n # update incumbent solution\n if z_tmp > incumbent:\n incumbent = copy.deepcopy(z_tmp)\n incumbent_sol = tmp_sol\n\n return incumbent, incumbent_sol\n\n\ndef heuristic_b_inc(data, epoch, input_size, network):\n ##\n # Function that compute heuristic solutions with greedy incumbent\n ##\n\n # compute greedy solution and NN items\n _, maybe = heuristic_base(data, epoch, input_size, network)\n incumbent, incumbent_sol = heuristic_inc(data, epoch, input_size, network, maybe)\n # initialize incumbent solution\n inv_gr_sol = inv_greedy(data, epoch)\n z_inv_gr = compute_z(data, inv_gr_sol, epoch)\n\n if z_inv_gr > incumbent:\n incumbent = z_inv_gr\n incumbent_sol = inv_gr_sol\n\n for i in range(len(maybe)):\n # compute actual solution for NN items\n inv_items, idx = create_items(data, epoch, maybe, i, True)\n tmp_inv_sol = partial_greedy(data[epoch].capacity, inv_items)\n for j in range(len(tmp_inv_sol)):\n tmp_inv_sol[j] = maybe[idx[tmp_inv_sol[j]] + i]\n\n z_inv_tmp = compute_z(data, tmp_inv_sol, epoch)\n\n if z_inv_tmp > incumbent:\n incumbent = z_inv_tmp\n incumbent_sol = tmp_inv_sol\n return incumbent, incumbent_sol\n\n\ndef heuristic_rand(data, epoch, input_size, network):\n ##\n # Function that compute heuristic solutions with greedy incumbent\n ##\n\n # compute greedy solution for random items\n maybe = []\n for i in range(data[epoch].n_item):\n if rndm.random() > 0.5:\n maybe.append(i)\n\n incumbent, incumbent_sol = heuristic_inc(data, epoch, input_size, network, maybe)\n # initialize incumbent solution\n inv_gr_sol = inv_greedy(data, epoch)\n z_inv_gr = compute_z(data, inv_gr_sol, epoch)\n\n if z_inv_gr > incumbent:\n incumbent = z_inv_gr\n incumbent_sol = inv_gr_sol\n\n for i in range(len(maybe)):\n # compute actual solution for NN items\n inv_items, idx = create_items(data, epoch, maybe, i, True)\n tmp_inv_sol = partial_greedy(data[epoch].capacity, inv_items)\n for j in range(len(tmp_inv_sol)):\n tmp_inv_sol[j] = maybe[idx[tmp_inv_sol[j]] + i]\n\n z_inv_tmp = compute_z(data, tmp_inv_sol, epoch)\n\n if z_inv_tmp > incumbent:\n incumbent = z_inv_tmp\n incumbent_sol = tmp_inv_sol\n return incumbent, incumbent_sol\n\n\ndef heuristic_b_inc_pr(data, epoch, input_size, network, maybe):\n ##\n # Function that compute heuristic solutions with greedy incumbent\n ##\n\n # compute greedy solution and NN items\n incumbent, incumbent_sol = heuristic_inc(data, epoch, input_size, network, maybe)\n # initialize incumbent solution\n inv_gr_sol = inv_greedy(data, epoch)\n z_inv_gr = compute_z(data, inv_gr_sol, epoch)\n\n if z_inv_gr > incumbent:\n incumbent = z_inv_gr\n incumbent_sol = inv_gr_sol\n\n for i in range(len(maybe)):\n # compute actual solution for NN items\n inv_items, idx = create_items(data, epoch, maybe, i, True)\n tmp_inv_sol = partial_greedy(data[epoch].capacity, inv_items)\n for j in range(len(tmp_inv_sol)):\n tmp_inv_sol[j] = maybe[idx[tmp_inv_sol[j]] + i]\n\n z_inv_tmp = compute_z(data, tmp_inv_sol, epoch)\n\n if z_inv_tmp > incumbent:\n incumbent = z_inv_tmp\n incumbent_sol = tmp_inv_sol\n return incumbent, incumbent_sol\n\n\ndef check_heu_sol(heuristic, data):\n ##\n # Function that check feasibility of heuristic solutions\n ##\n if len(heuristic) > 0:\n for i in range(len(heuristic)):\n weight = 0\n for j in range(len(heuristic[i])):\n weight += data[i].items[heuristic[i][j]][0]\n\n if weight > data[i].capacity:\n return -1\n return 0\n\n\ndef error_accuracy(targets, error, accuracy, z_heu, better, it):\n ##\n # Function that compute error and accuracy for heuristic\n ##\n if (z_heu[it] - targets) / targets < error[0]:\n better[0] += 1\n error[0] = (z_heu[it] - targets) / targets\n elif (z_heu[it] - targets) / targets > error[1]:\n better[1] += 1\n error[1] = (z_heu[it] - targets) / targets\n\n error[2] = error[2] + abs((z_heu[it] - targets) / targets)\n\n if z_heu[it] == targets:\n accuracy = accuracy + 1\n\n if z_heu[it] - targets < 0:\n better[2] += 1\n error[3] += (z_heu[it] - targets) / targets\n elif z_heu[it] - targets > 0:\n better[3] += 1\n error[4] += (z_heu[it] - targets) / targets\n\n return accuracy, error, better\n\n\ndef heuristic_performance(data, compare, heuristic, divide, tp):\n ##\n # Function that compare error and accuracy between heuristic / solver / greedy solutions\n ##\n z_heu = []\n error = [0, 0, 0, 0, 0]\n accuracy = 0\n better = [0, 0, 0, 0]\n\n for i in range(len(heuristic)):\n if tp == 'solver':\n targets = data[i].z_opt\n else:\n targets = compute_z(data, compare[i], i)\n\n z_heu.append(compute_z(data, heuristic[i], i))\n accuracy, error, better = error_accuracy(targets, error, accuracy, z_heu, better, i)\n\n accuracy = accuracy / divide\n for i in range(len(better)):\n if better[i] != 0:\n error[i + 1] = error[i + 1] / better[i]\n error[2] = error[2] / divide\n\n return accuracy, error, better\n\n\ndef compute_feasibility(data, epoch, solution):\n ##\n # Function that compute solution feasible\n ##\n weight = 0\n for i in range(len(solution)):\n weight += data[epoch].items[solution[i]][0]\n if weight > data[epoch].capacity:\n return -1\n else:\n return 0\n","sub_path":"Heuristic/Compute solutions/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":25957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"304203643","text":"# -*- Encoding: utf-8 -*-\nfrom flask import Blueprint, jsonify\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn import metrics\nfrom sklearn.linear_model import LogisticRegression\n\nbp = Blueprint('apis', __name__)\n\n\n@bp.route('/api/v1/kmeans/', methods=['GET'])\ndef kmeans(kvalue):\n dataMat = []\n fr = open(\"E:\\\\code\\\\python\\\\data\\\\dshl_kmeans.txt\")\n for line in fr.readlines():\n curLine = line.strip().split('\\t')\n fltLine = list(map(float, curLine)) # 映射所有的元素为 float(浮点数)类型\n dataMat.append(fltLine)\n km = KMeans(n_clusters=int(kvalue)) # 初始化\n km.fit(dataMat) # 拟合\n km_preds = km.predict(dataMat).tolist() # 预测\n centers = km.cluster_centers_.tolist() # 质心\n result_list = []\n for i, centerPoint in enumerate(centers):\n result = {'kIndex': i + 1, 'centerPoint': centerPoint, 'dataCount': 0}\n result_list.append(result)\n for km_pred in km_preds:\n result_list[km_pred]['dataCount'] = result_list[km_pred]['dataCount'] + 1\n ch_value = metrics.calinski_harabaz_score(dataMat, km_preds)\n return jsonify({'resultList': result_list, 'chValue': ch_value})\n\n\n@bp.route('/api/v1/logisticRegression', methods=['GET'])\ndef logistic_regression():\n xDataMat = []\n fr = open(\"E:\\\\code\\\\python\\\\data\\\\dshl_lr_X.txt\")\n for line in fr.readlines():\n curLine = line.strip().split('\\t')\n fltLine = list(map(float, curLine))\n xDataMat.append(fltLine)\n yDataMat = []\n fr = open(\"E:\\\\code\\\\python\\\\data\\\\dshl_lr_Y.txt\")\n for line in fr.readlines():\n fltLine = float(line.replace('\\n', ''))\n yDataMat.append(fltLine)\n\n lr = LogisticRegression()\n lr.fit(xDataMat, yDataMat)\n print(lr.coef_.tolist())\n print(lr.intercept_.tolist())\n #print(lr.score(xDataMat, yDataMat))\n score = 0\n for i, xData in enumerate(xDataMat):\n sig = 1 / (1 + np.exp(-(np.dot(xData, lr.coef_.tolist()[0]) + lr.intercept_)))\n # print(sig)\n # temp_x = []\n # temp_x.append(xData)\n # print(lr.predict_proba(temp_x))\n if sig > 0.5:\n result = 1\n elif sig <= 0.5:\n result = 0\n if result == yDataMat[i]:\n score += 1\n my_score = float(score) / float(len(xDataMat))\n print(my_score)\n print(lr.score(xDataMat, yDataMat))\n return \"done\"\n\n","sub_path":"app/resources/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358451532","text":"import numpy as np\nimport pandas as pd\n\n\nclass State:\n def __init__(self, name = None, relation_matrix = None):\n self.name = name\n self.relation_matrix = relation_matrix\n\n def modifRelationMtx(self, relation_matrix):\n self.relation_matrix = relation_matrix\n\n\nclass Chain:\n def __init__(self, current_state = None):\n self.names = 0\n self.transMtx = 0\n\n self.num_of_states = 0\n self.states = []\n self.current_state = current_state\n\n def addState(self, name = None, relation_matrix = None):\n if name is None:\n name = self.num_of_states + 1\n if relation_matrix is None:\n relation_matrix = [i for i in range(self.num_of_states)]\n\n self.states.append(State(name, relation_matrix))\n self.num_of_states += 1\n\n def returnTransMtx(self):\n N = self.num_of_states\n if len(self.current_state) != len(self.states):\n print(\"Current state matrix has to have same shape as there is states!\")\n transMtx = np.zeros((N,N))\n names = []\n\n for i_state in range(0, N):\n state = self.states[i_state]\n relation_matrix = state.relation_matrix\n names.append(state.name)\n for i_record in range(0, len(relation_matrix)):\n record = relation_matrix[i_record]\n transMtx[i_state, i_record] = record\n if i_record < N-1:\n print(\"State \", state.name, \" has missing transitions replace with 0 !\")\n self.names = names\n self.transMtx = transMtx\n return transMtx, names\n\n def nextState(self):\n if type(self.current_state) is list:\n current_state = np.array(self.current_state)\n else:\n current_state = self.current_state\n trans_mtx, names = self.returnTransMtx()\n next_state = np.matmul(current_state, trans_mtx)\n self.current_state = next_state\n #print(next_state)\n return next_state\n\n def calcChapKolm(self, num_trans = 1):\n current_state = self.current_state\n transMtx, _ = self.returnTransMtx()\n for i in range(0, num_trans):\n transMtx = np.matmul(transMtx, self.transMtx)\n prob_of_existance = np.matmul(current_state, transMtx)\n return transMtx, prob_of_existance\n\n def show(self):\n print(self.names)\n print(self.transMtx)\n print(self.current_state)\n\n'''Markov = Chain([0.1, 0.9])\nMarkov.addState('Frugo', [0.9, 0.1])\nMarkov.addState('Hortex', [0.7, 0.3])\nMarkov.returnTransMtx()\nMarkov.nextState()\nMarkov.returnTransMtx()\nMarkov.show()'''\nMarkov = Chain([1,0,0])\nMarkov.addState(relation_matrix=[0.5,0,0.5])\nMarkov.addState(relation_matrix=[0,0.25,0.75])\nMarkov.addState(relation_matrix=[0.5,0.5,0])\nr,f = Markov.returnTransMtx()\n#Markov.nextState()\n#Markov.show()\n\nrr,ff = Markov.calcChapKolm(0)\nprint(rr)\nprint(ff)\n\n\n\n\n\n\n\n\n","sub_path":"classes/Chain.py","file_name":"Chain.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"341578990","text":"#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: Quan\n#\n# Created: 01/06/2017\n# Copyright: (c) Quan 2017\n# Licence: \n#-------------------------------------------------------------------------------\n\nimport arcpy\nimport os\nfrom arcpy import env\n\ndef clipShp(path):\n for (dirpath, dirnames, filenames) in os.walk(path):\n for filename in filenames:\n if filename.endswith('.shp'):\n in_features = os.sep.join([dirpath, filename])\n clip_features = \"D:\\\\Our Data\\\\Bondaries\\\\Fire Planning Units\\\\fpu\\\\az_bound.shp\"\n out_feature_class = in_features[:-4] + \"_AZ.shp\"\n arcpy.Clip_analysis(in_features, clip_features, out_feature_class)\n\ndef main():\n clipShp(\"D:\\\\Our Data\\\\Bondaries\\\\Fire Planning Units\\\\AZ\")\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"cutAZboundary.py","file_name":"cutAZboundary.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"630475375","text":"import json\n\nfrom flask import jsonify,request,render_template,flash\nfrom app.web import web\nfrom app.libs.helper import is_isbn_or_key\nfrom app.spider.yushu_book import YuShuBook\nfrom app.forms.book import SearchForm\nfrom app.view_models.book import BookViewModel, BookCollection\n\n\n@web.route('/book/search')\ndef search():\n \"\"\"\n q isbn\n start count\n \"\"\"\n #q = request.args['q']\n #page = request.args['page']\n books = BookCollection()\n\n form = SearchForm(request.args)\n if form.validate():\n q = form.q.data.strip()\n page = form.page.data\n isbn_or_key = is_isbn_or_key(q)\n\n yushu_book = YuShuBook()\n\n if isbn_or_key == 'isbn':\n yushu_book.search_by_isbn(q)\n else:\n yushu_book.search_by_keyword(q,page)\n books.fill(yushu_book, q)\n\n headers = {\n 'content-type': 'application/json'\n }\n\n # return json.dumps(result),200,headers\n #return jsonify(books)\n #将对象序列化为字典\n #return json.dumps(books,default=lambda o: o.__dict__),200,headers\n\n else:\n #return jsonify(form.errors)\n flash('搜索的关键字不符合要求,请重新输入')\n\n return render_template('search_result.html', books=books)\n\n@web.route('/book//detail')\ndef book_detail(isbn):\n yushu_book = YuShuBook()\n yushu_book.search_by_isbn(isbn)\n book_collection = BookCollection()\n book_collection.fill(yushu_book,isbn)\n return render_template('book_detail.html',book = book_collection.books[0],wishes=[],gifts=[])\n\n\n\n@web.route('/test')\ndef test():\n r = {\n 'name': '郭家兴',\n 'age': 18\n }\n flash(\"hello\")\n\n return render_template('test.html',data = r)\n\n","sub_path":"app/web/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"265562121","text":"# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\r\n# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\r\n\r\nn = 2520\r\nx = 0\r\ncheck = False\r\nli = [19, 18, 17, 16, 15, 14, 13, 12, 11]\r\nwhile(check==False):\r\n check = True\r\n for i in li:\r\n if n % i != 0:\r\n check = False\r\n break\r\n if check == True:\r\n print(n)\r\n n += 20","sub_path":"Solutions/problem_5.py","file_name":"problem_5.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"209415830","text":"import spotipy\nimport spotipy.util as sp_util\nfrom .api_secret import get_id, get_redirect, get_scope, get_secret, get_username\n\nclass Client:\n def __init__(self):\n self._client = self.initialize_client()\n\n\n def initialize_client(self):\n \"\"\"\n Initializes the Spotipy API client\n Also creates an authorization token for retrieving more detailed information\n :return: a reference to the client\n \"\"\"\n token = sp_util.prompt_for_user_token(get_username(), get_scope(), client_id=get_id(),\n client_secret=get_secret(), redirect_uri=get_redirect())\n if token:\n return spotipy.Spotify(auth=token)\n else:\n print(\"ERROR: Couldn't authorize token\")\n return None\n\n\n def get_global_top_50(self):\n \"\"\"\n Gets the global top 50 tracks playlist\n :return: a list of 'Track' objects\n \"\"\"\n uri = 'spotify:user:spotifycharts:playlist:37i9dQZEVXbMDoHDwVN2tF'\n username = uri.split(':')[2]\n playlist_id = uri.split(':')[4]\n response = None\n try:\n response = self._client.user_playlist(username, playlist_id)\n except spotipy.client.SpotifyException as e:\n print(\"ERROR\", e)\n finally:\n return response\n\n\n def get_country_top_50(self, country_uri):\n \"\"\"\n Gets a specific country's top 50 tracks playlist\n :return: a list of 'Track' objects\n \"\"\"\n username = country_uri.split(':')[2]\n playlist_id = country_uri.split(':')[4]\n response = None\n try:\n response = self._client.user_playlist(username, playlist_id)\n except spotipy.client.SpotifyException as e:\n print(\"ERROR\", e)\n finally:\n return response\n\n\n def get_user_playlist(self, playlist_uri):\n username = playlist_uri.split(':')[2]\n playlist_id = playlist_uri.split(':')[4]\n response = None\n try:\n response = self._client.user_playlist(username, playlist_id)\n except spotipy.client.SpotifyException as e:\n print(\"ERROR\", e)\n finally:\n return response","sub_path":"django_website/top50worldmap/src/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"506625093","text":"import os,sys\nimport numpy as np\nimport pandas as pd\nimport glob, re\nimport math\nimport multiprocessing as mp\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom keras.utils import to_categorical\n\n\ndef get_df(path):\n content = np.load(path)\n df = pd.DataFrame(data=content)\n df = filter(df)\n return df\n\ndef get_dataset(path, dataset):\n df_all = pd.DataFrame()\n dataset_regex = f\"{dataset}_[0-9]+.npy\"\n filenames = [f\"{path}/{f}\" for f in os.listdir(path) if re.search(dataset_regex,f)]\n pool = mp.Pool(mp.cpu_count()-1)\n dfs = pool.map(get_df, filenames)\n df_all = pd.concat(dfs)\n pool.close()\n pool.join()\n return df_all\n\ndef filter(df):\n df = df[(df['Higgs_mass']>110) & (df['Higgs_mass']<150) & (df['cat_index']==5) & (df['M_jj']>400)]\n return df\n\ndef train_filter(df):\n df = df[(df['Higgs_mass']>115) & (df['Higgs_mass']<135)]\n return df\n\nclass MVASetup(object):\n def __init__(self, name):\n self.name = name\n self.category_labels = {}\n self.categories = []\n self.mva_models = []\n self.roc_curves = {}\n self.feature_sets = {}\n self.scalers = {}\n self.df = pd.DataFrame()\n self.df_dict = {}\n self.inputs = []\n self.out_dir = \"\"\n self.model_dir = \"\"\n self.converted_to_cat = False\n self.year = '2016'\n os.system(\"mkdir -p \"+self.out_dir)\n os.system(\"mkdir -p \"+self.model_dir)\n\n def add_feature_set(self, name, option):\n self.feature_sets[name] = option\n\n def load_model(self, model):\n print(\"Adding model: {0}\".format(model.name))\n self.mva_models.append(model)\n\n def load_categories(self):\n for k,v in self.category_labels.items():\n self.categories.append(k)\n self.df_dict[k] = pd.DataFrame()\n\n def load_as_category(self, path, name, category, wgt, for_train, for_test):\n if (category not in self.categories):\n cat_name = \"{0}\".format(self.category_labels[category]) if (category in self.category_labels.keys()) else \"\"\n print(\"Added new category: {0} ({1})\".format(category, cat_name))\n self.categories.append(category)\n self.df_dict[category] = pd.DataFrame()\n new_df = get_dataset(path, name)\n new_df[\"label\"] = name\n new_df[\"category\"] = category\n new_df[\"wgt\"] = wgt\n new_df[\"for_train\"] = for_train\n new_df[\"for_test\"] = for_test\n \n integral = np.multiply(new_df[\"wgt\"], new_df[\"genweight\"]).sum()\n\n new_df[\"resweight\"] = 1/new_df[\"massErr_rel\"] if \"signal\" in self.category_labels.values() else 1\n\n print(f\"Appended {name} from {path}\")\n print(f\"Train: {for_train}, Test: {for_test}\")\n print(f\"Entries: {new_df.shape[0]}, Event yield: {integral}\")\n print(\"-\"*30)\n self.df_dict[category] = pd.concat((self.df_dict[category], new_df))\n\n def prepare_data(self, label, inputs):\n for i in inputs:\n if i not in self.df.columns:\n print(\"Feature set {0}: variable {1} not in columns!\".format(label, i))\n sys.exit(1)\n\n x_mean = np.mean(self.x_train[inputs].values,axis=0)\n x_std = np.std(self.x_train[inputs].values,axis=0)\n training_data = (self.x_train[inputs]-x_mean)/x_std\n testing_data = (self.x_test[inputs]-x_mean)/x_std\n np.save(\"{0}/{1}_{2}_scalers\".format(self.model_dir, self.name, label), [x_mean, x_std])\n\n return training_data, testing_data\n\n def train_models(self):\n if not self.feature_sets:\n print(\"Error: no input feature sets found!\")\n sys.exit(1)\n self.df = pd.concat(self.df_dict.values())\n\n only_train = self.df[self.df[\"for_train\"] & ~self.df[\"for_test\"]]\n x_otrain = only_train.loc[:,only_train.columns!='category']\n y_otrain = only_train[\"category\"]\n \n only_test = self.df[~self.df[\"for_train\"] & self.df[\"for_test\"]]\n x_otest = only_test.loc[:,only_test.columns!='category']\n y_otest = only_test[\"category\"]\n \n both = self.df[self.df[\"for_train\"] & self.df[\"for_test\"]]\n x_both = both.loc[:, both.columns!='category']\n y_both = both[\"category\"]\n \n train_frac = 0.6\n # if sample used for both training and testing, split it\n x_train, x_test, y_train, y_test = train_test_split(x_both, y_both, train_size=train_frac, test_size=(1-train_frac), shuffle=True)\n # if only for testing - assign a weight so roc curves don't mess up\n only_test[\"wgt\"] = only_test[\"wgt\"]*(1-train_frac)\n\n x_train[\"category\"] = y_train\n x_otrain[\"category\"] = y_otrain\n train = pd.concat([x_train, x_otrain])\n train = train.sample(frac=1) # shuffle\n\n x_test[\"category\"] = y_test\n x_otest[\"category\"] = y_otest\n test = pd.concat([x_test, x_otest])\n\n tr_filter = False\n if tr_filter:\n train = train_filter(train)\n\n self.x_train = train.loc[:, train.columns!='category']\n self.y_train = train['category']\n\n self.x_test = test.loc[:, test.columns!='category']\n self.y_test = test['category']\n \n for feature_set_name, feature_set in self.feature_sets.items():\n\n for model in self.mva_models:\n training_data, testing_data = self.prepare_data(feature_set_name, feature_set)\n \n if model.binary:\n if len(self.categories) is not 2:\n print(\"Can't perform binary classification with {0} categories!\".format(len(self.categories)))\n sys.exit(1)\n elif not self.converted_to_cat:\n self.y_train = to_categorical(self.y_train, len(self.categories))\n self.y_test = to_categorical(self.y_test, len(self.categories))\n # need this to convert only once (for the case when several models are trained)\n self.converted_to_cat = True\n \n if \"resweights\" in model.name:\n self.y_train = train[['category', 'resweight']]\n self.y_test = test[['category', 'resweight']]\n else:\n training_data = training_data.loc[:, training_data.columns!='category']\n testing_data = testing_data.loc[:, testing_data.columns!='category']\n \n model.train(training_data, self.y_train, feature_set_name, self.model_dir, self.name)\n print(f\"Test shape: {testing_data.shape}\")\n prediction = model.predict(testing_data, self.y_test, feature_set_name)\n\n if model.binary:\n if \"resweights\" in model.name:\n roc = roc_curve(self.y_test.iloc[:,0], prediction, sample_weight=self.x_test['wgt']*self.x_test[\"genweight\"])\n testing_data[\"category\"]=self.y_test.iloc[:,0]\n else:\n roc = roc_curve(self.y_test, prediction, sample_weight=self.x_test['wgt']*self.x_test[\"genweight\"])\n testing_data[\"category\"]=self.y_test\n\n self.print_yields(roc, prediction, 0.01)\n\n self.plot_hist(\"dnn_score_{0}_{1}_{2}\".format(self.name, model.name, feature_set_name), df=testing_data, values=prediction)\n np.save(\"{0}/{1}_{2}_{3}_roc\".format(self.out_dir, self.name, model.name, feature_set_name), roc)\n self.roc_curves[model.name+\"_\"+feature_set_name] = roc\n\n else:\n vbf_pred = prediction[0]\n ggh_pred = prediction[1]\n dy_pred = prediction[2]\n ewk_pred = prediction[3]\n\n# cuts = (ewk_pred<0.7)\n cuts = None\n if cuts:\n self.x_test = self.x_test[cuts]\n self.y_test = self.y_test[cuts]\n vbf_pred = vbf_pred[cuts]\n ggh_pred = ggh_pred[cuts]\n dy_pred = dy_pred[cuts]\n ewk_pred = ewk_pred[cuts]\n pred = vbf_pred\n# pred = np.sum([vbf_pred,ggh_pred], axis=0)\n# pred = np.sum([vbf_pred, (-1)*ewk_pred], axis=0)\n roc = roc_curve(np.logical_or(self.y_test[:,0], self.y_test[:,1]), pred, sample_weight=self.x_test['wgt']*self.x_test[\"genweight\"])\n\n self.print_yields(roc, pred, 0.01)\n \n# np.save(\"{0}/{1}_{2}_{3}_roc\".format(self.out_dir, self.name, model.name, feature_set_name), roc)\n# np.save(\"{0}/{1}_{2}_{3}_vbf-ewk_roc\".format(self.out_dir, self.name, model.name, feature_set_name), roc)\n np.save(\"{0}/{1}_{2}_{3}_ewk<07_roc\".format(self.out_dir, self.name, model.name, feature_set_name), roc)\n\n# testing_data[\"category\"]=y_test \n# self.plot_hist(\"vbf_score_{0}_{1}_{2}\".format(self.name, model.name, feature_set_name), df=testing_data, values=prediction[0])\n# self.plot_hist(\"ggh_score_{0}_{1}_{2}\".format(self.name, model.name, feature_set_name), df=testing_data, values=prediction[1])\n# self.plot_hist(\"dy_score_{0}_{1}_{2}\".format(self.name, model.name, feature_set_name), df=testing_data, values=prediction[2])\n# self.plot_hist(\"ewk_score_{0}_{1}_{2}\".format(self.name, model.name, feature_set_name), df=testing_data, values=prediction[3])\n# self.plot_hist(\"ttbar_score_{0}_{1}_{2}\".format(self.name, model.name, feature_set_name), df=testing_data, values=prediction[4])\n\n def print_yields(self, roc, prediction, bkg_eff_threshold):\n threshold = roc[2][np.abs(roc[0]-bkg_eff_threshold).argmin()]\n yields = np.multiply(self.x_test['wgt'],self.x_test[\"genweight\"])\n\n if self.year is '2016':\n vbfy = yields[(self.x_test[\"label\"]==\"vbf\") | (self.x_test[\"label\"]==\"vbf_powheg\")]\n vbf_pred = prediction[(self.x_test[\"label\"]==\"vbf\") | (self.x_test[\"label\"]==\"vbf_powheg\")]\n elif self.year is '2017':\n vbfy = yields[(self.x_test[\"label\"]==\"vbf\") | (self.x_test[\"label\"]==\"vbf_powheg_herwig\")]\n vbf_pred = prediction[(self.x_test[\"label\"]==\"vbf\") | (self.x_test[\"label\"]==\"vbf_powheg_herwig\")]\n elif self.year is '2018':\n vbfy = yields[(self.x_test[\"label\"]==\"vbf\") | (self.x_test[\"label\"]==\"vbf_powhegPS\")]\n vbf_pred = prediction[(self.x_test[\"label\"]==\"vbf\") | (self.x_test[\"label\"]==\"vbf_powhegPS\")]\n vbfy = vbfy[vbf_pred>threshold]\n vbf_yield = vbfy.sum()/0.4\n\n yields_by_process = {\"vbf\": vbf_yield}\n \n other_processes = [\"ggh\", \"dy\", \"ewk\", \"tt\"]\n\n for process in other_processes:\n y = yields[(self.x_test[\"label\"].str.contains(process))]\n pred = prediction[self.x_test[\"label\"].str.contains(process)]\n y = y[pred>threshold]\n y = y.sum()/0.4\n if y:\n yields_by_process[process] = y\n\n for key, value in yields_by_process.items():\n print(f\"{key} yield at bkg. eff. {bkg_eff_threshold} = {value}\")\n\n processes = {\n \"sig\": [\"ggh\", \"vbf\"],\n \"bkg\": [\"dy\", \"ewk\", \"tt\"]\n }\n sb_yields = {\"sig\": 0, \"bkg\": 0}\n for p, pp in processes.items():\n for proc in pp:\n if yields_by_process[proc]:\n sb_yields[p] += yields_by_process[proc]\n \n sigma = sb_yields[\"sig\"] / math.sqrt(sb_yields[\"bkg\"])\n print(f\"S/sqrt(B) at bkg. eff. {bkg_eff_threshold} = {sigma}\")\n\n\n def plot_hist(self, var_name, xlim=None, df=None, values=None):\n if df is None:\n self.df = pd.concat(self.df_dict.values())\n self.df = filter(self.df)\n df = self.df\n print(\"Plotting \"+var_name)\n plt.clf()\n ax = plt.gca()\n\n if values is not None:\n df[\"values\"] = values\n\n for cat_num, cat_name in self.category_labels.items():\n df_cat = df[df[\"category\"]==cat_num]\n if \"_score\" in var_name:\n ax.hist(df_cat[\"values\"], bins=40, histtype='step', label=cat_name,normed=True, range=xlim)\n else:\n ax.hist(df_cat[var_name].values, bins=40, histtype='step', label=cat_name,normed=True, range=xlim)\n plt.xlabel(var_name)\n plt.legend(loc='best')\n plt.savefig(\"tests/hmm/mva/plots_updated/{0}.png\".format(var_name))\n","sub_path":"tests/hmm/mva/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"634783968","text":"import os, logging, json, zipfile\nlogging.basicConfig(\n filename=\"diana.log\",\n format=\"%(asctime)s :: %(levelname)s :: %(message)s\",\n datefmt=\"%b %d, %Y %I:%M %p (%A)\",\n level=logging.INFO,\n)\ndef sign_in(data):\n os.system('clear')\n print(\"Enter your login credentials\")\n try:\n uname = input(\"Username: \")\n pword = input(\"Password: \")\n uname = \"Finn_98\"\n pword = \"VxQbBvac\"\n for line in data:\n if line['username'] == uname and line['password'] == pword:\n logging.info(\"{0} - logged in\".format(uname))\n os.system(\"clear\")\n menu(line)\n break\n else:\n logging.info(\"Invalid log in\")\n print(\"\\nInvalid username and password\")\n except KeyboardInterrupt:\n sign_in(data)\ndef menu(data):\n current = os.getcwd().split(\"/\")[-1:][0]\n print(f\"\\nCurrent Directory: {current}\")\n print(\"\\nMenu directory\")\n print(f\"\\t{1:<3d} - Create Directory\")\n print(f\"\\t{2:<3d} - Create File\")\n print(f\"\\t{3.1:.1f} - Open File\")\n print(f\"\\t{3.2:.1f} - Open Folder\")\n print(f\"\\t{4:<3d} - Delete File\")\n print(f\"\\t{5:<3d} - Show Files\")\n print(f\"\\t{6:<3d} - Exit\")\n try:\n command = input(\"\\nEnter Command: \")\n os.system(\"clear\")\n if command == \"1\":\n cDir(data)\n elif command == \"2\":\n cFile(data)\n elif command == \"3.1\":\n oFile(data)\n elif command == \"3.2\":\n oDir(data)\n elif command == \"4\":\n dFile(data)\n elif command == \"5\":\n sFile(data)\n elif command == \"6\":\n pass\n else:\n print(\"\\nWrong Command!\")\n menu(data)\n except KeyboardInterrupt:\n os.system('clear')\n menu(data)\ndef cDir(data):\n print(os.chdir())\n print(\"\\nCreate Directory\")\n try:\n newDir = input(\"Folder name: \")\n os.mkdir(newDir)\n print(\"Folder Created!\")\n logging.info(\"{0} - created a folder named: '{1}'\".format(data['username'], newDir))\n except FileExistsError as err:\n print(err)\n logging.error(\"{0} - {1}\".format(data['username'], err))\n except KeyboardInterrupt:\n cDir(data)\n finally:\n menu(data)\ndef cFile(data):\n print(\"\\nCreate File\")\n try:\n newFile = input(\"File name: \")\n os.mknod(newFile)\n print(\"File Created!\")\n logging.info(\"{0} - created a file named: '{1}'\".format(data['username'], newFile))\n except FileExistsError as err:\n print(err)\n logging.error(\"{0} - {1}\".format(data['username'], err))\n except KeyboardInterrupt:\n cFile(data)\n finally:\n menu(data)\ndef oFile(data):\n print(\"\\nOpen File\")\n\n for files in os.listdir('.'):\n\n print(files)\n if os.path.isfile(files):\n print(\"-\", files)\n try:\n openFile = input(\"File name: \")\n f = os.open(openFile, os.O_RDONLY)\n read = os.read(f, os.path.getsize(openFile))\n print(\"\\n\".ljust(30, \"-\"))\n print(read.decode(\"utf-8\"))\n print(\"\".ljust(30, \"-\"))\n logging.info(\"{0} - opened a file named: '{1}'\".format(data['username'], openFile))\n except FileNotFoundError as err:\n print(err)\n logging.error(\"{0} - {1}\".format(data['username'], err))\n except KeyboardInterrupt:\n oFile(data)\n finally:\n menu(data)\ndef oDir(data):\n print(\"\\nOpen Folder\")\n for directory in os.listdir('.'):\n if os.path.isdir(directory):\n print(\"-\", directory)\n try:\n openFolder = input(\"Folder name: \")\n if openFolder == data['last_name']:\n os.chdir(openFolder)\n print(f\"\\nOpened folder {openFolder}\")\n logging.info(\"{0} - opened a folder named: '{1}'\".format(data['username'], openFolder))\n elif openFolder == \"..\":\n os.chdir(openFolder)\n print(f\"\\nFolder UP\")\n elif openFolder == '':\n os.system('clear')\n oDir(data)\n else:\n logging.error(\"{0} - Access to folder named '{1}' not allowed\".format(data['username'], openFolder))\n print(\"Folder access not allowed!\")\n except FileNotFoundError as err:\n print(err)\n logging.error(\"{0} - {1}\".format(data['username'], err))\n except KeyboardInterrupt:\n oDir(data)\n finally:\n menu(data)\ndef dFile(data):\n print(\"\\nDelete File\")\n for files in os.listdir('.'):\n if os.path.isfile(files):\n print(\"-\", files)\n try:\n delFile = input(\"File name: \")\n for files in os.listdir('.'):\n if os.path.isfile(files):\n if delFile == files:\n os.remove(delFile)\n logging.info(\"{0} - deleted a file named: '{1}'\".format(data['username'], delFile))\n print(\"File Deleted\")\n break\n else:\n print(\"File not found!\")\n logging.error(\"{0} - File named '{1}' not found\".format(data['username'], delFile))\n dFile(data)\n except FileNotFoundError as err:\n print(err)\n logging.error(\"{0} - {1}\".format(data['username'], err))\n except KeyboardInterrupt:\n dFile(data)\n finally:\n menu(data)\ndef sFile(data):\n print(\"\\nShow Files\")\n for files in os.listdir('.'):\n print(\"-\", files)\n menu(data)\n\n\nwith open(\"../my_accounts.json\") as accounts:\n data = json.load(accounts)\nwith zipfile.ZipFile(\"../Folders.zip\", 'r') as zip_ref:\n zip_ref.extractall(\".\")\nos.chdir(\"Folders\")\nsign_in(data)","sub_path":"Modules/Mix/File Handling/allan.py","file_name":"allan.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"397873492","text":"# -*- coding: UTF-8 -*-\n\n\"\"\"\n fbchat\n ~~~~~~\n\n Facebook Chat (Messenger) for Python\n\n :copyright: (c) 2015 by Taehoon Kim.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\nimport requests\nfrom uuid import uuid1\nfrom random import random, choice\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup as bs\n\nfrom .utils import *\nfrom .models import *\n\n# URLs\nLoginURL =\"https://m.facebook.com/login.php?login_attempt=1\"\nSearchURL =\"https://www.facebook.com/ajax/typeahead/search.php\"\nSendURL =\"https://www.facebook.com/ajax/mercury/send_messages.php\"\nThreadsURL =\"https://www.facebook.com/ajax/mercury/threadlist_info.php\"\nThreadSyncURL=\"https://www.facebook.com/ajax/mercury/thread_sync.php\"\nMessagesURL =\"https://www.facebook.com/ajax/mercury/thread_info.php\"\nUnreadURL =\"https://www.facebook.com/ajax/mercury/unread_threads.php\"\nReadStatusURL=\"https://www.facebook.com/ajax/mercury/change_read_status.php\"\nDeliveredURL =\"https://www.facebook.com/ajax/mercury/delivery_receipts.php\"\nMarkSeenURL =\"https://www.facebook.com/ajax/mercury/mark_seen.php\"\nBaseURL =\"https://www.facebook.com\"\nMobileURL =\"https://m.facebook.com/\"\n\nclass Client(object):\n \"\"\"A client for the Facebook Chat (Messenger).\n\n See http://github.com/carpedm20/fbchat for complete\n documentation for the API.\n\n \"\"\"\n\n def __init__(self, email, password, debug=True, user_agent=None):\n \"\"\"A client for the Facebook Chat (Messenger).\n\n :param email: Facebook `email` or `id` or `phone number`\n :param password: Facebook account password\n\n import fbchat\n chat = fbchat.Client(email, password)\n\n \"\"\"\n\n if not (email and password):\n raise Exception(\"id and password or config is needed\")\n\n self.email = email\n self.password = password\n self.debug = debug\n self._session = requests.session()\n self.req_counter = 1;\n self.payloadDefault={}\n self.client = 'mercury'\n self.lastSeen = 0\n\n if not user_agent:\n user_agent = choice(USER_AGENTS)\n\n self._header = {\n 'Content-Type' : 'application/x-www-form-urlencoded',\n 'Referer' : BaseURL,\n 'Origin' : BaseURL,\n 'User-Agent' : user_agent,\n 'Connection' : 'keep-alive',\n }\n\n self._console(\"Logging in...\")\n\n if not self.login():\n raise Exception(\"id or password is wrong\")\n\n self.threads = []\n\n def _console(self, msg):\n if self.debug: print(msg)\n\n def _setttstamp(self):\n for i in self.fb_dtsg:\n self.ttstamp += str(ord(i))\n self.ttstamp += '2'\n\n def _generatePayload(self, query):\n '''\n Adds the following defaults to the payload:\n __rev, __user, __a, ttstamp, fb_dtsg, __req\n '''\n payload=self.payloadDefault.copy()\n if query: payload.update(query)\n payload['__req'] = str_base(self.req_counter, 36)\n self.req_counter+=1\n return payload\n\n def _get(self, url, query=None, timeout=30):\n payload=self._generatePayload(query)\n return self._session.get(url, headers=self._header, params=payload, timeout=timeout)\n\n def _post(self, url, query=None, timeout=30):\n payload=self._generatePayload(query)\n return self._session.post(url, headers=self._header, data=payload, timeout=timeout)\n\n def _cleanPost(self, url, query=None, timeout=30):\n self.req_counter+=1\n return self._session.post(url, headers=self._header, data=query, timeout=timeout)\n\n def login(self):\n if not (self.email and self.password):\n raise Exception(\"id and password or config is needed\")\n\n soup = bs(self._get(MobileURL).text, \"lxml\")\n data = dict((elem['name'], elem['value']) for elem in soup.findAll(\"input\") if elem.has_attr('value') and elem.has_attr('name'))\n data['email'] = self.email\n data['pass'] = self.password\n data['login'] = 'Log In'\n\n r = self._cleanPost(LoginURL, data)\n\n if 'home' in r.url:\n self.client_id = hex(int(random()*2147483648))[2:]\n self.start_time = now()\n self.uid = int(self._session.cookies['c_user'])\n self.user_channel = \"p_\" + str(self.uid)\n self.ttstamp = ''\n\n r = self._get(BaseURL)\n soup = bs(r.text, \"lxml\")\n self.fb_dtsg = soup.find(\"input\", {'name':'fb_dtsg'})['value']\n self._setttstamp()\n # Set default payload\n self.payloadDefault['__rev']= int(r.text.split('\"revision\":',1)[1].split(\",\",1)[0])\n self.payloadDefault['__user']= self.uid\n self.payloadDefault['__a']= '1'\n self.payloadDefault['ttstamp']= self.ttstamp\n self.payloadDefault['fb_dtsg']= self.fb_dtsg\n\n self.form = {\n 'channel' : self.user_channel,\n 'seq' : '0',\n 'partition' : '-2',\n 'clientid' : self.client_id,\n 'viewer_uid' : self.uid,\n 'uid' : self.uid,\n 'state' : 'active',\n 'format' : 'json',\n 'idle' : 0,\n 'cap' : '8'\n }\n\n self.prev = now()\n self.tmp_prev = now()\n self.last_sync = now()\n\n return True\n else:\n return False\n\n def getUsers(self, name):\n \"\"\"Find and get user by his/her name\n\n :param name: name of a person\n \"\"\"\n payload = {\n 'value' : name.lower(),\n 'viewer' : self.uid,\n 'rsp' : \"search\",\n 'context' : \"search\",\n 'path' : \"/home.php\",\n 'request_id' : str(uuid1()),\n }\n\n r = self._get(SearchURL, payload)\n self.j = j = get_json(r.text)\n\t\t\n users = []\n for entry in j['payload']['entries']:\n if entry['type'] == 'user':\n users.append(User(entry))\n return users\n\n def sendMessage(self, message, thread_id):\n \"\"\"Send a message with given thread id\n\n :param message: a text that you want to send\n :param thread_id: a thread id that you want to send a message\n \"\"\"\n timestamp = now()\n date = datetime.now()\n data = {\n 'client' : self.client,\n 'message_batch[0][action_type]' : 'ma-type:user-generated-message',\n 'message_batch[0][author]' : 'fbid:' + str(self.uid),\n 'message_batch[0][specific_to_list][0]' : 'fbid:' + str(thread_id),\n 'message_batch[0][specific_to_list][1]' : 'fbid:' + str(self.uid),\n 'message_batch[0][timestamp]' : timestamp,\n 'message_batch[0][timestamp_absolute]' : 'Today',\n 'message_batch[0][timestamp_relative]' : str(date.hour) + \":\" + str(date.minute).zfill(2),\n 'message_batch[0][timestamp_time_passed]' : '0',\n 'message_batch[0][is_unread]' : False,\n 'message_batch[0][is_cleared]' : False,\n 'message_batch[0][is_forward]' : False,\n 'message_batch[0][is_filtered_content]' : False,\n 'message_batch[0][is_spoof_warning]' : False,\n 'message_batch[0][source]' : 'source:chat:web',\n 'message_batch[0][source_tags][0]' : 'source:chat',\n 'message_batch[0][body]' : message,\n 'message_batch[0][html_body]' : False,\n 'message_batch[0][ui_push_phase]' : 'V3',\n 'message_batch[0][status]' : '0',\n 'message_batch[0][message_id]' : generateMessageID(self.client_id),\n 'message_batch[0][manual_retry_cnt]' : '0',\n 'message_batch[0][thread_fbid]' : thread_id,\n 'message_batch[0][has_attachment]' : False\n }\n\n r = self._post(SendURL, data)\n return r.ok\n\n\n def getThreadInfo(self, userID, start, end=None):\n \"\"\"Get the info of one Thread\n\n :param userID: ID of the user you want the messages from\n :param start: the start index of a thread\n :param end: (optional) the last index of a thread\n \"\"\"\n if not end: end = start + 20\n if end <= start: end=start+end\n\n data={}\n data['messages[user_ids][%s][offset]'%userID]= start\n data['messages[user_ids][%s][limit]'%userID]= end\n data['messages[user_ids][%s][timestamp]'%userID]= now()\n\n r = self._post(MessagesURL, query=data)\n if not r.ok or len(r.text) == 0:\n return None\n\n j = get_json(r.text)\n if not j['payload']:\n return None\n messages=[]\n for message in j['payload']['actions']:\n messages.append(Message(**message))\n return list(reversed(messages))\n\n\n def getThreadList(self, start, end=None):\n \"\"\"Get thread list of your facebook account.\n\n :param start: the start index of a thread\n :param end: (optional) the last index of a thread\n \"\"\"\n if not end: end = start + 20\n if end <= start: end=start+end\n\n data = {\n 'client' : self.client,\n 'inbox[offset]' : start,\n 'inbox[limit]' : end,\n }\n\n r = self._post(ThreadsURL, data)\n if not r.ok or len(r.text) == 0:\n return None\n\n j = get_json(r.text)\n\n if not \"participants\" in j['payload']:\n return []\n\n # Get names for people\n participants={}\n for participant in j['payload']['participants']:\n participants[participant[\"fbid\"]] = participant[\"name\"]\n\n # Prevent duplicates in self.threads\n threadIDs=[getattr(x, \"thread_id\") for x in self.threads]\n for thread in j['payload']['threads']:\n if thread[\"thread_id\"] not in threadIDs:\n try:\n thread[\"other_user_name\"] = participants[int(thread[\"other_user_fbid\"])]\n except:\n thread[\"other_user_name\"] = \"\"\n t = Thread(**thread)\n self.threads.append(t)\n\n return self.threads\n\n def getUnread(self):\n data = {\n 'client': self.client,\n 'folders[0]': 'inbox'\n }\n r = self._post(UnreadURL, data)\n if not r.ok or len(r.text) == 0:\n return None\n\n j = get_json(r.text)\n try:\n return j['payload']['unread_thread_ids']\n except:\n return []\n\n def getUnseen(self):\n form = {\n 'client': 'mercury_sync',\n 'folders[0]': 'inbox',\n 'last_action_timestamp': self.lastSeen\n }\n self.lastSeen = now()\n r = self._post(ThreadSyncURL, form)\n if not r.ok or len(r.text) == 0:\n return None\n\n j = get_json(r.text)\n result = {\n \"message_counts\": j['payload']['message_counts'],\n \"unseen_threads\": j['payload']['unseen_thread_ids']}\n return result\n\n def sendSticker(self):\n pass\n\n def markAsDelivered(self, userID, threadID):\n data={\"message_ids[0]\": threadID}\n data[\"thread_ids[%s][0]\"%userID] = threadID\n r = self._post(DeliveredURL, data)\n return r.ok\n\n def markAsRead(self, userID):\n data={\n \"watermarkTimestamp\": now(),\n \"shouldSendReadReceipt\": True}\n data[\"ids[%s]\"%userID] = True\n r = self._post(ReadStatusURL, data)\n return r.ok\n\n def markAsSeen(self):\n r = self._post(MarkSeenURL, {\"seen_timestamp\": 0})\n return r.ok\n\n","sub_path":"fbchat/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":11605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"15162862","text":"import pytest\nimport os.path\nfrom chirc.tests.common import IRCSession\n \ndef pytest_addoption(parser):\n parser.addoption(\"-C\", action=\"store\", metavar=\"CATEGORY_ID\",\n help=\"only run tests in category CATEGORY_ID.\") \n parser.addoption(\"--chirc-exe\", action=\"store\", metavar=\"CHIRC_EXE\",\n help=\"set location of chirc executable\") \n parser.addoption(\"--chirc-loglevel\", action=\"store\", type=int, metavar=\"LOGLEVEL\",\n help=\"set log level in chirc to LOGLEVEL (-1: -q, 0: normal, 1: -v, 2: --v).\") \n parser.addoption(\"--chirc-port\", action=\"store\", type=int,\n help=\"port to run server on\") \n parser.addoption(\"--randomize-ports\", action=\"store_true\",\n help=\"randomize server's port when running tests\")\n parser.addoption(\"--path\", action=\"store\",\n help=\"choose path for jar file\")\n\n@pytest.fixture\ndef irc_session(request): \n chirc_exe = request.config.getoption(\"--chirc-exe\")\n chirc_loglevel = request.config.getoption(\"--chirc-loglevel\")\n chirc_port = request.config.getoption(\"--chirc-port\")\n randomize_ports = request.config.getoption(\"--randomize-ports\")\n path = request.config.getoption(\"--path\")\n \n session = IRCSession(chirc_exe = chirc_exe, \n loglevel = chirc_loglevel, \n default_port = chirc_port,\n randomize_ports=randomize_ports,\n path=path)\n \n session.start_session()\n \n def fin():\n session.end_session()\n \n request.addfinalizer(fin) \n \n return session\n\ndef pytest_configure(config):\n f = open(\"alltests\", \"w\")\n f.close()\n\ndef pytest_itemcollected(item):\n category_marker = item.get_marker(\"category\")\n if category_marker is not None:\n category = category_marker.args[0]\n with open(\"alltests\", \"a\") as f:\n f.write(\"{},{}\\n\".format(category, item.nodeid))\n\ndef pytest_runtest_setup(item):\n only_category = item.config.getoption(\"-C\")\n if only_category is not None: \n category_marker = item.get_marker(\"category\")\n if category_marker is not None:\n category = category_marker.args[0]\n if category != item.config.getoption(\"-C\"):\n pytest.skip(\"Only running tests in category {}\".format(only_category))\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n # execute all other hooks to obtain the report object\n outcome = yield\n report = outcome.get_result()\n category = item.get_marker(\"category\").args[0]\n\n if report.when == \"call\":\n report.metadata = {\n 'category': category\n } \n report.test_metadata = {\n 'category': category\n }","sub_path":"src/test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"123426123","text":"import sys\n\nimport subprocess, os, platform\n\nimport os\nfrom PyQt5 import QtWidgets,QtCore,QtGui\nfrom gui.demo import demo_ui\n\nclass FileBrowser(demo_ui.Ui_MainWindow,QtWidgets.QMainWindow):\n\n def __init__(self):\n super(FileBrowser,self).__init__()\n self.setupUi(self)\n self.fileBrower.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n self.fileBrower.customContextMenuRequested.connect(self.context_menu)\n self.populate()\n\n def populate(self):\n path = \"/Users/trannam\"\n self.model = QtWidgets.QFileSystemModel()\n self.model.setRootPath((QtCore.QDir.rootPath()))\n self.fileBrower.setModel(self.model)\n self.fileBrower.setRootIndex(self.model.index(path))\n self.fileBrower.setSortingEnabled(True)\n\n def context_menu(self):\n menu = QtWidgets.QMenu()\n open = menu.addAction(\"Open\")\n open.triggered.connect(self.openFile)\n cursor = QtGui.QCursor()\n menu.exec_(cursor.pos())\n\n def openFile(self):\n index = self.fileBrower.currentIndex()\n path = self.model.filePath(index)\n name = self.model.fileName(index)\n print(path)\n print(name)\n if platform.system() == 'Darwin': # macOS\n subprocess.call(('open', path))\n elif platform.system() == 'Windows': # Windows\n os.startfile(path)\n else: # linux variants\n subprocess.call(('xdg-open', path))\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n fileBrowser = FileBrowser()\n fileBrowser.show()\n sys.exit(app.exec_())","sub_path":"gui/demo/fileBrowser.py","file_name":"fileBrowser.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"97391464","text":"\"\"\"\nPizzas.py\nDate: 2015-09-23\nPeter Taylor\n\nPurpose:\nThe Pizza Challenge\n\"\"\"\n#I know You're Watching, There's no point denying it\n#okay?\n# Input Fix\ntry: input = raw_input\nexcept NameError: pass\n \ndef DictCount(dic, name, a = False):\n print(\"We Have \" + str(len(dic)) + \" types of \" + name + \" Those are\")\n i = 0\n for each in dic:\n i += 1\n if (a == False):\n print(str(i) + \": \" + each)\n else:\n print(str(i) + \": \" + each + \" Costing \" + unichr(163) + str(dic[each]))\n \nprint(\"\"\"\n.___________. __ __ _______ .______ __ ________ ________ ___ .__ __. ___ .___________. ______ .______ _____ ___ ___ ___ \n| || | | | | ____| | _ \\ | | | / | / / \\ | \\ | | / \\ | | / __ \\ | _ \\ | ____| / _ \\ / _ \\ / _ \\ \n`---| |----`| |__| | | |__ | |_) | | | `---/ / `---/ / / ^ \\ | \\| | / ^ \\ `---| |----`| | | | | |_) | | |__ | | | | | | | | | | | | \n | | | __ | | __| | ___/ | | / / / / / /_\\ \\ | . ` | / /_\\ \\ | | | | | | | / |___ \\ | | | | | | | | | | | | \n | | | | | | | |____ | | | | / /----. / /----./ _____ \\ | |\\ | / _____ \\ | | | `--' | | |\\ \\----. ___) | | |_| | | |_| | | |_| | \n |__| |__| |__| |_______| | _| |__| /________| /________/__/ \\__\\ |__| \\__| /__/ \\__\\ |__| \\______/ | _| `._____| |____/ \\___/ \\___/ \\___/ \"\"\")\nprint(\"The Pizzanator5000, or pn5k for short\")\n\nBases = {\n \"Thin Crust\":3,\n \"Deep Pan\":4,\n \"Stuffed Crust\":5\n}\nToppings = {\n \"Extra Cheese\":False,\n \"Salami\":False,\n \"Ham\":False,\n \"Mushroom\":False,\n \"Pineapple\":False,\n \"Chicken\":False,\n \"Peppers\":False,\n \"Onion\":False,\n \"Bacon\":False,\n \"Olives\":False\n}\nCost = 0\nTopping = 0\nBase = \"\"\nToppings2 = {}\n \nDictCount(Bases, \"bases\", True)\nwhile True:\n TBase = input(\"Choose Your Base: \")\n if TBase in Bases.keys():\n Base = TBase\n Cost += Bases[Base]\n break\n print(\"INVALID INPUT PLEASE TRY AGAIN\")\nprint(\"Toppings Cost\" + unichr(163) + \"1 each\\nYou may have up to 5 Toppings\\nWhen Prompted, input 1 to add selected topping to pizza and 0 to continue to the next topping\")\nfor each in Toppings:\n if Topping == 5:\n break\n resp = input(\"Do you want \" + each + \"?\")\n if resp == \"1\":\n Toppings[each] = True\n Topping += 1\nfor each in Toppings:\n if Toppings[each]:\n Cost += 1\n Toppings2[each] = Toppings[each]\nToppings = Toppings2\nprint(\"Your Pizza is calculated\")\nprint(\"It costs \" + unichr(163) + str(Cost) )\nprint(\"It has a \" + Base + \" base, costing \" + unichr(163) + str(Bases[Base]))\nprint(\"It has \" + str(Topping) + \"Toppings, each costing \" + unichr(163) + \"1 each\")\nprint(\"These Were the toppings You Selected:\")\nfor each in Toppings:\n print(each)","sub_path":"September/22/Pizzas.py","file_name":"Pizzas.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"294504752","text":"\"\"\" \n Quick and Dirty to get the ISUMET station data into the DB\n\"\"\"\nimport mx.DateTime\nimport re\nimport os\nimport sys\nimport access\nimport pg\niemaccess = pg.connect('iem', 'iemdb')\nnow = mx.DateTime.now()\nfp = now.strftime(\"/mesonet/ARCHIVE/data/%Y/%m/%d/text/ot/ot0002.dat\")\n\nif not os.path.isfile(fp):\n sys.exit(0)\n\niem = access.Ob(\"OT0002\", \"OT\")\n\nlines = open(fp, \"r\").readlines()\n\nlastLine = lines[-1]\n\ntokens = re.split(\"[\\s+]+\", lastLine)\n\ntparts = re.split(\":\", tokens[4])\nvalid = now + mx.DateTime.RelativeDateTime(hour= int(tparts[0]), \n minute = int(tparts[1]), second = int(tparts[2]) )\n\niem.data['valid'] = valid\niem.data['year'] = valid.year\n\nsped = float(tokens[8])\nsknt = round(sped * 0.868976, 1)\n\niem.data['sknt'] = sknt\niem.data['drct'] = tokens[9]\niem.data['tmpf'] = tokens[7]\n\niem.updateDatabase(iemaccess)\n\n#mydb.query(\"SELECT zero_record('OT0002')\")\n#mydb.query(\"UPDATE current SET tmpf = %s, indoor_tmpf = %s, valid = '%s', \\\n# sknt = %s, drct = %s WHERE station = '%s'\" % (tokens[7], tokens[6], \\\n# valid, tokens[8], tokens[9], \"OT0002\") )\n","sub_path":"scripts/ingestors/parse0002.py","file_name":"parse0002.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"489924121","text":"from xml.etree.ElementTree import Element, SubElement, tostring\nfrom xml.dom import minidom\nfrom collections import namedtuple\nfrom copy import deepcopy\nimport pickle\nimport argparse\n\n\nTurn = namedtuple('Turn', ['in_edge', 'outflows', 'probabilities'])\nOutflow = namedtuple('Outflow', ['out_edge', 'phase'])\n\n\nclass Flow(object):\n def __init__(self, route, count, begin, end):\n self.route = route\n self.count = count\n self.begin = begin\n self.end = end\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--demand', required=True, help='Demand label')\n args = parser.parse_args()\n return args\n\n\ndef get_possible_flows(flows, turns):\n\n partial_routes = flows\n full_routes = []\n\n while partial_routes:\n flow = partial_routes.pop(0)\n last_edge = flow.route[-1]\n if last_edge not in turns:\n full_routes.append(flow)\n else:\n next_turn = turns[last_edge]\n for outflow, probability in zip(next_turn.outflows, next_turn.probabilities):\n new_vehicle_count = flow.count * probability\n new_route = deepcopy(flow.route)\n new_route.append(outflow.out_edge)\n partial_routes.insert(0, Flow(route=new_route, count=new_vehicle_count,\n begin=flow.begin, end=flow.end)) \n\n return full_routes\n\n\ndef create_flow_xml(flows):\n root = Element('routes')\n\n vType = SubElement(root, 'vType', {'id': 'car',\n 'speedDev': str(0.1),\n 'guiShape': 'passenger',\n 'color': '1,1,0'})\n\n for flow_id, flow in enumerate(flows):\n first_edge = flow.route.pop(0)\n last_edge = flow.route.pop(-1)\n attributes = {'id': str(flow_id),\n 'begin': str(flow.begin),\n 'end': str(flow.end),\n 'number': str(int(round(flow.count))),\n 'type': 'car',\n 'from': first_edge,\n 'to': last_edge}\n intermediate_edges = flow.route\n if intermediate_edges:\n attributes['via'] = ' '.join(intermediate_edges)\n flow = SubElement(root, 'flow', attributes)\n\n raw_string = tostring(root, 'utf-8')\n reparsed_string = minidom.parseString(raw_string)\n flow_xml = reparsed_string.toprettyxml(indent=' ')\n\n return flow_xml\n\n\n# TODO: Allow demand profile to be input from a file\ndef main():\n args = get_args()\n\n flows = [\n Flow(route=[\"-gneE3\"], count=105, begin=0, end=600),\n Flow(route=[\"gneE0\"], count=45, begin=0, end=600),\n Flow(route=[\"-gneE3\"], count=75, begin=600, end=1200),\n Flow(route=[\"gneE0\"], count=75, begin=600, end=1200),\n Flow(route=[\"-gneE3\"], count=45, begin=1200, end=1800),\n Flow(route=[\"gneE0\"], count=105, begin=1200, end=1800),\n ]\n \n turn_files = [\n '/home/srishti/adasco/experiments/ICAPS-2019/1x1/config/isolated.turn.pkl'\n ]\n\n flow_files = [\n '/home/srishti/adasco/experiments/ICAPS-2019/1x1/config/{0}/{0}.flow.xml'.format(args.demand)\n ]\n \n for turn_file, flow_file in zip(turn_files, flow_files):\n with open(turn_file) as fp:\n turns = pickle.load(fp)\n flow_xml = create_flow_xml(get_possible_flows(flows, turns))\n with open(flow_file, 'w') as fp:\n fp.write(flow_xml)\n\n\nif __name__ == '__main__':\n main()","sub_path":"utils/scenarios/generate_all_possible_flows.py","file_name":"generate_all_possible_flows.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"599768315","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.contrib import messages\n\n\ndef homepage(request):\n return render(\n request=request,\n template_name=\"main/home.html\",\n )\n\n\ndef register(request):\n if request.method == \"POST\":\n return post_register(request)\n\n form = UserCreationForm()\n return render(\n request=request,\n template_name=\"main/register.html\",\n context={\"form\": form}\n )\n\n\ndef post_register(request):\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f\"New account created {username}\")\n login(request, user)\n return redirect(\"main:homepage\")\n else:\n for m in form.error_messages:\n messages.error(request, f\"{m}:{form.error_messages[m]}\")\n\n return render(\n request=request,\n template_name=\"main/register.html\",\n context={\"form\": form}\n )\n\n\ndef login_request(request):\n if request.method == \"POST\":\n return post_register(request)\n\n form = AuthenticationForm()\n return render(\n request=request,\n template_name=\"main/login.html\",\n context={\"form\": form}\n )\n\n\ndef post_login(request):\n form = AuthenticationForm(request, data=request.POST)\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n messages.success(request, f\"Hi {username}\")\n return redirect(\"main:homepage\")\n else:\n messages.error(request, \"authentication failed\")\n else:\n for m in form.error_messages:\n messages.error(request, f\"{m}:{form.error_messages[m]}\")\n return render(\n request=request,\n template_name=\"main/login.html\",\n context={\"form\": form}\n )\n\n\ndef logout_request(request):\n logout(request)\n messages.success(request, f\"You've been logged out\")\n return redirect(\"main:homepage\")\n","sub_path":"finances/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"5608996","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ======================================================================================\n#\n# Ian Minatrea\n# Implementation of the Particle Swarm Optimization (PSO) Algorithm in Py3\n# January, 2019\n#\n# ======================================================================================\n\n__author__ = \"Ian Minatrea\"\n__date__ = \"01/23/2019\"\n__copyright__ = \"Copyright 2019, The Helios Project\"\n__email__ = \"Minatrea.Ian@gmail.com\"\n__version__ = \"0.1.0\"\n__status__ = \"Prototype\"\n\n# ======================================================================================\n# Imports\n# ======================================================================================\n\nimport math\nimport random\n#import numpy as np\n#import scipy as sp\n#import matplotlib as plt\n\n# =====================================================================================\n# Cost Function - The Function we want to Minimize\n# =====================================================================================\n\n\ndef cost(x):\n \n # A simple, if not the simplest cost function with any meaningful result. Arbitrary\n\n total = 0\n for i in range(len(x)):\n total += x[i] ** 2\n return total\n\n\n# =====================================================================================\n# Main\n# =====================================================================================\n\nclass Swarm:\n \"\"\"\n This Class contains all the particles from a given swarm, and by extension, their \n properties.\n\n The point of these two classes being separate is purely a conceptual one, it could\n be much more efficient, but I feel that this way best illustraits the relationship\n between individual particle and the aggregate swarm.\n \"\"\"\n def __init__(self):\n self.err_bg = -1 # best error for group\n self.pos_bg = [] # best position for group\n self.swarm = [] # array that holds all the Particle Objects\n \n def __iter__(self, costFunc, x0, bounds, partNum):\n self.cost = costFunc # The cost fuction feed into the swarm\n self.x0 = x0\n self.partNum = partNum\n self.bounds = bounds\n self.iter = 0\n # establish the swarm\n for i in range(0, self.partNum):\n self.swarm.append(Particle(self.x0))\n\n def __next__(self, maxIter):\n # begin optimization loop\n # cycle through particles in swarm and evaluate fitness\n\n #print(self.iter)\n self.iter += 1\n \n for i in range(0, len(self.swarm)):\n self.swarm[i].err_i = self.cost(self.swarm[i].pos_i)\n \n # check to see if the current position is an individual best\n if self.swarm[i].err_i < self.swarm[i].err_bi or self.swarm[i].err_bi == -1:\n self.swarm[i].pos_bi = self.swarm[i].pos_i\n self.swarm[i].err_bi = self.swarm[i].err_i\n\n if self.swarm[i].err_i < self.err_bg or self.err_bg == -1:\n self.pos_bg = list(self.swarm[i].pos_i)\n self.err_bg = float(self.swarm[i].err_i)\n \n # cycle through swarm and update velocities and position \n for i in range(0, len(self.swarm)):\n self.swarm[i].vUpdate(self.pos_bg)\n self.swarm[i].xUpdate(self.bounds)\n\n if self.iter > maxIter:\n raise StopIteration\n else:\n return self\n\n\nclass Particle(Swarm):\n \"\"\"\n A subclass of Swarm, these particles have little meaning outsite the greater\n context of the swarm, but nevertheless must contain their own individual \n properties to be referenced by the fitness algorithm. None of their stats\n matter indiviually\n \"\"\"\n def __init__(self, x0):\n self.pos_i = [] # particle position\n self.vel_i = [] # particle velocity\n self.pos_bi = [] # best position individual\n self.err_bi = -1 # best error individual\n self.err_i = -1 # error individual\n self.dimNum = len(x0)\n\n for i in range(0, self.dimNum):\n self.vel_i.append(random.uniform(-1,1))\n self.pos_i.append(x0[i])\n\n # update new particle velocity\n def vUpdate(self, pos_bg):\n w = 0.5 # constant inertia weight (how much to weigh the previous velocity)\n c1 = 1 # cognative constant\n c2 = 2 # social constant\n\n for i in range(0, self.dimNum):\n r1 = random.random()\n r2 = random.random()\n\n vCog = c1 * r1 * (self.pos_bi[i] - self.pos_i[i])\n vSoc = c2 * r2 * (pos_bg[i] - self.pos_i[i])\n self.vel_i[i] = w * self.vel_i[i] + vCog + vSoc\n\n # update the particle position based off new velocity updates\n def xUpdate(self, bounds):\n for i in range(0, self.dimNum):\n self.pos_i[i] = self.pos_i[i] + self.vel_i[i]\n\n # adjust maximum position if necessary\n if self.pos_i[i] > bounds[i][1]:\n self.pos_i[i] = bounds[i][1]\n\n # adjust minimum position if neseccary\n if self.pos_i[i] < bounds[i][0]:\n self.pos_i[i] = bounds[i][0]\n\nx0 = [5, 5] # initial starting location [x1,x2...]\nbounds = [(-10, 10), (-10, 10)] # input bounds [(x1_min,x1_max),(x2_min,x2_max)...]\npso1 = Swarm()\npso1.__iter__(cost, x0, bounds, partNum = 15)\nfor i in range(30):\n pso1.__next__(30)\nprint(\"FINAL:\")\nprint(pso1.pos_bg)\nprint(pso1.err_bg)\n\n","sub_path":"PSO.py","file_name":"PSO.py","file_ext":"py","file_size_in_byte":5434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"90999676","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see http://www.gnu.org/licenses/.\n#\n##############################################################################\n\nfrom openerp import models, fields, api\n\n\n\nclass product_category(models.Model):\n\t_inherit = 'product.category'\n\n\tno_auto_create_product = fields.Boolean(string='No auto create product',\n\t\t\t\t\t\t\t\t\t\thelp='If checked, nolonger auto create a product or several product variants'\n\t\t\t\t\t\t\t\t\t\t'when this product template saved')\n\t\t\t\t\t\t\t\t\t\t\nclass product_template(models.Model):\n\t_inherit = 'product.template'\n\t\n\tno_auto_create_product = fields.Boolean(string='No auto create a product',\n\t\t\t\t\t\t\t\t\t\thelp=\"When choose, it will nolong create a product or several product variants\"\n\t\t\t\t\t\t\t\t\t\t\"when it saved.If not, it will depend on this product template's category\")\n\n\tdef _get_product_tmpl_attributes_dict(self):\n\t\tproduct_tmpl_attributes = []\n\t\tfor attribute in self.attribute_line_ids:\n\t\t\tproduct_tmpl_attributes.append({'attribute_id': attribute.attribute_id.id})\n\t\t\n\t\treturn product_tmpl_attributes\n\t\n\t\n\t@api.multi\n\tdef create_variant_ids(self):\n\t\tfor tmpl in self:\n\t\t\tif ((tmpl.categ_id.no_auto_create_product is True) or\n\t\t\t\t\t\t( tmpl.no_auto_create_product is True)):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn super(product_template, self).create_variant_ids()\n\n\n\t\n","sub_path":"cproduct_noauto/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"190250581","text":"import argparse\nimport cv2\nimport gym\nimport copy\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nfrom lightsaber.tensorflow.util import initialize\nfrom network import make_actor_network, make_critic_network\nfrom agent import Agent\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--env', type=str, default='Pendulum-v0')\n parser.add_argument('--gpu', type=int, default=0)\n parser.add_argument('--load', type=str, default=None)\n parser.add_argument('--render', action='store_true')\n args = parser.parse_args()\n\n env = gym.make(args.env)\n\n obs_dim = env.observation_space.shape[0]\n n_actions = env.action_space.shape[0]\n\n actor = make_actor_network([30])\n critic = make_critic_network()\n\n sess = tf.Session()\n sess.__enter__()\n\n agent = Agent(actor, critic, obs_dim, n_actions, None)\n\n saver = tf.train.Saver()\n if args.load is not None:\n saver.restore(sess, args.load)\n\n global_step = 0\n episode = 0\n\n while True:\n sum_of_rewards = 0\n done = False\n step = 0\n state = env.reset()\n\n while True:\n if args.render:\n env.render()\n\n action = agent.act(state)\n\n if done:\n break\n\n state, reward, done, info = env.step(action)\n\n sum_of_rewards += reward\n step += 1\n global_step += 1\n\n episode += 1\n\n print('Episode: {}, Step: {}: Reward: {}'.format(\n episode, global_step, sum_of_rewards))\n\nif __name__ == '__main__':\n main()\n","sub_path":"AI-for-Prosthetics/PPO/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"21449056","text":"\"\"\"\nPriority Queue\n\nQueue priorities are from 0 to 10\n\"\"\"\nfrom typing import Any\n\npqueue = {}\n\n\ndef enqueue(elem: Any, priority: int = 0) -> None:\n \"\"\"\n Operation that add element to the end of the queue\n\n :param elem: element to be added\n :return: Nothing\n \"\"\"\n if priority in pqueue:\n pqueue[priority].append(elem)\n else:\n pqueue[priority] = [elem]\n\n return None\n\n\ndef dequeue() -> Any:\n \"\"\"\n Return element from the beginning of the queue. Should return None if not elements.\n\n :return: dequeued element\n \"\"\"\n if len(pqueue):\n m = min(pqueue.keys())\n value = pqueue[m].pop(0)\n if not pqueue[m]:\n pqueue.pop(m)\n return value\n\n return None\n\n\ndef peek(ind: int = 0, priority: int = 0) -> Any:\n \"\"\"\n Allow you to see at the element in the queue without dequeuing it\n\n :param ind: index of element (count from the beginning)\n :return: peeked element\n \"\"\"\n if priority in pqueue and 0 <= ind < len(pqueue[priority]):\n return pqueue[priority][ind]\n\n return None\n\n\ndef clear() -> None:\n \"\"\"\n Clear my queue\n\n :return: None\n \"\"\"\n pqueue.clear()\n\n return None\n","sub_path":"Tasks/a2_priority_queue.py","file_name":"a2_priority_queue.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"323377230","text":"# PERFORM KERNEL PCA TO GET RELEVANT FEATURES FROM STATE\nimport pickle\nimport os\nimport numpy as np\nfrom sklearn.decomposition import KernelPCA\n\nACTIONS = ['UP', 'RIGHT', 'DOWN', 'LEFT', 'WAIT', 'BOMB']\nACTION_INDEX = {'UP': 0, 'RIGHT': 1, 'DOWN': 2, 'LEFT': 3, 'WAIT': 4, 'BOMB': 5}\n\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nMODEL_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/my-saved-model_rule.pt')\nSTATE_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/states_1_agent_crates.pt')\nNEXT_STATE_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/next_states_1_agent_crates.pt')\nNEXT_ACTION_INDEX_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/next_action_index_1_agent_crates.pt')\nREWARD_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/rewards_1_agent_crates.pt')\n\nPCA_TRANSFORMER_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/pca_transformer_1_agent_crates.pt')\nTRANSFORMED_STATES_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/pca_transformed_states_1_agent_crates.pt')\nTRANSFORMED_NEXT_STATES_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/pca_transformed_states_1_agent_crates.pt')\n\nN_COMPONENTS = 20 # dimension of the output\n\nwith open(STATE_PATH, \"rb\") as file:\n states = pickle.load(file)\n\nwith open(NEXT_STATE_PATH, \"rb\") as file:\n next_states = pickle.load(file)\n\n# print(np.shape(states), np.shape(next_states))\n\npca_transformer = KernelPCA(n_components=20, kernel='linear')\n\nn_actions, n_states, dim_states = np.shape(states)\n# select a random subset of the states for the fit. Fitting all 6*100000 states would require 80GB of memory\nrandom_indices = np.random.permutation(np.linspace(0, n_actions*n_states, n_actions*n_states + 1)).astype(int)[0:5000]\npca_transformer.fit(X=np.reshape(states, (n_actions * n_states, dim_states))[random_indices])\n\n# to train a model using SARSA later, we need for each target the state and the following state\ntransformed_states = []\ntransformed_next_states = []\n\nfor i in range(len(ACTIONS)):\n transformed_states.append(pca_transformer.transform(X=states[i]))\n\nfor i in range(len(ACTIONS)):\n transformed_next_states.append(pca_transformer.transform(X=next_states[i]))\n\n# print(np.shape(transformed_states), np.shape(transformed_next_states))\n\nwith open(PCA_TRANSFORMER_PATH, \"wb\") as file:\n pickle.dump(pca_transformer, file)\n\nwith open(TRANSFORMED_STATES_PATH, \"wb\") as file:\n pickle.dump(transformed_states, file)\n\nwith open(TRANSFORMED_NEXT_STATES_PATH, \"wb\") as file:\n pickle.dump(transformed_next_states, file)\n\n\n","sub_path":"agent_code/custom_sarsa_pca_agent/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"501233479","text":"__author__ = 'David Mitchell'\n#This script creates an example/test db.\n\nfrom app import db\nfrom app import MenuCategory, MenuItem\n\ndb.drop_all()\ndb.create_all()\n\nappetizer_category = MenuCategory(name='Appetizers')\nentree_category = MenuCategory(name='Entrees')\ndesert_category = MenuCategory(name='Deserts')\nbacon_item = MenuItem(name='Bacon', description='Delicious bacon', category=appetizer_category)\nbaconz_item = MenuItem(name='Baconz', description='Bacon with Bacon on top, fried in a bacon crust', category=entree_category)\nbaconIceCream_item = MenuItem(name='Bacon Ice Cream', description='Bacon Ice Cream topped with bacon bits', category=desert_category)\n\ndb.session.add_all([appetizer_category, entree_category, desert_category, bacon_item, baconz_item, baconIceCream_item])\ndb.session.commit()\n","sub_path":"web/create_db.py","file_name":"create_db.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"114646876","text":"import tensorflow as tf\nfrom TextRNN.TextRNN import TextRNN\nfrom TextRNN.data_utils import data_tool\nimport datetime\nimport time\nimport os\nimport numpy as np\n\nclass Training(data_tool, TextRNN):\n def __init__(self, train_data_path, test_data_path, corpus_path, word_vector_path, batch_size, epoch_size,\n rnn_size, outdir='./',\n Glove_path=None, check_dir=None):\n data_tool.__init__(self, train_data_path=train_data_path,\n test_data_path=test_data_path, corpus_path=corpus_path, word_vector_path=word_vector_path, Glove_path=Glove_path)\n self.outdir = outdir\n with tf.Graph().as_default():\n self.sess = tf.Session()\n with self.sess.as_default():\n TextRNN.__init__(self, sequence_length=self.max_document_length,\n embedding_size=self.word_vec.shape[1],\n word_vector=self.word_vec, rnn_size=rnn_size)\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n lr = tf.train.exponential_decay(0.001, global_step=global_step, decay_steps=10000, decay_rate=1)\n optimizer = tf.train.AdamOptimizer(lr)\n grads_and_vars = optimizer.compute_gradients(self.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n # save/restore + temporary working directory\n saver = tf.train.Saver()\n if check_dir:\n checkpoint_file = tf.train.latest_checkpoint(check_dir)\n print('load existing checkpoint:', checkpoint_file)\n saver.restore(self.sess, checkpoint_file)\n temp_dir = os.path.split(check_dir)[-2]\n else:\n temp_dir = str(int(time.time()))\n checkpoint_dir = os.path.join(outdir, 'TextCNN_runs', temp_dir, 'checkpoints')\n checkpoint_model_dir = checkpoint_dir + '/model.ckpt'\n\n # Summary for loss and accuracy\n loss_summary = tf.summary.scalar(\"loss\", self.loss)\n acc_summary = tf.summary.scalar(\"accuracy\", self.accuracy)\n\n # Train Summaries\n train_summary_op = tf.summary.merge([loss_summary, acc_summary])\n train_summary_dir = os.path.join(outdir, \"TextRNN_runs\", temp_dir, \"summaries\", \"train\")\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, self.sess.graph)\n\n # Test Summaries\n test_summary_op = tf.summary.merge([loss_summary, acc_summary])\n test_summary_dir = os.path.join(outdir, 'TextRNN_runs', temp_dir, 'summaries', 'test')\n test_summary_writer = tf.summary.FileWriter(test_summary_dir, self.sess.graph)\n\n # define operations\n def train_(batch_x, batch_y):\n feed_dict = {self.input_x: batch_x,\n self.input_y: batch_y,\n self.real_length: self.real_words_length(batch_x),\n self.keep_prob: 0.5}\n\n loss, _, accuracy, step, summaries = self.sess.run(\n [self.loss, train_op, self.accuracy, global_step, train_summary_op],\n feed_dict=feed_dict)\n\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n train_summary_writer.add_summary(summaries, step)\n\n def test_():\n feed_dict = {self.input_x: self.test_x[:500],\n self.input_y: self.test_y[:500],\n self.real_length: self.real_words_length(self.test_x[:500]),\n self.keep_prob: 1.0}\n\n loss, accuracy, step, summaries = self.sess.run(\n [self.loss, self.accuracy, global_step, test_summary_op],\n feed_dict=feed_dict)\n\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n test_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n # initialize\n self.sess.run(tf.global_variables_initializer())\n\n # generate batches\n batches_train = self.batches_generate(data_x=self.train_x, data_y=self.train_y, epoch_size=epoch_size,\n batch_size=batch_size, shuffle=True)\n\n total = (len(self.train_y) // batch_size + 1) * epoch_size\n # training on batches\n print(\"Total step:\", total)\n for i, batch in enumerate(batches_train):\n batch_x, batch_y = batch\n train_(batch_x, batch_y)\n current_step = tf.train.global_step(self.sess, global_step)\n if i % 100 == 0 and i > 0:\n print('\\nEvaluation:\\n')\n loss, accuracy = test_()\n # print(\"Writing model...\\n\")\n # saver.save(self.sess, checkpoint_model_dir, global_step=current_step)\n self.Evaluation_test(self.sess, window=500, save=temp_dir)\n\n def real_words_length(self, batches):\n return np.ceil([np.argmin(batch.tolist() + [0]) for batch in batches.reshape((-1, batches.shape[-1]))])\n\n def Evaluation_test(self, sess, window=500, save=None):\n # start testing and saving data\n data_size = len(self.test_x)\n result = []\n for i in range(data_size // window + 1):\n left_, right_ = i * window, min((i+1) * window, data_size)\n result.append(sess.run(self.output,\n feed_dict={self.input_x: self.test_x[left_:right_],\n self.keep_prob: 1.0,\n self.real_length: self.real_words_length(self.test_x[left_:right_])}))\n result = np.concatenate(result, axis=0)\n print(\"Test data accuracy:\", np.mean(np.equal(np.argmax(self.test_y, axis=1), result)))\n self.test['pred'] = result+1\n self.test.to_csv(os.path.join(self.outdir, 'TextRNN_runs', save, 'textrnn.tsv'), sep='\\t')\n\nif __name__ == '__main__':\n train_data_path = \"../data/business_reviews2017_train.tsv\"\n test_data_path = \"../data/business_reviews2017_test.tsv\"\n corpus_path = \"corpus.pkl\"\n word_vect = \"word_vector.npy\"\n test = Training(train_data_path, test_data_path, corpus_path, word_vect, epoch_size=20)\n","sub_path":"TextRNN/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"464850381","text":"import numpy as np\nfrom scipy.linalg import expm\n#function M = forwardKinematicsUr3(theta)\ndef forwardKinematicsUr3(theta):\n a1=np.array([[0],[0],[1]])\n q1 = np.array([[0],[0],[0]])\n S1=rev_screw(a1,q1)\n\n a2=np.array([[0],[-1],[0]])\n q2 = np.array([[0],[0],[-.152]])\n S2=rev_screw(a2,q2)\n\n a3=np.array([[0],[-1],[0]])\n q3 = np.array([[0],[-.120],[.396]])\n S3=rev_screw(a3,q3)\n\n a4=np.array([[0],[1],[0]])\n q4 = np.array([[0],[-.027],[.609]])\n S4=rev_screw(a4,q4)\n\n a5=np.array([[0],[0],[1]])\n q5 = np.array([[0],[-0.110],[0.692]])\n S5=rev_screw(a5,q5)\n\n a6=np.array([[0],[-1],[0]])\n q6 = np.array([[0],[-.192],[.692]])\n S6=rev_screw(a6,q6)\n\n\n\n Tinit = np.array([[1,0,0,0],[0,0,-1,-.192],[0,1,0,0.692],[0,0,0,1]])\n\n T_1in0 = Pose(S1,theta[0])\n T_2in0 = np.dot(T_1in0,Pose(S2,theta[1]))\n T_3in0 = np.dot(T_2in0,Pose(S3,theta[2]))\n T_4in0 = np.dot(T_3in0,Pose(S4,theta[3]))\n T_5in0 = np.dot(T_4in0,Pose(S5,theta[4]))\n T_6in0 = np.dot(T_5in0,Pose(S6,theta[5]))\n T_toolin0 = np.dot(T_6in0,Tinit)\n M = T_toolin0\n\n return M\n\n#J = [S1 adjoint_matrix(T_1in0)*S2 adjoint_matrix(T_2in0)*S3];\n#Jbod=inv(adjoint_matrix(Pose(S1,theta(1))*Pose(S2,theta(2))*Pose(S3,theta(3))*Tinit))*J;\n\n\n\ndef Pose(S,theta):\n M=expm(np.dot(bracket_twist(S),theta))\n return M\n\ndef rev_screw(a,q):\n M=screw(a,np.dot(-bracket_3x3(a),q));\n return M\n\ndef screw(W,V):\n S = np.zeros((6,1))\n S[0:3]=W\n S[3:6]=V\n #S = np.transpose(S)\n return S\n\ndef bracket_twist(S):\n M = np.zeros((4,4))\n M[0:3,0:3] = bracket_3x3(S[0:3,])\n M[0:3,[3]] = S[3:6]\n M[3] = [0,0,0,1]\n return M\n\ndef bracket_3x3(R):\n\n M = np.array([[0, -R[2], R[1]],[R[2],0,-R[0]],[-R[1],R[0],0]])\n return M\n\n\n\n","sub_path":"forwardKinematics.py","file_name":"forwardKinematics.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"449896765","text":"from django.test import TestCase\nfrom django.contrib.contenttypes.models import ContentType\nfrom facilities.data_loader import DataLoader\nfrom facilities.models import Sector, FacilityType\n\n\nclass ImportDataTest(TestCase):\n\n def setUp(self):\n self.data_loader = DataLoader()\n\n def test_create_sectors(self):\n self.data_loader.create_sectors()\n sectors = dict([(s.slug, s.name) for s in Sector.objects.all()])\n expected_dict = {\n 'education': 'Education',\n 'health': 'Health',\n 'water': 'Water'\n }\n self.assertEquals(sectors, expected_dict)\n\n def test_create_facility_types(self):\n self.data_loader.create_facility_types()\n self.assertEquals(FacilityType.objects.count(), 23)\n\n def test_limited_import(self):\n # this needs to be rewritten with small csvs\n\n # data_loader.load()\n # expected_info = {\n # \"number of facilities\": 41,\n # \"unused variables\": [],\n # \"facilities without lgas\": 0,\n # \"number of lga records\": 183,\n # \"number of facility records\": 4419\n # }\n # self.assertEquals(data_loader.get_info(), expected_info)\n pass\n\n def count_all_objects(self):\n result = {}\n for ct in ContentType.objects.all():\n result[ct.natural_key()] = ct.model_class().objects.count()\n return result\n","sub_path":"facilities/tests/import_tests.py","file_name":"import_tests.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"318133752","text":"import math\nfrom decimal import *\n\n# Set the precision to greater than 100 to avoid rounding\ngetcontext().prec = 105\n\n# Get all of the non-squares from 1 to 100\nsquares = list(map(lambda x: x**2, range(1, 10)))\nnonsquares = list(filter(lambda x: x not in squares, range(1, 100)))\n\n# Set counter\nans = 0\n\n# Count all of the relevant digits\nfor i in nonsquares:\n lead = int(math.sqrt(i))\n digits = list(str(Decimal(i).sqrt())[2:101])\n ans += lead + sum(map(lambda x: int(x), digits))\n\nprint(ans)\n","sub_path":"080.py","file_name":"080.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"49917008","text":"#Frederick Herzog\n# Python Word Count\n# 11/3/2020\n\nfrom re import sub\nfrom collections import Counter\nfrom pydoop import hdfs\n\ndef txt_WordsToList(file):\n\twith open(file, 'r') as f:\n\t\tdata = f.read().split()\n\t\treturn data\n\t\ndef removePunct(dat):\n\tcleandat = []\n\tfor word in dat:\n\t\tcleaned_word = sub('[^A-Za-z0-9]+', '', word)\n\t\tcleandat.append(cleaned_word)\n\treturn cleandat\n\ndef makeLowerCase(dat):\n\tlower_case = [w.lower() for w in dat]\n\treturn lower_case\n\ndef countWords(dat):\n\tcount = Counter\n\tc = count(dat)\n\treturn dict_to_tuples(c)\n\ndef dict_to_tuples(dat):\n\tfreq = []\n\tfor k, v in dat.items():\n\t\tfreq.append((v,k))\n\tfreq.sort(reverse = True)\n\treturn freq\n\ndef out_to_txt(dat, file):\n\twith open(file, 'w') as f:\n\t\tfor i in dat:\n\t\t\tf.write(' '.join (str(s) for s in i) + '\\n')\n\ndef out_to_dfs(file, dfs_path):\n\tprint(\"Writing file to HDFS...\")\n\thdfs.put(file, dfs_path)\n\nif __name__ == '__main__':\n\tfile_path = \"Shakespeare.txt\"\n\tout_path = \"count_python.txt\"\n\tdfs_path = \"hdfs://localhost:9000/SPtext/\"+out_path\n\twords = txt_WordsToList(file_path)\n\twords_no_punct = removePunct(words)\n\tlower_c_words = makeLowerCase(words_no_punct)\n\tmy_count = countWords(lower_c_words)\n\tprint(my_count)\n\tout_to_txt(my_count, out_path)\n\tout_to_dfs(out_path, dfs_path)\n\n\n\n","sub_path":"Task-002/wrdcount.py","file_name":"wrdcount.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"320936552","text":"from django.contrib import admin\nfrom .models import User\n\n\n@admin.register(User)\nclass Admin(admin.ModelAdmin):\n '''Admin View for '''\n\n list_display = ('email', 'id', 'user_name', 'phone_number',)\n list_filter = (\n 'gender', 'date_created', 'active', 'followers', 'following',\n )\n\n readonly_fields = ('date_created',)\n search_fields = ('id', 'email', 'user_name', 'phone_number',)\n fieldsets = (\n (None, {\n 'fields': (\n 'id', 'email', 'user_name', 'active',\n ),\n }),\n ('More Details', {\n 'classes': ('collapse',),\n 'fields': (\n 'phone_number', 'date_created', 'profile_image',\n 'gender', 'bio',\n ),\n }),\n ('User Statistics', {\n 'classes': ('collapse',),\n 'fields': (\n 'followers', 'following',\n ),\n }),\n )\n readonly_fields = (\n 'id', 'followers', 'following', 'date_created', 'profile_image',\n 'email', 'user_name'\n )\n","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207118545","text":"import logging\nfrom flask import jsonify\nfrom flask_restful import Resource\nfrom flask_jwt_extended import fresh_jwt_required\nfrom database import db\n\n\nclass Users(Resource):\n @fresh_jwt_required\n def get(self):\n try:\n users = db \\\n .get_collection(\"users\") \\\n .find()\n return jsonify({\n \"success\": True,\n \"error\": None,\n \"payload\": users\n })\n except Exception as e:\n logging.exception(str(e))\n return jsonify({\n \"success\": False,\n \"error\": str(e),\n \"payload\": None\n })\n","sub_path":"app/api/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"264308361","text":"import tkinter\n# Aprendendo a utilizar toplevels\n\ndef abrir_formulario():\n # criando um toplevel\n top = tkinter.Toplevel()\n top.title('Nova Página')\n top.geometry('200x100')\n la1 = tkinter.Label(top, text='Esta é uma nova janela').pack()\n\n\nroot = tkinter.Tk()\nroot.geometry('300x200')\n\ncmd = tkinter.Button(root, text='Abrir nova janela', command=abrir_formulario)\ncmd.pack()\n\nroot.mainloop()","sub_path":"tkinter/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"643012336","text":"import urllib3\nfrom bs4 import BeautifulSoup\n\ndef retrieve_versionsOS(os):\n url = 'https://app.vagrantup.com/' + os\n req = urllib3.PoolManager()\n res = req.request('GET', url)\n soup = BeautifulSoup(res.data, 'html.parser')\n boxes = soup.findAll('div', {'class': 'col-md-6'})\n versions = []\n for box in boxes:\n version = box.text.split()[0]\n description = box.text.rsplit('\\n', 3)[2][12:]\n versions.append((version, description))\n return versions\n","sub_path":"fromHTMLtoVagrant/OldScripts/vagrantDB.py","file_name":"vagrantDB.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"456533701","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# This module contants two timer context managers, one a class and another\n# a generator function style context managers using a decorator\n\nfrom __future__ import print_function\nimport sys\nimport time\nfrom StringIO import StringIO\nfrom contextlib import contextmanager\n\n\nclass Timer(object):\n \"\"\"This is a timer context manager Class to time code execution.\n \"\"\"\n def __init__(self, f=sys.stdout, handle_error=True):\n self.f = f\n self.start_time = time.time()\n self.handle_error = handle_error\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n end_time = time.time() - self.start_time\n self.f.write(u\"This code took {:f} seconds\\n\".format(end_time))\n return self.handle_error\n\n\n@contextmanager\ndef timer(f=sys.stdout):\n \"\"\"This is a timer context manager to time code execution.\n \"\"\"\n start_time = time.time()\n try:\n yield object()\n except Exception as e:\n print(u\"An error occured: %s\" % e)\n raise e\n finally:\n end_time = time.time() - start_time\n f.write(u\"This code took {:f} seconds\\n\".format(end_time))\n\nif __name__ == \"__main__\":\n\n # This is a test to make sure that the context handler Class works\n with Timer() as t:\n for i in range(100000):\n i = i ** 20\n print(u\"Done processing\")\n\n\n # This is a test to make sure that the context handler Decorator works\n with timer() as t:\n for i in range(100000):\n i = i ** 20\n print(u\"Done processing\")\n\n # This is a test to make sure that the context handler Class works\n # with a STringIO() passsed in\n f = StringIO()\n with Timer(f) as t:\n for i in range(100000):\n i = i ** 20\n print(u\"Done processing\")\n\n print(f.getvalue())\n f.close()\n\n # This is a test to make sure that the context handler Decorator works\n # with a STringIO() passsed in\n f2 = StringIO()\n with timer(f2) as t:\n for i in range(100000):\n i = i ** 20\n print(u\"Done processing\")\n\n print(f2.getvalue())\n f2.close()\n\n print(u\"All tests succesful. First two are in different order than\")\n print(u\"last two because the timer is writing to the default sys.stdout\")\n print(u\"so timer output comes out on the screen right away.\")\n print(u\"\\nThis last test makes sure exceptions handler works:\")\n print(u\"(only tests Class version, generator versino already tested)\")\n\n # This test make' sure that the exception in the context handler works\n # With True passed in to ignore exceptions\n f = StringIO()\n with Timer(f, True) as t:\n l = range(500)\n i = 0\n while True:\n i += 1\n l[i] = 1\n print(u\"Done Processing\")\n print(f.getvalue())\n f.close()\n\n # This test make' sure that the exception in the context handler works\n # With False passed in to bubble up exceptions\n f = StringIO()\n with Timer(f, False) as t:\n l = range(500)\n i = 0\n while True:\n i += 1\n l[i] = 1\n print(u\"Done Processing\")\n print(f.getvalue())\n f.close()\n\n # This test make's sure that the exception in the generatorcontext\n # handler works. Tried this and it does throw an exception\n # with timer() as t:\n # l = range(500)\n # i = 0\n # while True:\n # i += 1\n # l[i] = 1\n # print(u\"How long does this time take\")\n\n\n\n \n","sub_path":"Students/HenryGrantham/session09/timer_context_manager.py","file_name":"timer_context_manager.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"491571428","text":"\"\"\"'add_post_model'\n\nRevision ID: e18f070061fb\nRevises: d0bb797e137b\nCreate Date: 2019-01-02 13:47:22.937945\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e18f070061fb'\ndown_revision = 'd0bb797e137b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('posts',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=50), nullable=True),\n sa.Column('body', sa.Text(), nullable=True),\n sa.Column('body_html', sa.Text(), nullable=True),\n sa.Column('author_id', sa.Integer(), nullable=True),\n sa.Column('add_time', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_posts_add_time'), 'posts', ['add_time'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_posts_add_time'), table_name='posts')\n op.drop_table('posts')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e18f070061fb_add_post_model.py","file_name":"e18f070061fb_add_post_model.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"322523436","text":"from scipy import spatial\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as mpatches\r\nfrom sklearn import decomposition as sk\r\nfrom CanculationB import main as calculateB\r\n\r\n\r\ndef plotBk(B): # pca!!\r\n \"\"\"\r\n plt.plot(x_arr,reg_y, color='salmon', linewidth=1.5)\r\n patchC = mpatches.Patch(color='salmon', label='y = '+str(round(c,4))+'x + e')\r\n patchR = mpatches.Patch(color='salmon', label='r^2 = ' + str(round(r,4)))\r\n patchP = mpatches.Patch(color='salmon', label='p = ' + str(p_value))\r\n plt.legend(handles=[patchC ,patchR,patchP],fontsize = 'small',loc=2)\r\n plt.title(\"bk vectors after pca\")\r\n plt.xlabel(x,fontsize=10)\r\n plt.ylabel(y,fontsize=10)\r\n plt.tight_layout()\r\n plt.savefig(path)\r\n plt.clf()\r\n plt.close()\r\n \"\"\"\r\n\r\n\r\ndef calculateParam(B, closeNeighbors=5):\r\n \"\"\"\r\n we recieve a matrix of bk by rows (row1=b1)\r\n :return:list =[[param,vertix]]\r\n \"\"\"\r\n dMat = spatial.distance_matrix(B, B)\r\n dMat = dMat.astype(float)\r\n np.fill_diagonal(dMat, np.inf) # diagonal is zeros\r\n dim, dim = dMat.shape\r\n paramList = []\r\n for graphk in range(dim):\r\n sum = 0\r\n dMat_row=np.asarray(dMat[graphk,:])\r\n sorted_row=np.sort(dMat_row)\r\n for col in range(closeNeighbors):\r\n sum += sorted_row[col]\r\n param = 1 / sum\r\n paramList.append((param, graphk))\r\n return paramList\r\n","sub_path":"algorithm/AnomalyParameter.py","file_name":"AnomalyParameter.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"8181373","text":"from bs4 import BeautifulSoup\r\nimport urllib2\r\nimport json\r\nimport codecs\r\nimport string\r\n\r\n\r\nclass SoundFxFinder:\r\n def __init__(self, transcription):\r\n \"\"\"\r\n The constructor takes a file name and creates a json\r\n file with extracted keywords and links to each word's sound effect\r\n \"\"\"\r\n\r\n self.base_url = \"http://www.findsounds.com/ISAPI/search.dll?keywords=\"\r\n self.keywords_with_sounds = {}\r\n\r\n # Pronouns, prepositions, and conjunctions cannot be illustrated by sound fx\r\n self.exclude = ['I', 'you', 'he', 'she', 'it', 'they', 'we',\r\n 'me', 'you', 'him', 'her', 'it', 'us', 'them',\r\n 'aboard', 'about', 'above', 'across', 'after',\r\n 'against', 'along', 'amid', 'among', 'anti',\r\n 'around', 'as', 'at', 'before', 'behind',\r\n 'below', 'beneath', 'beside', 'besides', 'between',\r\n 'beyond', 'but', 'by', 'concerning', 'considering',\r\n 'despite', 'down', 'during', 'except', 'excepting',\r\n 'excluding', 'following', 'for', 'from', 'in',\r\n 'inside', 'into', 'like', 'minus', 'near', 'of',\r\n 'off', 'on', 'onto', 'opposite', 'outside', 'over',\r\n 'past', 'per', 'plus', 'regarding', 'round', 'save',\r\n 'since', 'than', 'through', 'to', 'toward', 'towards',\r\n 'under', 'underneath', 'unlike', 'until', 'up', 'upon',\r\n 'versus', 'via', 'with', 'within', 'without',\r\n 'for', 'nor', 'and', 'but', 'or', 'although', 'as', 'if',\r\n 'because', 'than', 'that', 'unless', 'until', 'til', 'when',\r\n 'where', 'whether', 'which', 'while', 'who', 'both', 'such', 'rather',\r\n 'a', 'to']\r\n\r\n # Creates json file\r\n self.find_sounds(transcription)\r\n\r\n def find_sounds(self, transcription):\r\n \"\"\"\r\n Builds dictionary of keywords in transcription that can be\r\n illustrated using sound fx and link to sound effect for each word.\r\n Then, writes this dict to a json file.\r\n \"\"\"\r\n\r\n update = self.keywords_with_sounds.update\r\n\r\n f = file(transcription).read()\r\n f = f.translate(None, string.punctuation)\r\n\r\n # Searches and scrapes findsounds.com for sound fx\r\n for word in f.split():\r\n if word not in self.exclude and word not in self.keywords_with_sounds:\r\n word = word.lower()\r\n fx_url = self.base_url + word\r\n fx_request = urllib2.urlopen(fx_url)\r\n\r\n webpage = BeautifulSoup(fx_request, 'html.parser')\r\n form = webpage.findAll('form')[0]\r\n\r\n if len(form.contents) > 5:\r\n table = form.find('table')\r\n row = table.find('tr', valign=\"TOP\")\r\n table2 = row.find('table')\r\n link_loc = table2.contents[1]\r\n link = link_loc.contents\r\n ls = link[0].split()\r\n ls = str(ls[0])\r\n ls2 = ls.split(',')\r\n fx_link = ls2[4].strip('\\\"')\r\n\r\n update({word: fx_link})\r\n\r\n # Writes keywords_with_sounds to json file\r\n with open('keywords_with_fx.json', 'wb') as f:\r\n json.dump(self.keywords_with_sounds, codecs.getwriter('utf-8')(f),\r\n ensure_ascii=False, indent=4, sort_keys=True)\r\n\r\n return\r\n","sub_path":"find_sound_fx.py","file_name":"find_sound_fx.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"514740963","text":"\n\nfrom xai.brain.wordbase.verbs._undervalue import _UNDERVALUE\n\n#calss header\nclass _UNDERVALUING(_UNDERVALUE, ):\n\tdef __init__(self,): \n\t\t_UNDERVALUE.__init__(self)\n\t\tself.name = \"UNDERVALUING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"undervalue\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_undervaluing.py","file_name":"_undervaluing.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"508125292","text":"from PyQt5.QtCore import QThread\nfrom myLibrary import DriverChrome\nfrom myLibrary import MainWindow\nfrom datetime import datetime, timedelta\nfrom bs4 import BeautifulSoup\nfrom bs4.dammit import EncodingDetector\nimport requests\nimport locale\nimport re\nimport time\n\nlocale.setlocale(locale.LC_ALL, '')\n\n\nclass FindProxyThreading(QThread, DriverChrome.Execute):\n def __init__(self, mainWindow=None, *args, **kwargs):\n super(FindProxyThreading, self).__init__(mainWindow=mainWindow, *args, **kwargs)\n self.mainWindow = mainWindow\n m: MainWindow.MainWindow\n m = self.mainWindow\n self.url_proxy = kwargs.get('url')\n self.time_out_proxy = None\n self.working = False\n self.page = 1\n\n def run(self):\n m: MainWindow.MainWindow\n m = self.mainWindow\n\n self.working = True\n\n if m.inp_auto_get_proxy:\n self.auto_input_and_check_proxy()\n else:\n self.manual_input_and_check_proxy()\n\n self.stop_threading()\n\n self.working = False\n\n def stop_threading(self):\n\n try:\n if self.driver is not None:\n self.driver.quit()\n self.driver = None\n\n except Exception as error:\n print(\"ERROR stop_threading:\", error)\n\n def manual_input_and_check_proxy(self):\n m: MainWindow.MainWindow\n m = self.mainWindow\n\n try:\n if not m.parsing_avito:\n return\n\n m.uslugio_proxy_finded = open(m.inp_path_manual_proxy).read().split('\\n')\n\n for i in m.uslugio_proxy_finded:\n if not m.parsing_avito:\n return\n\n if self.proxy_check('https://www.avito.ru', i):\n if not i in m.verified_proxies and not i in m.uslugio_used_proxies:\n m.verified_proxies.append(i)\n # Посылаем сигнал на главное окно в прокси\n m.Commun.proxyUpdate.emit(m.verified_proxies)\n print(f\"Подходящий прокси сервер найден\")\n\n time.sleep(5)\n return self.manual_input_and_check_proxy()\n\n except Exception as error:\n print(f\"ERROR manual_input_and_check_proxy {error}\")\n time.sleep(5)\n\n return False\n\n def auto_input_and_check_proxy(self):\n m: MainWindow.MainWindow\n m = self.mainWindow\n\n try:\n if not m.parsing_avito:\n return\n\n # Запус WebDriverChrome\n if not self.star_driver(url=self.url_proxy, proxy=False):\n return\n time.sleep(10)\n\n # Устанавливаем на вебсайт скрипты\n if not self.set_library():\n return\n\n if re.search(r'advanced', self.url_proxy):\n # Прокси сервера\n m.uslugio_proxy_finded = self.execute_js(tr=2, sl=3, rt=True, t=2, data=f\"get_proxy_from_advanced_name()\")\n\n if type(m.uslugio_proxy_finded) == bool:\n self.page = 1\n self.url_proxy = f\"https://advanced.name/ru/freeproxy?type=https&page={self.page}\"\n return self.manual_input_and_check_proxy()\n\n for i in m.uslugio_proxy_finded:\n if not m.parsing_avito:\n return\n\n # if self.time_out_proxy is None or datetime.now() > self.time_out_proxy:\n # self.time_out_proxy = datetime.now() + timedelta(minutes=40)\n # m.verified_proxies, m.uslugio_used_proxies = [], []\n\n if self.proxy_check('https://uslugio.com/', i):\n if not i in m.verified_proxies and not i in m.uslugio_used_proxies:\n m.verified_proxies.append(i)\n # Посылаем сигнал на главное окно в прокси\n m.Commun.proxyUpdate.emit(m.verified_proxies)\n print(f\"Подходящий прокси сервер найден\")\n\n if m.uslugio_proxy_finded[-1] == i:\n self.page += 1\n self.url_proxy = f\"https://advanced.name/ru/freeproxy?type=https&page={self.page}\"\n # Запускаем поиск proxy занаво\n return self.manual_input_and_check_proxy()\n\n except Exception as detail:\n print(\"ERROR find_and_check_proxy:\", detail)\n if m.parsing_avito:\n return self.manual_input_and_check_proxy()\n else:\n return","sub_path":"myLibrary/UslugioLibrary/FindProxy.py","file_name":"FindProxy.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"382548486","text":"#!/usr/bin/python\n#coading:utf-8\n\n# https://blog.csdn.net/FloraCHY/article/details/80253846\n\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nfrom email.mime.multipart import MIMEMultipart\nimport time\nimport unittest\nfrom BSTestRunner import BSTestRunner\n\nclass Send_NewReport():\n # 存放测试报告文件夹\n report_dire =r'D:\\shuo-huahua\\Public_number_jieko_0919\\test_report\\fujian_reoprt'\n def Send_NewReport(report_dire):\n # os.listdir()方法用于返回指定文件包含文件或者文件夹的名字列表\n lists = os.listdir(report_dire)\n # 按照时间顺序对该目录文件夹下面的文件进行排序\n lists.sort(key=lambda fn: os.path.getatime(report_dire + '\\\\' + fn))\n # 输出最近的报告路径\n file = os.path.join(report_dire,lists[-1])\n print(file)\n # return file\n # 发送邮件\n # 发送邮件服务器 qq邮箱\n\n smtpserver = 'smtp.qq.com'\n # 发送邮箱用户名和密码\n sender = '1585620775@qq.com'\n passwd = 'zbhrftpklsirjafb'\n # 发送和接收邮件邮箱\n user = '1585620775@qq.com'\n receiver = ['1585620775@qq.com']\n # 发送邮件和内容\n dateT = time.strftime('%Y-%m-%d')\n subject = '人力情报.liate Test Report'+dateT\n content = '

人力情报 Test Report %s

' \\\n '

Please download the testreport,Thank you! 此报告建议下载后查看!谢谢!

'%dateT\n\n # 构造附件内容\n send_file = open(file,'rb').read()\n att = MIMEText(send_file,'base54','utf-8')\n att['Content-Type'] = 'application/octest-stream'\n att['Content-Disposition'] = 'attachment;filename =%s' % lists[-1]\n # 构建发送和接收消息\n msg = MIMEMultipart()\n msg.attach(MIMEText(content,'html','utf-8'))\n msg['Subject'] = Header(subject,'utf-8')\n msg['From'] = sender\n msg['To'] = ','.join(receiver)\n msg.attach(att)\n\n # SSL协议端口号使用\n smtp = smtplib.SMTP_SSL(smtpserver,465)\n # 向服务���表示用户身份\n smtp.helo(smtpserver)\n # 服务器返回结果确认\n smtp.ehlo(smtpserver)\n # 登录邮箱服务器用户和密码\n smtp.login(user,passwd)\n print(\"Start Send Email....\")\n smtp.sendmail(sender,receiver,msg.as_string())\n smtp.quit()\n print('Email Send Sucess!')\n\nif __name__ == '__main__':\n # 定位到当前目录\n test_dir = r'D:\\shuo-huahua\\Public_number_jieko_0919\\test_case'\n # 执行所有test开头方法\n discovery = unittest.defaultTestLoader.discover(test_dir,pattern = 'test*.py')\n #存放测试报告的文件夹\n report_dir = r'D:\\shuo-huahua\\Public_number_jieko_0919\\test_report\\fujian_reoprt'\n #报告命名格式\n now = time.strftime('%Y-%m-%d %H%M%S')\n #报告文件完整路径\n report_name = report_dir + '\\\\'+ now + ' result.html'\n #打开文件再报告文件写入测试结果\n with open(report_name,'wb') as f:\n runner = BSTestRunner(stream = f,title ='人力情报 Test Report',\n description = 'Test Case Result by Chy'\n )\n runner.run(discovery)\n # 通过邮件发送最新的报告\n Send_NewReport.Send_NewReport(report_dir)\n\n\n","sub_path":"test_report/test_fujian_email.py","file_name":"test_fujian_email.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"526226749","text":"from lxml import etree\nimport time\ntree = etree.parse(\"input.xml\")\n\nns = {'tei': 'http://www.tei-c.org/ns/1.0'}\n\nroot = tree.getroot()\n\nfrom rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef\nfrom rdflib.namespace import XSD, DCTERMS\n\nbase_uri = root.get('{http://www.w3.org/XML/1998/namespace}base')\ndocument_id = root.get('{http://www.w3.org/XML/1998/namespace}id')\n\ncurrent_date = Literal(time.strftime(\"%Y-%m-%d\"), datatype=XSD.date)\n\nex = Namespace(base_uri + '/')\ncao = Namespace(\"https://w3id.org/cao/\")\nlawd = Namespace(\"http://lawd.info/ontology/\")\nfrbroo = Namespace(\"http://iflastandards.info/ns/fr/frbr/frbroo/\")\ncrm = Namespace(\"http://www.cidoc-crm.org/cidoc-crm/\")\nprov = Namespace(\"http://www.w3.org/ns/prov#\")\noa = Namespace(\"http://www.w3.org/ns/oa#\")\n\n# empty dictionary for any prefix declared in TEI document within prefixDef\n\nprefix_dict = {}\n\nfor prefixDef in root.findall('.//tei:prefixDef', ns):\n\tprefix = prefixDef.get('ident')\n\tprefix_uri = prefixDef.get('replacementPattern')\n\tprefix_uri = prefix_uri.replace('$1', '')\n\t\n# update prefix dictionary\n\t\n\tprefix_dict[prefix] = prefix_uri\n\n\ng = Graph()\n\n# agent responsible for extracting the CAO graph from the TEI edition using this script\n\nextraction_resp = 'f-giov' # agent id\n\nextraction_resp_uri = URIRef(ex + 'agent/' + extraction_resp) #agent uri\n\n\n\n\n\n\n\n\n\n\n############################\n\n# extraction script begins\n\n############################\n\n\n# tei:app\n\nfor app in root.findall('.//tei:app', ns):\n\tapp_id = app.get('{http://www.w3.org/XML/1998/namespace}id')\n\tapp_uri = URIRef(ex + 'app/' + app_id)\n\tg.add( (app_uri, RDF.type, cao.VariationUnit))\n\n# new annotation\n\t\n\tannot_uri = URIRef(ex + 'annot/an-' + app_id)\n\tvarloc_uri = URIRef(ex + 'varloc/vl-' + app_id)\n\tg.add( (annot_uri, RDF.type, oa.Annotation))\n\tg.add( (annot_uri, oa.hasBody, app_uri))\n\tg.add( (annot_uri, oa.hasTarget, varloc_uri))\n\tg.add( (annot_uri, DCTERMS.created, current_date))\n\tg.add( (annot_uri, DCTERMS.creator, extraction_resp_uri))\n\n# empty list to store @varSeq\n\n\tvarlist = []\n\n# tei:rdg and tei:lem in tei:app\n\n\tfor rdg in app.xpath('./tei:rdg | ./tei:lem', namespaces=ns):\n\t\trdg_id = rdg.get('{http://www.w3.org/XML/1998/namespace}id') \n\t\trdg_uri = URIRef(ex + 'rdg/' + rdg_id)\n\t\texpr_frag_uri = URIRef(ex + 'rdg-fragment/' + rdg_id)\n\t\trdg_value = Literal(rdg.xpath('./text()', namespaces=ns), datatype=XSD.string)\n\t\tif rdg.tag == '{http://www.tei-c.org/ns/1.0}rdg':\n\t\t\tg.add( (app_uri, cao.hasReading, rdg_uri))\n\t\t\tg.add( (rdg_uri, RDF.type, cao.Reading))\n\t\tif rdg.tag == '{http://www.tei-c.org/ns/1.0}lem':\n\t\t\tg.add( (app_uri, cao.hasBaseReading, rdg_uri))\n\t\t\tg.add( (rdg_uri, RDF.type, cao.BaseReading))\n\t\tg.add( (rdg_uri, cao.isWitnessedBy, expr_frag_uri))\n\t\tg.add( (rdg_uri, RDF.value, rdg_value))\n\n# expression fragment bearing the reading\n\n\t\tg.add( (expr_frag_uri, RDF.type, frbroo.F23_Expression_Fragment))\n\t\t\n# @wit, @type, @cause, @hand, @resp, @source attributes on tei:rdg and tei:lem\n\n\t\tif rdg.get('wit') is not None:\n\t\t\twit_id = rdg.get('wit').split()\n\t\t\ti = 0\n\t\t\twhile i < len(wit_id):\n\t\t\t\twit_uri = URIRef(ex + 'wit/' + wit_id[i].replace('#', ''))\n\t\t\t\tg.add( (expr_frag_uri, frbroo.R4_carriers_provided_by, wit_uri))\n\t\t\t\ti += 1\n\n\t\tif rdg.get('type') is not None:\t\t\t\n\t\t\trdg_type = rdg.get('type').split(':')\n\t\t\trdg_type_prefix = rdg_type[0]\n\t\t\trdg_type_value = rdg_type[1]\n\t\t\tif prefix_dict.has_key(rdg_type_prefix):\n\t\t\t\trdg_type_uri = URIRef(prefix_dict[rdg_type_prefix] + rdg_type[1])\n\t\t\t\tg.add( (rdg_uri, cao.hasReadingType, rdg_type_uri))\n\n\t\t# omission\n\t\tif rdg.get('type') is None and rdg.find(\"./[Value='']\"):\n\t\t\tg.add( (rdg_uri, cao.hasReadingType, cao.omission))\n\n\n\t\tif rdg.get('cause') is not None:\t\t\t\n\t\t\trdg_cause = rdg.get('cause').split(':')\n\t\t\trdg_cause_prefix = rdg_cause[0]\n\t\t\trdg_cause_value = rdg_cause[1]\n\t\t\tif prefix_dict.has_key(rdg_cause_prefix):\n\t\t\t\trdg_cause_uri = URIRef(prefix_dict[rdg_cause_prefix] + rdg_cause[1])\n\t\t\t\tg.add( (rdg_uri, cao.hasReadingCause, rdg_cause_uri))\n\t\t\n\t\tif rdg.get('varSeq') is not None:\t\n\t\t\trdg_seq = rdg.get('varSeq')\n\t\t\tvarlist.insert(int(rdg_seq)-1, rdg_uri)\n\n\t\tif rdg.get('hand') is not None:\t\n\t\t\trdg_hand = rdg.get('hand')\n\t\t\trdg_hand_uri = URIRef(ex + 'hand/' + rdg_hand.replace('#', ''))\n\t\t\tg.add( (expr_frag_uri, cao.hasAttributedHand, rdg_hand_uri))\n\n\n\t\tif rdg.get('resp') is not None:\n\t\t\trdg_resp = rdg.get('resp')\n\t\t\trdg_resp_uri = URIRef(ex + 'agent/' + rdg_resp.replace('#', ''))\n\t\t\tg.add( (rdg_uri, prov.wasAttributedTo, rdg_resp_uri))\t\n\n\t\tif rdg.get('source') is not None:\n\t\t\tsource_id = rdg.get('source').replace('#', '').split()\n\t\t\ti = 0\n\t\t\twhile i < len(source_id):\n\t\t\t\tsource_bibl_path = './ancestor::tei:text/preceding-sibling::tei:teiHeader//tei:bibl[@xml:id=\"' + source_id[i] + '\"]'\n\t\t\t\tfor path in rdg.xpath(source_bibl_path, namespaces=ns):\n\t\t\t\t\tif path.get('sameAs') is not None:\n\t\t\t\t\t\tsource_uri = URIRef(path.get('sameAs'))\n\t\t\t\t\telse:\n\t\t\t\t\t\tsource_uri = URIRef(ex + 'source-edition/' + source_id[i])\n\t\t\t\t\tg.add( (rdg_uri, prov.hadPrimarySource, source_uri))\n\t\t\t\ti += 1\n\t\t\t\t\n# variants sequence for each tei:app\n\n\ti = len(varlist)-1\n\twhile i > 0: \n\t\tg.add( (varlist[i], cao.follows, varlist[i-1]))\n\t\ti = i-1\n\n# tei:note in tei:app\n\n\tfor note in app.xpath('./tei:note', namespaces=ns):\n\t\tnote_id = note.get('{http://www.w3.org/XML/1998/namespace}id')\n\t\tnote_uri = URIRef(ex + 'note/' + note_id)\n\t\tnote_value = Literal(note.xpath('./text()', namespaces=ns), datatype=XSD.string)\n\t\tif note.get('target') is not None:\n\t\t\ttarget_rdg = URIRef(ex + 'rdg/' + note.get('target').replace('#',''))\n\t\telse:\n\t\t\ttarget = note.xpath('./ancestor::app[1]')\n\t\t\ttarget_rdg = app_uri\n\t\tg.add( (note_uri, RDF.type, crm.E62_String))\n\t\tg.add( (note_uri, RDF.value, note_value))\n\n# @source on tei:note\n\t\t\n\t\tif note.get('source') is not None:\n\t\t\tsource_id = note.get('source').replace('#', '').split()\n\t\t\ti = 0\n\t\t\twhile i < len(source_id):\n\t\t\t\tsource_bibl_path = './ancestor::tei:text/preceding-sibling::tei:teiHeader//tei:bibl[@xml:id=\"' + source_id[i] + '\"]'\n\t\t\t\tfor path in note.xpath(source_bibl_path, namespaces=ns):\n\t\t\t\t\tif path.get('sameAs') is not None:\n\t\t\t\t\t\tsource_uri = URIRef(path.get('sameAs'))\n\t\t\t\t\telse:\n\t\t\t\t\t\tsource_uri = URIRef(ex + 'source-edition/' + source_id[i])\n\t\t\t\t\tg.add( (note_uri, prov.hadPrimarySource, source_uri)) \n\t\t\t\ti += 1\n\n\t\tif note.get('target') is not None:\n\t\t\ttarget_ref = note.get('target').replace('#', '')\n\t\t\tfor rdg in app.xpath('./tei:rdg | ./tei:lem', namespaces=ns):\n\t\t\t\trdg_id = rdg.get('{http://www.w3.org/XML/1998/namespace}id') \n\t\t\t\trdg_uri = URIRef(ex + 'rdg/' + rdg_id)\n\t\t\tif target_ref == rdg_id:\n\t\t\t\tg.add( (rdg_uri, crm.P3_has_note, note_uri))\n\t\t\telif target_ref == app_id:\n\t\t\t\tg.add( (app_uri, crm.P3_has_note, note_uri))\n\t\t\telse:\n\t\t\t\tg.add( (app_uri, crm.P3_has_note, note_uri)) \n\t\t\t\t\n\t\n\n# Bind prefix\n\ng.bind(\"prov\", prov)\ng.bind(\"frbroo\", frbroo)\ng.bind(\"crm\", crm)\ng.bind(\"cao\", cao)\ng.bind(\"\", ex)\ng.bind(\"oa\", oa)\ng.bind(\"dcterms\", DCTERMS)\n\ng.serialize(destination='output.nt', format='nt')\ng.serialize(destination='output.n3', format='n3')\ng.serialize(destination='output.rdf', format='xml')\ng.serialize(destination='output.jsonld', format='json-ld')","sub_path":"TEI2RDF_scripts/7-CritApp.py","file_name":"7-CritApp.py","file_ext":"py","file_size_in_byte":7152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"18083974","text":"# This file is part of the pyMor project (http://www.pymor.org).\n# Copyright Holders: Felix Albrecht, Rene Milk, Stephan Rave\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\nfrom __future__ import absolute_import, division, print_function\nimport time\nfrom datetime import datetime\n\nfrom pymor.core import cache\nfrom pymortests.base import TestBase, runmodule\n\nSLEEP_SECONDS = 0.2\n\n\nclass IamMemoryCached(cache.Cachable):\n\n @cache.cached\n def me_takey_long_time(self, arg):\n time.sleep(SLEEP_SECONDS)\n return arg\n\n\nclass IamDiskCached(cache.Cachable):\n\n def __init__(self, ):\n super(IamDiskCached, self).__init__(config=cache.DEFAULT_DISK_CONFIG)\n\n @cache.cached\n def me_takey_long_time(self, arg):\n time.sleep(SLEEP_SECONDS)\n return arg\n\n\nclass IamLimitedCached(cache.Cachable):\n\n def __init__(self, config=cache.DEFAULT_DISK_CONFIG):\n super(IamLimitedCached, self).__init__(config=config)\n\n @cache.cached\n def me_takey_no_time(self, arg):\n return int(arg)\n\n\nclass IWillBeCopied(cache.Cachable):\n\n def __init__(self):\n super(IWillBeCopied, self).__init__()\n\n @cache.cached\n def my_id(self, x):\n return id(self)\n\n\nclass CacheTest(TestBase):\n\n def test_runtime(self):\n for Class in [IamMemoryCached, IamDiskCached]:\n r = Class()\n for val in ['koko', 'koko', 'other']:\n int0 = datetime.now()\n r.me_takey_long_time(val)\n int1 = datetime.now()\n self.logger.info(int1 - int0)\n\n def test_limit(self):\n for c in [IamLimitedCached(cache.SMALL_MEMORY_CONFIG),\n IamLimitedCached(cache.SMALL_DISK_CONFIG)]:\n for i in range(25):\n c.cache_region.backend.print_limit()\n _ = c.me_takey_no_time(i)\n c.cache_region.backend.print_limit()\n\n def test_copy(self):\n from copy import copy\n x = IWillBeCopied()\n x_id = x.my_id(1)\n y = copy(x)\n y_id = y.my_id(1)\n self.assertNotEqual(x_id, y_id)\n\n def test_backend_api(self):\n for backend_cls in [cache.LimitedFileBackend, cache.LimitedMemoryBackend, cache.DummyBackend]:\n backend = backend_cls({})\n self.assertEqual(backend.get('mykey'), cache.NO_VALUE)\n backend.set('mykey', 1)\n self.assertEqual(backend.get('mykey'), 1 if backend_cls != cache.DummyBackend else cache.NO_VALUE)\n backend.delete('mykey')\n self.assertEqual(backend.get('mykey'), cache.NO_VALUE)\n\n\nif __name__ == \"__main__\":\n runmodule(name='pymortests.core.cache')\n","sub_path":"src/pymortests/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"270128137","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url\n\nfrom people import views\n\n\nurlpatterns = patterns(\n '',\n url(r'^all/$', views.get_peoples, name='people_get_peoples'),\n url(r'^(?P[0-9]+)/$', views.get_people, name='people_get_people'),\n # url(r'^analysis/kmeans/$', views.analysis_people_by_kmeans, name='people_analysis_kmeans')\n)\n\n","sub_path":"nobody/people/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"221599102","text":"# import numpy as np\nfrom . import adtributor\nfrom . import mctreesearch\nfrom . import pscore\nfrom . import util\nimport copy\n\n\ndef dict2output(root_cause):\n output = \"\"\n for item in root_cause:\n if len(output) != 0:\n output += \"&\"\n output += root_cause[item]\n return output\n\n\ndef output2list(output):\n columns = [\"i\", \"e\", \"c\", \"p\", \"l\"]\n out2list = [0] * len(columns)\n outstate = output.split('&')\n for dim in outstate:\n out2list[columns.index(dim[0])] = dim\n return out2list\n\n\ndef adtributor_hotspot_FullSearch(forecast, real, M, PT, T_EEP, T_EP, T_S0):\n columns = [\"i\", \"e\", \"c\", \"p\", \"l\"]\n\n result_list, ExpSet = adtributor.root_cause_adtributor(forecast, real, T_EEP, T_EP, T_S=T_S0)\n if len(ExpSet) == 1:\n root_cause = [util.d2l(temp) for temp in result_list]\n maxQ = pscore.potential_score(forecast, real, root_cause)\n state_output = [dict2output(temp) for temp in result_list]\n node_set = [(state_output, maxQ)]\n return root_cause, maxQ, node_set\n\n OptionalDict = {}\n for subset in ExpSet:\n # print(\"subset is {}\".format(subset))\n attr = subset[0][0][0]\n if attr not in columns:\n attr = subset[0][1][0]\n OptionalDict[attr] = subset[0]\n\n node_set = []\n best_set_all = []\n\n layerindex = [[0] * len(columns)]\n for i in range(len(ExpSet)):\n maxQ_layer = 0\n best_set_layer = []\n\n layer_pre = copy.deepcopy(layerindex)\n layerindex = []\n for index in layer_pre:\n for k in range(len(index)):\n if columns[k] in OptionalDict and index[k] == 0:\n item = copy.deepcopy(index)\n item[k] = 1\n if item not in layerindex:\n layerindex.append(item)\n # print(item)\n\n for index in layerindex:\n choice = []\n itemset = [0] * len(columns)\n choice.append(itemset)\n for k in range(len(index)):\n new_choice = []\n if index[k] == 1:\n for item in choice:\n for ops in OptionalDict[columns[k]]:\n itemtemp = copy.deepcopy(item)\n itemtemp[k] = ops\n new_choice.append(itemtemp)\n choice = new_choice\n # print(\"choice is: {}\".format(choice))\n best_node = mctreesearch.MCTreeSearch(forecast, real, choice, M, PT)\n\n if len(best_node.state) > 0:\n state_temp = [util.l2d(cause_list) for cause_list in best_node.state]\n state_output = [dict2output(cause_dict) for cause_dict in state_temp]\n node_set.append((state_output, best_node.Q))\n\n # is_subset = [False for item in best_node.state if item not in best_set]\n EP1 = util.get_EP(forecast, real, best_node.state)\n EP2 = util.get_EP(forecast, real, best_set_layer)\n is_average = best_node.Q*EP1/max(len(best_node.state), 1) > maxQ_layer*EP2/max(len(best_set_layer), 1)\n # count1 = max(util.get_count_cuboid(forecast, real, best_node.state), 1)\n # count2 = max(util.get_count_cuboid(forecast, real, best_set_layer), 1)\n # print(\"best node score is {}\".format(best_node.Q))\n # print(\"{} EP1 is {}; {} EP2 is {}\".format(best_node.state, EP1, best_set_layer, EP2))\n # print(\"count1 is {}; count2 is {}\".format(count1, count2))\n # if best_node.Q*EP1/count1 >= maxQ_layer*EP2/count2 and is_average:\n if best_node.Q >= maxQ_layer and is_average:\n maxQ_layer = best_node.Q\n best_set_layer = best_node.state\n best_set_all.append((best_set_layer, maxQ_layer))\n\n maxQ = 0\n best_set = []\n for k in range(len(best_set_all)):\n print(best_set_all[k])\n if is_descent(best_set, best_set_all[k][0]):\n is_average = best_set_all[k][1]/max(len(best_set_all[k][0]), 1) > maxQ/max(len(best_set), 1)\n if best_set_all[k][1] > maxQ and is_average:\n maxQ = best_set_all[k][1]\n best_set = best_set_all[k][0]\n else:\n is_average = best_set_all[k][1]/max(len(best_set_all[k][0]), 1) > maxQ/max(len(best_set), 1)\n if best_set_all[k][1] > maxQ and is_average:\n maxQ = best_set_all[k][1]\n best_set = best_set_all[k][0]\n\n node_set.sort(reverse=True, key=lambda cause: cause[1])\n if maxQ == node_set[0][1] == node_set[1][1]:\n is_same_dim = False\n for i in range(len(node_set)):\n node_state = [output2list(tempitem) for tempitem in node_set[i][0]]\n if node_set[i][1] != maxQ:\n if is_same_dim and is_descent(node_state, best_set) and node_set[i][1]/maxQ > 0.99:\n maxQ = node_set[i][1]\n best_set = node_state\n break\n if len(set(best_set[0]) - set([0])) == len(set(node_state[0]) - set([0])):\n is_same_dim = True\n\n root_cause = best_set\n if len(root_cause) == 0:\n root_cause = [util.d2l(temp) for temp in result_list]\n return root_cause, maxQ, node_set\n\n\ndef is_descent(upper_set, curr_set):\n if len(upper_set) == 0:\n return False\n isDescent = True\n for cause in curr_set:\n upstream = False\n for ups in upper_set:\n set_ups = set(ups) - set([0])\n if set_ups.issubset(set(cause)):\n upstream = True\n break\n if not upstream:\n isDescent = False\n break\n return isDescent\n","sub_path":"Code/AMCTS/AMCTSFullSearch/amcts.py","file_name":"amcts.py","file_ext":"py","file_size_in_byte":5720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"203112776","text":"# Copyright (c) 2015 Rackspace\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport datetime\nimport unittest2 as unittest\n\nimport mock\n\nfrom winchester import pipeline_handler\n\n\nclass TestException(Exception):\n pass\n\n\nclass TestAtomPubHandler(unittest.TestCase):\n\n def test_constructor_event_types(self):\n fakeurl = 'fake://'\n h = pipeline_handler.AtomPubHandler(fakeurl)\n self.assertEqual(h.included_types, ['*'])\n self.assertEqual(h.excluded_types, [])\n\n h = pipeline_handler.AtomPubHandler(fakeurl,\n event_types='test.thing')\n self.assertEqual(h.included_types, ['test.thing'])\n self.assertEqual(h.excluded_types, [])\n\n h = pipeline_handler.AtomPubHandler(fakeurl,\n event_types=['test.thing'])\n self.assertEqual(h.included_types, ['test.thing'])\n self.assertEqual(h.excluded_types, [])\n\n h = pipeline_handler.AtomPubHandler(fakeurl,\n event_types=['!test.thing'])\n self.assertEqual(h.included_types, ['*'])\n self.assertEqual(h.excluded_types, ['test.thing'])\n\n def test_match_type(self):\n event_types = [\"test.foo.bar\", \"!test.wakka.wakka\"]\n h = pipeline_handler.AtomPubHandler('fakeurl',\n event_types=event_types)\n self.assertTrue(h.match_type('test.foo.bar'))\n self.assertFalse(h.match_type('test.wakka.wakka'))\n self.assertFalse(h.match_type('test.foo.baz'))\n\n event_types = [\"test.foo.*\", \"!test.wakka.*\"]\n h = pipeline_handler.AtomPubHandler('fakeurl',\n event_types=event_types)\n self.assertTrue(h.match_type('test.foo.bar'))\n self.assertTrue(h.match_type('test.foo.baz'))\n self.assertFalse(h.match_type('test.wakka.wakka'))\n\n def test_handle_events(self):\n event_types = [\"test.foo.*\", \"!test.wakka.*\"]\n h = pipeline_handler.AtomPubHandler('fakeurl',\n event_types=event_types)\n event1 = dict(event_type=\"test.foo.zazz\")\n event2 = dict(event_type=\"test.wakka.zazz\")\n event3 = dict(event_type=\"test.boingy\")\n events = [event1, event2, event3]\n res = h.handle_events(events, dict())\n self.assertEqual(events, res)\n self.assertIn(event1, h.events)\n self.assertNotIn(event2, h.events)\n self.assertNotIn(event3, h.events)\n\n def test_format_cuf_xml(self):\n expected = (''\n '')\n d1 = datetime.datetime(2015, 8, 10, 0, 0, 0)\n d2 = datetime.datetime(2015, 8, 11, 0, 0, 0)\n d3 = datetime.datetime(2015, 8, 9, 15, 21, 0)\n event = dict(message_id='1234-56789',\n event_type='test.thing',\n audit_period_beginning=d1,\n audit_period_ending=d2,\n launched_at=d3,\n instance_id='98765-4321',\n state='active',\n state_description='',\n rax_options='4')\n extra = dict(data_center='TST1', region='TST')\n h = pipeline_handler.AtomPubHandler('fakeurl',\n extra_info=extra)\n res, content_type = h.format_cuf_xml(event)\n self.assertEqual(res, expected)\n self.assertEqual(content_type, 'application/xml')\n\n def test_generate_atom(self):\n expected = (\"\"\"\"\"\"\n \"\"\"urn:uuid:12-34\"\"\"\n \"\"\"\"\"\"\n \"\"\"\"\"\"\n \"\"\"Server\"\"\"\n \"\"\"TEST_CONTENT\"\"\"\n \"\"\"\"\"\")\n event = dict(message_id='12-34',\n original_message_id='56-78',\n event_type='test.thing')\n event_type = 'test.thing.bar'\n ctype = 'test/thing'\n content = 'TEST_CONTENT'\n h = pipeline_handler.AtomPubHandler('fakeurl')\n atom = h.generate_atom(event, event_type, content, ctype,\n title='Server')\n self.assertEqual(atom, expected)\n\n @mock.patch.object(pipeline_handler.requests, 'post')\n @mock.patch.object(pipeline_handler.AtomPubHandler, '_get_auth')\n def test_send_event(self, auth, rpost):\n test_headers = {'Content-Type': 'application/atom+xml',\n 'X-Auth-Token': 'testtoken'}\n auth.return_value = test_headers\n test_response = mock.MagicMock('http response')\n test_response.status_code = 200\n rpost.return_value = test_response\n h = pipeline_handler.AtomPubHandler('fakeurl', http_timeout=123,\n wait_interval=10, max_wait=100)\n test_atom = mock.MagicMock('atom content')\n\n status = h._send_event(test_atom)\n\n self.assertEqual(1, auth.call_count)\n self.assertEqual(1, rpost.call_count)\n rpost.assert_called_with('fakeurl',\n data=test_atom,\n headers=test_headers,\n timeout=123)\n self.assertEqual(status, 200)\n","sub_path":"tests/test_atompub.py","file_name":"test_atompub.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"286802297","text":"# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=jp\n# Parallel/Orthogonal : python3\n# 2018.12.15 yonezawa\n\n#from collections import deque\nimport sys\ninput = sys.stdin.readline\n#import cProfile\nfrom math import cos,sin,radians,sqrt\n\ndef main():\n\n for i in range(int(input())):\n (x1,y1,x2,y2,x3,y3,x4,y4) = map(int,input().split())\n\n inner = (x2-x1) * (x4-x3) + (y2-y1) * (y4-y3)\n cross = (x2-x1) * (y4-y3) - (x4-x3) * (y2-y1) \n if inner == 0:\n print(\"1\")\n elif cross == 0:\n print (\"2\")\n else:\n print(\"0\")\n\n \nif __name__ == '__main__':\n main()\n #pr = cProfile.Profile()\n #pr.runcall(main)\n #pr.print_stats()","sub_path":"CGL/CGL_2_A.py","file_name":"CGL_2_A.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"257551981","text":"import matplotlib.pyplot as plt\n\nmax_iter = 200\n\npis = []\n\npi_2 = 1\nnum = 2\nden = 1\nfor i in range(max_iter):\n pi_2 *= num / den\n pi = pi_2 * 2\n \n print(pi)\n pis.append(pi)\n\n if i % 2 == 0:\n den += 2\n else:\n num += 2\n\nplt.plot(pis)\nplt.show()\n","sub_path":"math/multiply_pi_approx.py","file_name":"multiply_pi_approx.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"531388455","text":"#!/usr/bin/python()\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport os\nfrom os import path\nimport sys\n\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) # Enable imports from project root directory\nfrom meta_definitions import DATA_DIR\n\nBASE_DIR = path.join(DATA_DIR, 'S3DIS')\n\nobject_dict = {\n 'clutter': 0,\n 'ceiling': 1,\n 'floor': 2,\n 'wall': 3,\n 'beam': 4,\n 'column': 5,\n 'door': 6,\n 'window': 7,\n 'table': 8,\n 'chair': 9,\n 'sofa': 10,\n 'bookcase': 11,\n 'board': 12}\n\npath_dir_areas = [entry for entry in os.listdir(BASE_DIR)\n if path.isdir(path.join(BASE_DIR, entry))]\n\nif \"prepare_label_rgb\" in path_dir_areas:\n path_dir_areas.remove(\"prepare_label_rgb\")\n\nfor area in path_dir_areas:\n print(\"Area:\", area)\n path_dir_rooms = os.listdir(path.join(BASE_DIR, area))\n for room in path_dir_rooms:\n print(\"Room:\", room)\n # make store directories\n path_prepare_label = path.join(DATA_DIR, \"S3DIS\", \"prepare_label_rgb\", area, room)\n if not os.path.exists(path_prepare_label):\n os.makedirs(path_prepare_label)\n elif len(os.listdir(path_prepare_label)) != 0:\n print(\"Room data already exists, skipping.\")\n continue\n #############################\n xyz_room_list = list()\n label_room_list = list()\n path_annotations = path.join(BASE_DIR, area, room, \"Annotations\")\n path_items = os.listdir(path_annotations)\n for item in path_items:\n label = item.split(\"_\", 1)[0]\n if label in object_dict:\n xyz_object = np.loadtxt(path.join(path_annotations, item)) # (N,6)\n label_object = np.full((xyz_object.shape[0], 1), object_dict[label]) # (N,1)\n else:\n continue\n\n xyz_room_list.append(xyz_object)\n label_room_list.append(label_object)\n\n xyz_room = np.vstack(xyz_room_list)\n label_room = np.vstack(label_room_list)\n\n np.save(path.join(path_prepare_label, \"xyzrgb.npy\"), xyz_room)\n np.save(path.join(path_prepare_label, \"label.npy\"), label_room)\n\n print(area, \"done.\\n\")","sub_path":"data_conversions/prepare_s3dis_label.py","file_name":"prepare_s3dis_label.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"640000656","text":"import librosa\nimport numpy as np\n#from test_timetable import start, end\nfrom timetable import start, end\n\nWORKING_DIR = '/home/stealthdrone/Desktop/data/'\nROW_AUDIO_PATH=WORKING_DIR + 'rawdata/'\nSR = 44100\nAUG=WORKING_DIR + 'augmentation/Drone_audio_'\nTARGET_PATH_LIST = ['','test/']\n\nidx_list = [1,2,3,4,5,6]\nk=1\n\n\ndef min2sec(time): # change minute to seconds\n minute = int(time.split(':')[0])\n second = int(time.split(':')[1])\n milisec = int(time.split(':')[2])\n\n return minute * 60 + second + milisec / 100\n\n\nfor j in idx_list :\n left_audio = librosa.core.load(ROW_AUDIO_PATH + str(j) + '-L.wav', sr = SR)[0]\n right_audio = librosa.core.load(ROW_AUDIO_PATH + str(j) + '-R.wav', sr = SR)[0]\n\n for i in range(1, len(start[j])):\n \n l_start = int(min2sec(start[j][i]) * SR)\n l_end= int(min2sec(end[j][i]) * SR)\n\n r_start = l_start\n r_end = l_end\n\n data1 = left_audio[l_start:l_end]\n data2 = right_audio[r_start:r_end]\n\n data3 = np.append(data1, data2)\n if i%4 == 0:\n librosa.output.write_wav(AUG + TARGET_PATH_LIST[1] + str(j) + '-' + str(k) + '-' + 'h' + \".wav\", data3, SR)\n k+=1\n if k==4:\n k=1\n else :\n librosa.output.write_wav(AUG + TARGET_PATH_LIST[1] + str(j) + '-' + str(k) + '-'+ str(i%4) + \".wav\", data3, SR)\n \n","sub_path":"drone_detector/data/code/val_extraction.py","file_name":"val_extraction.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"623438531","text":"\r\n\r\nfile_name = 'c:/Users/deore/OneDrive/Escritorio/Python/Calidad/test1.0.txt'\r\nfile = open(file_name, 'r')\r\ncontent = file.readline()\r\nsplt = content.split(',')\r\nfile.close()\r\nprint(splt)\r\n\r\ndef Promedio(list):\r\n #Calificaciones Alumno 1\r\n Stud1 = splt[0]\r\n splt1 = Stud1.split(\" \")\r\n Stud2 = splt[1]\r\n splt2 = Stud2.split(\" \") \r\n #Calificaciones Alumno 2\r\n Stud3 = splt[2]\r\n splt3 = Stud3.split(\" \")\r\n Stud4 = splt[3]\r\n splt4 = Stud4.split(\" \")\r\n\r\n JosePromedio = (float(splt1[2]) + float(splt2[2]))/2\r\n #print(JosePromedio)\r\n MariaPromedio = (float(splt3[2]) + float(splt4[2]))/ 2\r\n #print(MariaPromedio)\r\n return '{} - {}\\n{} - {}'.format(splt1[0], JosePromedio, splt3[0], MariaPromedio)\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Promedio(splt))","sub_path":"ene-jun-2020/DeorelaLara/SegundoParcial/promedio.py","file_name":"promedio.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"457042139","text":"from game_data import *\n\nclass player:\n def __init__(self):\n self.money = 0\n self.money_per_second = 0 # added to money every second\n self.clicking_power = 1 # 10% of money per second\n self.auto_clickers = 0\n self.mines = 0\n\n def update_money_per_second(self):\n self.money_per_second = 0\n self.money_per_second += (self.auto_clickers * returns['auto_clickers']\n + self.mines * returns['mines'])\n\n self.clicking_power = max(1, self.money_per_second / 10)\n \n def update_money(self):\n self.money += self.money_per_second\n\n def click(self):\n self.money += self.clicking_power\n\n def buy_business(self, business_name, quantity):\n if business_name not in prices:\n return\n \n if business_name == 'auto_clickers':\n for i in range(quantity):\n if self.money < prices[business_name]:\n return\n self.money -= prices[business_name]\n self.auto_clickers += 1\n prices[business_name] *= price_scale\n\n elif business_name == 'mines':\n for i in range(quantity):\n if self.money < prices[business_name]:\n return\n self.money -= prices[business_name]\n self.mines += 1\n prices[business_name] *= price_scale\n \n self.update_money_per_second()\n \n def upgrade_business(self, business_name):\n if business_name not in upgrade_prices:\n return\n \n if self.money < upgrade_prices[business_name]:\n return\n self.money -= upgrade_prices[business_name]\n returns[business_name] *= 2\n upgrade_prices[business_name] *= 100\n self.update_money_per_second()\n \n def gift_money(self, amount):\n self.money += amount\n","sub_path":"Unofficial Releases/Clicker_Pygame/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"208567223","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport wiringpi2\nimport sys\nimport argparse\na=24 # relay A \nb=25 # relay B\nwiringpi2.wiringPiSetupGpio()\nwiringpi2.pinMode(a, 1)\nwiringpi2.pinMode(b, 1)\ndef relay(position='not_defined', pin=a):\n if (position != 'not_defined'):\n if (position == True or position == 'closed' or int(position) == 1):\n wiringpi2.digitalWrite(pin, 1)\n elif(position == False or position == 'open' or int(position) == 0):\n wiringpi2.digitalWrite(pin, 0)\n else:\n print('unknown position {}'.format(position))\n return wiringpi2.digitalRead(pin)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('--relay', '-r', default='1', help='the relay number - 25=back hall, 24=main hall ')\n parser.add_argument('--position', '-p', default= 'not_defined', help='send interger 1 or \"close\" or boolean True to close the relay')\n\n flags=parser.parse_args(sys.argv[1:])\n print(relay(position=flags.position,pin=int(flags.relay)))\n# if len(sys.argv) == 2:\n# #print(sys.argv[1], type(sys.argv[1]))\n# print(relay(position=sys.argv[1]))\n# else:\n# print(relay())\n","sub_path":"slice_of_relay.py","file_name":"slice_of_relay.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"182471895","text":"\nimport tkinter as tk\nfrom tkinter import messagebox\nimport cv2\nimport os\nfrom PIL import Image\nimport numpy as np \nimport mysql.connector\n# import speech_recognition\nimport pyttsx3\n\n\nwindow = tk.Tk()\n# door_ear = speech_recognition.Recognizer()\n# door_mouth = pyttsx3.init()\n# passw_open = \"open\"\n# with speech_recognition.Microphone() as mic:\n# audio = door_ear.listen(mic)\n# try:\n# you = door_ear.recognize_google(audio)\n# except:\n# you = \" \"\n\nwindow.title(\"face recognition system\")\n\nL1 = tk.Label(window, text = \"Name\", font = (\"Arria\", 15))\nL1.grid(column = 0, row = 0)\nT1 = tk.Entry(window, width = 50, bd = 10)\nT1.grid(column = 1, row = 0)\n\n# L2 = tk.Label(window, text = \"Age\", font = (\"Arria\", 20))\n# L2.grid(column = 0, row = 1)\n# T2 = tk.Entry(window, width = 50, bd = 10)\n# T2.grid(column = 1, row = 1)\n\n# L3 = tk.Label(window, text = \"Address\", font = (\"Arria\", 20))\n# L3.grid(column = 0, row = 2)\n# T3 = tk.Entry(window, width = 50, bd = 10)\n# T3.grid(column = 1, row = 2)\n\ndef train_classifier():\n # tạo file data trước bên ngoài\n data_dir = \"F:/Program Files/VS code _ python/data\"\n path = [os.path.join(data_dir,m) for m in os.listdir(data_dir)]\n faces = []\n ids = []\n\n for image in path:\n img = Image.open(image).convert('L')\n imageNp = np.array(img, 'uint8')\n id = int(os.path.split(image)[1].split('.')[1])\n faces.append(imageNp)\n ids.append(id)\n ids = np.array(ids)\n\n clf = cv2.face.LBPHFaceRecognizer_create()\n clf.train(faces,ids)\n clf.write(\"classifier.xml\")\n messagebox.showinfo(\"result\", \" Trainning dataset completed\")\n\nB1 = tk.Button(window,text = \"Tranning\", font = (\"Arria\",15), bg = \"orange\", fg = 'red',command = train_classifier)\nB1.grid(column = 0, row = 2)\n\ndef detect_face():\n def draw_boundary(img, classifier, scaleFactor, minNeighbors, color, text, clf):\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n features = classifier.detectMultiScale(gray_img, scaleFactor, minNeighbors)\n\n coords = []\n\n for (x,y,w,h) in features:\n cv2.rectangle(img, (x,y), (x+w, y+h), color, 2)\n id, pred = clf.predict(gray_img[y:y+h,x:x+w])\n confidence = int(100*(1-pred/300))\n mydb = mysql.connector.connect(host = \"localhost\", user = \"root\", passwd = \"\", database = \"Authorized_user\" )\n mycursor = mydb.cursor()\n \n mycursor.execute(\"select name from faces_table where id = \" +str(id))\n name = mycursor.fetchone()\n name = ''+''.join(name)\n \n if confidence > 80:\n cv2.putText(img,name + \" \" + str(confidence), (x,y-5), cv2.FONT_HERSHEY_COMPLEX, 0.8, color, 1, cv2.LINE_AA)\n # if you == passw_open:\n # res = \"door was open\"\n # else:\n # res = \"try again\"\n # door_mouth.say(res)\n # door_mouth.runAndWait()\n else:\n cv2.putText(img, \"unknow\" + \" \" + str(confidence), (x,y-5), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0,0,255) , 1, cv2.LINE_AA)\n \n coords = [x,y,w,h]\n return coords\n def recognize(img, clf, faceCascade):\n coords = draw_boundary(img, faceCascade, 1.1, 10, (255, 255, 255), \"Face\", clf)\n return img\n # tạo file tên là DT, vào thư mục C:\\Users\\admim\\AppData\\Local\\Programs\\Python\\Python36\\Lib\\site-packages\\cv2\\data\n # copy mục haarcascade_frontalface_default.xml vào file DT\n faceCascade = cv2.CascadeClassifier(\"DT/haarcascade_frontalface_default.xml\")\n clf = cv2.face.LBPHFaceRecognizer_create()\n clf.read(\"classifier.xml\")\n\n video_capture = cv2.VideoCapture(0)\n\n while True:\n ret, img = video_capture.read()\n img = recognize(img,clf, faceCascade)\n cv2.imshow(\"face detection\", img)\n\n if cv2.waitKey(1) == ord(\"q\"):\n break\n video_capture.release()\n cv2.destroyAllWindows()\n \nB2 = tk.Button(window,text = \"Detect the face\", font = (\"Arria\",15), bg = \"green\", fg = 'white', command = detect_face)\nB2.grid(column = 1, row = 2)\n\n# cài xampp \ndef generate_dataset():\n if (T1.get() == \"\" ):\n messagebox.showinfo(\"result\", \"Please provide complete details of the user\")\n else:\n mydb = mysql.connector.connect(host = \"localhost\", user = \"root\", passwd = \"\", database = \"Authorized_user\" )\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT * from faces_table\")\n myresult = mycursor.fetchall()\n id = 1\n for x in myresult:\n id+=1\n sql = \"insert into faces_table(Id, Name) values (%s,%s)\"\n val = (id, T1.get())\n mycursor.execute(sql,val)\n mydb.commit()\n \n faces_classifier = cv2.CascadeClassifier(\"DT/haarcascade_frontalface_default.xml\")\n def face_cropped(img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = faces_classifier.detectMultiScale(gray,scaleFactor =1.3, minNeighbors = 5)\n if faces is():\n return None\n for (x,y,w,h) in faces:\n cropper_face = img[y:y+h, x:x+w]\n return cropper_face\n\n cap = cv2.VideoCapture(0)\n img_id = 0\n while True:\n ret, frame = cap.read()\n if face_cropped(frame) is not None:\n img_id += 1\n face = cv2.resize(face_cropped(frame), (200,200)) \n face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\n file_name_path = \"data/user.\" +str(id)+ '.' +str(img_id)+ \".jpg\"\n cv2.imwrite(file_name_path, face)\n cv2.putText(face, str(400 - img_id), (50,50), cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2 )\n\n cv2.imshow(\"Cropped face\", face)\n if cv2.waitKey(1) == 13 or int(img_id)==400:\n break\n cap.release()\n cv2.destroyAllWindows()\n messagebox.showinfo(\"result\", \" Generating dataset completed\")\n\nB3 = tk.Button(window,text = \"Generate dataset\", font = (\"Arria\",15), bg = \"pink\", fg = 'blue', command = generate_dataset)\nB3.grid(column = 2, row = 2)\n\nwindow.geometry(\"700x200\")\nwindow.mainloop()","sub_path":"face_recognition.py","file_name":"face_recognition.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"608192893","text":"import pygame\nimport os\nimport sys\nimport numpy as np\n\npygame.init()\n\n# base appearance settings:\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\n\n# base game settings:\nFPS = 60\nWIDTH, HEIGHT = 1280, 720\nWIN = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Walking man\") # app title\n\n# load images:\nPLAYER_RIGHT = pygame.image.load(os.path.join(\"Assets\", \"player_right.png\"))\nPLAYER_LEFT = pygame.image.load(os.path.join(\"Assets\", \"player_left.png\"))\nPLAYER_STAND = pygame.image.load(os.path.join(\"Assets\", \"player_stand.png\"))\n# PLAYER_STAND = pygame.image.load(os.path.join(\"Assets\", \"player_stand_ground.png\"))\nGUARD_RIGHT = pygame.image.load(os.path.join(\"Assets\", \"guard_right.png\"))\nGUARD_LEFT = pygame.image.load(os.path.join(\"Assets\", \"guard_left.png\"))\nGUARD_STAND = pygame.image.load(os.path.join(\"Assets\", \"guard_stand.png\"))\nGUARD_DEAD = pygame.image.load(os.path.join(\"Assets\", \"guard_dead.png\"))\nFIGHT_CLOUD = pygame.image.load(os.path.join(\"Assets\", \"fight_cloud.png\"))\nVIEW_RANGE = pygame.image.load(os.path.join(\"Assets\", \"view_range.png\"))\nBACKGROUND = pygame.image.load(os.path.join(\"Assets\", \"background.png\"))\nWALL_1 = pygame.image.load(os.path.join(\"Assets\", \"wall_left_bottom.png\"))\nWALL_2 = pygame.image.load(os.path.join(\"Assets\", \"wall_right_bottom.png\"))\nWALL_3 = pygame.image.load(os.path.join(\"Assets\", \"wall_left_top.png\"))\nWALL_4 = pygame.image.load(os.path.join(\"Assets\", \"wall_right_top.png\"))\nBRIDGE = pygame.image.load(os.path.join(\"Assets\", \"bridge.png\"))\nARROW = pygame.image.load(os.path.join(\"Assets\", \"arrow.png\"))\nBUSH = pygame.image.load(os.path.join(\"Assets\", \"bush.png\"))\nKING = pygame.image.load(os.path.join(\"Assets\", \"king.png\"))\n\nOBSTACLES = [\n # edges:\n pygame.Rect(0, 0, 10, HEIGHT),\n pygame.Rect(0, 0, WIDTH, 20),\n pygame.Rect(0, HEIGHT-20, WIDTH, 20),\n pygame.Rect(WIDTH-10, 1, 10, HEIGHT),\n # other objects:\n pygame.Rect(644, 32, 49, 323),\n pygame.Rect(644, 430, 49, 237),\n pygame.Rect(167, 31, 49, 228),\n pygame.Rect(167, 336, 49, 156),\n pygame.Rect(148, 446, 67, 46),\n pygame.Rect(438, 0, 118, 110),\n pygame.Rect(438, 163, 118, 380),\n pygame.Rect(438, 595, 118, 120),\n pygame.Rect(0, 0, 500, 50),\n pygame.Rect(0, 0, 150, 115),\n pygame.Rect(0, 115, 70, 30),\n pygame.Rect(0, 145, 40, 30),\n pygame.Rect(0, 420, 40, 30),\n pygame.Rect(0, 448, 142, 300),\n pygame.Rect(142, 640, 25, 100),\n pygame.Rect(275, 50, 55, 25),\n pygame.Rect(550, 675, 30, 30),\n pygame.Rect(915, 220, 55, 310),\n pygame.Rect(950, 480, 50, 180),\n pygame.Rect(915, 610, 55, 310),\n pygame.Rect(1145, 20, 150, 30),\n pygame.Rect(1210, 50, 150, 30),\n pygame.Rect(1230, 80, 150, 20),\n pygame.Rect(1250, 80, 150, 40),\n pygame.Rect(1250, 345, 150, 30),\n pygame.Rect(1225, 370, 150, 30),\n pygame.Rect(1195, 400, 150, 30),\n pygame.Rect(1165, 430, 150, 30),\n pygame.Rect(1142, 460, 150, 40),\n]\n\n# user generated events for guard alerts and for finding the king:\nGUARD_ALERT = pygame.USEREVENT + 1 # these numbers are just identifiers\nKING_FOUND = pygame.USEREVENT + 2\n\n\nclass Character:\n def __init__(self, pic, name=\"John Doe\", x=0, y=0, speed=2, rotation_speed=4, rotation=0, size=35):\n # self.__dict__.update(locals())\n self.pic, self.name, self.x, self.y, self.speed, self.rotation_speed, self.rotation, self.size = pic, name, x, \\\n y, speed, rotation_speed, rotation, size\n self.walk_last_time = 0\n self.walk_start_time = None\n self.rect = pygame.Rect(self.x, self.y, self.size, self.size)\n\n\nclass Player(Character):\n def __init__(self, pic, name, x, y, speed, rotation_speed, rotation, size):\n super().__init__(pic, name, x, y, speed, rotation_speed, rotation, size)\n self.hiding = False\n\n def move(self, keys_pressed):\n # rotation:\n if keys_pressed[pygame.K_a]:\n self.rotation += self.rotation_speed\n if keys_pressed[pygame.K_d]:\n self.rotation -= self.rotation_speed\n # movement with 'W':\n if keys_pressed[pygame.K_w]:\n # animation:\n time_now = pygame.time.get_ticks()\n # the updating time in the walking images is tied to the character's speed:\n time_diff = (time_now - self.walk_start_time) / (500 / self.speed)\n time_diff_mod = np.mod(int(time_diff), 4) # 3 possible states rotate in a 4 element cycle\n if time_diff_mod == 0:\n self.pic = PLAYER_RIGHT\n elif (time_diff_mod == 1) or (time_diff_mod == 3):\n self.pic = PLAYER_STAND\n else:\n self.pic = PLAYER_LEFT\n\n # it will eventually move if some time passed since the last update (making it less smooth intentionally):\n if (pygame.time.get_ticks() - self.walk_last_time > (FPS * 0.6)):\n x_delta = -np.sin(self.rotation * np.pi / 180) * self.speed\n y_delta = -np.cos(self.rotation * np.pi / 180) * self.speed\n\n # create a temporary rectangle with the new positions and check if the move is valid:\n temp_rect = pygame.Rect(self.rect.x+x_delta, self.rect.y+y_delta, self.size, self.size)\n num_collides = np.sum([temp_rect.colliderect(obstacle) for obstacle in OBSTACLES])\n # if valid then move, else just stand at that point:\n if num_collides == 0:\n self.rect.x += x_delta\n self.rect.y += y_delta\n self.x = self.rect.x\n self.y = self.rect.y\n self.walk_last_time = pygame.time.get_ticks()\n else:\n self.pic = PLAYER_STAND\n\n\nclass Guard(Character):\n \"\"\"Guard class\"\"\"\n\n def __init__(self, pic, name, x, y, rotation, size):\n super().__init__(pic, name, x, y, speed=0, rotation_speed=0, rotation=rotation, size=size)\n self.alive = True\n self.killed_at = None\n # view range scale and the (x, y) coordinates for the image positioning:\n self.view_range_scale = 8\n self.view_range_x = self.x + self.size / 2 - self.size * self.view_range_scale / 2\n self.view_range_y = self.y + self.size / 2 - self.size * self.view_range_scale / 2\n\n def move(self):\n pass\n\n\nclass GuardStanding(Guard):\n \"\"\"Standing guard class\"\"\"\n\n\nclass GuardWalking(Guard):\n \"\"\"Walking guard class\"\"\"\n\n def __init__(self, pic, name, x, y, rotation, size, speed, moving_direction, target):\n super().__init__(pic, name, x, y, rotation=rotation, size=size)\n # the walking guard will walk between (x1, y1) and (x2, y2) with some speed\n # the walking is implemented in a way that it can only move to horizontal or vertical direction\n if moving_direction == \"horizontal\":\n assert np.abs(target - x) > 100, \"The distance between the end points must be larger than 100\"\n self.x_1, self.y_1, self.x_2, self.y_2 = x, y, target, y\n self.target_rotation = 90 if self.x_1 > self.x_2 else 270\n elif moving_direction == \"vertical\":\n assert np.abs(target - y) > 100, \"The distance between the end points must be larger than 100\"\n self.x_1, self.y_1, self.x_2, self.y_2 = x, y, x, target\n self.target_rotation = 0 if self.y_1 > self.y_2 else 180\n else:\n print(\"Not a valid walking direction\")\n self.speed = speed\n\n # these are auxiliary variables for the guard movement:\n self.at_targets = True\n self.at_start = True # if we are just at the start we don't want the target_rotation switched\n\n def move(self):\n \"\"\"Movement of the walking guard\"\"\"\n if self.killed_at is None:\n # rotate the guard if it is not at the target_rotation:\n if np.mod(self.rotation, 360) != self.target_rotation:\n self.rotation += self.speed\n else:\n if self.walk_start_time is None:\n self.walk_start_time = pygame.time.get_ticks() # moving\n # animation:\n time_now = pygame.time.get_ticks()\n time_diff = (time_now - self.walk_start_time) / (500 / self.speed)\n time_diff_mod = np.mod(int(time_diff), 4) # 3 possible states rotate in a 4 element cycle\n if time_diff_mod == 0:\n self.pic = GUARD_RIGHT\n elif (time_diff_mod == 1) or (time_diff_mod == 3):\n self.pic = GUARD_STAND\n else:\n self.pic = GUARD_LEFT\n if (pygame.time.get_ticks() - self.walk_last_time > (FPS * 0.6)):\n # move if the guard is in the proper direction:\n if self.target_rotation == 270:\n self.x += self.speed\n elif self.target_rotation == 90:\n self.x -= self.speed\n elif self.target_rotation == 180:\n self.y += self.speed\n else:\n self.y -= self.speed\n self.rect.x = self.x\n self.rect.y = self.y\n # move the view range too:\n self.view_range_x = self.x + self.size / 2 - self.size * self.view_range_scale / 2\n self.view_range_y = self.y + self.size / 2 - self.size * self.view_range_scale / 2\n self.walk_last_time = pygame.time.get_ticks()\n\n # if we are not at the start and we have just collided with one of the end points now,\n # switch target rotation:\n if self.at_start == False and self.at_targets == False and \\\n (self.rect.collidepoint(self.x_1, self.y_1) or self.rect.collidepoint(self.x_2, self.y_2)):\n self.target_rotation = np.mod(self.target_rotation + 180, 360)\n self.at_targets = True\n self.walk_start_time = None\n self.pic = GUARD_STAND\n\n # set these variables to false if we are far from the end points:\n # this is probably not the nicest way to implement this\n # if the distance from any of the end points is larger than 50 we can say we have left these points\n # unfortunately this means that the end points must be at least 101 distance away from each other\n if (np.sqrt((self.x - self.x_1)**2 + (self.y - self.y_1)**2) > 50) and \\\n (np.sqrt((self.x - self.x_2)**2 + (self.y - self.y_2)**2) > 50):\n self.at_targets = False\n self.at_start = False\n\n\nclass Bush:\n \"\"\"Bush class\"\"\"\n\n def __init__(self, picture, x, y, size):\n self.picture, self.x, self.y, self.size = picture, x, y, size\n # the bush rectangle is a third of the bush size to make the hiding more realistic:\n self.rect = pygame.Rect(self.x+self.size/3, self.y+self.size/3, self.size/3, self.size/3)\n\n\ndef draw_window(player, guards, bushes):\n WIN.blit(BACKGROUND, (0, 0))\n WIN.blit(WALL_1, (149, 336))\n WIN.blit(WALL_2, (644, 430))\n WIN.blit(WALL_3, (167, 31))\n WIN.blit(WALL_4, (644, 32))\n WIN.blit(BRIDGE, (430, 100))\n WIN.blit(BRIDGE, (430, 530))\n\n for guard in guards:\n WIN.blit(reshape_and_rotate(guard.pic, guard.size, guard.rotation), (guard.x, guard.y))\n # if not killed or being killed, add the view range:\n if guard.killed_at is None:\n WIN.blit(reshape_and_rotate(VIEW_RANGE, guard.size * guard.view_range_scale, guard.rotation-180),\n (guard.view_range_x, guard.view_range_y))\n\n WIN.blit(reshape_and_rotate(player.pic, player.size, player.rotation), (player.x, player.y))\n\n for bush in bushes:\n WIN.blit(reshape_and_rotate(bush.picture, bush.size, 0), (bush.x, bush.y))\n\n if player.x == 1200 and player.y == 570:\n WIN.blit(reshape_and_rotate(ARROW, 100, 0), (1100, 535))\n\n if player.hiding:\n WIN.blit(reshape_and_rotate(ARROW, 35, player.rotation-90), (player.x, player.y))\n\n # interaction with guards:\n for guard in guards:\n # if the player meets with a living guard we create the fighting cloud and after a small time the guard is dead:\n if player.rect.collidepoint(guard.rect.center) > 0 and guard.alive:\n WIN.blit(reshape_and_rotate(FIGHT_CLOUD, 70, np.random.randint(180)),\n (guard.x-guard.size/2, guard.y-guard.size/2))\n now_time = pygame.time.get_ticks()\n if guard.killed_at is None:\n guard.killed_at = now_time\n elif now_time - guard.killed_at > 200:\n guard.alive = False\n guard.pic = GUARD_DEAD\n\n # draw the king:\n WIN.blit(reshape_and_rotate(KING, 40, 270), (50, 275))\n pygame.display.update()\n\n\ndef rotate_around_center(image, angle):\n \"\"\"rotate an image while keeping its center and size\"\"\"\n rotation_rect = image.get_rect().copy()\n rotation_image = pygame.transform.rotate(image, angle)\n rotation_rect.center = rotation_image.get_rect().center\n rotation_image = rotation_image.subsurface(rotation_rect).copy()\n return rotation_image\n\n\ndef reshape_and_rotate(img, size, rotation):\n return rotate_around_center(pygame.transform.scale(img, (size, size)), rotation)\n\n\ndef get_distance_and_angle(obj1, obj2):\n \"\"\"Get the distance and the angle between two objects with a rectangle in their attributes using cosine law\"\"\"\n # applying cosine law:\n a_x, a_y = obj1.rect.centerx, obj1.rect.centery # A: obj1 location\n c_x, c_y = obj2.rect.centerx, obj2.rect.centery # C: obj2 location\n distance_ac = np.sqrt((a_x - c_x)**2 + (a_y - c_y)**2) # distance between obj1 and obj2\n # generate an auxiliary point B at the direction of obj2 rotation with distance 100 from C:\n x_delta = -np.sin(obj2.rotation * np.pi / 180) * 100\n y_delta = -np.cos(obj2.rotation * np.pi / 180) * 100\n b_x, b_y = c_x + x_delta, c_y + y_delta # B\n distance_bc = 100\n distance_ab = np.sqrt((a_x - b_x)**2 + (a_y - b_y)**2)\n # cosine law:\n angle = np.arccos((distance_bc**2 + distance_ac**2 - distance_ab**2) /\n (2 * distance_bc * distance_ac)) * 180 / np.pi\n return distance_ac, angle\n\n\ndef guard_alerts(player, guards):\n \"\"\"Check if the guards see the player or any dead body. If so, raise an alert\"\"\"\n for guard in guards:\n distance, angle = get_distance_and_angle(player, guard)\n if guard.alive and guard.killed_at is None:\n # if the player is within view range (we cover a little bit less than the half circle, hence the 80 degrees)\n if not player.hiding and distance < 140 and angle < 80:\n pygame.event.post(pygame.event.Event(GUARD_ALERT))\n # this is really not an optimal or scalable solution to check all other guards for all guards but with just\n # a few of them it is ok for now\n for other_guard in guards:\n if other_guard != guard:\n distance, angle = get_distance_and_angle(other_guard, guard)\n # if the other guard is dead and within view range:\n if other_guard.killed_at is not None and distance < 140 and angle < 80:\n pygame.event.post(pygame.event.Event(GUARD_ALERT))\n\n\ndef king_found(player):\n \"\"\"King is found event\"\"\"\n if player.rect.colliderect(pygame.Rect(40, 270, 60, 40)):\n pygame.event.post(pygame.event.Event(KING_FOUND))\n\n\ndef main():\n player = Player(PLAYER_STAND, name=\"John\", x=1200, y=570, speed=3, rotation_speed=4, rotation=90, size=35)\n bushes = [Bush(BUSH, np.random.randint(1075, 1200), np.random.randint(100, 300), 50) for i in range(25)] + \\\n [Bush(BUSH, np.random.randint(1075, 1150), np.random.randint(300, 350), 50) for i in range(5)] + \\\n [Bush(BUSH, np.random.randint(700, 900), np.random.randint(25, 75), 50) for i in range(10)] + \\\n [Bush(BUSH, np.random.randint(800, 850), np.random.randint(200, 350), 50) for i in range(15)] + \\\n [Bush(BUSH, np.random.randint(700, 850), np.random.randint(575, 625), 50) for i in range(7)] + \\\n [Bush(BUSH, np.random.randint(200, 230), np.random.randint(450, 650), 50) for i in range(12)] + \\\n [Bush(BUSH, np.random.randint(225, 240), np.random.randint(100, 200), 50) for i in range(7)] + \\\n [Bush(BUSH, np.random.randint(375, 400), np.random.randint(200, 450), 50) for i in range(10)]\n guards = [\n GuardStanding(GUARD_STAND, name=\"Guard_1\", x=1075, y=570, rotation=90, size=35),\n GuardStanding(GUARD_STAND, name=\"Guard_2\", x=1040, y=200, rotation=180, size=35),\n GuardWalking(GUARD_STAND, name=\"Guard_3\", x=1040, y=250, rotation=0,\n size=35, speed=3, moving_direction=\"vertical\", target=400),\n ]\n\n clock = pygame.time.Clock()\n run = True\n while run:\n # controlling FPS:\n clock.tick(FPS)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit() # quit game\n sys.exit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n player.walk_start_time = pygame.time.get_ticks() # moving\n if event.key == pygame.K_LSHIFT:\n player.speed *= 2 # running\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_w:\n player.pic = PLAYER_STAND # stop moving\n if event.key == pygame.K_LSHIFT:\n player.speed /= 2 # stop running\n\n # break the game if the player or a dead body was been detected:\n if event.type == GUARD_ALERT:\n pygame.time.delay(3000) # wait 3 sec\n run = False\n\n # break the game (winning!) if the king has been found:\n if event.type == KING_FOUND:\n pygame.time.delay(6000) # wait 3 sec\n run = False\n # move player:\n player.move(pygame.key.get_pressed())\n\n # move guards:\n for guard in guards:\n guard.move()\n\n # is the player hiding:\n player.hiding = True if np.sum([player.rect.colliderect(bush.rect) for bush in bushes]) > 0 else False\n\n # guard alerts:\n guard_alerts(player, guards)\n\n # is the king found:\n king_found(player)\n\n # draw window:\n draw_window(player, guards, bushes)\n\n # draw obstacles:\n # for obstacle in OBSTACLES:\n # pygame.draw.rect(WIN, RED, obstacle)\n # pygame.display.update()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"to_blog/main_part_vi.py","file_name":"main_part_vi.py","file_ext":"py","file_size_in_byte":18752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"38854014","text":"firstSundays = 0\n\ntotalDays = 1\nmonth = 1\nyear = 1900\n\nwhile year <= 2000:\n\tif totalDays % 7 == 0 and year >= 1901:\n\t\tfirstSundays += 1\n\n\tif month in [1, 3, 5, 7, 8, 10, 12]:\n\t\ttotalDays += 31\n\telif month in [4, 6, 9, 11]:\n\t\ttotalDays += 30\n\telif year % 4 == 0:\n\t\ttotalDays += 29\n\telse:\n\t\ttotalDays += 28\n\n\tif month == 12:\n\t\tyear += 1\n\t\tmonth = 1\n\telse:\n\t\tmonth += 1\n\nprint(firstSundays)","sub_path":"p019/p019.py","file_name":"p019.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"342171066","text":"#----------------------------------------------------------------------------#\n# Imports\n#----------------------------------------------------------------------------#\n\nfrom flask import render_template, request, Response, flash, redirect, url_for\nfrom flask_wtf import Form\nfrom forms import *\nfrom db_data_models import *\n\n#----------------------------------------------------------------------------#\n# Venues\n# ----------------------------------------------------------------\n\n\n@app.route('/venues')\ndef venues():\n data = []\n venues = Venue.query.all()\n\n for venue in venues:\n data.append({\n \"city\": venue.city,\n \"state\": venue.state,\n \"venues\": [{\n \"id\": venue.id,\n \"name\": venue.name\n }]\n })\n return render_template('pages/venues.html', areas=data)\n\n\n@app.route('/venues/search', methods=['POST'])\ndef search_venues():\n search_term = request.form.get('search_term', '')\n data = Venue.query.filter(Venue.name.ilike(f'%{search_term}%')).all()\n\n result = []\n for venue in data:\n result.append({\n \"id\": venue.id,\n \"name\": venue.name,\n \"num_upcoming_shows\": len(Show.query.filter(Show.venue_id == venue.id).filter(Show.start_time > datetime.now()).all())\n })\n response = {\n \"count\": len(data),\n \"data\": result\n }\n return render_template('pages/search_venues.html', results=response, search_term=search_term)\n\n\n# Venue Details\n# ----------------------------------------------------------------\n\n@ app.route('/venues/')\ndef show_venue(venue_id):\n selected_venue = Venue.query.get(venue_id)\n upcoming_shows = selected_venue.venues_show.filter(\n Show.start_time >= datetime.now()).all()\n\n past_shows = selected_venue.venues_show.filter(\n Show.start_time < datetime.now()).all()\n\n data = selected_venue.map_venue_to_dict()\n\n data[\"upcoming_shows\"] = upcoming_shows\n data[\"upcoming_shows_count\"] = len(upcoming_shows)\n data[\"past_shows\"] = past_shows\n data[\"past_shows_count\"] = len(past_shows)\n\n return render_template('pages/show_venue.html', venue=data)\n\n# Create Venue\n# ----------------------------------------------------------------\n\n\n@ app.route('/venues/create', methods=['GET'])\ndef create_venue_form():\n form = VenueForm()\n return render_template('forms/new_venue.html', form=form)\n\n\n@ app.route('/venues/create', methods=['POST'])\ndef create_venue_submission():\n form = VenueForm(request.form)\n try:\n seeking_talent = False\n seeking_description = ''\n if 'seeking_talent' in form:\n seeking_talent = form.seeking_talent.data\n if 'seeking_description' in form:\n seeking_description = form.seeking_description.data\n\n venue = Venue(\n name=form.name.data,\n genres=form.genres.data,\n city=form.city.data,\n state=form.state.data,\n phone=form.phone.data,\n address=form.address.data,\n facebook_link=form.facebook_link.data,\n image_link=form.image_link.data,\n website=form.website.data,\n seeking_talent=seeking_talent,\n seeking_description=seeking_description\n )\n db.session.add(venue)\n db.session.commit()\n flash('Venue ' + venue.name + ' was successfully listed!')\n except:\n db.session.rollback()\n flash('An error occurred. Venue ' +\n request.form['name'] + ' could not be listed.')\n finally:\n db.session.close()\n\n return render_template('pages/home.html')\n\n\n@app.route('/venues//edit', methods=['GET'])\ndef edit_venue(venue_id):\n form = VenueForm()\n selected_venue = Venue.query.get(venue_id)\n form.name.data = selected_venue.name\n form.address.data = selected_venue.address\n form.genres.data = selected_venue.genres\n form.city.data = selected_venue.city\n form.state.data = selected_venue.state\n form.phone.data = selected_venue.phone\n form.facebook_link.data = selected_venue.facebook_link\n form.image_link.data = selected_venue.image_link\n form.website.data = selected_venue.website\n form.seeking_talent.data = selected_venue.seeking_talent\n form.seeking_description.data = selected_venue.seeking_description\n\n venue = selected_venue.map_venue_to_dict()\n return render_template('forms/edit_venue.html', form=form, venue=venue)\n\n\n@app.route('/venues//edit', methods=['POST'])\ndef edit_venue_submission(venue_id):\n venue = Venue.query.get(venue_id)\n\n try:\n form = VenueForm(request.form)\n\n seeking_talent = False\n seeking_description = ''\n if 'seeking_talent' in request.form:\n seeking_talent = form.seeking_talent.data\n if 'seeking_description' in request.form:\n seeking_description = form.seeking_description.data\n\n venue.name = form.name.data\n venue.address = form.address.data\n venue.genres = form.genres.data\n venue.city = form.city.data\n venue.state = form.state.data\n venue.phone = form.phone.data\n venue.facebook_link = form.facebook_link.data\n venue.image_link = form.image_link.data\n venue.website = form.website.data\n venue.seeking_talent = seeking_talent\n venue.seeking_description = seeking_description\n\n db.session.commit()\n flash('Venue ' + venue.name + ' was successfully edited!')\n\n except:\n db.session.rollback()\n flash('An error occurred. Venue ' +\n venue.name + ' could not be edited.')\n finally:\n db.session.close()\n return redirect(url_for('show_venue', venue_id=venue_id))\n","sub_path":"projects/01_fyyur/starter_code/controllers/venue_controller.py","file_name":"venue_controller.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"384967334","text":"'''\nself : 代表类的实例对象,在类里面用self表示\n哪个对象调用方法,那么该方法中的self就代表哪个对象\n\n__class__ : 代表类名\n'''\n# Meakelra\n\nclass Person():\n def __init__(self,name):\n self.name = name\n # 可以在当前类里面调用及使用属性, 需要写self.属性\n def eat(self):\n print(self.name +' eat')\n print(self.__class__)\n\n # self不是关键字,换成其他的也可以,但是帅/漂亮的人都用self\n # def run(abc):\n # print(abc.name)\n\nper1 = Person(name='Tom')\nper1.eat()\n# per1.run()\nprint(per1.__class__)\n\nper2 = Person(name='PYC')\nper2.eat()\n# per2.run()\n\nper3 = Person(name='Lily')\n\n\n","sub_path":"python/12.6-self.py","file_name":"12.6-self.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"246811359","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/py3plex/core/supporting.py\n# Compiled at: 2019-02-24 13:10:35\n# Size of source mod 2**32: 2330 bytes\nfrom collections import defaultdict\nimport networkx as nx, itertools, multiprocessing as mp\n\ndef split_to_layers(input_network):\n layer_info = defaultdict(list)\n subgraph_dictionary = {}\n for node in input_network.nodes(data=True):\n try:\n layer_info[node[0][1]].append(node[0])\n except Exception as err:\n try:\n layer_info[node[1]['type']].append(node[0])\n finally:\n err = None\n del err\n\n for layer, nodes in layer_info.items():\n subnetwork = input_network.subgraph(nodes)\n subgraph_dictionary[layer] = subnetwork\n\n del layer_info\n return subgraph_dictionary\n\n\ndef add_mpx_edges(input_network):\n _layerwise_nodes = split_to_layers(input_network)\n min_node_layer = {}\n for layer, network in _layerwise_nodes.items():\n min_node_layer[layer] = set([n[0][0] for n in network.nodes(data=True)])\n\n for pair in itertools.combinations(list(min_node_layer.keys()), 2):\n layer_first = pair[0]\n layer_second = pair[1]\n pair_intersection = set.intersection(min_node_layer[layer_first], min_node_layer[layer_second])\n for node in pair_intersection:\n n1 = (node, layer_first)\n n2 = (node, layer_second)\n input_network.add_edge(n1, n2, key='mpx', type='mpx')\n\n return input_network\n\n\ndef parse_gaf_to_uniprot_GO(gaf_mappings, filter_terms=None):\n uniGO = defaultdict(list)\n with open(gaf_mappings) as (im):\n for line in im:\n parts = line.split('\\t')\n try:\n if 'GO:' in parts[4]:\n uniGO[parts[1]].append(parts[4])\n if 'GO:' in parts[3]:\n uniGO[parts[1]].append(parts[3])\n except:\n pass\n\n all_terms = list((itertools.chain)(*uniGO.values()))\n if filter_terms is not None:\n sorted_d = sorted((Counter(all_terms).items()), key=(operator.itemgetter(1)), reverse=True)\n top_100 = [x[0] for x in sorted_d[0:filter_terms]]\n new_map = defaultdict(list)\n for k, v in uniGO.items():\n v = [x for x in v if x in top_100]\n new_map[k] = v\n\n return new_map\n return uniGO","sub_path":"pycfiles/py3quizlet2-0.1.tar/supporting.cpython-37.py","file_name":"supporting.cpython-37.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"170304699","text":"import json\nimport logging\n\nfrom skippy.data.decorator import consume, produce\nfrom skippy.data.minio import download_files, upload_file\n\n\n@consume()\n@produce()\ndef handle(req, data=None):\n print(\"handle.(\", data, \")\")\n data = req + json.dumps(data)\n print(\"handle.(\", data, \")\")\n return data\n\ndef main():\n handle('bbbbbbbbbb')\n #files = download_files(urns=None)\n #upload_file(json.dumps(files),urn=None)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"skippy/tests/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"481015362","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\nclass RCNN_Classifer(nn.Module):\n def __init__(self, word_num, input_dim, core_lens, output_channel, output_dim):\n super(RCNN_Classifer, self).__init__()\n self.word_num = word_num\n self.conv_list = nn.ModuleList()\n self.core_lens = core_lens\n assert input_dim % 2 == 0\n self.input_dim = input_dim\n self.hidden_dim = input_dim//2\n self.output_channel = output_channel\n self.output_dim = output_dim\n self.embedding = nn.Embedding(self.word_num, self.input_dim, padding_idx=0)\n self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, batch_first=True, dropout=0.2, num_layers=2, bidirectional=True)\n for conv_len in self.core_lens:\n self.conv_list.append(nn.Conv1d(self.input_dim, self.output_channel, conv_len))\n self.output = nn.Linear(self.output_channel*len(self.core_lens), self.output_dim)\n\n def forward(self, x, T=1):\n results = []\n x = self.embedding(x)\n batch_size = x.size()[0]\n h0 = torch.zeros(2*self.lstm.num_layers, batch_size, self.hidden_dim).to(x.device)\n c0 = torch.zeros(2*self.lstm.num_layers, batch_size, self.hidden_dim).to(x.device)\n x_, (_, _) = self.lstm(x, (h0, c0))\n x = x+x_\n x = x.permute(0, 2, 1)\n for corv in self.conv_list:\n results.append(torch.max(F.relu(corv(x)), dim=-1)[0])\n results = torch.cat(tuple(results), dim=-1)\n results = self.output(results)/T\n output = F.softmax(results, dim=-1)\n return output\n\n","sub_path":"LanguageFluency/Distillation_RCNN/rcnn_model.py","file_name":"rcnn_model.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"445687054","text":"from io import BytesIO\nfrom urllib.parse import urlparse\nfrom typing import List, cast\n\nfrom requests.sessions import session\n\nfrom errors import LoginRequired\nfrom utils import Downloader, Soup, Session, clean_title\n\nfrom bs4.element import Tag\nimport requests\n\n\n@Downloader.register\nclass Downloader_novelpia(Downloader):\n type = \"novelpia\"\n URLS = [\"novelpia.com\"]\n\n def __get_number(self, url: str) -> str:\n return url.replace(\"/viewer/\", \"\")\n\n def __get_cookie(self) -> Session:\n session = requests.Session()\n user_key = Session().cookies.get(\"USERKEY\", domain=\".novelpia.com\")\n login_key = Session().cookies.get(\"LOGINKEY\", domain=\".novelpia.com\")\n\n if user_key and login_key:\n session.cookies.set(\"USERKEY\", user_key, domain=\".novelpia.com\")\n session.cookies.set(\"LOGINKEY\", login_key, domain=\".novelpia.com\")\n return session\n\n def init(self) -> None:\n self.parsed_url = urlparse(self.url) # url 나눔\n self.soup = Soup(requests.get(self.url).text)\n\n def read(self):\n session = self.__get_cookie()\n f = BytesIO()\n\n title_element = self.soup.find(\"b\", {\"class\": \"cut_line_one\"})\n\n if not title_element:\n raise LoginRequired\n\n # Maybe NavigableString?\n assert isinstance(title_element, Tag)\n self.title = title_element.text\n\n # css selecter is not working :(\n ep_num = self.soup.find(\n \"span\",\n {\n \"style\": \"background-color:rgba(155,155,155,0.5);padding: 1px 6px;border-radius: 3px;font-size: 11px; margin-right: 3px;\"\n },\n )\n assert isinstance(ep_num, Tag)\n\n ep_name = self.soup.find(\"span\", {\"class\": \"cut_line_one\"})\n assert isinstance(ep_name, Tag)\n\n # Dirty but for clean filename\n self.print_(ep_name.text)\n ep_name.text.replace(ep_num.text, \"\")\n self.print_(ep_name.text)\n self.print_(ep_num.text)\n\n self.filenames[f] = clean_title(f\"{ep_num.text}: {ep_name.text}.txt\", \"safe\")\n\n # https://novelpia.com/viewer/:number:\n numbers: List[str] = []\n numbers.append(self.__get_number(self.parsed_url[2]))\n\n # Get real contents\n # https://novelpia.com/proc/viewer_data/:number:\n # {\"s\": [{\"text\": \"\"}]}\n viewer_datas = map(\n lambda number: f\"https://novelpia.com/proc/viewer_data/{number}\", numbers\n )\n for viewer_data in viewer_datas:\n response = session.get(viewer_data)\n if response.text:\n response = response.json()\n for text_dict in response[\"s\"]:\n text = text_dict[\"text\"]\n if \"img\" in text:\n soup = Soup(text)\n img = soup.find(\"img\")\n # Maybe NavigableString here too?\n assert isinstance(img, Tag)\n src = img.attrs[\"src\"]\n filename = img.attrs[\"data-filename\"]\n f.write(f\"[{filename}]\".encode(\"UTF-8\"))\n self.urls.append(f\"https:{src}\")\n else:\n f.write(text_dict[\"text\"].encode(\"UTF-8\"))\n f.seek(0)\n self.urls.append(f)\n else:\n raise LoginRequired\n","sub_path":"src/extractor/novelpia_downloader.py","file_name":"novelpia_downloader.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"567800616","text":"import os \r\nimport numpy as np \r\nimport re, json\r\nimport pickle\r\nfrom support import get_langauges_short\r\nfrom wordfreq import get_frequency_dict\r\n\r\nwords_directory = 'C:/Users/Samuel/Desktop/my_version/dictionaries/'\r\nlang = get_langauges_short()\r\n\r\ndef create_dictionary(path, lang):\r\n\t\tf = {}\r\n\t\tf[''] = 0\r\n\t\tf[''] = 1\r\n\t\tf[''] = 2\r\n\t\tf[''] = 3\r\n\t\tcount = 4\r\n\t\tfor entry in d:\r\n\t\t\tf[entry] = count\r\n\t\t\tcount+=1\r\n\t\t\tif count>10000:\r\n\t\t\t\tbreak\r\n\r\njson.dump(f, open(words_directory+str(lang)+'_dic.json','w'))\r\n\r\nfor x in lang:\r\n\tcreate_dictionary(words_directory,x)\r\n\r\n# d = json.load(open(words_directory+str(lang[0])+'_dic.json'))\r\n# print(d['terrifying'])\r\n# print(len(d))\r\n\r\n\r\n# loaded_words = np.load(r'C:/Users/Samuel/Desktop/my_version/words_list/vocab_'+str(lang[0])+'.npy')\r\n\r\n# The length of dictionaries with samples\r\n\r\n# ['english', 'french', 'italian', 'spanish', 'dutch']\r\n# 10001\r\n# ['the', 'of', 'and', 'to', 'a', 'in', 'for', 'is', 'on', 'that']\r\n# 10010\r\n# ['de', 'la', 'le', 'et', 'les', 'des', 'en', 'un', 'du', 'une']\r\n# 10001\r\n# ['e', 'non', 'che', 'di', 'la', 'il', 'un', 'a', 'per', 'è']\r\n# 10001\r\n# ['que', 'de', 'no', 'a', 'la', 'el', 'es', 'y', 'en', 'lo']\r\n# 10001\r\n# ['ik', 'je', 'het', 'de', 'dat', 'is', 'een', 'niet', 'en', 'van']\r\n","sub_path":"my_version/create_vocab.py","file_name":"create_vocab.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"366234061","text":"# -*- coding: utf-8 -*-\nimport bluetooth\nimport time\n\n\nclass BtClient:\n \"\"\" Responsible for Connecting and reconnecting explore devices via bluetooth\"\"\"\n\n def __init__(self):\n self.is_connected = False\n self.lastUsedAddress = None\n self.socket = None\n self.host = None\n self.port = None\n self.name = None\n\n def init_bt(self, device_name=None, device_addr=None):\n \"\"\"\n Initialize Bluetooth connection\n\n Args:\n device_name(str): Name of the device (either device_name or device address should be given)\n device_addr(str): Devices MAC address\n \"\"\"\n assert (device_addr is not None) or (device_name is not None), \"Missing name or address\"\n\n if device_name is not None:\n nearby_devices = bluetooth.discover_devices(lookup_names=True)\n for address, name in nearby_devices:\n if name == device_name:\n self.lastUsedAddress = address\n break\n else:\n # No need to scan if we have the address\n self.lastUsedAddress = device_addr\n\n uuid = \"1101\" # Serial Port Profile (SPP) service\n service_matches = bluetooth.find_service(uuid=uuid, address=self.lastUsedAddress)\n assert len(service_matches) > 0, \"Couldn't find the Device! Restart your device and run the \" \\\n \"code again and check if MAC address/name is entered correctly.\"\n\n first_match = service_matches[0]\n self.port = first_match[\"port\"]\n self.name = first_match[\"name\"]\n self.host = first_match[\"host\"]\n\n print(\"Connecting to serial port on %s\" % self.host)\n\n def bt_connect(self):\n \"\"\"Creates the socket\n \"\"\"\n while True:\n try:\n socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n socket.connect((self.host, self.port))\n break\n except bluetooth.BluetoothError as error:\n self.socket.close()\n print(\"Could not connect: \", error, \"; Retrying in 2s...\")\n time.sleep(2)\n return socket\n\n def reconnect(self):\n \"\"\"\n tries to open the last bt socket, uses the last port and host. if after 1 minute the connection doesnt succeed,\n program will end\n \"\"\"\n\n timeout = 1\n while timeout < 5:\n try:\n socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n socket.connect((self.host, self.port))\n break\n except bluetooth.BluetoothError as error:\n print(\"Bluetooth Error: Probably timeout, attempting reconnect. Error: \", error)\n time.sleep(5)\n\n timeout += 1\n\n if timeout == 5:\n print(\"Device not found, exiting the program!\")\n self.socket.close()\n return False\n","sub_path":"src/explorepy/bt_client.py","file_name":"bt_client.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"454840730","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/ocfl/object_utils.py\n# Compiled at: 2020-03-27 17:33:06\n# Size of source mod 2**32: 3291 bytes\n\"\"\"Utility functions to support the OCFL Object library.\"\"\"\nimport copy, hashlib, os, os.path, re, logging, sys\ntry:\n from urllib.parse import quote as urlquote\nexcept ImportError:\n from urllib import quote as urlquote\n\nNORMALIZATIONS = [\n 'uri', 'md5']\n\ndef add_object_args(parser):\n \"\"\"Add Object settings to argparse or argument group instance parser.\"\"\"\n parser.add_argument('--skip', action='append', default=['README.md', '.DS_Store'], help='directories and files to ignore')\n parser.add_argument('--normalization', '--norm', default=None, help=('filepath normalization strategy (None, %s)' % ', '.join(NORMALIZATIONS)))\n parser.add_argument('--no-forward-delta', action='store_true', help='do not use forward deltas')\n parser.add_argument('--no-dedupe', '--no-dedup', action='store_true', help='do not use deduplicate files within a version')\n parser.add_argument('--lax-digests', action='store_true', help='allow use of any known digest')\n parser.add_argument('--objdir', '--obj', help='read from or write to OCFL object directory objdir')\n parser.add_argument('--ocfl-version', default='draft', help='OCFL specification version')\n\n\ndef next_version(version):\n \"\"\"Next version identifier following existing pattern.\n\n Must deal with both zero-prefixed and non-zero prefixed versions.\n \"\"\"\n m = re.match('v((\\\\d)\\\\d*)$', version)\n if not m:\n raise ObjectException(\"Bad version '%s'\" % version)\n next = int(m.group(1)) + 1\n if m.group(2) == '0':\n next_version = ('v0%0' + str(len(version) - 2) + 'd') % next\n if len(next_version) != len(version):\n raise ObjectException('Version number overflow for zero-padded version %d to %d' % (version, next_version))\n return next_version\n else:\n return 'v' + str(next)\n\n\ndef remove_first_directory(path):\n \"\"\"Remove first directory from input path.\n\n The return value will not have a trailing parh separator, even if\n the input path does. Will return an empty string if the input path\n has just one path segment.\n \"\"\"\n rpath = ''\n while True:\n head, tail = os.path.split(path)\n if head == path or tail == path:\n break\n else:\n path = head\n rpath = tail if rpath == '' else os.path.join(tail, rpath)\n\n return rpath\n\n\ndef make_unused_filepath(filepath, used, separator='__'):\n \"\"\"Find filepath with string appended that makes it disjoint from those in used.\"\"\"\n n = 1\n while 1:\n n += 1\n f = filepath + separator + str(n)\n if f not in used:\n return f","sub_path":"pycfiles/ocfl_py-0.0.3-py3.6/object_utils.cpython-36.py","file_name":"object_utils.cpython-36.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"14324108","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.views.generic import View\nfrom django.contrib.auth.models import User\n\nfrom .models import *\nfrom .forms import *\n\n\nclass PostsList(View):\n def get(self, request, username='', subscribe=''):\n if username and subscribe:\n user = User.objects.get(username=username)\n subscribe_blogs = Subscribe.objects.filter(user=user)\n blog = Blog.objects.get(author=user)\n posts = blog.post_set.all()\n elif username:\n user = User.objects.get(username=username)\n blog = Blog.objects.get(author=user)\n posts = blog.post_set.all()\n else:\n posts = Post.objects.all()\n return render(request, 'blogs/post_list_user.html', context={'posts': posts})\n\nclass SubscribePostsList(View):\n def get(self, request, username):\n\n return render(request, 'blogs/post_list_user.html', context={'posts': posts})\n\n\nclass NewPost(View):\n def get(self, request):\n form = PostForm()\n return render(request, 'blogs/new_post.html', context={'form': form})\n\n def post(self, request):\n bound_form = PostForm(request.POST)\n blog = Blog.objects.get(author=request.user)\n if bound_form.is_valid():\n cleaned_data = bound_form.cleaned_data\n cleaned_data['blog'] = blog\n new_post = Post.objects.create(**cleaned_data)\n new_post.save()\n return redirect(new_post)\n return render(request, 'blogs/new_post.html', context={'form': bound_form})","sub_path":"blogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"4933512","text":"import tensorflow as tf\n\n# # gradient descent :\n# 개 요 : 머신러닝에서 알고리즘의 Bias-variance Trade-off 를 최적점에 맞추기 위한\n# 모델 최적화의 단계\n\nx_train = [1, 2, 3]\ny_train = [1, 2, 3]\n\n# standard deviation = 1, mean = 0, 표준 정규분포\nW = tf.Variable(tf.random_normal([1]), name='weight')\nb = tf.Variable(tf.random_normal([1]), name='bias')\n\n# 실제 모델의 트레이닝 데이터가 정규분포의 확률을 따르고 이에 대한 bias 도 표준정규분포의 확률을 따른다고 가정\nhypothesis = x_train * W + b\n\n# Our hypothesis XW+b\ncost = tf.reduce_mean(tf.square(hypothesis - y_train))\n\n# 위의 데이터는 선형회귀 모델을 따르므로....(1변량 모델)\n# y = ax + b 라는 함수로 모델링 할 수 있고, 그 a와 b를 가우시안 분포를 따르는 변수들과 대입하여 보면서\n# 최적의 모델을 찾을 수 있다.\n\n# 다변량 모델에서는 cost = SSE (각각의 편차의 합 / 변량의 갯수) 로 정의 될 수 있고, 이를 최소화 하는\n# 모델을 찾기 위해 아래의 두 줄의 코드를 사용할 수 있다.\n\n# Minimize\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\ntrain = optimizer.minimize(cost)\n\n# Launch the graph in a session\nsess = tf.Session()\n\n# Initializes gglobal variables in the graph.\nsess.run(tf.global_variables_initializer())\n\n# Fit the line\n\nfor step in range(2001):\n sess.run(train)\n if step % 20 == 0:\n print(step, sess.run(cost), sess.run(W), sess.run(b))\n\n\n# # ex.2 #################################################################################################################\n#\n# import tensorflow as tf\n#\n# # gradient decision :\n# # 개 요 : 머신러닝에서 알고리즘의 Bias-variance Trade-off 를 최적점에 맞추기 위한\n# # 모델 최적화의 단계\n#\n# X = tf.placeholder(tf.float32)\n# Y = tf.placeholder(tf.float32)\n#\n# # standard deviation = 1, mean = 0, 표준 정규분포\n# W = tf.Variable(tf.random_normal([1]), name='weight')\n# b = tf.Variable(tf.random_normal([1]), name='bias')\n#\n# hypothesis = X * W + b\n#\n# cost = tf.reduce_mean(tf.square(hypothesis - Y))\n#\n# # Minimize\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\n# train = optimizer.minimize(cost)\n#\n# # Launch the graph in a session\n# sess = tf.Session()\n#\n# # Initializes gglobal variables in the graph.\n# sess.run(tf.global_variables_initializer())\n#\n# for step in range(2001):\n# cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X:[1,2,3,4,5], Y:[2.1, 3.1, 4.1, 5.1, 6.1]})\n# if step % 20 == 0:\n# print(step, cost_val, W_val, b_val)","sub_path":"basic_tensorflow/gradient descent_1.py","file_name":"gradient descent_1.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"634895234","text":"import csv #This Python module helps read and write csv files\r\nfrom urllib import request #for accessing files on the internet\r\nimport json #allow simplified use of json data\r\nimport csv #allow\r\n\r\nURL_Apple = 'https://www.quandl.com/api/v3/datasets/EOD/AAPL.json?api_key=zwzJQCDVUU-CXGCxSiY_&start_date=2014-01-01&end_date=2015-01-01'\r\nURL_Boeing = 'https://www.quandl.com/api/v3/datasets/EOD/BA.json?api_key=zwzJQCDVUU-CXGCxSiY_&start_date=2014-01-01&end_date=2015-01-01'\r\nURL_Chevron = 'https://www.quandl.com/api/v3/datasets/EOD/CVX.json?api_key=zwzJQCDVUU-CXGCxSiY_&start_date=2014-01-01&end_date=2015-01-01'\r\nURL_Cisco = 'https://www.quandl.com/api/v3/datasets/EOD/CSCO.json?api_key=zwzJQCDVUU-CXGCxSiY_&start_date=2014-01-01&end_date=2015-01-01'\r\nURL_AmericanExpress = 'https://www.quandl.com/api/v3/datasets/EOD/AXP.json?api_key=zwzJQCDVUU-CXGCxSiY_&start_date=2014-01-01&end_date=2015-01-01'\r\nWriteCount = 0\r\n\r\nclass URL:\r\n\tdef URLInput(self, URLInputJSON):\r\n\t\tglobal WriteCount #counter for keeping the heading proper\r\n\t\t#Global variables are generally bad mkay, but due to the simplicity of this program, I'll allow it\r\n\t\tresponse = request.urlopen(URLInputJSON)\r\n\t\tstring = response.read().decode('utf-8') #This grabs all the data at once\r\n\t\tjson_obj = json.loads(string) #This parses the json data\r\n\t\tJSONData = json_obj['dataset']\r\n\r\n\t\tcsvwriter = csv.writer(fil) # create the csv writer object\r\n\r\n\t\t#Our data set has two important items in the json hierarchy: column_names and data\r\n\t\tDatasetCode = JSONData['dataset_code'] #store the dataset code for further use\r\n\t\tcolumnNames = JSONData['column_names'] #store the column_names element for further use\r\n\t\tdata = JSONData['data'] #store the data element for further use\r\n\t\t \r\n\t\t\r\n\r\n\t\t#Put the Headings into the csv file\r\n\t\theadings = [] #make a list to store the values\r\n\t\tfor Heading in columnNames: #Find each heading in the list\r\n\t\t\theadings.append(Heading) #add each heading to the list\r\n\t\theadings.append('Stock Code') #manually inserts 'Stock Code' because it's not included in the column_names JSON\r\n\t\tif WriteCount == 0: #I don't want to have it spit out a heading each time, and rather than reformat the code, I just created a counter that if not true, then doesn't write a heading\r\n\t\t\tcsvwriter.writerow(headings) #Now that you have them all, write them in the file\r\n\r\n\t\t#Write the the data into the file, the data element has a list of lists\r\n\t\t# the csvwriter can be given a list or items which it sepearates by commas\r\n\t\tfor Row in data:\r\n\t\t\tRow.append(DatasetCode) #adds the dataset code to each row of information\r\n\t\t\tcsvwriter.writerow(Row) #each input row has multiple items\r\n\r\n\t\t#Demonstrate how to process each value: show the metadata\r\n\t\tfor item in JSONData:\r\n\t\t\tif item != 'data' and item != 'columnNames':\r\n\t\t\t\titemKey = item\r\n\t\t\t\tvalue = str(JSONData[itemKey])\r\n\t\t\t\tprint(itemKey + ' : ' + value)\r\n\t\tWriteCount += 1 #adds to writecount to keep value above 1 so as to not add headings each time running through\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\r\nfil = open('StockPrices.csv', 'w', newline='')\t#Use Python's CSV object to write data\r\n\t\t# w opens an output file, newline='' protects against multiple newlines in windows\r\n\t\t # open a file for writing\r\n\t\t \t\t \r\n\t \t\t\t\r\nURL = URL()\r\nURL.URLInput(URL_Apple)\r\nURL.URLInput(URL_Boeing)\r\nURL.URLInput(URL_Chevron)\r\nURL.URLInput(URL_Cisco)\r\nURL.URLInput(URL_AmericanExpress)\r\n\r\n\r\nfil.close()\t#Close files after you are done to ensure all the data is written","sub_path":"StockPrices.py","file_name":"StockPrices.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"492727630","text":"from random import randint\nimport time\nnumero = input(\"Digite um numero entre 0 e 5: \")\nn = randint(0, 5)\nprint('processando...')\ntime.sleep(2)\nif numero == n:\n print('Acertou!')\nelse:\n print('Tente novamente, eu escolhi {}'.format(n))\n\n","sub_path":"CursoEmVideo/pythonTestes/Exercício 028.py","file_name":"Exercício 028.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"310446909","text":"from __main__ import vtk, ctk, qt, slicer\nimport datetime, time\n\nimport os\nimport sys\nimport shutil\nimport csv\nimport urllib2\n\nfrom XNATUtils import *\n\n#===============================================================================\n# XNATAddProjEditor is used for creating new projects/folders within a given\n# XNAT host. It manages talking to a given XNATCommunicator and its associated\n# string inputs. \n#===============================================================================\n\nclass XNATAddProjEditor(object):\n def __init__(self, viewer = None, browser = None, XNATCommunicator = None):\n self.browser = browser\n self.viewer = viewer\n self.XNATCommunicator = XNATCommunicator\n self.projLabel = qt.QLabel(\"Project\")\n self.projDD = qt.QComboBox()\n self.projDD.addItems(self.XNATCommunicator.getFolderContents('/projects'))\n self.projDD.connect(\"currentIndexChanged(const QString&)\", self.populateSubjectDD)\n self.projLE = qt.QLineEdit()\n self.projLE.connect(\"textEdited(const QString&)\", self.projLineEdited)\n self.projError = qt.QLabel()\n self.projError.setTextFormat(1)\n self.subjLabel = qt.QLabel(\"Subject\")\n self.subjDD = qt.QComboBox()\n self.subjLE = qt.QLineEdit()\n self.subjLE.connect(\"textEdited(const QString&)\", self.subjLineEdited)\n self.subjError = qt.QLabel()\n self.subjError.setTextFormat(1)\n self.exptLabel = qt.QLabel(\"Experiment\")\n self.exptLE = qt.QLineEdit()\n self.exptError = qt.QLabel()\n self.exptError.setTextFormat(1)\n p = None\n s = None\n proj = \"\"\n if (self.viewer.viewWidget.currentItem() != None):\n p = self.viewer.getParentItemByCategory(self.viewer.viewWidget.currentItem(), \"projects\")\n s = self.viewer.getParentItemByCategory(self.viewer.viewWidget.currentItem(), \"subjects\")\n proj = p.text(self.viewer.column_name)\n self.projDD.setCurrentIndex(self.projDD.findText(proj))\n else:\n proj = self.projDD.currentText \n self.populateSubjectDD(proj) \n if s:\n self.subjDD.setCurrentIndex(self.subjDD.findText(s.text(self.viewer.column_name)))\n\n def populateSubjectDD(self, proj):\n subjs_raw = self.XNATCommunicator.getFolderContents('/projects/' + proj + '/subjects')\n subjs_name = []\n for r in subjs_raw:\n subjs_name.append(self.XNATCommunicator.getItemValue('/projects/' + proj + '/subjects/' + str(urllib2.quote(r)), 'label'))\n self.subjDD.clear()\n self.subjDD.addItems(subjs_name)\n \n def show(self):\n l = qt.QGridLayout()\n self.addProjWindow = qt.QWidget()\n self.addProjWindow.setFixedWidth(700)\n mainWindow = slicer.util.mainWindow()\n screenMainPos = mainWindow.pos\n x = screenMainPos.x() + mainWindow.width/2 - self.addProjWindow.width/2\n y = screenMainPos.y() + mainWindow.height/2 - self.addProjWindow.height/2\n existingCol = qt.QLabel(\"Existing\")\n newCol = qt.QLabel(\"New\")\n l.addWidget(existingCol, 0, 1)\n l.addWidget(newCol, 0, 2)\n l.addWidget(self.projLabel, 1, 0)\n l.addWidget(self.projDD, 1, 1)\n l.addWidget(self.projLE, 1, 2)\n l.addWidget(self.projError, 2, 2)\n l.addWidget(self.subjLabel, 3, 0)\n l.addWidget(self.subjDD, 3, 1)\n l.addWidget(self.subjLE, 3, 2)\n l.addWidget(self.subjError, 4, 2)\n l.addWidget(self.exptLabel, 5, 0)\n l.addWidget(self.exptLE, 5, 2)\n l.addWidget(self.exptError, 6, 2)\n #=======================================================================\n # BUTTONS\n #=======================================================================\n createButton = qt.QPushButton()\n createButton.setText(\"Create\")\n cancelButton = qt.QPushButton()\n cancelButton.setText(\"Cancel\")\n buttonRow = qt.QDialogButtonBox()\n buttonRow.addButton(createButton, 0)\n buttonRow.addButton(cancelButton, 2)\n buttonRow.connect('clicked(QAbstractButton*)', self.createButtonClicked)\n l.addWidget(buttonRow, 7, 2)\n self.addProjWindow.setLayout(l)\n self.addProjWindow.move(qt.QPoint(x,y))\n self.addProjWindow.setWindowTitle(\"Add Folder to XNAT\")\n self.addProjWindow.show()\n \n def createButtonClicked(self,button):\n #=======================================================================\n # If OK button clicked..,.\n #=======================================================================\n if 'create' in button.text.lower():\n self.exptError.setText(\"\")\n self.subjError.setText(\"\")\n self.projError.setText(\"\")\n pathStr = \"/projects/\"\n #===================================================================\n # STEP 1: Sum up the xnat text boxes according to XNAT file organizational rules\n #===================================================================\n if len(self.projLE.text)>0:\n pathStr += self.projLE.text\n if len(self.subjLE.text)>0:\n pathStr += \"/subjects/\" + self.subjLE.text\n if len(self.exptLE.text)>0:\n pathStr += \"/experiments/\" + self.exptLE.text\n else:\n pathStr += self.projDD.currentText\n if len(self.subjLE.text)>0:\n pathStr += \"/subjects/\" + self.subjLE.text\n if len(self.exptLE.text)>0:\n pathStr += \"/experiments/\" + self.exptLE.text\n else:\n pathStr += \"/subjects/\" + self.subjDD.currentText\n if len(self.exptLE.text)>0:\n pathStr += \"/experiments/\" + self.exptLE.text\n #===================================================================\n # STEP 2: After summing up the text to XNAT folders, see if they exist already\n #===================================================================\n if (self.XNATCommunicator.fileExists(pathStr)):\n print (\"%s ALREADY EXISTS!\"%(pathStr))\n projStr = pathStr.split(\"/subjects\")[0]\n subjStr = None\n exptStr = None\n if \"/subjects\" in pathStr:\n subjStr = pathStr.split(\"/experiments\")[0]\n if \"/experiments\" in pathStr:\n exptStr = pathStr\n if (exptStr and self.XNATCommunicator.fileExists(exptStr)):\n self.exptError.setText(\"*Experiment already exists.\")\n elif (subjStr and self.XNATCommunicator.fileExists(subjStr)):\n self.subjError.setText(\"*Subject already exists.\")\n elif (projStr and self.XNATCommunicator.fileExists(projStr)):\n self.projError.setText(\"*Project already exists.\")\n #===================================================================\n # STEP 3: Doesn't exist? Then make the folders.\n #===================================================================\n else:\n self.XNATCommunicator.makeDir(pathStr)\n slicer.app.processEvents()\n self.viewer.selectItem_byPath(pathStr)\n print (\"CREATING %s \"%(pathStr))\n self.addProjWindow.close()\n elif 'cancel' in button.text.lower():\n self.addProjWindow.close()\n \n def projLineEdited(self, str):\n if (len(str.strip(\" \")) > 0):\n self.projDD.setEnabled(False)\n self.subjDD.setEnabled(False)\n else:\n self.projDD.setEnabled(True)\n \n def subjLineEdited(self, str):\n if (len(str.strip(\" \")) > 0):\n self.subjDD.setEnabled(False)\n else:\n self.subjDD.setEnabled(True)","sub_path":"XNATSlicerLib/XNATAddProjEditor.py","file_name":"XNATAddProjEditor.py","file_ext":"py","file_size_in_byte":8091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"348947249","text":"class Solution:\n\n def isPrime(self, N):\n if N < 2:\n return False\n for i in range(2, int(N ** (1.0 / 2.0)) + 1):\n if (N / i).is_integer():\n return False\n return True\n\n def isPalindrome(self, N):\n st = str(N)\n\n for i in range(0, int(len(st) / 2)):\n if st[i] != st[len(st) - i - 1]:\n return False\n return True\n\n def get_left_right(self, st):\n right = int(len(st) / 2)\n if right == len(st) / 2:\n left = right - 1\n else:\n left = right\n return left, right\n\n def increase_middle(self, st):\n mid_left, mid_right = self.get_left_right(st)\n\n self.propagate_increase(st, mid_left, mid_right)\n\n return st\n\n def propagate_increase(self, st, left, right):\n\n new_num = int(st[left]) + 1\n if new_num<10:\n st[left] = str(new_num)\n st[right] = str(new_num)\n else:\n st[left] = '0'\n st[right] = '0'\n return self.propagate_increase(st, left-1, right+1)\n\n def next_palindrome(self, N):\n\n st = list(str(N))\n if not self.isPalindrome(N):\n left, right = self.get_left_right(st)\n\n while left >= 0:\n if st[left] != st[right]:\n if int(st[left]) < int(st[right]):\n st = self.increase_middle(st)\n st[right] = st[left]\n left -= 1\n right += 1\n\n return int(''.join(st))\n else:\n return N\n\n def increase_palindrome(self, st, left, right):\n if left < 0:\n return '1' + st[0:-1] + '1'\n num = int(st[left])\n if num < 9:\n if left == right:\n return st[:left] + str(num+1) + st[right + 1:]\n else:\n return st[:left] + str(num+1) + st[left+1:right] + str(num+1) + st[right + 1:]\n else:\n if left == right:\n st = st[:left] + \"0\" + st[right + 1:]\n else:\n st = st[:left] + \"0\" + st[left+1:right] + \"0\" + st[right + 1:]\n return self.increase_palindrome(st, left - 1, right + 1)\n\n def primePalindrome(self, N: int) -> int:\n N = self.next_palindrome(N)\n\n while True:\n if self.isPrime(N):\n return N\n\n st = str(N)\n left = int(len(st) / 2) - 1\n if (len(st) / 2).is_integer():\n right = left + 1\n else:\n left = left + 1\n right = left\n N = int(self.increase_palindrome(st, left, right))\n\n\nif __name__ == '__main__':\n s = Solution()\n\n n = 13\n\n # n = 1\n #\n # n = 9989900\n # n = 9999999\n # n = 10000001\n # print(s.next_palindrome(n))\n n = 102\n # n = 13\n print(s.primePalindrome(n))\n","sub_path":"p866.py","file_name":"p866.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"374414623","text":"\nfrom sanic import Sanic, response\nfrom redis import Redis\n\napp = Sanic(__name__)\n\nredis = Redis(host=\"redis\", port=6379)\n\n\n@app.route(\"/\")\nasync def index(req):\n return response.json(dict(\n name=\"archever\"\n ))\n\n\n@app.route(\"/redis\", methods=[\"GET\"])\nasync def redis_keys(req):\n return response.json({\n \"keys\": redis.keys(\"*\")\n })\n\n\n@app.route(\"/redis/\", methods=[\"GET\", \"POST\", \"DELETE\"])\nasync def redis_opt(req, key):\n ret = dict(key=key)\n if req.method == \"GET\":\n ret[\"value\"] = redis.get(key)\n if req.method == \"POST\":\n ret[\"value\"] = req.form.get(\"value\", \"\")\n ret[\"result\"] = redis.set(key, ret[\"value\"])\n if req.method == \"DELETE\":\n ret[\"result\"] = redis.delete(key)\n return response.json(ret)\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"0.0.0.0\", port=8000, workers=2)\n","sub_path":"app/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"520346509","text":"import math\ndef prime(n):\n if (n <= 1): \n return False\n for i in range (2,int(math.sqrt(n))):\n if (n % i == 0): \n return False\n \n return True\n\ndef pallindrome(n):\n sum=0\n rev=n\n while(n>0):\n rem=n%10\n sum=sum*10+rem\n n//=10\n if(sum==rev):\n print(rev, \"is a pallindrome no.\")\n\ndef armstrong(n):\n sum=0\n rev=n\n while(n>0):\n rem=n%10\n sum+=rem**3\n n//=10\n if(sum==rev):\n print(rev, \"is an armstrong no.\")\n \nn=int(input(\"Enter the no. to be checked\"))\nif(n%2==0):\n print(n,\" is a even no.\")\nelse:\n print(n,\" is a odd no.\")\nif(prime(n)):\n print(n,\" is a prime no.\")\npallindrome(n)\narmstrong(n)\n","sub_path":"day_2/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"386479519","text":"from chat import SslClient, socket\n\ndef main():\n HOST = '' #'localhost'\n PORT = 61563 # server port for chat room\n \n\n ssl_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ssl_server.bind((HOST, PORT))\n ssl_server.listen()\n\n while True:\n\n conn, addr = ssl_server.accept()\n print('Accept a new connection', conn.getsockname(), conn.fileno())\n #Every times a Sslclient instance is created, a thread is created\n newThread = SslClient(conn)\n newThread.setDaemon(True)\n newThread.start()\n \n\nif __name__ == \"__main__\":\n \n main()\n","sub_path":"SSL server/SSL_server.py","file_name":"SSL_server.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"300674796","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n@auth:buxiangjie\n@date:2020-05-12 11:26:00\n@describe: \n\"\"\"\nbind = [\"localhost:8817\"]\nworkers = 2\ndaemon = True\nreload = True\nworker_class = \"uvicorn.workers.UvicornH11Worker\"\nreload_engine = \"auto\"\npreload_app = True","sub_path":"tools_api/gun_config.py","file_name":"gun_config.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"168279847","text":"###################################################################\n#\n# Study Fresh Project - Monitoring Program\n#\n# Using Citizen Science to Engage Children with Indoor Air Quality\n#\n# Recipient of Queensland Citizen Science Grant from\n# Queensland Department of Environment and Science\n#\n# Project Lead: Dr Steven Snow\n#\n# Project Members: Dr Lisa Ottenhaus, Dr Mashhuda Glencross\n# Dr Paola Leardini, Brett Beeson,\n# Rohith Nunna\n#\n###################################################################\n\n###################################################################\n# Peripheral File for RGB LED Scheme\n###################################################################\n\n###################################################################\n# File Imports\n###################################################################\n\n# GPIO Library for LED\nfrom gpiozero import LED\n\n###################################################################\n# Global Classes\n###################################################################\nclass LedArray:\n\n \"\"\"\n Purpose: Class to manage the RYB LEDs\n Inputs: None\n Outputs: None\n \"\"\"\n\n def __init__(self, redLED, yellowLED, greenLED):\n\n \"\"\"\n Purpose: Initialise the LEDs\n Inputs: redLED, yellowLED and greenLED\n Outputs: None\n \"\"\"\n\n self.redLED = redLED\n self.yellowLED = yellowLED\n self.greenLED = greenLED\n\n self.redLED.off()\n self.yellowLED.off()\n self.greenLED.off()\n\n def write(self, led, signal):\n\n \"\"\"\n Purpose: Toggle the LED based on the signal\n Inputs: led is the required LED\n signal is the binary signal\n Outputs: None\n \"\"\"\n\n if signal == 1:\n led.on()\n else:\n led.off()\n\n def write_duo(self, ledOne, ledTwo, signal):\n\n \"\"\"\n Purpose: Toggle two LEDs based on the signal\n Inputs: ledOne is the required LED\n ledTwo is the second LED \n signal is the binary signal\n Outputs: None\n \"\"\"\n\n if signal == 1:\n ledOne.on()\n ledTwo.on()\n else:\n ledOne.off()\n ledTwo.off()\n\n def write_all(self, signal):\n\n \"\"\"\n Purpose: Toggle two LEDs based on the signal\n Inputs: signal is the binary signal\n Outputs: None\n \"\"\"\n\n if signal == 1:\n\n self.redLED.on()\n self.yellowLED.on()\n self.greenLED.on()\n\n else:\n\n self.redLED.off()\n self.yellowLED.off()\n self.greenLED.off()\n\n","sub_path":"Workshop/peripherals/led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"439775966","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMain script for IWCoeffs \n\nCreated on Fri Aug 26 00:15:51 2016\n\n@author: Artem Rybin\n@email: arybin93@gmail.com\n\"\"\"\nimport sys\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QMessageBox\nfrom mainwindow import Ui_MainWindow\n\nTAG = \"IWCoeffs-main:\"\n\nclass MainWindow(QtWidgets.QMainWindow):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n self.ui.actionNewCalc.setShortcut('Ctrl+N')\n self.ui.actionNewCalc.setStatusTip('New Calculation')\n self.ui.actionNewCalc.triggered.connect(self.newCalc)\n\n self.ui.actionLoadCalc.setShortcut('Ctrl+L')\n self.ui.actionLoadCalc.setStatusTip('Load Calculation')\n self.ui.actionLoadCalc.triggered.connect(self.loadCalc)\n\n self.ui.actionExit.setShortcut('Ctrl+Q')\n self.ui.actionExit.setStatusTip('Exit application')\n self.ui.actionExit.triggered.connect(self.quit)\n\n def newCalc(self):\n print(TAG + \" new calc\")\n\n def loadCalc(self):\n print(TAG + \" load calc\")\n\n def quit(self):\n reply = QMessageBox.question(self, 'Exit IWCoeffs',\n \"Are you sure to quit?\", QMessageBox.Yes | \n QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n print(TAG + \" exit\") \n app.quit()\n else:\n print(TAG + \" continue work\") \n\nif __name__ == '__main__':\n print(TAG + \" start app\")\n app = QtWidgets.QApplication(sys.argv)\n mWindow = MainWindow()\n mWindow.show()\n sys.exit(app.exec_())","sub_path":"scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"474669895","text":"import csv\n\nR_TIMER_SEC = 65536\nduration = 120\n \ndef main():\n arrayOfPacketNums = []\n arrayOfTimeStamps = []\n\n with open('./data/3.4.3/100_64_nullrdc_25_d_20-2.csv', 'r') as csvfile:\n csvreader = csv.reader(csvfile)\n for row in csvreader:\n if \"Size\" in row[0]:\n attributes = row[0].split()\n #packetSize = 64\n #sendingRate = R_TIMER_SEC \n packetSize = int(attributes[2])\n sendingRate = int((attributes[5])[:-1])\n # print(sendingRate)\n else:\n packetNumAndTimeStamp = row[0].split()\n packetNum = packetNumAndTimeStamp[6]\n timeStamp = packetNumAndTimeStamp[9][:-1]\n arrayOfPacketNums.append(int(packetNum))\n arrayOfTimeStamps.append(float(timeStamp)) \n \n print(getThroughput(arrayOfPacketNums, arrayOfTimeStamps, packetSize))\n print(getLossRatio(arrayOfPacketNums, sendingRate))\n\ndef getThroughput(arrayOfPacketNums, arrayOfTimeStamps, packetSize):\n return len(arrayOfPacketNums) * packetSize * 8 / duration\n\ndef getLossRatio(arrayOfPacketNums, sendingRate):\n # totalPackets = 3 minutes * 60 secondss * sendingRate\n # print(sendingRate)\n totalPackets = duration * (R_TIMER_SEC / sendingRate)\n # print(totalPackets)\n # print(len(arrayOfPacketNums))\n return (totalPackets - len(arrayOfPacketNums)) / totalPackets\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"74157556","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom .models import Project, Area, Product, Server\n\n\nall_project = Project.objects.all()\nall_area = Area.objects.all()\nall_product = Product.objects.all()\n\nall_servers = Server.objects.all()\n\nall_project = all_project.values_list('name', flat=True)\nall_project = sorted(all_project)\nall_project.insert(0, 'ALL')\nall_project_set = ((project, project) for project in all_project)\n\nall_area = all_area.values_list('name', flat=True)\nall_area = sorted(all_area, key=lambda s: s.lower())\nall_area.insert(0, 'ALL')\nall_area_set = ((area, area) for area in all_area)\n\nall_product = all_product.values_list('model_name', flat=True)\nall_product = sorted(all_product)\nall_product.insert(0, 'ALL')\nall_product_set = ((product, product) for product in all_product)\n\nall_warranty = ('all', 'valid', 'expired')\nall_warranty_set = (('all', 'ALL'), ('valid', 'Valid'), ('expired', 'Expired'))\n\nall_display_per_page_set = [(x, x) for x in [25, 50, 75, 100, 150, 200, 'ALL']]\n\n\nclass SearchForm(forms.Form):\n hostname = forms.CharField(max_length=50,\n widget=forms.TextInput(attrs={'placeholder': '호스트명의 일부를 입력하여 검색하세요.',\n 'class': 'form-control'}))\n service_tag = forms.CharField(max_length=50,\n widget=forms.TextInput(attrs={'placeholder': '서비스태그로 검색하세요.',\n 'class': 'form-control'}))\n project = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(),\n choices=all_project_set, initial=all_project)\n area = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(),\n choices=all_area_set, initial=all_area)\n model = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,\n choices=all_product_set, initial=all_product)\n warranty = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,\n choices=all_warranty_set, initial=all_warranty)\n display_per_page = forms.ChoiceField(choices=all_display_per_page_set,\n widget=forms.Select(attrs={'onchange': 'this.form.submit();'}),\n initial=50)\n\n\n","sub_path":"server_data/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207448843","text":"\"\"\"optical 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\"\"\"\n\nfrom django.urls import path, include\nfrom .views import (\n PatientList,\n PrescriptionList,\n DoctorList,\n PatientDetail,\n DoctorDetail,\n PrescriptionDetail,\n ClinicView,\n BookList,\n BookDetail\n)\n\napp_name = 'clinic'\n\nurlpatterns = [\n path('', ClinicView.as_view(), name='dashboard'),\n path('patient/', PatientList.as_view(), name='patient-list'),\n path('prescription/', PrescriptionList.as_view(), name='prescription-list'),\n path('doctor/', DoctorList.as_view(), name='doctor-list'),\n path('book/', BookList.as_view(), name='book-list'),\n path('book//', BookDetail.as_view(), name='book-detail'),\n path('doctor//', DoctorDetail.as_view(), name='doctor-detail'),\n path('patient//', PatientDetail.as_view(), name='patient-detail'),\n path('prescription//', PrescriptionDetail.as_view(), name='prescription-detail'),\n\n\n]\n\n","sub_path":"clinic/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"408910906","text":"from Tkinter import *\nimport tkMessageBox\nfrom operator import itemgetter,attrgetter\nfrom char_class003 import char\nclass dnd_main:\n\t'''Creates the window and sets the initial values.'''\n\tdef __init__(self):\n\t\tself.current=0\n\t\tself.root=Tk()\n\t\tself.maxrow=20\n\t\tself.maxcol=20\n\t\tself.field_w=800\n\t\tself.field_h=640\n\t\tself.line_list=[[],[]]\n\t\tself.txt_list=[[],[]]\n\t\tself.root.title('D&D Battle Grid')\n\t\tself.initative_list=[]\n\t\tself.img=[]\n\t\tself.chars=[]\n\t\tself.chars_dead=[]\n\t\tself.char_imgs=[]\n\t\tself.mn=Frame(self.root)\n\t\tself.mn.grid()\n\t\tself.b_field=Canvas(self.mn, bg=\"#339900\",width=self.field_w,height=self.field_h)\n\t\tself.grid_highlight=[]\n\t\tself.moving=False\n\t\tself.atking=False\n\t\tself.attacker=[]\n\t\tself.defender=[]\n\t\tself.conf=[]\n\t\t\n\t\tself.moves_left='not started'\n\t\t\n\t\tfor i in range(int(self.field_w/32)):\n\t\t\tself.line_list[0].append(self.b_field.create_line((i+1)*32,0,(i+1)*32,self.field_h))\n\t\t\tself.txt_list[0].append(self.b_field.create_text(i*32+16,8,text=(str(i+1))))\n\t\tfor i in range(int(self.field_h/32)):\n\t\t\tself.line_list[1].append(self.b_field.create_line(0,(i+1)*32,self.field_w,(i+1)*32))\n\t\t\tself.txt_list[1].append(self.b_field.create_text(10,i*32+24,text=(str(i+1))))\n\t\t\n\t\tself.qu=Button(self.mn, text=\"QUIT\", fg=\"red\", command=self.qu_confirm)\n\t\tself.qu.grid(column=self.maxcol, row=self.maxrow)\n\t\tself.fu=Button(self.mn, text=\"RAGE!\", fg=\"red\", command=self.rage)\n\t\t#self.fu.grid(column=self.maxcol,row=0)\n\t\tself.next_chr=Button(self.mn,text=\"Next\",command=self.next_char)\n\t\tself.next_chr.grid(column=9,row=self.maxrow)\n\t\tself.move_but=Button(self.mn,text=\"Move\",command=self.move_chr)\n\t\tself.move_but.grid(column=10,row=self.maxrow)\n\t\tself.atk_but=Button(self.mn,text='Attack',command=self.atk_from_but)\n\t\tself.atk_but.grid(column=11,row=self.maxrow)\n\t\tself.move_end_but=Button(self.mn,text='End Move',command=self.move_end)\n\t\tself.move_end_but.grid(column=12,row=self.maxrow)\n\t\tself.b_field.grid(column=1,row=1,columnspan=(self.maxcol-3),rowspan=(self.maxrow-3))\n\t\tself.b_r_menu=Menu(self.root)\n\t\tself.test_var=IntVar()\n\t\tself.mes=Text(self.mn,takefocus=0,undo=False,wrap='word',height=3)\n\t\tself.mes.grid(column=1,row=self.maxrow-1,columnspan=5,rowspan=1)\n\t\t#self.move_but.grid(column=10,row=self.maxrow)\n\t\t#self.next_chr.grid(column=9,row=self.maxrow)\n\t\tself.message_add('Right click on the battle field to add characters.')\n\t\tself.message_add('try skeleton, bugbear, hob goblin, or regdar')\n\t\t#self.b_r_menu.add_checkbutton ( label=\"test\",variable=self.test_var )\n\t\tself.b_r_menu.add_command(label='Add Character Here',command=self.addchar)\n\t\tself.b_field.bind('',self.canvas_right_click)\n\t\tself.b_field.bind('',self.canvas_left_click)\n\t\tself.root.bind('',self.root_left_click)\n\t\tself.root.mainloop()\n\tdef rage(self):\n\t\t'''This is an easteregg'''\n\t\tself.message_add('fffffffuuuuuuuuuuuuuuuu')\n\tdef pics_update(self):\n\t\t'''Updates the pictures'''\n\t\tself.img=[]\n\t\tself.char_imgs=[]\n\t\tfor i in self.chars:\n\t\t\tself.img.append(PhotoImage(file=(i.get_img_name())))\n\t\t\tcen_x=(i.get_x()*32)-16\n\t\t\tcen_y=(i.get_y()*32)-16\n\t\t\tself.char_imgs.append(self.b_field.create_image(cen_x,cen_y,image=self.img[-1],state=NORMAL))\n\tdef creater(self):\n\t\t'''Adds a character to the list and screen'''\n\t\t#self.char_win.destroy()\n\t\tself.chars.append(char(self.import_char.get()+\".txt\",0,'assigned','statblock',int(self.lastx/32)+1,int(self.lasty/32)+1))\n\t\tself.pics_update()\n\t\tif self.chars[self.current].get_initiative()-1:\n\t\t\tself.current+=1\n\t\t\tself.chars[self.current].act_rep()\n\t\t\t#self.message_add(str(self.chars[self.current]))\n\t\t\tself.unhighlightbox()\n\t\t\tself.highlightbox()\n\t\telse:\n\t\t\tself.current=0\n\t\t\tself.chars[self.current].act_rep()\n\t\t\t#self.message_add(str(self.chars[self.current]))\n\t\t\tself.unhighlightbox()\n\t\t\tself.highlightbox()\n#\t\tself.mes=str(self.chars[self.current])\n#\t\tself.mes_dis=Label(self.mn,text=self.mes)\n#\t\tself.mes_dis.grid(column=2,row=self.maxrow,columnspan=7)\n\t\n\tdef highlightbox(self):\n\t\t'''Adds a blue outline around the current character'''\n\t\tprint(self.current)\n\t\tx=(self.chars[self.current].get_x()-1)*32\n\t\ty=(self.chars[self.current].get_y()-1)*32\n\t\tself.grid_highlight.append(self.b_field.create_line(x,y,x+32,y,fill='blue',width=2))\n\t\tself.grid_highlight.append(self.b_field.create_line(x,y,x,y+32,fill='blue',width=2))\n\t\tself.grid_highlight.append(self.b_field.create_line(x+32,y,x+32,y+32,fill='blue',width=2))\n\t\tself.grid_highlight.append(self.b_field.create_line(x,y+32,x+32,y+32,fill='blue',width=2))\n\t\t\n\tdef unhighlightbox(self):\n\t\t'''Removes the box around the active character'''\n\t\tfor i in self.grid_highlight:\n\t\t\tself.b_field.delete(i)\n\t\tself.grid_highlight=[]\n\t\t\n\tdef addchar(self):\n\t\t'''This function creates the window to add characters where you just clicked'''\n\t\tif self.sq_occupied(self.lastx,self.lasty)==False and self.moving==False:\n\t\t\tself.import_char=StringVar()\n\t\t\tself.import_char.set('orc_warrior')\n\t\t\t#self.message_add(self.import_char)\n\t\t\tself.char_win=Toplevel()\n\t\t\tself.char_win.title('Character Addition')\n\t\t\tself.con=Frame(self.char_win)\n\t\t\tself.con.grid()\n\t\t\tl=Label(self.con, text=\"Choose which character to add.\")\n\t\t\tchar_ent=Entry(self.con,textvariable=self.import_char)\n\t\t\tself.canc = Button(self.con, text=\"Cancel\", command=self.char_win.destroy)\n\t\t\tself.ok = Button(self.con, text=\"OK\", command=self.creater)\n\t\t\tself.canc.grid(row=3,column=0)\n\t\t\tself.ok.grid(row=3,column=1)\n\t\t\tl.grid(row=1,column=0,columnspan=2)\n\t\t\tchar_ent.grid(row=2,column=0,columnspan=2)\n\t\telse:\n\t\t\tself.char_win=Toplevel()\n\t\t\tself.char_win.title('Character Addition')\n\t\t\tself.con=Frame(self.char_win)\n\t\t\tself.con.grid()\n\t\t\tif self.moving==False:\n\t\t\t\tl=Label(self.con, text=\"Square is occupied.\")\n\t\t\telif self.moving==True:\n\t\t\t\tl=Label(self.con, text=\"You can't add a character while another character is moving.\")\n\t\t\tself.canc = Button(self.con, text=\"Cancel\", command=self.char_win.destroy)\n\t\t\tself.canc.grid(row=3,column=0)\n\t\t\tl.grid(row=1,column=0,columnspan=2)\n\t\t\t\n\tdef move_chr(self):\n\t\t'''sets the move value to true and disables the buttons'''\n\t\tself.moving=True\n\t\tself.next_chr['state']=DISABLED\n\t\tself.move_but['state']=DISABLED\n\t\tself.atk_but['state']=DISABLED\n\tdef root_left_click(self,event):\n\t\t'''removes the rightclick window'''\n\t\tself.b_r_menu.unpost()\n\tdef canvas_left_click(self,event):\n\t\t''''resolves what happens when you click on the window,attacking and moving are included'''\n\t\t#if self.moves_left<5:\n\t\t#\tself.moving=False\n\t\tif self.moving==True:\n\t\t\tself.b_r_menu.unpost()\n\t\t\t\n\t\t\tif self.char_adjacent(int(event.x/32)+1,int(event.y/32+1),self.chars[self.current])==True\\\n\t\t\tand self.sq_occupied(event.x,event.y)==False:\n\t\t\t\tx=int(event.x/32)+1\n\t\t\t\ty=int(event.y/32)+1\n\t\t\t\tself.mv_act(x,y)\n\t\telif self.atking==True:\n\t\t\tself.b_r_menu.unpost()\n\t\t\tx=int(event.x/32)+1\n\t\t\ty=int(event.y/32)+1\n\t\t\tfor i in range (len(self.chars)):\n\t\t\t\tif i!=self.current:\n\t\t\t\t\tif self.chars[i].get_x()==x and self.chars[i].get_y()==y:\n\t\t\t\t\t\tself.atk_confirm(self.chars[self.current],self.chars[i])\n\t\telse:\n\t\t\tself.b_r_menu.unpost()\n\tdef canvas_right_click(self,event):\n\t\t'''Handles rightclicking on the window and popping up the menu '''\n\t\tself.lastx, self.lasty = event.x, event.y\n\t\tself.b_r_menu.post(event.x_root,event.y_root)\n\tdef get_test_var(self):\n\t\t'''this is just a test'''\n\t\treturn(self.test_var)\n\tdef qu_confirm(self):\n\t\t'''The quit confirmation window.'''\n\t\tqu= Toplevel()\n\t\tqu.title(\"Confirm\")\n\t\tself.con=Frame(qu)\n\t\tself.con.grid()\n\t\tl=Label(self.con, text = \"Are you sure?\")\n\t\t#l.grid()\n\t\t#print(event.x,event.y)\n\t\tself.resume = Button(self.con, text=\"NO!!!!\", command=qu.destroy)\n\t\t\n\t\t#self.resume.grid()\n\t\tself.ex = Button(self.con, text=\"QUIT\", fg=\"red\", command=self.root.destroy)\n\t\tself.resume.grid(row=3,column=0)\n\t\tself.ex.grid(row=3,column=1)\n\t\tl.grid(row=1,column=0,columnspan=2)\n\tdef sq_occupied(self,x,y):\n\t\t'''Tests to see if a square is occupied'''\n\t\ttmp=False\n\t\tfor i in self.chars:\n\t\t\tif i.get_x()==(int(x/32)+1) and i.get_y()==(int(y/32)+1):\n\t\t\t\ttmp=True\n\t\t\t\tbreak\n\t\treturn(tmp)\n\tdef char_adjacent (self,x,y,character):\n\t\t'''Tests to see if a square is next to a character'''\n\t\tfrom math import sqrt\n\t\tx2=character.get_x()\n\t\ty2=character.get_y()\n\t\td=sqrt(((x2-x)**2)+((y2-y)**2))\n\t\tif d<1.75:\n\t\t\treturn(True)\n\t\telse:\n\t\t\treturn(False)\n\t\n\t\n\tdef mv_act(self,x,y):\n\t\t'''Actually moves the characters.'''\n\t\tif self.chars[self.current].get_move()==True or self.chars[self.current].get_standard()==True:\n\t\t\tif self.moves_left=='not started':\n\t\t\t\tself.moves_left=int(self.chars[self.current].get_speed())\n\t\t\tif self.moves_left>0:\n\t\t\t\tif self.get_distance(x,y,self.chars[self.current].get_x(),self.chars[self.current].get_y())<1.1:\n\t\t\t\t\tself.moves_left-=5\n\t\t\t\telse:\n\t\t\t\t\tself.moves_left-=7.5\n\t\t\t\tself.atk_of_opportunity()\n\t\t\t\tself.chars[self.current].set_x(int(x))\n\t\t\t\tself.chars[self.current].set_y(int(y))\n\t\t\t\tself.pics_update()\n\t\t\t\tself.unhighlightbox()\n\t\t\t\tself.highlightbox()\n\t\t\tif self.moves_left<=0:\n\t\t\t\tif self.chars[self.current].get_move()==True:\n\t\t\t\t\tself.chars[self.current].set_move(False)\n\t\t\t\t\t#self.message_add('setting move false')\n\t\t\t\telse:\n\t\t\t\t\tself.chars[self.current].set_standard(False)\n\t\t\t\t\t#self.message_add('setting standard false')\n\t\t\t\tself.moving=False\n\t\t\t\tself.moves_left='not started'\n\t\t\t\tself.next_chr['state']=NORMAL\n\t\t\t\tself.move_but['state']=NORMAL\n\t\t\t\tself.atk_but['state']=NORMAL\n\t\t\t\t#self.message_add(str(self.chars[self.current].get_move())+str(self.chars[self.current].get_standard()))\n\t\t\t\tif self.chars[self.current].get_move()==False and self.chars[self.current].get_standard()==False:\n\t\t\t\t\t#self.message_add('here we are')\n\t\t\t\t\tself.next_char()\n\t\telse:\n\t\t\t#self.message_add('here we are')\n\t\t\tself.next_char()\n\tdef move_end(self):\n\t\t'''Ends movement and sets actions remaining false'''\n\t\tif self.moving==True:\n\t\t\tif self.chars[self.current].get_move()==True:\n\t\t\t\tself.chars[self.current].set_move(False)\n\t\t\t\t#self.message_add('setting move false')\n\t\t\t\tdo=True\n\t\t\telif self.chars[self.current].get_standard()==True:\n\t\t\t\tself.chars[self.current].set_standard(False)\n\t\t\t\t#self.message_add('setting standard false')\n\t\t\t\tdo=True\n\t\t\telse:\n\t\t\t\tdo=False\n\t\t\tif do==True:\n\t\t\t\tself.moving=False\n\t\t\t\tself.moves_left='not started'\n\t\t\t\tself.next_chr['state']=NORMAL\n\t\t\t\tself.move_but['state']=NORMAL\n\t\t\t\tself.atk_but['state']=NORMAL\n\t\t\t\t#self.message_add(str(self.chars[self.current].get_move())+str(self.chars[self.current].get_standard()))\n\t\t\t\tif self.chars[self.current].get_move()==False and self.chars[self.current].get_standard()==False:\n\t\t\t\t\t#self.message_add('here we are')\n\t\t\t\t\tself.next_char()\n\t\t\n\tdef atk_from_but(self):\n\t\t'''Initiates the attack process by setting atking to be true'''\n\t\tself.atking=True\n\t\tself.aoe=False\n\tdef atk_of_opportunity(self):\n\t\t#if self.attacker.get_aoe():\n\t\t#self.message_add('TRYING')\n\t\tx=self.chars[self.current].get_x()\n\t\ty=self.chars[self.current].get_y()\n\t\tfor i in range (len(self.chars)):\n\t\t\tif i!=self.current:\n\t\t\t\tif self.char_adjacent(x,y,self.chars[i])==True:\n\t\t\t\t\tif self.chars[i].get_aoe:\n\t\t\t\t\t\tself.aoe=True\n\t\t\t\t\t\tself.atk_confirm(self.chars[i],self.chars[self.current])\n\t\t\t\t\t\t\n\t\t\n\tdef atk_confirm(self, attacker,defender):\n\t\t#self.message_add('atk_confirm')\n\t\tconfirm=False\n\t\tprint('atl_confirm')\n\t\t#self.message_add('test')\n\t\tself.attacker.append(attacker)\n\t\tself.defender.append(defender)\n\t\tif (self.attacker[-1].get_standard()==True and self.aoe==False) or (self.aoe==True and self.attacker[-1].get_aoe()==True):\n\t\t\tconfirm=tkMessageBox.askokcancel('Attack Confirmation',\\\n\t\t\t \"Are you sure you want \"+attacker.get_name()+' to attack '\\\n\t\t\t +defender.get_name()+'?')\n\t\t\tif confirm==True:\n\t\t\t\t#self.message_add('atk')\n\t\t\t\t#print('atk')\n\t\t\t\t##self.conf.destroy()\n\t\t\t\tself.atk_num=StringVar()\n\t\t\t\tself.atk_num.set('0')\n\t\t\t\tself.atk_mod=StringVar()\n\t\t\t\tself.atk_mod.set('0')\n\t\t\t\tself.atk_win=Toplevel()\n\t\t\t\tself.atk_win.title('Attack Selection')\n\t\t\t\tself.con=Frame(self.atk_win)\n\t\t\t\tself.con.grid()\n\t\t\t\tl=Label(self.con, text=\"Choose attack to use and any external modifier to the attack roll.\",)\n\t\t\t\tself.atk_buts=[]\n\t\t\t\tfor i in range(len(self.attacker[-1].get_attack())):\n\t\t\t\t\tself.atk_buts.append(Radiobutton(self.con,\n\t\t\t\t\ttext=self.attacker[-1].get_attack()[i]['name'],value=i,variable=self.atk_num,anchor=W))\n\t\t\t\t\tself.atk_buts[-1].grid(row=i+2,column=0,columnspan=1)\n\t\t\t\t#atk_num_ent=Entry(self.con,textvariable=self.atk_num)\n\t\t\t\tatk_mod_ent=Entry(self.con,textvariable=self.atk_mod)\n\t\t\t\tself.ok = Button(self.con, text=\"OK\", command=self.atk_execute)\n\t\t\t\tself.ok.grid(row=4,column=3)\n\t\t\t\tl.grid(row=1,column=0,columnspan=4)\n\t\t\t\t#atk_num_ent.grid(row=2,column=0,columnspan=2)\n\t\t\t\tatk_mod_ent.grid(row=2,column=3,columnspan=2)\n\t\t\t\t\n\t\t\t\n\t\telse:\n\t\t\tself.conf=Toplevel()\n\t\t\tself.conf.title('Attack Confirmation')\n\t\t\tself.conl=Frame(self.conf)\n\t\t\tself.conl.grid()\n\t\t\tl=Label(self.conl, text=attacker.get_name()+' doesn\\'t have an action remaining.')\n\t\t\tcanc=Button(self.conl,text='Cancel',command=self.conf.destroy)\n\t\t\tcanc.grid(row=2,column=3)\n\t\t\tl.grid(row=1,column=0,columnspan=6)\n\t\t\t\n\t\t\t\n\t\t\n\tdef atk_execute(self):\n\t\t'''actualy carries out the attack, also calculates range and removes the attacker and defender from the pending list'''\n\t\tself.atk_win.destroy()\n\t\t#print([int(self.atk_num.get())]['mr'])\n\t\tif self.attacker[-1].get_attack()[int(self.atk_num.get())]['mr']=='melee' and\\\n\t\t self.get_char_distance(self.attacker[-1],self.defender[-1])<=1.5*int(int(self.attacker[-1].get_attack()[int(self.atk_num.get())]['r'])/5):\n\t\t\tatkd=self.attacker[-1].atk(int(self.atk_num.get()),int(self.atk_mod.get()),self.defender[-1].get_ac())\n\t\t\tif atkd[0]==True:\n\t\t\t\tif atkd[2]>1:\n\t\t\t\t\tself.message_add(\"CRITICAL HIT!\")\n\t\t\t\t\tself.message_add (str(atkd[1])+' damage')\n\t\t\t\telse:\n\t\t\t\t\tself.message_add(\"HIT!\")\n\t\t\t\t\tself.message_add(str(atkd[1])+' damage')\n\t\t\telse:\n\t\t\t\tself.message_add(\"Miss\")\n\t\t\t#self.message_add(self.defender[-1].get_hp())\n\t\t\tif atkd[0]:\n\t\t\t\tself.defender[-1].atk_def(atkd[1],atkd[3])\n\t\t\t\tself.message_add('The defender\\'s hitpoints have been reduced to '+str(self.defender[-1].get_hp()))\n\t\t\t\tself.dead()\n\t\t\tif self.aoe==True:\n\t\t\t\tself.attacker[-1].set_aoe(False)\n\t\t\t\tself.aoe=False\n\t\t\telse:\n\t\t\t\tself.attacker[-1].set_standard(False)\n\t\t\t\tif self.chars[self.current].get_move()==False and self.chars[self.current].get_standard()==False:\n\t\t\t\t\tself.next_char()\n\t\telif self.attacker[-1].get_attack()[int(self.atk_num.get())]['mr']=='ranged':\n\t\t\trangemod= -2*(int((self.get_char_distance(self.attacker[-1],self.defender[-1])/\n\t\t\tint(self.attacker[-1].get_attack()[int(self.atk_num.get())]['r']))))\n\t\t\tatkd=self.attacker[-1].atk(int(self.atk_num.get()),rangemod+int(self.atk_mod.get()),self.defender[-1].get_ac())\n\t\t\tif atkd[0]==True:\n\t\t\t\tif atkd[2]>1:\n\t\t\t\t\tself.message_add(\"CRITICAL HIT!\")\n\t\t\t\t\tself.message_add (str(atkd[1])+' damage')\n\t\t\t\telse:\n\t\t\t\t\tself.message_add(\"HIT!\")\n\t\t\t\t\tself.message_add(str(atkd[1])+' damage')\n\t\t\telse:\n\t\t\t\tself.message_add(\"Miss\")\n\t\t\t#self.message_add(self.defender[-1].get_hp())\n\t\t\tif atkd[0]:\n\t\t\t\tself.defender[-1].atk_def(atkd[1],atkd[3])\n\t\t\t\tself.message_add('The defender\\'s hitpoints have been reduced to '+str(self.defender[-1].get_hp()))\n\t\t\t\tself.dead()\n\t\t\t\n\t\t\tif self.aoe==True:\n\t\t\t\tself.attacker[-1].set_aoe(False)\n\t\t\t\tself.aoe=False\n\t\t\telse:\n\t\t\t\tself.attacker[-1].set_standard(False)\n\t\t\t\tif self.chars[self.current].get_move()==False and self.chars[self.current].get_standard()==False:\n\t\t\t\t\tself.next_char()\n\t\telse:\n\t\t\ttkMessageBox.showerror('Out of range','The target is not in range.')\n\t\tdel self.attacker[-1]\n\t\tdel self.defender[-1]\n\t\t\n\tdef get_distance(self,x,y,x2,y2):\n\t\t'''calculates the distance between two points'''\n\t\tfrom math import sqrt\n\t\treturn(sqrt(((x2-x)**2)+((y2-y)**2)))\n\tdef get_char_distance(self,char1,char2):\n\t\tfrom math import sqrt\n\t\treturn(sqrt(((char2.get_x()-char1.get_x())**2)+((char2.get_y()-char1.get_y())**2)))\n\t\t\n\tdef message_add(self,mes_txt):\n\t\t'''adds a message to the bottom box'''\n\t\tself.mes['state']=NORMAL\n\t\tself.mes.insert ( END, '\\n'+str(mes_txt))\n\t\tself.mes.yview(SCROLL,9001,UNITS)\n\t\tself.mes['state']=DISABLED\n\t\t#self.mes.grid(column=2,row=self.maxrow-1,columnspan=5,rowspan=2)\n\t\t\n\tdef dead(self):\n\t\t'''calculates to see if anyone should be dead because of their negative hitpoints'''\n\t\tfor i in range(len(self.chars)):\n\t\t\tif self.chars[i].get_hp()<0:\n\t\t\t\tif self.moving==True:\n\t\t\t\t\tself.move_end()\n\t\t\t\ttmp=self.current\n\t\t\t\tself.chars_dead.append(self.chars[i])\n\t\t\t\tdel self.chars[i]\n\t\t\t\tself.pics_update()\n\t\t\t\tif i score (-log prob)\ndef compute_m(stat_map, grammar):\n if stat_map is None: return None\n # rules : non-terminal -> rewrite list\n rules = grammar.rules\n m = {}\n\n for nt, prods in rules.items():\n new_value = max_score\n for prod in prods:\n ph_vars, nts, expr = prod.to_template_expr()\n if len(nts) > 0:\n continue\n else:\n topsymb = fetchop(expr)\n prob = max([topsymb_to_prob.get(topsymb, 0.001) for ctx, topsymb_to_prob in stat_map.items()], default=0.001)\n m_ns = map(lambda n: m.get(n, max_score), nts)\n prod_value = functools.reduce(lambda x, y: x + y, m_ns, -1 * math.log2(prob))\n new_value = min(new_value, prod_value)\n m[nt] = math.fabs(new_value)\n\n def F():\n # prods : rewrite list\n updated = False\n for nt, prods in rules.items():\n old_value = m.get(nt, max_score)\n new_value = old_value\n for prod in prods:\n ph_vars, nts, expr = prod.to_template_expr()\n topsymb = fetchop(expr)\n prob = max([topsymb_to_prob.get(topsymb, 0.001) for ctx, topsymb_to_prob in stat_map.items()], default=0.001)\n m_ns = map(lambda n: m.get(n, max_score), nts)\n prod_value = functools.reduce(lambda x, y: x + y, m_ns, -1 * math.log2(prob))\n new_value = min(new_value, prod_value)\n\n updated = updated or (math.fabs(old_value - new_value) > 0.01)\n m[nt] = math.fabs(new_value)\n\n return updated\n\n updated = True\n while updated:\n updated = F()\n return m\n\n\ndef heuristic(m, nts):\n score = 0.0\n for nt in nts:\n score = score + m[nt]\n return score\n\n\ndef compute_m_sens(m, stat_map, grammar):\n if stat_map is None: return None\n rules = grammar.rules\n m_sens = {}\n prod2info = {}\n for nt, prods in rules.items():\n prod2info[nt] = []\n for prod in prods:\n topsymb = fetchop_rewrite(prod)\n prod_ph_vars, prod_nts, prod_expr = prod.to_template_expr()\n m_ns = map(lambda n: m.get(n, -1 * math.log2(0.001)), prod_nts)\n prod2info[nt].append((topsymb, m_ns))\n\n for nt, tuples in prod2info.items():\n if nt not in m_sens.keys(): m_sens[nt] = {}\n for ctx, topsymb_to_prob in stat_map.items():\n min_logprob = 9999999.0\n for (topsymb, m_ns) in tuples:\n prod_prob = topsymb_to_prob.get(topsymb, 0.001)\n prob = functools.reduce(lambda x, y: x + y, m_ns, -1 * math.log2(prod_prob))\n if prob < min_logprob: min_logprob = prob\n m_sens[nt][ctx] = min_logprob\n\n return m_sens\n\n\ndef heuristic_sens(m, m_sens, instrs, next_nts_addrs, next_nts, next_expr):\n if len(next_nts_addrs) == 0:\n return 0.0\n else:\n addr = next_nts_addrs[0]\n banned_addrs = {tuple(addr) for addr in next_nts_addrs[1:]}\n _,ctxt = get_ctxt(next_expr, addr, instrs, banned_addrs)\n cond = ','.join(ctxt)\n result = m_sens.get(next_nts[0], {}).get(cond, -1 * math.log2(0.001))\n if len(next_nts) > 1:\n m_ns = map(lambda n: m.get(n, -1 * math.log2(0.001)), next_nts[1:])\n result = functools.reduce(lambda x, y: x + y, m_ns, result)\n return result\n\n# g : graph of current_expr\ndef expansion_cost(stat_map, instrs, topsymb, expr, placeholders, addr=None):\n if addr == None:\n addr = get_addr(expr, placeholders[0])\n # banned list : all ther place holders other than one being expanded\n banned = set(placeholders)\n banned.discard(placeholders[0])\n banned_addrs = {tuple(get_addr(expr, e)) for e in banned}\n _,ctxt = get_ctxt(expr, addr, instrs, banned_addrs)\n cond = ','.join(ctxt)\n prob = stat_map.get(cond, {}).get(topsymb, 0.001)\n l_e = -1.0 * math.log2(prob)\n # print(exprs.expression_to_string(expr), \" \", cond, \" \", topsymb, \" \", l_e)\n return l_e\n\n\n# load stat_map and instrs from file\ndef phogFromFile(statFileName, for_eusolver, for_pred_exprs, ret_type):\n default_value = ((None, None), (None, None))\n try:\n statFile = open(statFileName, 'rb')\n except:\n # print('Phog file not found: %s... We use the basic solver.' % statFileName)\n return default_value[0]\n rettype2mle = pickle.load(statFile)\n # if there is no mle, fall back to the original e(u)solver\n ((term_instrs, term_stat_map), (pred_instrs, pred_stat_map)) = rettype2mle.get((str(ret_type), for_eusolver), default_value)\n statFile.close()\n if for_pred_exprs:\n return (pred_instrs, pred_stat_map)\n else:\n return (term_instrs, term_stat_map)\n # From text\n # lines = [line.strip() for line in statFile]\n # instrs = [int(token) for token in lines[0].split()]\n # stat_map['_'] = {}\n # for line in lines[1:]:\n # tokens = line.split()\n # assert (len(tokens) == 3)\n # ctxt = tokens[0]\n # term_symbol = tokens[1]\n # prob = float(tokens[2]) / 1000.0\n # if not ctxt in stat_map.keys(): stat_map[ctxt] = {}\n # stat_map[ctxt][term_symbol] = prob\n # statFile.close()\n\n\ndef collect_constants_from_phog(phog_file, rettype):\n def string_to_constant_rewrite(topsymb):\n if topsymb.isdigit() or (topsymb.startswith('-') and len(topsymb) >= 2 and topsymb[1:].isdigit):\n num = -1 * int(topsymb[1:]) if topsymb.startswith('-') else int(topsymb)\n return grammars.ExpressionRewrite(exprs.ConstantExpression(exprs.Value(num, exprtypes.IntType())))\n elif topsymb.startswith('#x'): # bitvector\n num = int('0' + topsymb[1:], 16)\n bitsize = (len(topsymb) - 2) * 4\n return grammars.ExpressionRewrite(exprs.ConstantExpression(exprs.Value(num, exprtypes.BitVectorType(bitsize))))\n else: # boolean\n return grammars.ExpressionRewrite(exprs.ConstantExpression(exprs.Value(bool(topsymb), exprtypes.BoolType())))\n\n (_, term_mle) = phogFromFile(phog_file, False, False, rettype)\n (_, eu_term_mle) = phogFromFile(phog_file, True, False, rettype)\n (_, eu_pred_mle) = phogFromFile(phog_file, True, True, rettype)\n vocabs = set([])\n constant_rewrites = set([])\n # only consider integer and bitvector types\n for mle in [term_mle, eu_term_mle, eu_pred_mle]:\n if mle is not None:\n for _, termsymb in mle.items():\n for topsymb in termsymb:\n vocabs.add(topsymb)\n\n for vocab in vocabs:\n rewrite = string_to_constant_rewrite(vocab)\n constant_rewrites.add(rewrite)\n # print([str(rewrite) for rewrite in constant_rewrites])\n return constant_rewrites\n\n\nclass Phog:\n\n def __init__(self, grammar, file, ret_type, for_eusolver=False, for_pred_exprs=False):\n instrs, stat_map = phogFromFile(file, for_eusolver, for_pred_exprs, ret_type)\n self.stat_map = stat_map\n self.instrs = instrs\n self.grammar = grammar\n self.enumerated_exps = []\n self.frontier = PriorityQueue()\n # pre processing for heuristic score function\n self.m = compute_m(self.stat_map, grammar)\n self.m_sens = compute_m_sens(self.m, self.stat_map, grammar)\n # self.print_phog()\n\n def print_phog(self):\n print('Instr : ', self.instrs)\n for cond, topsymb2prob in self.stat_map.items():\n for topsymb, prob in topsymb2prob.items():\n if prob > 0.001:\n print('%s [%s] -> %.3f' % (str(cond), topsymb, prob))\n\n def add_for_statistics(self, expr):\n self.enumerated_exps.append(expr)\n\n def clear_data(self):\n self.enumerated_exps.clear()\n\n # print scores of enumerated exps\n def print_statistics(self):\n if len(self.enumerated_exps) == 0: return\n # print('# enumerated : ', len(self.enumerated_exps), flush=True)\n\n def generate(self, compute_term_signature, points):\n grammar = self.grammar\n m = self.m\n m_sens = self.m_sens\n instrs = self.instrs\n stat_map = self.stat_map\n\n # ********************************************** Data structures ***************************************************\n # priority queue : list of str(rewrite)\n frontier = PriorityQueue()\n\n # str(rewrite)-> rewrite * addr of leftmost non-terminal symbol * (placeholder variables * non-terminals * expr)\n # roles:\n # 1. rewrite cannot be added to the priority queue as it is unhashable.\n # We add str(rewrite) to the queue and this map stores its corresponding rewrite object.\n # 2. to avoid repeating calling to_template_expr\n strrewrite_to_rewrite = {}\n\n # directed graph of str(rewrite)\n # expansion_history = nx.DiGraph()\n\n # str(rewrite) -> normalized str(rewrite)\n strrewrite_to_normstrrewrite = {}\n # normalized str(rewrite) -> str(rewrite) (representative of equivalence class)\n normstrrewrite_to_strrewrite = {}\n\n # sum of log probabilities of expansions so far\n # strrewrite -> R\n cost_so_far = {}\n\n # str(rewrite) -> priority\n strrewrite_to_priority = {}\n\n # set of ignored str(rewrite)\n ignored = []\n\n # ******************************************************************************************************************\n\n # start symbol\n start = grammars.NTRewrite(grammar.start, grammar.nt_type[grammar.start])\n\n # init for start symbol\n start_str = str(start)\n (start_ph_vars, start_nts, start_expr) = start.to_template_expr()\n strrewrite_to_rewrite[start_str] = (start, [[]], (start_ph_vars, start_nts, start_expr))\n strrewrite_to_normstrrewrite[start_str] = start_str\n normstrrewrite_to_strrewrite[start_str] = start_str\n frontier.put(start_str, 0)\n cost_so_far[start_str] = 0\n\n # init for non-terminals\n for nt in grammar.non_terminals:\n strrewrite_to_normstrrewrite[nt] = nt\n\n def incremental_update(ignored, frontier):\n strrewrite_to_normstrrewrite.clear()\n normstrrewrite_to_strrewrite.clear()\n\n for nt in grammar.non_terminals:\n strrewrite_to_normstrrewrite[nt] = nt\n\n for rewrite_str in ignored:\n frontier.put(rewrite_str, strrewrite_to_priority[rewrite_str])\n ignored.clear()\n\n num_points = len(points)\n while not frontier.empty():\n # incremental search with indistinguishability\n if len(points) > num_points and options.inc:\n incremental_update(ignored, frontier)\n\n num_points = len(points)\n _,current_str = frontier.get()\n (current, nts_addrs, (ph_vars, nts, current_expr)) = strrewrite_to_rewrite[current_str]\n if len(nts) == 0:\n #print('%50s :\\t %.2f' % (exprs.expression_to_string(current_expr), cost_so_far[current_str]), flush=True)\n yield [current_expr]\n else:\n assert (len(nts_addrs) > 0)\n _, ctxt = get_ctxt(current_expr, nts_addrs[0], instrs, {tuple(addr) for addr in nts_addrs[1:]})\n cond = ','.join(ctxt)\n\n # one step left-most expansion\n for rule, next_rewrite, generated_nts_addrs in grammar.one_step_expand(current, nts_addrs[0]):\n next_nts_addrs = nts_addrs[1:] if len(generated_nts_addrs) == 0 else generated_nts_addrs + nts_addrs[1:]\n next_ph_vars, next_nts, next_expr = next_rewrite.to_template_expr()\n # update rewrite_forest and get a string of next_rewrite\n next_str = str(next_rewrite)\n strrewrite_to_rewrite[next_str] = (next_rewrite, next_nts_addrs, (next_ph_vars, next_nts, next_expr))\n # if it is non-terminal rewriting, it causes no cost.\n topsymb = fetchop_rewrite(rule)\n if isinstance(rule, grammars.NTRewrite):\n expand_cost = 0.0\n else:\n expand_cost = -1.0 * math.log2(stat_map.get(cond, {}).get(topsymb, 0.001))\n new_cost = cost_so_far[current_str] + expand_cost\n\n if next_str not in cost_so_far or new_cost < cost_so_far[next_str]:\n cost_so_far[next_str] = new_cost\n future_cost = 0.0 if options.noheuristic else heuristic_sens(m, m_sens, instrs, next_nts_addrs, next_nts, next_expr)\n priority = new_cost + future_cost\n strrewrite_to_priority[next_str] = priority\n\n # get representative of eq class which current rewrite belongs to\n if not options.noindis:\n normalized_next_str = normalize_rewritestr(next_expr, strrewrite_to_normstrrewrite,\n compute_term_signature,\n grammar.non_terminals)\n # no normalization\n else:\n normalized_next_str = next_str\n\n rep = normstrrewrite_to_strrewrite[normalized_next_str] \\\n if normalized_next_str in normstrrewrite_to_strrewrite else next_str\n\n # switch representative\n if rep == next_str or priority < strrewrite_to_priority.get(rep, max_score):\n normstrrewrite_to_strrewrite[normalized_next_str] = next_str\n frontier.put(rep, priority, replace=next_str)\n # rep is ignored and replaced by new one.\n if rep != next_str and options.inc: ignored.append(rep)\n else:\n # next_str is ignored because it is worse than the current representative.\n if options.inc:\n ignored.append(next_str)\n\n return\n","sub_path":"bin/phogs/phog.py","file_name":"phog.py","file_ext":"py","file_size_in_byte":16166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"565697126","text":"import os\n\nenv = Environment(ENV = {'PATH' : os.environ['PATH'],\n 'HOME' : os.environ['HOME'],\n 'TERM' : 'xterm'},\n CXX='g++',\n tools=['default'], toolpath=[''])\n\nAddOption('--win64',\n action='store_true',\n help='cross-compiles for windows',\n default=False)\n\nif GetOption('win64'):\n env.Tool('crossmingw', toolpath = ['./utils/scripts/'])\n vardir='build/win/utils'\n targetsuffix='.exe'\n linkflags=('--static -Wl,--no-undefined ' +\n '-static-libgcc -static-libstdc++')\nelse:\n vardir='build/linux/utils'\n targetsuffix=''\n linkflags=''\n\nVariantDir(vardir, 'utils')\n\nbase ='#/src'\ntarget = '#/bin/obj2cobj' + targetsuffix\n\ngccWarningLevel = [\n '-Wall', '-Wextra', '-Wcast-align', '-Wcast-qual',\n '-fpermissive',\n '-Wconversion', '-Wdisabled-optimization', #'-Weffc++',\n '-Wfloat-equal', '-Wformat=2', '-Wimport', '-Winit-self',\n '-Winline', '-Winvalid-pch', '-Wlong-long',\n '-Wmissing-format-attribute', '-Wmissing-include-dirs',\n '-Wmissing-noreturn', '-Wpacked', '-Wpointer-arith',\n '-Wredundant-decls', '-Wshadow', '-Wstack-protector',\n '-Wstrict-aliasing=2', '-Wunreachable-code',\n '-Wunsafe-loop-optimizations', '-Wunused',\n '-Wvariadic-macros', '-Wwrite-strings', '-pedantic',\n '-pedantic-errors', '-Woverloaded-virtual',\n '-Wswitch-enum', # '-Werror'\n]\n\npathBoost = os.environ['BOOST_DIR'];\n\n# CPPFLAGS\n####################\ncppflags = ['-O0', '-g', '-gdwarf-2']\n#cppflags = ['-O3']\ncppflags.extend(['-fno-strict-aliasing',\n '-std=c++11'])\ncppflags.extend(gccWarningLevel)\ncppflags.extend(['-isystem', pathBoost + '/include'])\n\n\nsourcepaths = [\n base,\n pathBoost + '/include'\n]\n\nlibpaths = []\nlibs = []\ncppMain = [Glob('utils/obj2cobj/obj2cobj.cpp') +\n Glob('src/util/CObjUtil.cpp') +\n Glob('src/util/StringUtil.cpp') +\n Glob('src/extern/tiny_obj_loader.cpp')]\n\napp = env.Program(target, cppMain,\n LIBS = libs,\n LINKFLAGS = linkflags,\n LIBPATH = libpaths,\n CPPFLAGS = cppflags,\n CPPPATH = sourcepaths);\nDefault(app)\n","sub_path":"utils/obj2cobj/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"430612230","text":"# -*- coding: utf-8 -*-\nimport os\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport csv\nfrom tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img, ImageDataGenerator\nfrom scipy.optimize import minimize\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\nfrom pyquaternion import Quaternion\nimport pickle\nfrom flowlib import flow_to_image\nimport pdb\n# cv2.imshow('qwe', flow_to_image(opt_flow))\n\ndefault_data_dir = os.path.join('/mnt', 'data', 'AirSimCollectedData', 'testing')\ncsv_col_names = ['LV_x', 'LV_y', 'LV_z', 'AV_x', 'AV_y', 'AV_z', 'OQ_w', 'OQ_x', 'OQ_y', 'OQ_z']\ndatapoints_csv_name = os.path.join(default_data_dir, 'airsim_rec.csv')\n\ndefault_bins = [0, 0.25]\n\n# For some reason max values for collision distance seem to be bounded at 0.5\n# This multiplier aims to fix that\ncoll_dist_mul = 1\n\n# https://github.com/unrealcv/unrealcv/issues/14\norig_image_size = (270, 480) # (h,w)\nFOV = 90 # in degeres\ncam_f = orig_image_size[1] / 2 / np.tan( FOV / 180 * np.pi / 2 )\n\ncam_f = 4.47189418e+00 # calculated by minimization of horizontal flow in a yaw-only dataset\nxy_scale_default = 4.78224949e-06\n\n# velocity_input_mode = 'raw'\n# velocity_input_mode = 'camera-compensated'\nvelocity_input_mode = 'angle-magnitude'\n\nincl_ang_vel = True\ndef set_incl_ang_vel(val):\n global incl_ang_vel\n incl_ang_vel = val\n\ndef get_incl_ang_vel():\n global incl_ang_vel\n return incl_ang_vel\n\ndef set_correction_stats(vals):\n global cam_f\n global xy_scale_default\n cam_f = val[0]\n xy_scale_default = val[1]\n\ndef o_f_compensate_for_rotation(opt_flow, rot, focal=cam_f, xy_scaling=xy_scale_default):\n '''\n Removes estimated optical flow due to camera rotation.\n '''\n # Calculate OF due to rotation\n # http://scholarpedia.org/article/Optic_flow#Optic_flow_for_guidance_of_locomotion_and_scene_parsing\n # return opt_flow\n focal = np.abs(focal)\n xy_scaling = np.abs(xy_scaling)\n opt_flow_corrected = np.copy(opt_flow)\n current_size = opt_flow.shape[-3:-1]\n\n # Prepare a grid of equivalent pixel positions of original size image\n ys = np.expand_dims(np.linspace(-orig_image_size[0]/2, orig_image_size[0]/2, num=current_size[0]), axis=-1)\n xs = np.expand_dims(np.linspace(-orig_image_size[1]/2, orig_image_size[1]/2, num=current_size[1]), axis=0)\n ys = np.tile(ys, (1, current_size[1]))\n ys *= xy_scaling\n xs = np.tile(xs, (current_size[0], 1))\n xs *= xy_scaling\n\n # In AirSim Coordinates rot[0] is rotation around the central axis (roll)\n # rot[1] is pitch and rot[2] is negative yaw\n\n # First channel is the horizontal motion component\n opt_flow_corrected[..., 0] -= ys * xs * -rot[1]\n opt_flow_corrected[..., 0] -= -(focal * focal + xs * xs) * -rot[2]\n opt_flow_corrected[..., 0] -= ys * focal * rot[0]\n # Second channel is the vertical motion component\n opt_flow_corrected[..., 1] -= (focal * focal + ys * ys) * -rot[1]\n opt_flow_corrected[..., 1] -= - ys * xs * -rot[2]\n opt_flow_corrected[..., 1] -= - xs * focal * rot[0]\n\n opt_flow_corrected /= focal\n\n return opt_flow_corrected\n\n\n\n\ndef world2camera_coords(vect, cam_orient):\n '''\n Rotates a 3D vector from world orientation into camera orientation.\n cam_orient is a quaternion description of camera rotation w.r.t. world\n '''\n ret = np.empty_like(vect)\n if len(vect.shape) > 1:\n for idx, quat in enumerate(cam_orient):\n # To convert velocity from world orientation to camera orientation\n # need to apply rotation inverse to orientation.\n # Formula for applying quaternion rotation to a vector from wikipedia\n # https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation\n quat_vec = Quaternion(scalar=0, vector=vect[idx])\n quat_vec_rot = cam_orient[idx].inverse * quat_vec * cam_orient[idx]\n ret[idx] = quat_vec_rot.vector\n else:\n quat_vec = Quaternion(scalar=0, vector=vect)\n ret = cam_orient.inverse * quat_vec * cam_orient\n ret\n return ret\n\ndef load_optical_flow_metadata(data_dirs, force_metadata_refresh=False, bins=None):\n metadatas = {}\n metadatas['sums'] = np.empty((0,), dtype=np.float32)\n metadatas['max_vals'] = np.empty((0,), dtype=np.float32)\n metadatas['mean_vals'] = np.empty((0,), dtype=np.float32)\n metadatas['cam_lin_vel'] = np.empty((0, 3), dtype=np.float32)\n metadatas['cam_ang_vel'] = np.empty((0, 3), dtype=np.float32)\n metadatas['class_count'] = np.empty((0, len(bins)), dtype=np.float32)\n metadatas['timestamp_idx'] = {}\n idxs_all = 0\n for dir_idx, data_dir in enumerate(data_dirs):\n metadata = load_optical_flow_metadata_single_dir(data_dir[0],\n force_metadata_refresh=force_metadata_refresh,\n bins=bins,\n dir_idx=dir_idx)\n metadatas['sums'] = np.concatenate([metadatas['sums'], metadata['sums']], axis=0)\n metadatas['max_vals'] = np.concatenate([metadatas['max_vals'], metadata['max_vals']], axis=0)\n metadatas['mean_vals'] = np.concatenate([metadatas['mean_vals'], metadata['mean_vals']], axis=0)\n metadatas['cam_lin_vel'] = np.concatenate([metadatas['cam_lin_vel'], metadata['cam_lin_vel']], axis=0)\n metadatas['cam_ang_vel'] = np.concatenate([metadatas['cam_ang_vel'], metadata['cam_ang_vel']], axis=0)\n metadatas['class_count'] = np.concatenate([metadatas['class_count'], metadata['class_count']], axis=0)\n\n idxs_all += len(metadatas['timestamp_idx'])\n\n for timestamp, idx in metadata['timestamp_idx'].items():\n metadatas['timestamp_idx'][timestamp] = (idx[0]+idxs_all, idx[1])\n return metadatas\n\ndef load_optical_flow_metadata_single_dir(data_dir, datapoints=None, force_metadata_refresh=False, bins=None, dir_idx=None):\n if datapoints is None:\n datapoints_csv_name = os.path.join(data_dir, 'airsim_rec.csv')\n datapoints = pd.read_csv(datapoints_csv_name,\n header=None,\n sep=',',\n names=csv_col_names,\n index_col=0)\n if bins is None:\n bins = default_bins\n metadata_file = os.path.join(data_dir, 'optical_flow_metadata.pickle')\n if os.path.isfile(metadata_file) and not force_metadata_refresh:\n f = open(metadata_file, 'rb')\n metadata = pickle.load(f)\n else:\n # No metadata file, need to create one\n print('Creating metadata file.')\n metadata = {}\n metadata['sums'] = []\n metadata['max_vals'] = []\n metadata['mean_vals'] = []\n metadata['cam_lin_vel'] = []\n metadata['cam_ang_vel'] = []\n metadata['timestamp_idx'] = {}\n metadata['class_count'] = []\n vel = []\n orient = []\n idx = 0\n for timestamp in tqdm(datapoints.index):\n # Calculate sum of collision probability over pixels\n coll_dist_n = os.path.join(data_dir, 'images',\n 'misc_' + str(timestamp) + '.npz')\n coll_dist = np.load(coll_dist_n)['arr_0']\n coll_dist *= coll_dist_mul # not sure why the max value seems to be bounded at 0.5...\n metadata['sums'].append(np.sum(coll_dist))\n metadata['max_vals'].append(np.max(coll_dist))\n metadata['mean_vals'].append(np.mean(coll_dist))\n orient.append(Quaternion(datapoints.loc[timestamp][['OQ_w', 'OQ_x', 'OQ_y', 'OQ_z']]))\n metadata['cam_ang_vel'].append(datapoints.loc[timestamp][['AV_x', 'AV_y', 'AV_z']])\n if dir_idx is not None:\n metadata['timestamp_idx'][timestamp] = (idx, dir_idx)\n else:\n metadata['timestamp_idx'][timestamp] = idx\n\n class_count = []\n for bin_idx, a_bin in enumerate(bins):\n if bin_idx != len(bins)-1:\n upper = bins[bin_idx+1]\n else:\n upper = 1.1\n class_count.append(np.sum(np.logical_and(coll_dist >= a_bin, coll_dist < upper)))\n metadata['class_count'].append(class_count)\n\n idx += 1\n\n # Calculate the velocity w.r.t. camera\n vel = np.array(datapoints[['LV_x','LV_y','LV_z']])\n metadata['cam_lin_vel'] = world2camera_coords(vel, orient)\n metadata['sums'] = np.array(metadata['sums'])\n metadata['max_vals'] = np.array(metadata['max_vals'])\n metadata['mean_vals'] = np.array(metadata['mean_vals'])\n metadata['cam_ang_vel'] = np.array(metadata['cam_ang_vel'])\n metadata['class_count'] = np.array(metadata['class_count'])\n\n f = open(metadata_file, 'wb')\n pickle.dump(metadata, f, protocol=pickle.HIGHEST_PROTOCOL)\n return metadata\n\ndef calc_class_weights(data_dirs, force_metadata_refresh=False, bins=None, min_max_value=0):\n metadata = load_optical_flow_metadata(data_dirs,\n force_metadata_refresh=force_metadata_refresh,\n bins=bins)\n\n class_totals = np.sum(metadata['class_count'][np.nonzero(metadata['max_vals'] > min_max_value)], axis=0)\n weights = np.sum(class_totals) / (class_totals.shape[0] * class_totals)\n # weights = np.power(weights, 1/5)\n # weights = np.power(weights, 1/5)\n mismatch_weights = np.sum(weights) / weights\n return weights, mismatch_weights\n\ndef generator_size(data_dirs, bins=None,\n scrambled_range=None,\n timestamp_range=None, range_in_fractions=False,\n include_motion_data=False,\n min_sum_percentile=None,\n min_max_value=None,\n force_metadata_refresh=False):\n ''' Generator for data batches from AirSim-generated data. '''\n datapoints_all = pd.DataFrame()\n for data_dir in data_dirs:\n if os.path.isdir(data_dir[0]):\n datapoints_csv_name = os.path.join(data_dir[0], 'airsim_rec.csv')\n datapoints_one_dir = pd.read_csv(datapoints_csv_name,\n header=None,\n sep=',',\n names=csv_col_names,\n index_col=0)\n datapoints_all = datapoints_all.append(datapoints_one_dir)\n\n if min_sum_percentile or min_max_value or include_motion_data:\n metadata = load_optical_flow_metadata(data_dirs,\n force_metadata_refresh=force_metadata_refresh,\n bins=bins)\n # If needed, take only those datapoints where there is most collision\n # probability\n if min_sum_percentile is not None:\n min_sum = np.percentile(metadata['sums'], min_sum_percentile)\n datapoints_all = datapoints_all[metadata['sums'] > min_sum]\n elif min_max_value is not None:\n datapoints_all = datapoints_all[metadata['max_vals'] > min_max_value]\n\n if scrambled_range is not None:\n datapoints = datapoints_all.sample(frac=1., random_state=scrambled_range[2])\n datapoints = datapoints.iloc[int(scrambled_range[0] * len(datapoints)):int(scrambled_range[1] * len(datapoints))]\n else:\n # Figure out first and last timestep of the range\n if timestamp_range is None:\n timestamp_range = (datapoints_all.index[0], datapoints_all.index[-1])\n \n if range_in_fractions:\n start_idx = int(np.floor(timestamp_range[0] * datapoints_all.shape[0]))\n end_idx = int(np.ceil(timestamp_range[1] * datapoints_all.shape[0]))\n start_timestamp = datapoints_all.index[start_idx]\n end_timestamp = datapoints_all.index[end_idx-1]\n else:\n start_timestamp = timestamp_range[0]\n end_timestamp = timestamp_range[1]\n \n datapoints = datapoints_all.loc[start_timestamp:end_timestamp]\n batch_start = start_idx\n\n print('Analytical rotational motion OF compensation is {}'.format('OFF' if incl_ang_vel else 'ON'))\n return datapoints.shape[0]\n\n\ndef data_gen(data_dirs, batch_size, bins=None,\n scrambled_range=None,\n timestamp_range=None, range_in_fractions=False,\n img_resolution=None,\n random_order=True,\n include_rgb=False,\n include_motion_data=False,\n min_sum_percentile=None,\n min_max_value=None,\n force_metadata_refresh=False):\n ''' Generator for data batches from AirSim-generated data. '''\n datapoints_all = pd.DataFrame()\n for data_dir in data_dirs:\n if os.path.isdir(data_dir[0]):\n datapoints_csv_name = os.path.join(data_dir[0], 'airsim_rec.csv')\n datapoints_one_dir = pd.read_csv(datapoints_csv_name,\n header=None,\n sep=',',\n names=csv_col_names,\n index_col=0)\n datapoints_all = datapoints_all.append(datapoints_one_dir)\n\n if min_sum_percentile or min_max_value or include_motion_data:\n metadata = load_optical_flow_metadata(data_dirs,\n force_metadata_refresh=force_metadata_refresh,\n bins=bins)\n # If needed, take only those datapoints where there is most collision\n # probability\n if min_sum_percentile is not None:\n min_sum = np.percentile(metadata['sums'], min_sum_percentile)\n datapoints_all = datapoints_all[metadata['sums'] > min_sum]\n elif min_max_value is not None:\n datapoints_all = datapoints_all[metadata['max_vals'] > min_max_value]\n\n if scrambled_range is not None:\n datapoints = datapoints_all.sample(frac=1., random_state=scrambled_range[2])\n datapoints = datapoints.iloc[int(scrambled_range[0] * len(datapoints)):int(scrambled_range[1] * len(datapoints))]\n else:\n # Figure out first and last timestep of the range\n if timestamp_range is None:\n timestamp_range = (datapoints_all.index[0], datapoints_all.index[-1])\n \n if range_in_fractions:\n start_idx = int(np.floor(timestamp_range[0] * datapoints_all.shape[0]))\n end_idx = int(np.ceil(timestamp_range[1] * datapoints_all.shape[0]))\n start_timestamp = datapoints_all.index[start_idx]\n end_timestamp = datapoints_all.index[end_idx-1]\n else:\n start_timestamp = timestamp_range[0]\n end_timestamp = timestamp_range[1]\n \n datapoints = datapoints_all.loc[start_timestamp:end_timestamp]\n batch_start = start_idx\n\n while True:\n timestamps = []\n inputs = []\n vel_inputs = []\n labels = []\n rgbs = []\n if random_order or scrambled_range:\n ix = datapoints.sample(n=batch_size).index\n else:\n ix = np.arange(batch_start, batch_start + batch_size)\n ix[ix>=end_idx] = start_idx + ix[ix>=end_idx] % end_idx\n batch_start += batch_size\n if batch_start >= end_idx:\n batch_start = start_idx + batch_start % end_idx\n for timestamp in ix:\n idx, dir_idx = metadata['timestamp_idx'][timestamp]\n # Get the optical flow input\n opt_flow_n = os.path.join(data_dirs[dir_idx][0], 'images',\n 'flow_' + str(timestamp) + '.npz')\n opt_flow = np.load(opt_flow_n)['opt_flow']\n\n # Get the 'collision distance' labels\n coll_dist_n = os.path.join(data_dirs[dir_idx][0], 'images',\n 'misc_' + str(timestamp) + '.npz')\n coll_dist = np.load(coll_dist_n)['arr_0']\n coll_dist *= coll_dist_mul # not sure why the max value seems to be bounded at 0.5...\n coll_dist = coll_dist.flatten()\n\n if include_rgb:\n rgb_n = os.path.join(data_dirs[dir_idx][0], 'images',\n 'rgb_' + str(timestamp) + '.png')\n rgb = cv2.imread(rgb_n)\n rgbs.append(rgb)\n\n if img_resolution is not None:\n opt_flow = cv2.resize(opt_flow, (img_resolution[1], img_resolution[0]))\n if not incl_ang_vel:\n opt_flow = o_f_compensate_for_rotation(opt_flow, metadata['cam_ang_vel'][idx])\n # print(opt_flow.shape)\n timestamps.append(timestamp)\n inputs.append(opt_flow)\n labels.append(np.expand_dims(coll_dist, axis=-1))\n # print('cd:{}'.format(coll_dist.shape))\n if include_motion_data:\n if not incl_ang_vel:\n vel_info = metadata['cam_lin_vel'][idx]\n else:\n vel_info = np.concatenate((metadata['cam_lin_vel'][idx],\n metadata['cam_ang_vel'][idx]),\n axis=-1)\n vel_inputs.append(vel_info)\n timestamps = np.array(timestamps)\n inputs = np.array(inputs)\n if include_motion_data:\n vel_inputs = velocity_form(np.array(vel_inputs))\n # Turn motion vectors into motion 1x1 'images' with vector values as 'channels'\n vel_inputs = np.expand_dims(np.expand_dims(vel_inputs, axis=1), axis=1)\n inputs = [inputs, vel_inputs]\n labels = np.array(labels)\n if include_rgb:\n rgbs = np.array(rgbs)\n yield inputs, bin_pixels(labels, bins), rgbs, timestamps\n elif include_motion_data:\n yield inputs, bin_pixels(labels, bins)\n else:\n yield inputs, bin_pixels(labels, bins)\n\ndef velocity_form(vel_inputs):\n if vel_inputs.ndim == 1:\n vel_inputs = np.expand_dims(vel_inputs, axis=0)\n if velocity_input_mode == 'angle-magnitude':\n mag = np.linalg.norm(vel_inputs[:, 0:3], axis=-1)\n comp_hor = vel_inputs[:, 1] / mag\n comp_ver = vel_inputs[:, 2] / mag\n vel_inputs[:, 0:3] = np.concatenate((np.expand_dims(mag, axis=-1),\n np.expand_dims(comp_hor, axis=-1),\n np.expand_dims(comp_ver, axis=-1)),\n axis=-1)\n return vel_inputs\n\ndef bin_pixels(data, bins):\n '''\n Bins the values of 1-channel pixel data into N pre-defined buckets, and\n returns on-hot-encoded N-channel array corresponding to the result.\n '''\n if bins is None:\n return data\n bin_indices = np.digitize(data, bins) - 1\n result = np.zeros((data.shape[0], data.shape[1], len(bins)))\n \n for bin_idx in range(len(bins)):\n one_hot_indices = np.nonzero(bin_indices==bin_idx)\n one_hot_indices = (one_hot_indices[0],\n one_hot_indices[1],\n bin_idx * np.ones_like(one_hot_indices[0]))\n result[one_hot_indices] = 1\n # print('r{}'.format(result.shape))\n return result\n\ndef data_stats(data_dir, bins, number_for_analysis=None):\n datapoints_csv_name = os.path.join(data_dir, 'airsim_rec.csv')\n datapoints = pd.read_csv(datapoints_csv_name,\n header=None,\n sep=',',\n names=csv_col_names,\n index_col=0)\n if number_for_analysis is None:\n ix = range(datapoints.shape[0])\n else:\n ix = np.random.choice(np.arange(len(datapoints)), number_for_analysis)\n\n single_maxs = []\n single_mins = []\n single_means = []\n single_std_devs = []\n single_sums = []\n\n binned_sums = {}\n for bin_idx in range(len(bins)):\n binned_sums[bin_idx] = 0\n\n for i in tqdm(ix):\n coll_dist_n = os.path.join(data_dir, 'images',\n 'misc_' + str(datapoints.index[i]) + '.npz')\n coll_dist = np.load(coll_dist_n)['arr_0']\n coll_dist *= 2\n\n single_maxs.append(np.max(coll_dist))\n single_mins.append(np.min(coll_dist))\n single_means.append(np.mean(coll_dist))\n single_std_devs.append(np.std(coll_dist))\n single_sums.append(np.sum(coll_dist))\n\n bin_indices = np.digitize(coll_dist, bins) - 1\n\n for bin_idx in range(len(bins)):\n binned_sums[bin_idx] += np.sum(bin_indices==bin_idx)\n\n\n single_maxs = np.array(single_maxs)\n single_mins = np.array(single_mins)\n single_means = np.array(single_means)\n single_std_devs = np.array(single_std_devs)\n single_sums = np.array(single_sums)\n\n print('Min: {}\\n'\n 'Max: {}\\n'\n 'Avg mean: {}\\n'\n 'Max mean: {}\\n'\n 'Min mean: {}\\n'\n 'Avg std: {}\\n'\n 'Max std: {}\\n'\n 'Max sum: {}\\n'\n 'Min sum: {}\\n'\n 'Mean sum: {}\\n'\n 'Median sum: {}\\n'.format(np.min(single_mins),\n np.max(single_maxs),\n np.mean(single_means),\n np.max(single_means),\n np.min(single_means),\n np.mean(single_std_devs),\n np.max(single_std_devs),\n np.max(single_sums),\n np.min(single_sums),\n np.mean(single_sums),\n np.median(single_sums)))\n\n for bin_idx in range(len(bins)):\n print('#{} bin: {}'.format(bin_idx, binned_sums[bin_idx]))\n\n perc = 70\n prec_sum = np.percentile(single_sums, perc)\n sums = single_sums[single_sums>prec_sum]\n print('showing sums bigger than {} ({} of them)'.format(prec_sum, np.size(sums)))\n # plt.hist(sums, bins=40)\n # plt.show()\n\ndef find_focal_len(data_dir, horver=0):\n np.random.seed(777)\n starting_estimate = [100, 100]\n number_for_analysis = 100\n datapoints_csv_name = os.path.join(data_dir, 'airsim_rec.csv')\n datapoints = pd.read_csv(datapoints_csv_name,\n header=None,\n sep=',',\n names=csv_col_names,\n index_col=0)\n ix = np.random.choice(np.arange(len(datapoints)), number_for_analysis)\n\n x0 = [starting_estimate]\n minim_args = (datapoints.iloc[ix],horver)\n optimize = True\n res = None\n if optimize:\n res = minimize(avg_horizontal_flow, x0, args=minim_args, method='Nelder-Mead', tol=1e-3, options={'disp': True})\n else:\n # vals = [100, 125, 150, 175]\n vals = [134]\n for val in vals:\n print('F={} --> mean_OF:{}'.format(val, avg_horizontal_flow(val, datapoints.iloc[ix])))\n return res\n\ndef avg_horizontal_flow(inp, datapoints, horver=0):\n corr_opt_flow_cumul = 0\n for i in range(len(datapoints)):\n opt_flow_n = os.path.join(data_dir, 'images',\n 'flow_' + str(datapoints.index[i]) + '.npz')\n opt_flow = np.load(opt_flow_n)['opt_flow']\n opt_flow = cv2.resize(opt_flow, (256, 144))\n\n corr_opt_flow_cumul += np.mean(np.abs(o_f_compensate_for_rotation(opt_flow,\n datapoints.iloc[i][['AV_x', 'AV_y', 'AV_z']],\n focal=inp[0], xy_scaling=inp[1])[...,horver]))\n\n corr_opt_flow_cumul /= len(datapoints)\n return corr_opt_flow_cumul\n\nif __name__ == '__main__':\n # data_dirs = [[os.path.join('/mnt', 'data', 'AirSimCollectedData', '18-08-07_10-37-26')],\n # [os.path.join('/mnt', 'data', 'AirSimCollectedData', '18-07-23_21-21-59')]]\n data_dir = os.path.join('/mnt', 'data', 'AirSimCollectedData', '18-07-23_23-05-47')\n # with open('metadata_results.pickle', 'wb') as f:\n # mdata = load_optical_flow_metadata(data_dirs, force_metadata_refresh=True, bins=default_bins)\n # pickle.dump(mdata, f)\n res = find_focal_len(data_dir, 0)\n print('0: {}'.format(res))\n # res = find_focal_len(data_dir, 1)\n # print('1: {}'.format(res))\n\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":24362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"168449817","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Bool\nfrom sensor_msgs.msg import LaserScan\n\nclass Avoidar():\n def __init__(self):\n self.sub = rospy.Subscriber('/scan', LaserScan, self.laser_callback)\n self.pub = rospy.Publisher(\"/avoidar_output\", Bool, queue_size=10)\n\n def laser_callback(self, msg):\n right_ranges = msg.ranges[0:29]\n left_ranges = msg.ranges[330:359]\n #print ranges \n #extend(msg.ranges[330:359])\n \n m = Bool()\n m.data = False\n\n for r in right_ranges:\n if r < 0.4:\n m.data = True\n break\n \n if not m.data:\n for r in left_ranges:\n if r < 0.4:\n m.data = True\n break\n self.pub.publish(m)\n\nif __name__ == '__main__':\n rospy.init_node(\"avoidar\")\n n = Avoidar()\n rospy.spin()\n","sub_path":"src/avoidar/avoidar.py","file_name":"avoidar.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"551179218","text":"#!/usr/bin/env python3\n\"\"\"\nOpen example.txt and get sum of all integers\n\"\"\"\n\nimport argparse\nimport sys\n\ndef get_args():\n \"\"\"Get args from command line\"\"\"\n\n parser = argparse.ArgumentParser(description='Find string in example.txt')\n parser.add_argument('-s', '--search-string', dest='given_string',\n help='String to search for in example.txt')\n args = parser.parse_args()\n\n if args.given_string is None:\n print(\"No search string provided. Use -h for more info.\")\n sys.exit()\n else:\n return (args.given_string)\n\n\ndef open_file(filename):\n \"\"\" Open file for reading \"\"\"\n try:\n file_handle = open(filename)\n return file_handle\n except IOError:\n print(\"File not found or path is incorrect\")\n\n\ndef close_file(fhandle):\n \"\"\" Close file \"\"\"\n fhandle.close()\n\n\ndef search_string(file_handle, given_string):\n \"\"\" Parse through file and find given string \"\"\"\n total_sum = 0\n for line in file_handle:\n word_list = []\n line_words = line.split()\n for word in line_words:\n word = word.replace(',', '')\n if word == given_string:\n return True\n\n\nif __name__ == '__main__':\n given_string = get_args()\n file_handle = open_file(\"example.txt\")\n if search_string(file_handle, given_string):\n print(\"The string has been found!\")\n else:\n print(\"String not found\")\n","sub_path":"chapter2/fileread_ex3.py","file_name":"fileread_ex3.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"338935253","text":"from dateutil.relativedelta import relativedelta\nfrom edc_visit_schedule import (\n Crf,\n FormsCollection,\n Requisition,\n Schedule,\n Visit,\n VisitSchedule,\n)\nfrom edc_visit_schedule.tests.dummy_panel import DummyPanel\n\n\nclass MockPanel(DummyPanel):\n \"\"\"`requisition_model` is normally set when the lab profile\n is set up.\n \"\"\"\n\n def __init__(self, name):\n super().__init__(requisition_model=\"edc_appointment.subjectrequisition\", name=name)\n\n\npanel_one = MockPanel(name=\"one\")\npanel_two = MockPanel(name=\"two\")\npanel_three = MockPanel(name=\"three\")\npanel_four = MockPanel(name=\"four\")\npanel_five = MockPanel(name=\"five\")\npanel_six = MockPanel(name=\"six\")\n\ncrfs = FormsCollection(\n Crf(show_order=1, model=\"edc_metadata.crfone\", required=True),\n Crf(show_order=2, model=\"edc_metadata.crftwo\", required=True),\n Crf(show_order=3, model=\"edc_metadata.crfthree\", required=True),\n Crf(show_order=4, model=\"edc_metadata.crffour\", required=True),\n Crf(show_order=5, model=\"edc_metadata.crffive\", required=True),\n)\n\nrequisitions = FormsCollection(\n Requisition(show_order=10, panel=panel_one, required=True, additional=False),\n Requisition(show_order=20, panel=panel_two, required=True, additional=False),\n Requisition(show_order=30, panel=panel_three, required=True, additional=False),\n Requisition(show_order=40, panel=panel_four, required=True, additional=False),\n Requisition(show_order=50, panel=panel_five, required=True, additional=False),\n Requisition(show_order=60, panel=panel_six, required=True, additional=False),\n)\n\n\ncrfs_unscheduled = FormsCollection(\n Crf(show_order=1, model=\"edc_metadata.crfone\", required=True),\n Crf(show_order=3, model=\"edc_metadata.crfthree\", required=True),\n Crf(show_order=5, model=\"edc_metadata.crffive\", required=True),\n)\n\n\nvisit_schedule1 = VisitSchedule(\n name=\"visit_schedule1\",\n offstudy_model=\"edc_export.subjectoffstudy\",\n death_report_model=\"edc_export.deathreport\",\n locator_model=\"edc_export.subjectlocator\",\n)\n\nschedule1 = Schedule(\n name=\"schedule1\",\n onschedule_model=\"edc_export.onscheduleone\",\n offschedule_model=\"edc_export.offscheduleone\",\n appointment_model=\"edc_appointment.appointment\",\n consent_model=\"edc_export.subjectconsent\",\n)\n\n\nvisits = []\nfor index in range(0, 4):\n visits.append(\n Visit(\n code=f\"{index + 1}000\",\n title=f\"Day {index + 1}\",\n timepoint=index,\n rbase=relativedelta(days=index),\n rlower=relativedelta(days=0),\n rupper=relativedelta(days=6),\n requisitions=requisitions,\n crfs=crfs,\n requisitions_unscheduled=requisitions,\n crfs_unscheduled=crfs_unscheduled,\n allow_unscheduled=True,\n facility_name=\"5-day-clinic\",\n )\n )\nfor visit in visits:\n schedule1.add_visit(visit)\n\nvisits = []\nfor index in range(4, 8):\n visits.append(\n Visit(\n code=f\"{index + 1}000\",\n title=f\"Day {index + 1}\",\n timepoint=index,\n rbase=relativedelta(days=index),\n rlower=relativedelta(days=0),\n rupper=relativedelta(days=6),\n requisitions=requisitions,\n crfs=crfs,\n facility_name=\"7-day-clinic\",\n )\n )\nvisit_schedule1.add_schedule(schedule1)\n","sub_path":"edc_export/tests/visit_schedule.py","file_name":"visit_schedule.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"415527109","text":"# -*- coding: utf-8 -*-\n\nfrom fontbakery.fonts_spec import spec_factory # NOQA pylint: disable=unused-import\nspec_imports = (\n ('.', ('general', 'cmap', 'head', 'os2', 'post', 'name',\n 'hhea', 'dsig', 'hmtx', 'gpos', 'gdef', 'kern', 'glyf',\n 'prep', 'fvar', 'shared_conditions')\n ),\n)\n\n","sub_path":"Lib/fontbakery/specifications/opentype.py","file_name":"opentype.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"616436086","text":"import sys\n\nif __name__ == '__main__':\n \n X = int(sys.stdin.readline().strip())\n N = int(sys.stdin.readline().strip())\n \n #AQUI SE DEBEN PROCESAR X y N para calcular el saldo final\n \n # OJO QUE, DADO UN N, DEBEN LEER LAS LINEAS RESTANTES DEL ARCHIVO\n\n # LUEGO, SE SUGIERE CREAR UNA FUNCION QUE TOME LOS DATOS DEL PROBLEMA, y entregue el saldo final\n\n\t# FINALMENTE, SE DEBE IMPRIMIR DICHO SALDO\n\n","sub_path":"Tareas/Tarea 3/Material/tarifa_base.py","file_name":"tarifa_base.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"101652179","text":"import os, sys\nfrom sqlalchemy import select\nfrom . import TimeHelper\nfrom .app import config\nfrom .models import (\n automated_reports,\n automated_report_contacts,\n automated_report_recipients,\n report_logs\n)\nfrom .mailer import Mailer\nfrom .related_record import RelatedRecord\nfrom .queries import QueryGenerator\nfrom .xlsx import WorkbookBuilder\nfrom .logger import PortholeLogger\n\nlogger = PortholeLogger(name=__name__)\n\n\nclass Loggable(object):\n \"\"\"\n Inherit from this class to implement basic error logging. If derived class\n overrides __init__, it must invoke Loggable.__init__() or super().__init__().\n Args:\n log_to (list): Specify where logged errors should go. Intended to route\n errors from several different types of Loggable objects to one\n place.\n Usage\n\n class Component(Loggable):\n def __init__(self, log_to=[]):\n super().__init__(log_to=log_to)\n\n class Report(object):\n def __init__(self):\n self.error_log = []\n self.component = Component(log_to=self.error_log)\n \"\"\"\n def __init__(self, log_to=None):\n self.error_log = log_to if log_to is not None else []\n\n def log_error(self, msg=None):\n \"\"\"\n Args:\n msg (str) Optional. Appends msg and exception context to error_log\n list as an attribute of the object.\n \"\"\"\n if not hasattr(self, 'error_log'):\n self.error_log = []\n error_value = sys.exc_info()[1]\n log_record = str(error_value) + ': ' + str(error_value.__doc__)\n if msg:\n log_record = msg + ': ' + log_record\n self.error_log.append(log_record)\n\n\nclass ReportWriter(Loggable):\n \"\"\"\n The purpose of this class is to use the QueryGenerator and WorkbookBuilder\n together to make an Excel file and populate it with data.\n \"\"\"\n #TODO: Think of a better name for this class.\n\n def __init__(self, report_title, log_to=None):\n self.report_title = report_title\n self.report_file = None\n self.file_path = config['Default'].get('base_file_path')\n self.workbook_builder = None\n self.record_count = 0\n super().__init__(log_to=log_to if log_to is not None else [])\n\n def build_file(self):\n \"\"\"\n Loads file and path information and creates XLSX Writer Workbook object.\n Default file is named with convention yyyy-mm-dd - Report Name.xlsx\n \"\"\"\n try:\n # Construct the file path and create the workbook.\n local_timezone = config['Default'].get('local_timezone') or 'UTC'\n today = TimeHelper.today(timezone=local_timezone)\n report_file_name = f\"{today} - {self.report_title}.xlsx\"\n self.report_file = os.path.join(self.file_path, report_file_name)\n self.workbook_builder = WorkbookBuilder(filename=self.report_file)\n except:\n error = \"Unable to build file for {}\".format(self.report_title)\n logger.error(error)\n self.log_error(error)\n\n def close_workbook(self):\n \"\"\"\n Closes workbook object after creation is complete.\n Should always be executed before sending file.\n \"\"\"\n if self.workbook_builder:\n self.workbook_builder.workbook.close()\n\n def add_format(self, format_name, format_params):\n self.workbook_builder.add_format(format_name, format_params)\n\n def execute_query(self, cm, query={}, sql=None, increment_counter=True):\n \"\"\"\n Args:\n cm (ConnectionManager):\n Object which contains connection to desired database.\n sheet_name (str): The name of the worksheet to be created.\n query (dict): Optional. May contain filename and params for a query\n to be executed. If included, filename is required.\n filename (str): Name of file to be read without extension.\n params (dict): Optional. Contains parameter names and values,\n if applicable. Should only be included along with\n query_file containing parameter placeholders.\n sql (str or sqlalchemy.sql.selectable.Select statement):\n Optional. A SQL query ready for execution.\n\n Executes SQL and returns QueryResult object, containing data and metadata.\n \"\"\"\n filename = query.get('filename')\n params = query.get('params')\n q = QueryGenerator(cm=cm, filename=filename, params=params, sql=sql)\n try:\n results = q.execute()\n if increment_counter:\n self.record_count += results.result_count\n return results\n except:\n error = \"Unable to execute query {}\".format(query.get('filename'))\n logger.error(error)\n self.log_error(error)\n\n def make_worksheet(self, sheet_name, query_results, **kwargs):\n \"\"\"Adds worksheet to workbook using provided query results.\"\"\"\n try:\n self.workbook_builder.add_worksheet(\n sheet_name=sheet_name,\n field_names=query_results.field_names,\n sheet_data=query_results.result_data,\n **kwargs\n )\n except:\n error = \"Unable to add worksheet {}\".format(sheet_name)\n logger.error(error)\n self.log_error(error)\n\n def create_worksheet_from_query(self, cm, sheet_name, query=None, sql=None, query_kwargs=None, worksheet_kwargs=None):\n \"\"\"\n Args:\n cm (ConnectionManager):\n Object which contains connection to desired database.\n sheet_name (str): The name of the worksheet to be created.\n query (dict): Optional. May contain filename and params for a query\n to be executed. If included, filename is required.\n filename (str): Name of file to be read without extension.\n params (dict): Optional. Contains parameter names and values,\n if applicable. Should only be included along with\n query_file containing parameter placeholders.\n sql (str or sqlalchemy.sql.selectable.Select statement):\n Optional. A SQL query ready for execution.\n query_kwargs (dict): Optional. Dictionary of keyword arguments to pass to `execute_query`.\n worksheet_kwargs (dict): Optional. Dictionary of keyword arguments to pass to `make_worksheet`\n\n Executes a query and uses results to add worksheet to ReportWriter.workbook_builder.\n \"\"\"\n if query is None:\n query = {}\n if query_kwargs is None:\n query_kwargs = {}\n if worksheet_kwargs is None:\n worksheet_kwargs = {}\n results = self.execute_query(cm=cm, query=query, sql=sql, **query_kwargs)\n self.make_worksheet(sheet_name=sheet_name, query_results=results, **worksheet_kwargs)\n\n\nclass DatabaseLogger(Loggable):\n \"\"\"\n Don't want to log if report not active,\n or if logging is not enabled.\n \"\"\"\n def __init__(self, cm, report_name, log_to=None, log_table='report_logs'):\n self.cm = cm\n self.report_name = report_name\n self.log_table = log_table\n super().__init__(log_to=log_to if log_to is not None else [])\n\n def create_record(self):\n \"\"\"\n Inserts new log record into default report logging table\n using RelatedRecord and saves instance of RelatedRecord for updating\n later on with results of report execution.\n \"\"\"\n report_log = RelatedRecord(self.cm, self.log_table)\n try:\n report_log.insert({'report_name': self.report_name,\n 'started_at': TimeHelper.now(string=False)})\n except:\n self.log_error(\"Unable to create log record.\")\n self.report_log = report_log\n\n def finalize_record(self):\n \"\"\"Update log at conclusion of report execution to indicate success/failure.\"\"\"\n if self.error_log:\n data_to_update = {'completed_at': TimeHelper.now(string=False),\n 'success': 0,\n 'error_detail': \"; \".join(self.error_log)}\n else:\n data_to_update = {'completed_at': TimeHelper.now(string=False),\n 'success': 1}\n try:\n self.report_log.update(data_to_update)\n except:\n self.log_error(\"Unable to finalize log record.\")\n\n\nclass ReportActiveChecker(Loggable):\n\n def __init__(self, cm, report_name, log_to=None):\n self.cm = cm\n self.report_name = report_name\n self.active = False\n super().__init__(log_to=log_to if log_to is not None else [])\n self.check_if_active()\n\n def __bool__(self):\n return self.active\n\n def check_if_active(self):\n \"\"\"Queries database to determine if the 'active' attribute for this report\n is set to 1 (active) or 0 (inactive).\n \"\"\"\n statement = select([automated_reports.c.active])\\\n .where(automated_reports.c.report_name==self.report_name)\n try:\n q = QueryGenerator(cm=self.cm, sql=statement)\n results = q.execute()\n if results.result_data[0]['active'] == 1:\n self.active = True\n else:\n self.active = False\n except IndexError:\n error = (\n f\"Report <{self.report_name}> was not found in the {automated_reports.name} table. \"\n f\"Ensure <{self.report_name}> matches a record in the table and try again.\"\n )\n logger.error(error)\n self.log_error(error)\n raise Exception(error)\n\n\nclass RecipientsChecker(Loggable):\n def __init__(self, cm, report_name, log_to=None):\n self.cm = cm\n self.report_name = report_name\n self.to_recipients = []\n self.cc_recipients = []\n super().__init__(log_to=log_to if log_to is not None else [])\n\n def get_recipients(self):\n \"\"\"Performs lookup in database for report recipients based on report name.\"\"\"\n statement = select([automated_report_contacts.c.email_address,\n automated_report_recipients.c.recipient_type])\\\n .select_from(automated_reports\\\n .join(automated_report_recipients)\\\n .join(automated_report_contacts))\\\n .where(automated_reports.c.report_name==self.report_name)\n try:\n q = QueryGenerator(cm=self.cm, sql=statement)\n results = q.execute()\n for recipient in results.row_proxies:\n if recipient.recipient_type == 'to':\n self.to_recipients.append(recipient.email_address)\n else:\n self.cc_recipients.append(recipient.email_address)\n except:\n error = \"Error getting recipients for {}\".format(self.report_name)\n logger.error(error)\n self.log_error(error)\n if not self.to_recipients:\n error = \"No primary recipient found for {}\".format(self.report_name)\n logger.error(error)\n raise KeyError(\"No primary recipient found for {}\".format(self.report_name))\n return self.to_recipients, self.cc_recipients\n\n\nclass ReportErrorNotifier(object):\n\n def __init__(self, report_title, error_log):\n self.report_title = report_title\n self.notification_recipient = config['Default'].get('notification_recipient')\n self.error_log = error_log\n self.notified = False\n\n def send_log_by_email(self):\n email = Mailer()\n email.recipients = [self.notification_recipient]\n email.cc_recipients = ['']\n email.subject = \"Report Failure: {}\".format(self.report_title)\n email.message = self.construct_message()\n email.attachments = []\n email.send_email()\n self.notified = True\n\n def construct_message(self):\n msg = \"\"\"Execution of the following report failed: {}\n\nThe following errors were logged:\\n\"\"\".format(self.report_title)\n msg = msg.format(self.report_title)\n for i, error in enumerate(self.error_log, 1):\n msg += str(i) + '. ' + error + '\\n'\n return msg\n","sub_path":"porthole/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":12638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"252722855","text":"from setuptools import setup, find_packages\n\nrequirements = [\n \"keras\",\n \"tensorflow \",\n \"scikit-learn\",\n \"keras-rectified-adam\",\n \"numpy\",\n \"joblib\",\n]\n\nwith open(\"README.md\", \"r\") as f:\n LONG_DESCRIPTION = f.read()\n\n\n\nsetup(\n name=\"proglearn\",\n version=\"0.0.1\",\n author=\"Will Levine, Jayanta Dey, Hayden Helm\",\n author_email=\"levinewill@icloud.com\",\n description=\"A package to implement and extend the methods desribed in 'A General Approach to Progressive Learning'\",\n long_description=LONG_DESCRIPTION,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/neurodata/progressive-learning/\",\n license=\"Apache 2.0\",\n packages=find_packages(),\n install_requires=requirements,\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"582528605","text":"\"\"\"\nCommom strategies of trading\n\"\"\"\nimport utils\nimport numpy as np\n\n\"\"\"\nMACD signal, when macd cross 0 line signal positive, otherwise negative\n---\ndata: Input data with close price\n\"\"\"\ndef get_macd_signal(data):\n macd = utils.get_macd(data)\n sig = [1 if x > 0 else 0 for x in macd]\n return np.array(sig)\n\n\n\"\"\"\nMACD and MACDS crossover signal, when macd cross macds line signals positive, otherwise negative\n---\ndata: Input data with close price\n\"\"\"\ndef get_macds_signal(data):\n macd = utils.get_macd(data)\n macds = utils.get_macds(data)\n macd_diff = macd - macds\n sig = [1 if x > 0 else 0 for x in macd_diff]\n return np.array(sig)\n\n\n\"\"\"\nSingle moving average signals, when close price crosses sma line signals positive, otherwise negative\n---\ndata: Input data with close price and moving average period\n\"\"\"\ndef get_ema_signal(data, period=10):\n sma = utils.get_sma(data, period)\n diff = data[\"close\"].values - sma\n sig = [1 if x > 0 else 0 for x in diff]\n return np.array(sig)\n\n\"\"\"\nMoving average crossover signals, when shorter crosses longer line signals positive, otherwise negative\n---\ndata: Input data with close price and moving average period\n\"\"\"\ndef get_ema_cs_signal(data, period=[5, 10]):\n assert len(period) == 2\n min_sma = utils.get_sma(data, min(period))\n max_sma = utils.get_sma(data, max(period))\n sma_diff = min_sma - max_sma\n sig = [1 if x > 0 else 0 for x in sma_diff]\n return np.array(sig)\n\n\"\"\"\nRSI signal, when over upper bound is overbought signal and below lower bound is oversold signal.\n---\ndata: Input data with close price and RSI\n\"\"\"\ndef get_rsi_signal(data, period=14, bound=[30, 70]):\n rsi = utils.get_rsi(data, period)\n sig = []\n for r in rsi:\n if r >= max(bound):\n sig.append(-1)\n elif r <= min(bound):\n sig.append(1)\n else:\n sig.append(0)\n return np.array(sig)\n\n","sub_path":"utilities/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"436641701","text":"# foods = [ 'apples', 'bread', 'cheese', 'milk']\n\n# for food in foods:\n# if food == 'bread':\n# print(\"hay que comprar bread\")\n# break\n# print(food)\n\n# for food in foods:\n# if food == 'bread':\n# print(\"hay que comprar bread\")\n# continue\n# print(food)\n\n# for number in range(1, 8):\n# print(number)\n\n# for letter in \"Hola KC\":\n# print(letter)\n\ncount = 1\nwhile count <=10:\n print(count)\n count = count +1","sub_path":"inicial/loops.py","file_name":"loops.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"253885983","text":"\"\"\"\nFunctional tests for chocolatey state\n\"\"\"\nimport os\nimport pathlib\n\nimport pytest\n\nimport salt.utils.path\nimport salt.utils.win_reg\n\npytestmark = [\n pytest.mark.windows_whitelisted,\n pytest.mark.skip_unless_on_windows,\n pytest.mark.slow_test,\n pytest.mark.destructive_test,\n pytest.mark.skip_on_windows,\n]\n\n\n@pytest.fixture(scope=\"module\")\ndef chocolatey(states):\n yield states.chocolatey\n\n\n@pytest.fixture(scope=\"module\")\ndef chocolatey_mod(modules):\n\n current_path = salt.utils.win_reg.read_value(\n hive=\"HKLM\",\n key=r\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\",\n vname=\"PATH\",\n )[\"vdata\"]\n url = \"https://community.chocolatey.org/api/v2/package/chocolatey/\"\n with pytest.helpers.temp_file(name=\"choco.nupkg\") as nupkg:\n choco_pkg = pathlib.Path(str(nupkg))\n choco_dir = choco_pkg.parent / \"choco_dir\"\n choco_script = choco_dir / \"tools\" / \"chocolateyInstall.ps1\"\n\n def install():\n # Install Chocolatey 1.2.1\n\n # Download Package\n modules.cp.get_url(path=url, dest=str(choco_pkg))\n\n # Unzip Package\n modules.archive.unzip(\n zip_file=str(choco_pkg),\n dest=str(choco_dir),\n extract_perms=False,\n )\n\n # Run installer script\n assert choco_script.exists()\n result = modules.cmd.script(\n source=str(choco_script),\n cwd=str(choco_script.parent),\n shell=\"powershell\",\n python_shell=True,\n )\n assert result[\"retcode\"] == 0\n\n def uninstall():\n choco_dir = os.environ.get(\"ChocolateyInstall\", False)\n if choco_dir:\n # Remove Chocolatey Directory\n modules.file.remove(path=choco_dir, force=True)\n # Remove Chocolatey Environment Variables\n for env_var in modules.environ.items():\n if env_var.lower().startswith(\"chocolatey\"):\n modules.environ.setval(\n key=env_var, val=False, false_unsets=True, permanent=\"HKLM\"\n )\n modules.environ.setval(\n key=env_var, val=False, false_unsets=True, permanent=\"HKCU\"\n )\n salt.utils.win_reg.set_value(\n hive=\"HKLM\",\n key=r\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\",\n vname=\"PATH\",\n vdata=current_path,\n )\n modules.win_path.rehash()\n\n # Remove unknown version\n if salt.utils.path.which(\"choco.exe\"):\n uninstall()\n\n # Install known version\n install()\n\n yield modules.chocolatey\n\n # Remove\n uninstall()\n\n\n@pytest.fixture(scope=\"function\")\ndef clean(chocolatey_mod):\n chocolatey_mod.uninstall(name=\"vim\", force=True)\n yield\n chocolatey_mod.uninstall(name=\"vim\", force=True)\n\n\n@pytest.fixture(scope=\"function\")\ndef vim(chocolatey_mod):\n chocolatey_mod.install(name=\"vim\", version=\"9.0.1672\")\n yield\n chocolatey_mod.uninstall(name=\"vim\", force=True)\n\n\ndef test_installed_latest(clean, chocolatey, chocolatey_mod):\n chocolatey.installed(name=\"vim\")\n result = chocolatey_mod.version(name=\"vim\")\n assert \"vim\" in result\n\n\ndef test_installed_version(clean, chocolatey, chocolatey_mod):\n chocolatey.installed(name=\"vim\", version=\"9.0.1672\")\n result = chocolatey_mod.version(name=\"vim\")\n assert \"vim\" in result\n assert result[\"vim\"][\"installed\"][0] == \"9.0.1672\"\n\n\ndef test_uninstalled(vim, chocolatey, chocolatey_mod):\n chocolatey.uninstalled(name=\"vim\")\n result = chocolatey_mod.version(name=\"vim\")\n assert \"vim\" not in result\n\n\ndef test_upgraded(vim, chocolatey, chocolatey_mod):\n result = chocolatey_mod.version(name=\"vim\")\n assert \"vim\" in result\n assert result[\"vim\"][\"installed\"][0] == \"9.0.1672\"\n chocolatey.upgraded(name=\"vim\", version=\"9.0.1677\")\n result = chocolatey_mod.version(name=\"vim\")\n assert \"vim\" in result\n assert result[\"vim\"][\"installed\"][0] == \"9.0.1677\"\n","sub_path":"tests/pytests/functional/states/test_chocolatey_latest.py","file_name":"test_chocolatey_latest.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"475102469","text":"import asyncio\n\nimport aiocoap\nimport pytest\nfrom marshmallow import ValidationError\n\nfrom climate.sensor import Sensor, SensorSchema\n\n\n@pytest.fixture()\ndef schema():\n return SensorSchema()\n\n\ndef test_should_convert_sensor_to_dict():\n sensor = Sensor(mac='AA:BB:CC:DD:EE:FF', ip='192.168.0.1')\n\n assert sensor.as_dict() == {'mac': 'AA:BB:CC:DD:EE:FF', 'ip': '192.168.0.1'}\n\n\ndef test_should_pass_on_schema_conversion(sensor, schema):\n sensor, errors = schema.load({'mac': 'AA:BB:CC:DD:EE:FF', 'ip': '192.168.0.1'})\n\n assert not errors\n\n\ndef test_should_fail_on_schema_conversion(schema):\n with pytest.raises(ValidationError) as ex:\n schema.load({'ip': '127.0.1', 'mac': ''})\n\n assert ex.message\n assert 'mac' in ex.message\n assert 'ip' in ex.message\n\n\ndef test_should_make_sensor(schema):\n sensor = schema.load({'mac': 'a1:b2:c3:d4:e4:f6', 'ip': '8.8.8.8'}).data\n\n assert sensor.mac == 'a1:b2:c3:d4:e4:f6'\n assert sensor.ip == '8.8.8.8'\n\n\ndef test_should_return_temperature(event_loop, site, sensor):\n event_loop.set_debug(True)\n asyncio.set_event_loop(event_loop)\n\n server = event_loop.run_until_complete(aiocoap.Context.create_server_context(site))\n try:\n response = event_loop.run_until_complete(sensor.temperature())\n\n assert response == 10.0\n finally:\n event_loop.run_until_complete(server.shutdown())\n event_loop.stop()\n event_loop.close()\n","sub_path":"tests/test_sensor.py","file_name":"test_sensor.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"294657374","text":"from daftlistings import Daft, SaleType, HouseType\n\ndaft = Daft()\ndaft.set_listing_type(SaleType.HOUSES)\ndaft.set_house_type(HouseType.DETACHED)\n\nlistings = daft.search(fetch_all=False)\n\nfor listing in listings:\n print(listing.formalised_address)\n print(listing.daft_link)\n print(listing.price)\n print(\" \")\n","sub_path":"examples/house_by_type.py","file_name":"house_by_type.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185437862","text":"\"\"\"\nPubAnnotation generator for COVID-19\n\nAuthors:\n Annie Tallind, Lund University, Faculty of Engineering\n Kaggle ID: atllnd\n Github ID: annietllnd\n\n Sofi Flink, Lund University, Faculty of Engineering\n Kaggle ID: sofiflinck\n Github ID: obakanue\n\"\"\"\n\n\ndef construct_pubannotation(metadata_info, section_index, text, denotation):\n \"\"\"\n Returns a string in pub-annotation format.\n \"\"\"\n cord_uid = \"\\n\".ljust(4) + \"\\\"cord_uid\\\": \\\"\" + metadata_info[0] + \"\\\",\"\n\n source_x = \"\\n\".ljust(4) + \"\\\"sourcedb\\\": \\\"\" + metadata_info[1] + \"\\\",\"\n\n pmcid = \"\\n\".ljust(4) + \"\\\"sourceid\\\": \\\"\" + metadata_info[2] + \"\\\",\"\n\n divid = \"\\n\".ljust(4) + \"\\\"divid\\\": \" + str(section_index) + \",\"\n\n text = \"\\n\".ljust(4) + \"\\\"text\\\": \\\"\" + text.replace('\"', '\\\\\"') + \"\\\",\"\n\n project = \"\\n\".ljust(4) + \"\\\"project\\\": \\\"cdlai_CORD-19\\\", \"\n\n denotations_str = \"\\n\".ljust(4) + \"\\\"denotations\\\": \" + denotation\n\n return \"{\" + cord_uid + source_x + pmcid + divid + text + project + denotations_str + \"}\"\n\n\ndef concat_denotations(denotations):\n \"\"\"\n Returns a complete denotation string of all separate denotations in\n list parameter, or an empty string if there where no elements in the\n list.\n \"\"\"\n if not bool(denotations):\n return '[]'\n\n full_denotation = ''\n\n for denotation in denotations:\n if denotation == denotations[-1]:\n full_denotation += denotation\n else:\n full_denotation += denotation + \",\"\n return \"[\" + full_denotation + \"\\n\".ljust(4) + \"]\\n\"\n\n\ndef construct_denotation(obj, begin, end, idd):\n \"\"\"\n Returns a string denotation for a single match.\n \"\"\"\n obj = \"\\n\".ljust(12) + \"\\\"obj\\\": \\\"\" + obj + \"\\\"\"\n\n span = \"\\n\".ljust(12) + \"\\\"span\\\": {\\n\".ljust(24) + \"\\\"begin\\\":\" + begin + \",\\n\".ljust(16) + \"\\\"end\\\": \" + end + \\\n \"\\n\".ljust(12) + \"}, \"\n\n idd = \"\\n\".ljust(12) + \"\\\"id\\\": \\\"\" + idd + \"\\\",\"\n denotation = \"\\n\".ljust(8) + \"{\" + idd + span + obj + \"\\n\".ljust(8) + \"}\"\n return denotation\n\n\ndef print_progress(nbr_pubannotations_processed, total_pubannotations):\n \"\"\"\n Prints estimated progress based on number of total articles and number of articles processed.\n \"\"\"\n print_progress_bar(nbr_pubannotations_processed, total_pubannotations, prefix='GENERATOR PROGRESS\\t',\n suffix='COMPLETE')\n\n\ndef print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):\n \"\"\"\n Author: StackOverflow\n User Greenstick\n Question 30740258\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filled_length = int(length * iteration // total)\n bar = fill * filled_length + '-' * (length - filled_length)\n print('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='', flush=True)\n # Print New Line on Complete\n if iteration == total:\n print()\n\n\ndef get_paragraph_denotation(paragraph_matches, url):\n \"\"\"\n Constructs complete string denotation for a paragraph.\n \"\"\"\n denotations = []\n for match in paragraph_matches:\n denotations.append(construct_denotation(paragraph_matches[match],\n str(match.start()),\n str(match.end()), url))\n return concat_denotations(denotations)\n\n\nclass PubannotationGenerator:\n def __init__(self, pubannotations_dict, output_dir_path):\n self.pubannotations_dict = pubannotations_dict\n self.output_dir_path = output_dir_path\n\n def generate(self):\n pubannotation_nbr = 0\n pubannotations_total = len(self.pubannotations_dict)\n for pubannotation_key in self.pubannotations_dict:\n print_progress(pubannotation_nbr, pubannotations_total)\n denotation = get_paragraph_denotation(self.pubannotations_dict[pubannotation_key]['matches'],\n self.pubannotations_dict[pubannotation_key]['url'])\n # if not re.fullmatch(r'\\[\\]', denotation): # Uncomment in order to filter out only matches\n annotation = construct_pubannotation(self.pubannotations_dict[pubannotation_key]['metadata_info'],\n self.pubannotations_dict[pubannotation_key]['file_index'],\n self.pubannotations_dict[pubannotation_key]['paragraph_text'],\n denotation)\n self.__export_pubannotation(self.pubannotations_dict[pubannotation_key]['metadata_info'][0],\n self.pubannotations_dict[pubannotation_key]['file_index'],\n self.pubannotations_dict[pubannotation_key]['section_name'],\n annotation)\n pubannotation_nbr += 1\n print_progress(pubannotation_nbr, pubannotations_total)\n\n def __export_pubannotation(self, idd, file_index, section, annotation):\n \"\"\"\n Export pub-annotation string to corresponding section file.\n \"\"\"\n file_name = idd + '-' + str(file_index) + '-' + section\n full_path = self.output_dir_path + file_name + '.json'\n text_file = open(full_path, 'wt')\n text_file.write(annotation)\n text_file.close()\n","sub_path":"src/pubannotationgenerator.py","file_name":"pubannotationgenerator.py","file_ext":"py","file_size_in_byte":5946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"2544957","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef get_mat(dataset):\r\n # 清洗数据集\r\n # 输入:数据集\r\n # 输出:数据集的特征矩阵x_mat 标签矩阵y_mat(单列)\r\n # 矩阵好运算,所以转化成为mat\r\n x_mat = np.mat(dataset.iloc[:, :-1].values)\r\n y_mat = np.mat(dataset.iloc[:, -1].values).T\r\n return x_mat, y_mat\r\n\r\n\r\ndef plot_raw_data(dataset):\r\n # 绘制样本数的散点图\r\n x_mat, y_mat = get_mat(dataset)\r\n # .A操作将原矩阵转化为List,scatter散点图\r\n plt.scatter(x_mat.A[:, 1], y_mat.A, c='b', s=5)\r\n\r\n\r\ndef linear_regression(dataset):\r\n # 用普通最小二乘OLS计算回归系数估计\r\n # 输入:dataset\r\n # 输出:回归系数估计\r\n x_mat, y_mat = get_mat(dataset)\r\n xTx = x_mat.T * x_mat\r\n if np.linalg.det(xTx) == 0:\r\n print('矩阵不可逆 ')\r\n return\r\n ws = xTx.I * (x_mat.T * y_mat)\r\n return ws\r\n\r\n\r\ndef plot_linear_regression(dataset):\r\n # 用红线绘制回归模型,模型输入本应是规则数,此处懒得再变\r\n # 输入:dataset\r\n # 输出:红色标注的回归模型图像\r\n x_mat, y_mat = get_mat(dataset)\r\n ws = linear_regression(dataset)\r\n y_hat_mat = x_mat * ws\r\n plt.plot(x_mat[:, 1], y_hat_mat, c='r')\r\n\r\n\r\ndef assess_corrcoef(dataset):\r\n # 计算相关系数\r\n # 输入:dataset\r\n # 输出:相关系数R^2\r\n x_mat, y_mat = get_mat(dataset)\r\n ws = linear_regression(dataset)\r\n y_hat_mat = x_mat * ws\r\n cof = np.corrcoef(y_hat_mat.T, y_mat.T)\r\n return cof\r\n\r\n\r\ndef linear_regression_plt_assess():\r\n file = pd.read_table('ex0.txt', header=None) # 打开数据集\r\n plot_raw_data(file) # 绘制原始数据的散点图\r\n plot_linear_regression(file) # 绘制回归曲线\r\n cof = assess_corrcoef(file) # 计算相关系数,越接近1,则拟合程度越好\r\n plt.title(('Linear Regression, cof = %f' % cof[1][0]))\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n linear_regression_plt_assess()\r\n","sub_path":"LinearRegression_plt_assess.py","file_name":"LinearRegression_plt_assess.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"618676720","text":"from app import app, db\nfrom app.models import Task\n\ndb.drop_all()\ndb.create_all()\n\ntasks = [\n 'Eat some food',\n 'Listen to some music',\n 'Read a book',\n]\n\nfor task in tasks:\n new_task = Task(name=task, description='')\n db.session.add(new_task)\ndb.session.commit()","sub_path":"setup_db.py","file_name":"setup_db.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"125466943","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib import messages\nfrom django.contrib.auth.views import logout\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import RedirectView\nfrom django.views.generic import View\n\nfrom apps.common.manage_mixins import LoginRequiredMixin\nfrom apps.home.views import validate_login\nfrom apps.user.forms import LoginForm\n\n\nclass ManagerLoginView(View):\n form_class = LoginForm\n template_name = 'login.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class()\n return render(request, self.template_name, locals())\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n # 获取用户名,密码\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n # 验证登录\n user = validate_login(request, username, password)\n if user.id:\n if user.is_staff:\n return redirect(request.GET.get('next', reverse('blog:manage_list')))\n else:\n messages.warning(request, '您不是管理人员,无权登陆')\n else:\n messages.warning(request, '用户名或密码错误')\n else:\n messages.warning(request, '数据验证失败')\n\n return render(request, self.template_name, locals())\n\n\nclass ManagerLogoutView(LoginRequiredMixin, RedirectView):\n permanent = False\n query_string = True # 是否将GET 的查询字符串一起传递给新的地址\n pattern_name = 'user:login' # 重定向的目标URL模式的名称\n\n def get_redirect_url(self, *args, **kwargs):\n # 用户注销\n logout(self.request)\n return super(ManagerLogoutView, self).get_redirect_url(*args, **kwargs)","sub_path":"apps/user/manage_views.py","file_name":"manage_views.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"423685252","text":"import sys\r\nimport math\r\n\r\ndef sign(p):\r\n if p< 0:\r\n return -1\r\n elif p>0:\r\n return 1\r\n else:\r\n return 0\r\n\r\ndef solver(string):\r\n \r\n \r\n return 0\r\n\r\nif __name__ == \"__main__\":\r\n fid = sys.stdin\r\n if len(sys.argv) >= 2:\r\n fname = sys.argv[1]\r\n if fname != '-':\r\n fid = open(fname)\r\n output = open('A_TEST.out','w')\r\n T = int(fid.readline().strip())#the number for test cases\r\n #some settings code\r\n \r\n \r\n for _t in xrange(T):\r\n r,t = map(long, fid.readline().strip().split(' '))\r\n ans = int(2*t/((2*r-1)+math.sqrt((2*r-1)*(2*r-1)+8*t)))\r\n output.write(\"Case #%d: %d\\n\" % (_t+1,ans))\r\n \r\n\r\nfid.close()\r\noutput.close()\r\n","sub_path":"solutions_2464487_1/Python/lurs/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"296397921","text":"\ndef minput():\n return [int(x) for x in input().split()]\n\ndef solve():\n N=int(input())\n arr=minput()\n hash=set()\n start=-1\n end=-1\n length=0\n\n for i in arr:\n hash.add(i)\n\n for i in range(N):\n if arr[i]-1 not in hash:\n j=arr[i]\n while j in hash:\n j+=1\n \n if length< j - arr[i] :\n length= j -arr[i]\n start=i\n end=j-1\n elif length== j - arr[i]:\n if start>i:\n start=i\n end=j-1\n print(arr[start],end)\n\n\n return\n\n\nt=1\n# t=int(input())\nwhile t:\n t-=1\n solve()\n","sub_path":"Good-First-Issues/LongestConsecutiveSubsequence.py","file_name":"LongestConsecutiveSubsequence.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"410089829","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 14 18:32:03 2018\r\n\r\n@author: abooth\r\n\"\"\"\r\n\r\nimport pandas as pd\r\n\r\nminorBatting = pd.read_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\The baseball cube\\\\The baseball cube\\\\minor_batting.csv\")\r\nminorPitching = pd.read_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\The baseball cube\\\\The baseball cube\\\\minor_pitching.csv\")\r\n\r\nuniqueMinorPlayersCube = list(minorBatting[\"playerid\"].unique())\r\nuniqueMinorPlayersCube.extend(list(minorPitching[\"playerid\"].unique()))\r\nuniqueMinorPlayersCube = list(sorted(set(uniqueMinorPlayersCube)))\r\n\r\n\r\nmlbBatting = pd.read_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\The baseball cube\\\\The baseball cube\\\\mlb_batting.csv\")\r\nmlbPitching = pd.read_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\The baseball cube\\\\The baseball cube\\\\mlb_pitching.csv\")\r\n\r\nuniqueMLBPlayersCube = list(mlbBatting[\"playerid\"].unique())\r\nuniqueMLBPlayersCube.extend(list(mlbPitching[\"playerid\"].unique()))\r\nuniqueMLBPlayersCube = list(sorted(set(uniqueMLBPlayersCube)))\r\n\r\ncountMLB = len(set(uniqueMinorPlayersCube).intersection(uniqueMLBPlayersCube))\r\n\r\ndfMin = pd.DataFrame()\r\ndfMaj = pd.DataFrame()\r\n\r\nfor year in range(1977,2018):\r\n #Minors\r\n subBat = minorBatting[minorBatting[\"year\"] == year]\r\n subPit = minorPitching[minorPitching[\"year\"] == year]\r\n\r\n subUniqueMinorPlayersCube = list(subBat[\"playerid\"].unique())\r\n subUniqueMinorPlayersCube.extend(list(subPit[\"playerid\"].unique()))\r\n subUniqueMinorPlayersCube = list(sorted(set(subUniqueMinorPlayersCube)))\r\n \r\n dfMin = dfMin.append({'Year': year, 'UniquePlayers': len(subUniqueMinorPlayersCube)}, ignore_index=True)\r\n \r\n #Majors\r\n subBat2 = mlbBatting[mlbBatting[\"year\"] == year]\r\n subPit2 = mlbPitching[mlbPitching[\"year\"] == year]\r\n\r\n subUniqueMLBPlayersCube = list(subBat2[\"playerid\"].unique())\r\n subUniqueMLBPlayersCube.extend(list(subPit2[\"playerid\"].unique()))\r\n subUniqueMLBPlayersCube = list(sorted(set(subUniqueMLBPlayersCube)))\r\n\r\n dfMaj = dfMaj.append({'Year': year, 'UniquePlayers': len(subUniqueMLBPlayersCube)}, ignore_index=True)\r\n\r\n\r\n\r\n#dfMin.to_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\uniqueMinorPlayersPerYear.csv\", index=False)\r\n#dfMaj.to_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\uniqueMLBPlayersPerYear.csv\", index=False)\r\n\r\n##########################################################################################\r\n\r\ndfAllMin = pd.DataFrame()\r\n\r\nfor level in set(minorBatting.Level):\r\n subLevBat = minorBatting[minorBatting[\"Level\"] == level]\r\n subLevPit = minorPitching[minorPitching[\"Level\"] == level]\r\n \r\n subUniquePlayersCube = list(subLevBat[\"playerid\"].unique())\r\n subUniquePlayersCube.extend(list(subLevPit[\"playerid\"].unique()))\r\n subUniquePlayersCube = list(sorted(set(subUniquePlayersCube)))\r\n print(level + \" \" + str(len(subUniquePlayersCube)))\r\n\r\n for year in range(1977,2018):\r\n #Minors\r\n subBat = subLevBat[subLevBat[\"year\"] == year]\r\n subPit = subLevPit[subLevPit[\"year\"] == year]\r\n \r\n subUniqueMinorPlayersCube = list(subBat[\"playerid\"].unique())\r\n subUniqueMinorPlayersCube.extend(list(subPit[\"playerid\"].unique()))\r\n subUniqueMinorPlayersCube = list(sorted(set(subUniqueMinorPlayersCube)))\r\n \r\n dfAllMin = dfAllMin.append({'Level': level, 'Year': year, 'UniquePlayers': len(subUniqueMinorPlayersCube)}, ignore_index=True)\r\n\r\n#dfAllMin.to_csv(\"C:\\\\Users\\\\abooth\\\\Documents\\\\R\\\\uniqueMinorLevelPlayersPerYear.csv\", index=False)\r\n ","sub_path":"Code/Python/bbCubeEDAPt1.py","file_name":"bbCubeEDAPt1.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"389256364","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport math\nimport threading\nimport traceback\nimport pymodbox\nimport time\nfrom os import _exit as exit\n\ndef main():\n module = pymodbox.Module('test_game_object')\n module.ready()\n\n module.invoke('gameObject.addKind', ['testGameObject'], 's', '')\n module.invoke('gameObject.addKind', ['anotherGameObject'], 's', '')\n [drawable_handle] = module.invoke('graphics.drawable.createCube', [], '', 'u')\n module.invoke('graphics.drawable.setScale', [drawable_handle, 7, 7, 7], 'ufff', '')\n module.invoke('graphics.drawable.enablePhysics', [drawable_handle, 7, 7, 7], 'ufff', '')\n module.invoke('graphics.drawable.enableCollisions', [drawable_handle], 'u', '')\n [object_handle] = module.invoke('gameObject.add', ['testGameObject', drawable_handle], 'su', 'u')\n\n while True:\n time.sleep(1)\n\n [status] = module.invoke('_exit', [], '', 's')\n\n if status == 'exited':\n log('Exited normally')\n exit(0)\n else:\n raise Exception('Unknown exit status: \"{}\"'.format(status))\nif __name__ == '__main__':\n try:\n main()\n exit(0)\n except BaseException as e:\n traceback.print_exc()\n exit(1)\n","sub_path":"modules/mod_test_game_object/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"69049244","text":"\"\"\"Cold Pool class, allows to analyze and describe formation of cold pool\"\"\"\n\nimport pickle\n\nimport numpy as np\nimport pySAM\nfrom pySAM.cold_pool.composite import instant_mean_extraction_data_over_extreme\nfrom pySAM.cold_pool.condensation_rate import get_condensation_rate\nfrom pySAM.cold_pool.geometry_profile import geometry_profile\nfrom pySAM.cold_pool.potential_energy import potential_energy\nfrom pySAM.cold_pool.relative_humidity import get_qsatt\nfrom pySAM.utils import make_parallel\n\n\nclass ColdPool:\n\n \"\"\"ColdPool creates object that gathers all variables useful to analyse and descibe a cold pool.\n It allows you to calculate composite figures, ie statistical overview of extreme events.\n The potential energy of cold pool is here defined and calculated and from there you can deduce the\n propagation velocity of the cold pool. This can be put in parallel with the imposed wind shear.\n\n Attributes:\n BUOYANCY (xr.DataArray): Buoyancy (y,z,y,x)\n DEPTH_SHEAR (str): depth shear of the wind profile\n FMSE (xr.DataArray): Moist static energy (y,z,y,x)\n nt (int): number of time steps\n nx (int): number of x steps\n ny (int): number of y steps\n nz (int): number of z steps\n P (xr.DataArray): Pressure\n POTENTIAL_TEMPERATURE (xr.DataArray): Potential temperature (y,z,y,x)\n PRECi (xr.DataArray): Precipitation (t,y,x)\n QN (xr.DataArray): QN\n QPEVP (xr.DataArray): QVEPV\n QV (xr.DataArray): QV\n TABS (xr.DataArray): Absolute Temperature\n U (xr.DataArray): x component of velocity\n VIRTUAL_TEMPERATURE (xr.DataArray): Virual temperature\n VORTICITY (xr.DataArray): Vorticity\n W (xr.DataArray): z component of velocity\n X (xr.DataArray): x direction\n Y (xr.DataArray): y direction\n Z (xr.DataArray): z direction\n\n \"\"\"\n\n def __init__(\n self,\n absolute_temperature: np.array,\n precipitation: np.array,\n x_positions: np.array,\n y_positions: np.array,\n z_positions: np.array,\n x_velocity: np.array,\n z_velocity: np.array,\n cloud_base: np.array,\n humidity: np.array,\n pressure: np.array,\n depth_shear: str,\n humidity_evp: np.array = None,\n humidity_evp_2d: np.array = None,\n humidity_evp_2d_i: np.array = None,\n rho: np.array = None,\n precip_source: np.array = None,\n plot_mode: bool = False, # plot_mode=True to partially load dataset and earn time,\n ):\n\n self.depth_shear = depth_shear\n self.TABS = absolute_temperature\n self.Prec = precipitation\n self.X = x_positions\n self.Y = y_positions\n self.Z = z_positions\n self.U = x_velocity\n self.W = z_velocity\n self.QN = cloud_base\n self.QV = humidity / 1000 # must be kg/kg\n self.P = pressure\n self.QPEVP = humidity_evp\n self.QPEVP_2D = humidity_evp_2d\n self.QPEVPi = humidity_evp_2d_i\n self.RHO = rho\n self.QPSRC = precip_source\n\n self.nx = len(self.X)\n self.ny = len(self.Y)\n self.nz = len(self.Z)\n self.nt = len(self.TABS)\n\n if not plot_mode:\n self.FMSE = None\n self.VIRTUAL_TEMPERATURE = None\n self.POTENTIAL_TEMPERATURE = None\n self.BUOYANCY = None\n self.VORTICITY = None\n self.set_basic_variables_from_dataset()\n\n def save(self, path_to_save: str):\n \"\"\"Will save the class as a pickle but will ignore attributes wwritten in UPPERCASE\n Those ones are loaded directly from dataset, so no need to store them in pickle\n Args:\n path_to_save (str): path and name of the backup\n \"\"\"\n\n # SELECT ONLY attributes whose names are in lower cases\n black_list = [\n key\n for (key, value) in self.__dict__.items()\n if (key.isupper() or key in [\"PRECi\", \"IntQN\", \"Prec\"])\n ]\n\n dictionary = {\n key: value for (key, value) in self.__dict__.items() if key not in black_list\n }\n\n file = open(path_to_save, \"wb\")\n pickle.dump(dictionary, file, 2)\n file.close()\n\n def load(self, path_to_load: str):\n \"\"\"Load cold pool from pickle file\n Args:\n path_to_load (str): path of loaded file\n \"\"\"\n file = open(path_to_load, \"rb\")\n tmp_dict = pickle.load(file)\n file.close()\n\n self.__dict__.update(tmp_dict)\n\n def set_basic_variables_from_dataset(self):\n \"\"\"Compute basic variables from dataset variable\n\n One must care of dataset variable shape, here it is adapted to (nt,nz,ny,nx) data !\n this method is called ONLY IF self.plot_mode == FALSE\n \"\"\"\n z_3d_in_time = pySAM.utils.expand_array_to_tzyx_array(\n time_dependence=False,\n input_array=self.Z.values,\n final_shape=np.array((self.nt, self.nz, self.ny, self.nx)),\n )\n\n # @@@@ UNUSED !!!\n # vertical_mean_temperature_3d_in_time = pySAM.utils.expand_array_to_tzyx_array(\n # time_dependence=True,\n # input_array=np.mean(self.TABS.values, axis=(2, 3)),\n # final_shape=np.array((self.nt, self.nz, self.ny, self.nx)),\n # )\n\n pressure_3d_in_time = pySAM.utils.expand_array_to_tzyx_array(\n time_dependence=False,\n input_array=self.P.values[: self.nz],\n final_shape=np.array((self.nt, self.nz, self.ny, self.nx)),\n )\n\n self.FMSE = (\n pySAM.HEAT_CAPACITY_AIR * self.TABS\n + pySAM.GRAVITY * z_3d_in_time\n + pySAM.LATENT_HEAT_AIR * self.QV\n )\n self.VIRTUAL_TEMPERATURE = self.TABS * (\n 1\n + (pySAM.MIXING_RATIO_AIR_WATER_VAPOR - 1)\n / pySAM.MIXING_RATIO_AIR_WATER_VAPOR\n * self.QV.values\n )\n\n vertical_mean_virtual_temperature_3d_in_time = pySAM.utils.expand_array_to_tzyx_array(\n time_dependence=True,\n input_array=np.mean(self.VIRTUAL_TEMPERATURE.values, axis=(2, 3)),\n final_shape=np.array((self.nt, self.nz, self.ny, self.nx)),\n )\n\n self.POTENTIAL_TEMPERATURE = (\n self.TABS\n * (pySAM.STANDARD_REFERENCE_PRESSURE / pressure_3d_in_time)\n ** pySAM.GAS_CONSTANT_OVER_HEAT_CAPACITY_AIR\n )\n\n self.BUOYANCY = (\n pySAM.GRAVITY\n * (self.VIRTUAL_TEMPERATURE.values - vertical_mean_virtual_temperature_3d_in_time)\n / vertical_mean_virtual_temperature_3d_in_time\n )\n\n self.VORTICITY = np.gradient(self.U.values, self.Z, axis=1) - np.gradient(\n self.W.values, self.X, axis=3\n )\n\n self.QSATT = get_qsatt(self.P.values[: self.nz], self.TABS.values)\n\n self.RH = self.QV / self.QSATT\n\n self.CR = get_condensation_rate(\n vertical_velocity=self.W.values,\n density=self.RHO.values,\n humidity=self.QV.values,\n )\n\n def set_CR_3D(self):\n self.CR_3D = get_condensation_rate(\n vertical_velocity=self.W.values,\n density=self.RHO.values,\n humidity=self.QV.values,\n return_3D=True,\n )\n\n def set_composite_variables(\n self,\n data_name: str,\n variable_to_look_for_extreme: str,\n extreme_events_choice: str,\n x_margin: int,\n y_margin: int,\n parallelize: bool = True,\n return_3D: bool = False,\n ) -> np.array:\n \"\"\"Compute the composite, namely the mean over extreme events, of 2d or 3d variables evolving in time\n This method build attribute\n\n Args:\n data_name (str): name of the variable composite method is applying to\n variable_to_look_for_extreme (str): name of the variable that describe extreme event\n extreme_events_choice (str): max 1-percentile or 10-percentile\n x_margin (int): width of window zoom\n y_margin (int, optional): depth of window zoom\n parallelize (bool, optional): use all your cpu power\n \"\"\"\n\n if data_name not in [\n \"W\",\n \"QN\",\n \"VORTICITY\",\n \"BUOYANCY\",\n \"QPEVP\",\n \"QPEVP_2D\",\n \"QPEVPi\",\n \"QP\",\n \"rho_QPEVP\",\n \"RH\",\n \"U\",\n \"QV\",\n \"TABS\",\n \"CR\",\n ]:\n raise ValueError(\n \"data name must be in [W, QN, VORTICITY, BUOYANCY, QPEVP, QPEVP_2D, QPEVPi, QP, rho_QPEVP, RH, U, QV, TABS]\"\n )\n if variable_to_look_for_extreme not in [\n \"PRECi\",\n \"QPEVP_2D\",\n \"Prec\",\n \"CR\",\n \"IntQN\",\n \"QPSRC\",\n ]:\n raise ValueError(\n \"variable_to_look_for_extreme must be in [PRECi, QPEVP_2D, Prec, CR, IntQN, QPSRC]\"\n )\n\n if parallelize:\n parallel_composite = make_parallel(\n function=instant_mean_extraction_data_over_extreme, nprocesses=pySAM.N_CPU\n )\n composite_variable = parallel_composite(\n iterable_values_1=getattr(self, data_name),\n iterable_values_2=getattr(self, variable_to_look_for_extreme),\n extreme_events_choice=extreme_events_choice,\n x_margin=x_margin,\n y_margin=y_margin,\n return_3D=return_3D,\n )\n\n else: # NO PARALLELIZATION\n composite_variable = []\n data = getattr(self, data_name)\n variable_to_look_for_extreme = getattr(self, variable_to_look_for_extreme).values\n for image, variable_extreme in zip(data, variable_to_look_for_extreme):\n composite_variable.append(\n instant_mean_extraction_data_over_extreme(\n data=image,\n variable_to_look_for_extreme=variable_extreme,\n extreme_events_choice=extreme_events_choice,\n x_margin=x_margin,\n y_margin=y_margin,\n return_3D=return_3D,\n )\n )\n\n composite_variable = np.array(composite_variable)\n composite_variable = np.mean(composite_variable, axis=0)\n\n if return_3D:\n setattr(\n self,\n data_name + \"_composite_\" + variable_to_look_for_extreme + \"3D\",\n composite_variable,\n )\n else:\n setattr(\n self,\n data_name + \"_composite_\" + variable_to_look_for_extreme + \"3D\",\n composite_variable,\n )\n\n def set_geometry_profile(\n self,\n data_name: str,\n threshold: float,\n ):\n \"\"\"Computes the profile of the cold pool in the x and z plane\n\n Args:\n data_name (str): Name of the variable to catch the cold pool\n threshold (float): Variable threshold, below it is in cold pool, above not\n \"\"\"\n if \"_composite\" not in data_name:\n raise ValueError(\"data must be composite variable\")\n\n data_array = getattr(self, data_name)\n\n geometry_profile_line = geometry_profile(\n data_array=data_array,\n z_array=self.Z,\n cold_pool_threshold=threshold,\n vertical_level_0=pySAM.LOWEST_ATMOSPHERIC_LEVEL,\n )\n\n setattr(self, \"profile_\" + str(int(abs(threshold * 1000))), geometry_profile_line)\n setattr(\n self,\n \"mean_height_\" + str(int(abs(threshold * 1000))),\n np.mean(geometry_profile_line[1]),\n )\n\n def set_potential_energy(self, data_name: str, profile_name: str) -> np.array:\n \"\"\"Computes the potentential energy of a cold pool as a function of x.\n For each x, provided data is integrated in z from the bottom to the top of the cold pool.\n\n Args:\n data_name (str): Name of the variable to integrate in z\n x_size (int): range of x you want to compute the potential energy\n\n Raises:\n ValueError: Data must be composite variable\n \"\"\"\n if \"_composite\" not in data_name:\n raise ValueError(\"data must be composite variable\")\n\n data_array = getattr(self, data_name)\n profile_list = getattr(self, profile_name)\n\n potential_energy_array = potential_energy(\n data_array=data_array, z_array=self.Z.values, geometry_profile=profile_list\n )\n\n setattr(self, \"potential_energy\", potential_energy_array)\n setattr(self, \"mean_potential_energy\", np.mean(potential_energy_array))\n","sub_path":"pySAM/pySAM/cold_pool/cold_pool.py","file_name":"cold_pool.py","file_ext":"py","file_size_in_byte":12824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"538619820","text":"import sys\nimport os\nimport math\n\nfrom lib import agouti_gff as agGFF\nfrom lib import agouti_log as agLOG\n\ndef report_scaffold_path(paths, vertex2Name, outDir, prefix):\n\t'''\n\t\toutput scaffolding path\n\t\tcheck conflicts with original paths\n\t'''\n\toutPathFile = os.path.join(outDir, \"%s.agouti.scaffolding_paths.txt\" %(prefix))\n\twith open(outPathFile, 'w') as fSCAFPATH:\n\t\tfor i, path in enumerate(paths):\n\t\t\tscafName = prefix + \"_scaf_%d\" %(i+1)\n\t\t\tfSCAFPATH.write(\">%s\\n%s\\n\" %(scafName, \",\".join([vertex2Name[k] for k in path])))\n\ndef agouti_path_main(agoutiPaths, dSenses, vertex2Name,\n\t\t\t\t\t dGFFs, dCtgPair2GenePair,\n\t\t\t\t\t oriScafPathFile, outDir, prefix):\n\tmoduleName = os.path.basename(__file__).split('.')[0].upper()\n\tmoduleOutDir = os.path.join(outDir, \"agouti_path\")\n\tif not os.path.exists(moduleOutDir):\n\t\tos.makedirs(moduleOutDir)\n\tagPathProgress = agLOG.PROGRESS_METER(moduleName)\n\tagPathProgress.logger.info(\"Analyzing scaffolding paths\")\n\toutDebugFile = os.path.join(moduleOutDir, prefix) + \".agouti_path.debug\"\n\tagPathDebug = agLOG.DEBUG(\"SHREDDER\", outDebugFile)\n\tagPathProgress.logger.info(\"[BEGIN] Reading file with shred info\")\n\tdOriPaths, dOriGaps = read_original_path(oriScafPathFile, agPathProgress)\n\tagPathProgress.logger.info(\"[DONE]\")\n\tagPathProgress.logger.info(\"[BEGIN] Checking consistency\")\n\tcompare(dOriPaths, agoutiPaths, vertex2Name, outDir, prefix)\n\tagPathProgress.logger.info(\"[DONE]\")\n\tagPathProgress.logger.info(\"[BEGIN] Recovring original scaffolding\")\n\tagoutiPaths, dCtgPair2GenePair, dSenses = recover_untouched_sequences(dOriPaths, agoutiPaths,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t vertex2Name, dGFFs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t dCtgPair2GenePair,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t dSenses, agPathProgress,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t agPathDebug)\n\tagPathProgress.logger.info(\"[DONE]\")\n\n\treturn agoutiPaths, dCtgPair2GenePair, dSenses\n\ndef recover_untouched_sequences(dOriPaths, agoutiPaths, vertex2Name,\n\t\t\t\t\t\t\t\tdGFFs, dCtgPair2GenePair, dSenses,\n\t\t\t\t\t\t\t\tagPathProgress, agPathDebug):\n\t'''\n\t\tRecover scaffolds from contigs untouched by AGOUTI\n\t'''\n\n\tagPathDebug.debugger.debug(\"[RECOVER]\\t####\")\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of paths AGOUTI scaffolded: %d\"\n\t\t\t\t\t\t\t %(sum([len(path) for path in agoutiPaths])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of gene models in dGFFs: %d\"\n\t\t\t\t\t\t\t %(sum([len(geneModels) for geneModels in dGFFs.itervalues()])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of fake gene models in dGFFs: %d\"\n\t\t\t\t\t\t\t %(len([geneModel\n\t\t\t\t\t\t\t\t\t for geneModels in dGFFs.itervalues()\n\t\t\t\t\t\t\t\t\t for geneModel in geneModels\n\t\t\t\t\t\t\t\t\t if geneModel.fake == 1])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\t####\")\n\t# get a dictionary of contigs being scaffolded\n\tscaffoldedCtgs = {vertex2Name[k]:0 for path in agoutiPaths for k in path}\n\tn = 0\t\t\t\t# number of canonical joining gene models\n\tm = 0\t\t\t\t# number of fakeO gene model created\n\ttmpPaths = []\n\tfor k, path in dOriPaths.iteritems():\n\t\tpathLefts = [ctg for ctg in path if ctg not in scaffoldedCtgs]\n\t\tif not pathLefts:\n\t\t\tcontinue\n\t\tagPathDebug.debugger.debug(\"[RECOVER]\\tpathLefts=%s\" %(str(pathLefts)))\n\t\tagPathDebug.debugger.debug(\"[RECOVER]\\tGetting consective path from pathLefts\")\n\t\trecovPath = []\n\t\tpreCtg = pathLefts[0]\n\t\tpreCtgIndex = int(preCtg.split('_')[1])\n\t\ttmpPath = [preCtg]\n\t\tfor i in range(1, len(pathLefts)):\n\t\t\tcurCtg = pathLefts[i]\n\t\t\tcurCtgIndex = int(curCtg.split('_')[1])\n\t\t\tagPathDebug.debugger.debug(\"[RECOVER]\\tpreCtg=%s - preIndex=%d - curCtg=%s - curIndex=%d\"\n\t\t\t\t\t\t\t\t\t %(preCtg, preCtgIndex, curCtg, curCtgIndex))\n\t\t\tif math.fabs(curCtgIndex-preCtgIndex) == 1:\n\t\t\t\ttmpPath.append(curCtg)\n\t\t\telse:\n\t\t\t\t# add path with at least two contigs\n\t\t\t\tif len(tmpPath) <= 1:\n\t\t\t\t\ttmpPath = [curCtg]\n\t\t\t\telse:\n\t\t\t\t\trecovPath.append(tmpPath)\n\t\t\t\t\ttmpPath = [curCtg]\n\t\t\tpreCtg = curCtg\n\t\t\tpreCtgIndex = int(preCtg.split('_')[1])\n\t\t# add path with at least two contigs\n\t\tif len(tmpPath) > 1:\n\t\t\trecovPath.append(tmpPath)\n\t\tagPathDebug.debugger.debug(\"[RECOVER]\\tGetting gene pair for each contig pair\")\n\t\tfor path in recovPath:\n\t\t\tfor i in range(1, len(path)):\n\t\t\t\tpreCtg = path[i-1]\n\t\t\t\tcurCtg = path[i]\n\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER]\\tpreCtg=%s - curCtg=%s\"\n\t\t\t\t\t\t\t\t\t\t %(preCtg, curCtg))\n\t\t\t\tpreVertex = vertex2Name.index(preCtg)\n\t\t\t\tcurVertex = vertex2Name.index(curCtg)\n\t\t\t\tpreIndex = -1\n\t\t\t\tcurIndex = -1\n\t\t\t\tpreCtgGeneModel3 = None\n\t\t\t\tcurCtgGeneModel5 = None\n\t\t\t\t# check if pre and cur contigs\n\t\t\t\t# have gene models on them\n\t\t\t\tif preCtg in dGFFs:\n\t\t\t\t\tpreCtgGeneModel3 = dGFFs[preCtg][-1]\n\t\t\t\t\tif not preCtgGeneModel3.fake:\n\t\t\t\t\t\tpreGeneID = preCtgGeneModel3.geneID\n\t\t\t\t\t\tpreIndex = int(preGeneID.split('_')[1])\n\t\t\t\tif curCtg in dGFFs:\n\t\t\t\t\tcurCtgGeneModel5 = dGFFs[curCtg][0]\n\t\t\t\t\tif not curCtgGeneModel5.fake:\n\t\t\t\t\t\tcurGeneID = curCtgGeneModel5.geneID\n\t\t\t\t\t\tcurIndex = int(curGeneID.split('_')[1])\n\n\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER]\\t====preGeneIndex=%d - curGeneIndex=%d\"\n\t\t\t\t\t\t\t\t\t\t %(preIndex, curIndex))\n\t\t\t\t# both index should not be -1 if they are the\n\t\t\t\t# joining gene model between the two contigs\n\t\t\t\tif preIndex != -1 and curIndex != -1:\n\t\t\t\t\t# and they have to be consecutive\n\t\t\t\t\tif math.fabs(curIndex - preIndex) == 1:\n\t\t\t\t\t\tn += 1\n\t\t\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER]\\t====preGeneID=%s - curGeneID=%s\"\n\t\t\t\t\t\t\t\t\t\t\t\t %(preGeneID, curGeneID))\n\t\t\t\t\t# create fakeO genes as joining gene models\n\t\t\t\t\telse:\n\t\t\t\t\t\tpreCtgGeneModel3 = agGFF.AGOUTI_GFF()\n\t\t\t\t\t\tpreCtgGeneModel3.setGene(\"%s_fakeO_%d\" %(preCtg, m),\n\t\t\t\t\t\t\t\t\t\t\t\t 0, 0, 1)\n\t\t\t\t\t\tdGFFs[preCtg].append(preCtgGeneModel3)\n\t\t\t\t\t\tm += 1\n\t\t\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER\\t====preCtgGeneModels=%s\"\n\t\t\t\t\t\t\t\t\t\t\t\t %(str([k.geneID for k in dGFFs[preCtg]])))\n\t\t\t\t\t\tcurCtgGeneModel5 = agGFF.AGOUTI_GFF()\n\t\t\t\t\t\tcurCtgGeneModel5.setGene(\"%s_fakeO_%d\" %(curCtg, m),\n\t\t\t\t\t\t\t\t\t\t\t\t 0, 0, 1)\n\t\t\t\t\t\tdGFFs[curCtg] = [curCtgGeneModel5] + dGFFs[curCtg]\n\t\t\t\t\t\tm += 1\n\t\t\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER\\t====curCtgGeneModels=%s\"\n\t\t\t\t\t\t\t\t\t\t\t\t %(str([k.geneID for k in dGFFs[curCtg]])))\n\t\t\t\t# create fakeO gnes as joining gene models\n\t\t\t\telse:\n\t\t\t\t\tpreCtgGeneModel3 = agGFF.AGOUTI_GFF()\n\t\t\t\t\tpreCtgGeneModel3.setGene(\"%s_fakeO_%d\" %(preCtg, m),\n\t\t\t\t\t\t\t\t\t\t\t 0, 0, 1)\n\t\t\t\t\tdGFFs[preCtg].append(preCtgGeneModel3)\n\t\t\t\t\tm += 1\n\t\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER\\t====preCtgGeneModels=%s\"\n\t\t\t\t\t\t\t\t\t\t\t %(str([k.geneID for k in dGFFs[preCtg]])))\n\t\t\t\t\tcurCtgGeneModel5 = agGFF.AGOUTI_GFF()\n\t\t\t\t\tcurCtgGeneModel5.setGene(\"%s_fakeO_%d\" %(curCtg, m),\n\t\t\t\t\t\t\t\t\t\t\t 0, 0, 1)\n\t\t\t\t\tdGFFs[curCtg] = [curCtgGeneModel5] + dGFFs[curCtg]\n\t\t\t\t\tm += 1\n\t\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER\\t====curCtgGeneModels=%s\"\n\t\t\t\t\t\t\t\t\t\t\t %(str([k.geneID for k in dGFFs[curCtg]])))\n\t\t\t\t# record joining gene models for the two contigs\n\t\t\t\tdCtgPair2GenePair[preVertex, curVertex] = [preCtgGeneModel3, curCtgGeneModel5]\n\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER]\\t====preID=%s preCDS=%s\"\n\t\t\t\t\t\t\t\t\t\t %(preCtgGeneModel3.geneID, str(preCtgGeneModel3.lcds)))\n\t\t\t\tagPathDebug.debugger.debug(\"[RECOVER]\\t====curID=%s curCDS=%s\"\n\t\t\t\t\t\t\t\t\t\t %(curCtgGeneModel5.geneID, str(curCtgGeneModel5.lcds)))\n\t\t\t\tdSenses[preVertex, curVertex] = [('+', '-')]\n\t\tfor path in recovPath:\n\t\t\t# convert from name to vertex\n\t\t\tagoutiPaths.append([vertex2Name.index(k) for k in path])\n\tagPathDebug.debugger.debug(\"[RECOVER]\\t####\")\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of paths to update: %d\"\n\t\t\t\t\t\t\t %(sum([len(path) for path in agoutiPaths])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of gene models in dGFFs: %d\"\n\t\t\t\t\t\t\t %(sum([len(geneModels) for geneModels in dGFFs.itervalues()])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of fake gene models in dGFFs: %d\"\n\t\t\t\t\t\t\t %(len([geneModel\n\t\t\t\t\t\t\t\t\t for geneModels in dGFFs.itervalues()\n\t\t\t\t\t\t\t\t\t for geneModel in geneModels\n\t\t\t\t\t\t\t\t\t if geneModel.fake == 1])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\tNumber of fakeO gene models in dGFFs: %d\"\n\t\t\t\t\t\t\t %(len([geneModel\n\t\t\t\t\t\t\t\t\t for geneModels in dGFFs.itervalues()\n\t\t\t\t\t\t\t\t\t for geneModel in geneModels\n\t\t\t\t\t\t\t\t\t if geneModel.fake == 1\n\t\t\t\t\t\t\t\t\t\t and geneModel.geneStop == 0])))\n\tagPathDebug.debugger.debug(\"[RECOVER]\\t####\")\n\tagPathProgress.logger.info((\"Number of pairs of shredded contigs \"\n\t\t\t\t\t\t\t\t\"having joining gene models: %d\" %(n)))\n\treturn agoutiPaths, dCtgPair2GenePair, dSenses\n\ndef read_original_path(oriScafPathFile, agPathProgress):\n\t'''\n\t\tRead original scaffolding path\n\t'''\n\tdOriPaths = {}\n\tdOriGaps = {}\n\toriScafID = \"\"\n\twith open(oriScafPathFile, 'r') as fIN:\n\t\toriPath = []\n\t\tnLines = 0\n\t\tfor line in fIN:\n\t\t\tnLines += 1\n\t\t\tif line.startswith('>'):\n\t\t\t\tif len(oriPath) > 0:\n\t\t\t\t\tdOriPaths[oriScafID] = oriPath\n\t\t\t\t\toriPath = []\n\t\t\t\toriScafID = line.strip()[1:]\n\t\t\telse:\n\t\t\t\ttmpLine = line.strip().split(\"\\t\")\n\t\t\t\tcurCtg = tmpLine[0]\n\t\t\t\tnexCtg = tmpLine[1]\n\t\t\t\tif tmpLine[1] != \"NA\":\n\t\t\t\t\tgapLen = int(tmpLine[2])\n\t\t\t\t\tif (curCtg, nexCtg) not in dOriGaps:\n\t\t\t\t\t\tdOriGaps[curCtg, nexCtg] = gapLen\n\t\t\t\t\telse:\n\t\t\t\t\t\tagPathProgress.logger.error(\"Error: ctg1=%s ctg2=%s occurred twice\")\n\t\t\t\t\t\tagPathProgress.logger.error(\"Please check file: %s at line %d\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t%(oriScafPathFile, nLines))\n\t\t\t\t\t\tagPathProgress.logger.error((\"The error probably comes from incorrect\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"recording shred info\"))\n\t\t\t\t\t\tagPathProgress.logger.error(\"Please report this bug\")\n\t\t\t\t\t\tsys.exit(1)\n\t\t\t\t\tif len(oriPath) == 0:\n\t\t\t\t\t\toriPath += [curCtg, nexCtg]\n\t\t\t\t\telse:\n\t\t\t\t\t\toriPath.append(nexCtg)\n\t\t\t\telse:\n\t\t\t\t\toriPath.append(curCtg)\n\t\tif oriPath:\n\t\t\tdOriPaths[oriScafID] = oriPath\n\tagPathProgress.logger.info(\"Number of shredded contigs parsed: %d\"\n\t\t\t\t\t\t\t\t%(sum([len(v) for v in dOriPaths.itervalues()])))\n\n\treturn dOriPaths, dOriGaps\n\ndef compare(dOriPaths, agPaths, vertex2Name, outDir, prefix):\n\tfCONFLICT = None\n\tif dOriPaths:\n\t\toutConflicts = os.path.join(outDir, \"%s.agouti_vs_original.compare.txt\" %(prefix))\n\t\tfCONFLICT = open(outConflicts, 'w')\n\t\tif dOriPaths:\n\t\t\tfor i, path in enumerate(agPaths):\n\t\t\t\tpath = [vertex2Name[k] for k in path]\n\t\t\t\tconflictType = check_consistency(dOriPaths, path)\n\t\t\t\tscafName = \"%s_scaf_%d\" %(prefix, i)\n\t\t\t\tif conflictType is not None:\n\t\t\t\t\tfCONFLICT.write(\"%s\\t%s\\t%s\\n\" %(scafName, conflictType,\n\t\t\t\t\t\t\t\t\t\t\t\t\t \",\".join(path)))\n\ndef check_consistency(dOriPaths, agPath):\n\tfor i in range(1, len(agPath)):\n\t\tpreCtg = agPath[i-1]\n\t\tcurCtg = agPath[i]\n\t\tpreCtgScafID = preCtg.split('_')[0]\n\t\tcurCtgScafID = curCtg.split('_')[0]\n\t\t# cases where no shred on the original scaffold\n\t\tif preCtgScafID == preCtg or curCtgScafID == curCtg:\n\t\t\treturn \"INTERSCAFFOLDING\"\n\t\tif preCtgScafID != curCtgScafID:\n\t\t\tpreCtgScafIndex = dOriPaths[preCtgScafID].index(preCtg)\n\t\t\tcurCtgScafIndex = dOriPaths[curCtgScafID].index(curCtg)\n\t\t\tpreNCtg = len(dOriPaths[preCtgScafID])\n\t\t\tcurNCtg = len(dOriPaths[curCtgScafID])\n\t\t\tif ((preCtgScafIndex == 0 or preCtgScafIndex == preNCtg-1) and\n\t\t\t\t(curCtgScafIndex == 0 or curCtgScafIndex == curNCtg-1)):\n\t\t\t\treturn \"INTERSCAFFOLDING\"\n\t\t\telse:\n\t\t\t\treturn \"CONFLICT\"\n\tagStartCtg = agPath[0]\n\toriScafID = agStartCtg.split('_')[0]\n\tif oriScafID in dOriPaths:\n\t\toriPath = dOriPaths[oriScafID]\n\t\torder = -1\n\t\tfor i in range(1, len(agPath)):\n\t\t\tagCtgPre = agPath[i-1]\n\t\t\tagCtgScafIndexPre = int(agCtgPre.split('_')[1])\n\t\t\tagCtgNext = agPath[i]\n\t\t\tagCtgScafIndexNext = int(agCtgNext.split('_')[1])\n\t\t\tjump = agCtgScafIndexNext - agCtgScafIndexPre\n\t\t\tif order == -1:\n\t\t\t\tif jump <= -2:\n\t\t\t\t\treturn \"NONCONSECUTIVE\"\n\t\t\t\telif jump == -1:\n\t\t\t\t\torder = 1\n\t\t\t\telif jump >= 2:\n\t\t\t\t\treturn \"NONCONSECUTIVE\"\n\t\t\t\telif jump == 1:\n\t\t\t\t\torder = 0\n\t\t\telse:\n\t\t\t\tif math.fabs(jump) >= 2:\n\t\t\t\t\treturn \"NONCONSECUTIVE\"\n\t\t\t\telse:\n\t\t\t\t\tif order == 0 and jump < 0:\n\t\t\t\t\t\treturn \"SWITCHORDER\"\n\t\t\t\t\telif order == 1 and jump > 0:\n\t\t\t\t\t\treturn \"SWITCHORDER\"\n\treturn\n\n","sub_path":"src/agouti_path.py","file_name":"agouti_path.py","file_ext":"py","file_size_in_byte":11700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"343781668","text":"###############################################################################\n# calc_effsel: calculate the effective selection function for various setups, \n# **includes the area of the plate**\n###############################################################################\nimport os, os.path\nimport pickle\nimport multiprocessing\nimport numpy\nfrom optparse import OptionParser\nfrom galpy.util import save_pickles, multi\nimport apogee.select.apogeeSelect\nimport mwdust\nfrom define_rcsample import get_rcsample\ndef calc_effsel(args,options,sample=None):\n # Work-horse function to compute the effective selection function, \n # sample is a data sample of stars to consider for the (JK,Z) sampling\n # Setup selection function\n selectFile= '../savs/selfunc-nospdata.sav'\n if os.path.exists(selectFile):\n with open(selectFile,'rb') as savefile:\n apo= pickle.load(savefile)\n else:\n # Setup selection function\n apo= apogee.select.apogeeSelect()\n # Delete these because they're big and we don't need them\n del apo._specdata\n del apo._photdata\n save_pickles(selectFile,apo)\n # Get the full data sample for the locations (need all locations where \n # stars could be observed, so the whole sample, not just the subsample\n # being analyzed)\n data= get_rcsample()\n locations= list(set(list(data['LOCATION_ID'])))\n # Load the dust map and setup the effective selection function\n if options.dmap.lower() == 'green15':\n dmap3d= mwdust.Green15(filter='2MASS H')\n elif options.dmap.lower() == 'marshall06':\n dmap3d= mwdust.Marshall06(filter='2MASS H')\n elif options.dmap.lower() == 'drimmel03':\n dmap3d= mwdust.Drimmel03(filter='2MASS H')\n elif options.dmap.lower() == 'sale14':\n dmap3d= mwdust.Sale14(filter='2MASS H')\n elif options.dmap.lower() == 'zero':\n dmap3d= mwdust.Zero(filter='2MASS H')\n # Sample the M_H distribution\n if options.samplemh:\n if sample is None: sample= data\n MH= sample['H0']-sample['RC_DM']\n MH= numpy.random.permutation(MH)[:1000] # do 1,000 max\n else:\n MH= -1.49\n apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=dmap3d,MH=MH)\n # Distances at which to calculate the effective selection function\n distmods= numpy.linspace(options.dm_min,options.dm_max,options.ndm)\n ds= 10.**(distmods/5-2.)\n # Now compute all selection functions\n out= multi.parallel_map((lambda x: _calc_effsel_onelocation(\\\n locations[x],apof,apo,ds)),\n range(len(locations)),\n numcores=numpy.amin([len(locations),\n multiprocessing.cpu_count(),options.multi]))\n # Save out\n out= numpy.array(out)\n save_pickles(args[0],locations,out,distmods,ds)\n return None\n\ndef _calc_effsel_onelocation(locid,apof,apo,ds):\n # Calculate the effective selection function for a given location\n try:\n esf= apof(locid,ds)*apo.area(locid)\n except (IndexError, TypeError,ValueError):\n esf= -numpy.ones_like(ds)\n return esf\n\ndef get_options():\n usage = \"usage: %prog [options] \\n\\nsavefilename= name of the file that the effective selection function will be saved to\"\n parser = OptionParser(usage=usage)\n # Distances at which to calculate the effective selection function\n parser.add_option(\"--dm_min\",dest='dm_min',default=7.,type='float',\n help=\"Minimum distance modulus\")\n parser.add_option(\"--dm_max\",dest='dm_max',default=15.5,type='float',\n help=\"Maximum distance modulus\")\n parser.add_option(\"--ndm\",dest='ndm',default=301,type='int',\n help=\"Number of distance moduli to calculate the function at\")\n # Dust map to use\n parser.add_option(\"--dmap\",dest='dmap',default='green15',\n help=\"Dust map to use ('Green15', 'Marshall03', 'Drimmel03', 'Sale14', or 'zero'\")\n # Sample over the M_H of the sample?\n parser.add_option(\"--samplemh\",action=\"store_true\", dest=\"samplemh\",\n default=False,\n help=\"If set, sample the M_H distribution of the sub-sample (default= full sample)\")\n # Multiprocessing?\n parser.add_option(\"-m\",\"--multi\",dest='multi',default=1,type='int',\n help=\"number of cpus to use\")\n return parser\n\nif __name__ == '__main__':\n parser= get_options()\n options, args= parser.parse_args()\n calc_effsel(args,options)\n","sub_path":"py/calc_effsel.py","file_name":"calc_effsel.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"10064047","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019-08-18 14:24\n# @Author : Spoon\n# @Site : \n# @File : config.py\n# @Software: PyCharm\nfrom datetime import timedelta\n\nfrom celery.schedules import crontab\n\nBROKER_URL = 'redis://localhost:6379/1'\nCELERY_RESULT_BACKEND = 'redis://localhost:6379/2'\n\nCELERY_TIMEZONE = 'Asia/Shanghai'\n\nCELERY_IMPORTS = (\n 'app.task1',\n 'app.task2',\n)\n\nCELERYBEAT_SCHEDULE = {\n 'task1': {\n 'task': 'app.task1.sendMsg',\n 'schedule': timedelta(seconds=6),\n 'args': ('定时早上好',)\n },\n 'task2': {\n 'task': 'app.task2.sendMsg',\n 'schedule': crontab(hour=23, minute=15),\n 'args': ('定时晚上好',)\n }\n}","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"441291777","text":"\nfrom enigma import iPlayableService\nfrom Components.Converter.Converter import Converter\nfrom Components.Converter.Poll import Poll\nfrom Components.Element import cached, ElementError\n\n\nclass XStreamityServicePosition(Poll, Converter, object):\n TYPE_LENGTH = 0\n TYPE_POSITION = 1\n TYPE_REMAINING = 2\n TYPE_GAUGE = 3\n TYPE_SUMMARY = 4\n\n def __init__(self, type):\n Poll.__init__(self)\n Converter.__init__(self, type)\n\n args = type.split(\",\")\n type = args.pop(0)\n\n self.negate = \"Negate\" in args\n self.detailed = \"Detailed\" in args\n self.showHours = \"ShowHours\" in args\n self.showNoSeconds = \"ShowNoSeconds\" in args\n\n if type == \"Length\":\n self.type = self.TYPE_LENGTH\n elif type == \"Position\":\n self.type = self.TYPE_POSITION\n elif type == \"Remaining\":\n self.type = self.TYPE_REMAINING\n elif type == \"Gauge\":\n self.type = self.TYPE_GAUGE\n elif type == \"Summary\":\n self.type = self.TYPE_SUMMARY\n else:\n raise ElementError(\"type must be {Length|Position|Remaining|Gauge|Summary} with optional arguments {Negate|Detailed|ShowHours|ShowNoSeconds} for ServicePosition converter\")\n\n if self.detailed:\n self.poll_interval = 100\n elif self.type == self.TYPE_LENGTH:\n self.poll_interval = 2000\n else:\n self.poll_interval = 500\n\n self.poll_enabled = True\n\n def getSeek(self):\n s = self.source.service\n return s and s.seek()\n\n @cached\n def getPosition(self):\n seek = self.getSeek()\n if seek is None:\n return None\n pos = seek.getPlayPosition()\n if pos[0]:\n return 0\n return pos[1]\n\n @cached\n def getLength(self):\n seek = self.getSeek()\n if seek is None:\n return None\n length = seek.getLength()\n if length[0]:\n return 0\n return length[1]\n\n @cached\n def getCutlist(self):\n service = self.source.service\n cue = service and service.cueSheet()\n return cue and cue.getCutList()\n\n @cached\n def getText(self):\n seek = self.getSeek()\n if seek is None:\n return \"\"\n\n if self.type == self.TYPE_SUMMARY or self.type == self.TYPE_SUMMARY:\n s = self.position / 90000\n e = (self.length / 90000) - s\n return \"%02d:%02d +%2dm\" % (s / 60, s % 60, e / 60)\n\n l = self.length\n p = self.position\n r = self.length - self.position # Remaining\n\n if l < 0:\n return \"\"\n\n if not self.detailed:\n l /= 90000\n p /= 90000\n r /= 90000\n\n if self.negate:\n l = -l\n if self.negate:\n p = -p\n if self.negate:\n r = -r\n\n if l >= 0:\n sign_l = \"\"\n else:\n l = -l\n sign_l = \"-\"\n\n if p >= 0:\n sign_p = \"\"\n else:\n p = -p\n sign_p = \"-\"\n\n if r >= 0:\n sign_r = \"\"\n else:\n r = -r\n sign_r = \"-\"\n\n if self.type < 5:\n if not self.detailed:\n if self.showHours:\n if self.showNoSeconds:\n if self.type == self.TYPE_LENGTH:\n return sign_l + \"%d:%02d\" % (l / 3600, l % 3600 / 60)\n elif self.type == self.TYPE_POSITION:\n return sign_p + \"%d:%02d\" % (p / 3600, p % 3600 / 60)\n elif self.type == self.TYPE_REMAINING:\n return sign_r + \"%d:%02d\" % (r / 3600, r % 3600 / 60)\n else:\n if self.type == self.TYPE_LENGTH:\n return sign_l + \"%d:%02d:%02d\" % (l / 3600, l % 3600 / 60, l % 60)\n elif self.type == self.TYPE_POSITION:\n return sign_p + \"%d:%02d:%02d\" % (p / 3600, p % 3600 / 60, p % 60)\n elif self.type == self.TYPE_REMAINING:\n return sign_r + \"%d:%02d:%02d\" % (r / 3600, r % 3600 / 60, r % 60)\n else:\n if self.showNoSeconds:\n if self.type == self.TYPE_LENGTH:\n return ngettext(\"%d Min\", \"%d Mins\", (l / 60)) % (l / 60)\n elif self.type == self.TYPE_POSITION:\n return sign_p + ngettext(\"%d Min\", \"%d Mins\", (p / 60)) % (p / 60)\n elif self.type == self.TYPE_REMAINING:\n return sign_r + ngettext(\"%d Min\", \"%d Mins\", (r / 60)) % (r / 60)\n else:\n if self.type == self.TYPE_LENGTH:\n return sign_l + \"%d:%02d\" % (l / 60, l % 60)\n elif self.type == self.TYPE_POSITION:\n return sign_p + \"%d:%02d\" % (p / 60, p % 60)\n elif self.type == self.TYPE_REMAINING:\n return sign_r + \"%d:%02d\" % (r / 60, r % 60)\n\n # range/value are for the Progress renderer\n range = 10000\n\n @cached\n def getValue(self):\n pos = self.position\n len = self.length\n if pos is None or len is None or len <= 0:\n return None\n return pos * 10000 // len\n\n position = property(getPosition)\n length = property(getLength)\n cutlist = property(getCutlist)\n text = property(getText)\n value = property(getValue)\n\n def changed(self, what):\n cutlist_refresh = what[0] != self.CHANGED_SPECIFIC or what[1] in (iPlayableService.evCuesheetChanged,)\n time_refresh = what[0] == self.CHANGED_POLL or what[0] == self.CHANGED_SPECIFIC and what[1] in (iPlayableService.evCuesheetChanged,)\n\n if cutlist_refresh:\n if self.type == self.TYPE_GAUGE:\n self.downstream_elements.cutlist_changed()\n\n if time_refresh:\n self.downstream_elements.changed(what)\n","sub_path":"XStreamity/usr/lib/enigma2/python/Components/Converter/XStreamityServicePosition.py","file_name":"XStreamityServicePosition.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"317222567","text":"##############\n# Standard #\n##############\nimport io\nimport asyncio\nimport tempfile\n\n##############\n# External #\n##############\nimport pytest\n\n##############\n# Module #\n##############\nimport powermate\nfrom powermate.event import LedEvent, Event, EventType\n\nevents = [\n #Regular Push\n Event(23434040, 340340, EventType.PUSH, 0, 1),\n Event(23435040, 340340, EventType.PUSH, 1, 0),\n #Regular Push\n Event(23436040, 340340, EventType.PUSH, 1, 1),\n Event(23437040, 340340, EventType.PUSH, 1, 0),\n #Twist\n Event(23438040, 340340, EventType.PUSH, 1, 1),\n Event(23438140, 340340, EventType.ROTATE, 1, 2),\n Event(23438240, 340340, EventType.ROTATE, 1, 3),\n Event(23439040, 340340, EventType.PUSH, 1, 0),\n #Rotate\n Event(23441040, 340340, EventType.ROTATE, 1, 2),\n #Long Push\n Event(23442040, 340340, EventType.PUSH, 1, 1),\n Event(53443040, 340340, EventType.PUSH, 1, 0)]\n\nclass PseudoStream(io.BytesIO):\n \"\"\"\n BytesIO object that continually adds new events\n \"\"\"\n def __init__(self, stream, *args, **kwargs):\n self.stream = stream\n super().__init__(*args, **kwargs)\n\n def read(self, *args, **kwargs):\n return self.stream.pop(0).raw\n\n\nclass CountingPowerMate(powermate.PowerMateBase):\n \"\"\"\n PowerMate that counts the Events that happen\n \"\"\"\n def __init__(self, path, loop=None):\n #Store actions\n self.presses = 0\n self.releases = 0\n self.rotations = 0\n self.twists = 0\n self.twist_releases = 0 \n super().__init__(path, loop=loop)\n #Replace output with PseudoStream / input with file-like BytesIO\n self._source._output = PseudoStream(events)\n self._source._input = io.BytesIO()\n\n @asyncio.coroutine\n def pressed(self):\n super().pressed()\n self.presses += 1\n return self.illuminate(100)\n\n @asyncio.coroutine\n def rotated(self, value, pressed):\n super().rotated(value, pressed=pressed)\n if pressed:\n self.twists += value\n else:\n self.rotations += value\n\n @asyncio.coroutine\n def released(self, time, rotated):\n super().released(time)\n self.releases += 1\n self.twist_releases += int(rotated)\n if time > 1000000:\n return Event.stop()\n return self.illuminate(0)\n\n@pytest.fixture(scope='function')\ndef counting_powermate():\n with tempfile.NamedTemporaryFile() as tmp:\n yield CountingPowerMate(tmp.name)\n\ndef test_powermatebase(counting_powermate):\n #Load PowerMate\n #Run through fake event stream\n counting_powermate.run()\n #Check our count of actions\n assert counting_powermate.presses == 4\n assert counting_powermate.releases == 4\n assert counting_powermate.rotations == 2\n assert counting_powermate.twists == 5\n assert counting_powermate.twist_releases == 1\n #Check that we wrote back events to the Powermate\n counting_powermate._source._input.seek(0)\n _bytes = counting_powermate._source._input.read()\n assert LedEvent.max().raw in _bytes\n assert LedEvent.off().raw in _bytes\n","sub_path":"tests/test_powermate.py","file_name":"test_powermate.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"303389715","text":"\"\"\"\nRepresents a connection request message.\n\"\"\"\n\nfrom marshmallow import fields\n\nfrom ...agent_message import AgentMessage, AgentMessageSchema\nfrom ..message_types import CONNECTION_REQUEST\nfrom ....models.connection_detail import ConnectionDetail, ConnectionDetailSchema\n\nHANDLER_CLASS = (\n \"indy_catalyst_agent.messaging.connections.handlers\"\n + \".connection_request_handler.ConnectionRequestHandler\"\n)\n\n\nclass ConnectionRequest(AgentMessage):\n \"\"\" \"\"\"\n\n class Meta:\n \"\"\" \"\"\"\n\n handler_class = HANDLER_CLASS\n message_type = CONNECTION_REQUEST\n schema_class = \"ConnectionRequestSchema\"\n\n def __init__(\n self, *, connection: ConnectionDetail = None, label: str = None, **kwargs\n ):\n super(ConnectionRequest, self).__init__(**kwargs)\n self.connection = connection\n self.label = label\n\n\nclass ConnectionRequestSchema(AgentMessageSchema):\n \"\"\" \"\"\"\n\n class Meta:\n \"\"\" \"\"\"\n\n model_class = ConnectionRequest\n\n connection = fields.Nested(ConnectionDetailSchema, required=True)\n label = fields.Str(required=True)\n","sub_path":"agent/indy_catalyst_agent/messaging/connections/messages/connection_request.py","file_name":"connection_request.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"7624283","text":"\n# coding: utf-8\n\n# # Load Data Set and Import Packages\n\n# In[1]:\n\nimport pandas as pd\nimport numpy as np \nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport matplotlib.gridspec as gridspec\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.manifold import TSNE\n\n\n# In[2]:\n\nget_ipython().magic('matplotlib inline')\n\n\n# In[3]:\n\ndf = pd.read_csv(\"E:/6598/Credit-Card-Fraud-Detection-in-Python-master/creditcard.csv\")\n\n\n# # Data Exploration\n\n# In[4]:\n\ndf.info()\n\n\n# We have 28 anonymized features, amount of transaction, time of transaction and the class of transaction in the dataset.\n\n# In[5]:\n\ndf.head()\n\n\n# In[6]:\n\ndf.describe()\n\n\n# In[7]:\n\ndf.isnull().sum()\n\n\n# Result: There is no Missing Value in this dataset so no imputations are required.\n\n# Target Column \"Class\". It has 2 values: 1- For Normal Transaction and 0- Fraud Transactions. Let us look at their numbers.\n\n# In[8]:\n\ncount_classes = pd.DataFrame(pd.value_counts(df['Class'], sort = True).sort_index())\ncount_classes\n\n\n# Result: Fraud transactions are only 492/(492+284315) = 0.1727% of total transactions.\n\n# # Let's see how independent variables are affecting dependent variable.\n\n# In[9]:\n\n# Plot histogram of each parameter\ndf.hist(figsize = (20,20))\nplt.show()\n\n\n# Most of the features are clustered right around 0 with some fairly large outliers or no outliers. Also, very few fraud than normal transactions.\n\n# In[10]:\n\n# Correlation Matrix with the Heat Map\n\ncorrmat = df.corr()\nfig = plt.figure(figsize = (12,9))\n\nsns.heatmap(corrmat, vmax = 0.8, square = True)\nplt.show()\n\n\n# Lot of value really close to 0, so there is not strong relations between V parameters. But some are affecting Target variable i.e. \"Class\". So, V11 is strongly positive correlated where as V17 is strongly negative correlated with \"Class\". No Strong relation with Amount and Time. \n\n# Fraud and normal transaction vs. time: Let's see how time compares across fraudulent and normal transactions.\n\n# In[11]:\n\nprint (df.Time[df.Class == 1].describe())\nprint ()\nprint (\"Normal\")\nprint (df.Time[df.Class == 0].describe())\n\n\n# In[12]:\n\nf, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12,4))\n\nbins = 50\n\nax1.hist(df.Time[df.Class == 1], bins = bins)\nax1.set_title('Fraud')\n\nax2.hist(df.Time[df.Class == 0], bins = bins)\nax2.set_title('Normal')\n\nplt.xlabel('Time (in Seconds)')\nplt.ylabel('Number of Transactions')\nplt.show()\n\n\n# Result: Fraudulent are more uniformly distributed, while valid transactions have a cyclical distribution: Number of valid transactions is much smaller during the wee hours of the morning (between 1 to 5am). This could make it easier to detect a fraudulent transaction during at an 'off-peak' time.\n\n# Fraud and normal transaction vs. Amount: Let's see how Amount compares across fraudulent and normal transactions.\n\n# In[13]:\n\nprint (\"Fraud\")\nprint (df.Amount[df.Class == 1].describe())\nprint ()\nprint (\"Normal\")\nprint (df.Amount[df.Class == 0].describe())\n\n\n# In[14]:\n\nf, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12,4))\n\nbins = 30\n\nax1.hist(df.Amount[df.Class == 1], bins = bins)\nax1.set_title('Fraud')\n\nax2.hist(df.Amount[df.Class == 0], bins = bins)\nax2.set_title('Normal')\n\nplt.xlabel('Amount ($)')\nplt.ylabel('Number of Transactions')\nplt.yscale('log')\nplt.show()\n\n\n# Result: Most transactions are small amounts, less than 100. Fraudulent transactions have a maximum value far less than normal transactions, $2,125.87 vs $25,691.16.\n\n# # Neural Network Using Keras\n\n# Let us create the threshold of fraud transaction.\n\n# In[15]:\n\nimport itertools\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.utils.np_utils import to_categorical\n\n\n# In[16]:\n\n#df['Normal']=1-df['Class'], instead I am converting Class to categorical\n\ndf['Amount_max_fraud'] = 1\ndf.loc[df.Amount <= 2125.87, 'Amount_max_fraud'] = 0\ndf.head()\n\n\n# # Setting Up Training an Test Data Sets\n\n# Stratify Class column in train -test split to keep the same Fraud/Normal ratio in train and test data. I am not using any validation dataset here.\n\n# In[17]:\n\ntrain,test=train_test_split(df,test_size=0.2,random_state=0,stratify=df['Class'])# stratify the Class\n\n\n# In[18]:\n\ncount_train = pd.value_counts(train['Class'], sort = True).sort_index()\ncount_test = pd.value_counts(test['Class'], sort = True).sort_index()\nprint (count_train) \n'\\n' \nprint(count_test)\n\n\n# Drop target columns from model input datsets\n\n# In[19]:\n\nX_train = train.drop(['Class'], axis = 1)\nX_test = test.drop(['Class'], axis = 1)\n\n\n# Define target sets:\n\n# In[20]:\n\nY_train = train.loc[:, ['Class']]\nY_test = test.loc[:, ['Class']]\n\n\n# In[21]:\n\n# Just sanity check\nprint(np.shape(X_train))\nprint(np.shape(Y_train))\nprint(np.shape(X_test))\nprint(np.shape(Y_test))\n\n\n# In[22]:\n\n#Now convert Y_train and Y_test to categorical values with 2 classes.\n\nY_train = to_categorical(Y_train, num_classes = 2)\nY_test = to_categorical(Y_test, num_classes = 2)\n\n\n# # Feature Centering and scaling\n# Centering and scaling of input datasets\n\n# In[23]:\n\n#Names all of the features in X_train.\nfeatures = X_train.columns.values\n\nfor feature in features:\n mean, std = df[feature].mean(), df[feature].std()\n X_train.loc[:, feature] = (X_train[feature] - mean) / std\n X_test.loc[:, feature] = (X_test[feature] - mean) / std\n\n\n# Now we start Keras model building\n\n# In[24]:\n\n# fix random seed for reproducibility\nnp.random.seed(2)\n\n\n# Set up a 5 layer network with last layer being the output layer. First layer has input dimention as 31 (number of columns in X_train). Activation is relu except last layer is with softmax activation Each layer has dropout at 0.9 (90% of data used at each layer)\n\n# In[25]:\n\nmodel = Sequential()\nmodel.add(Dense(64, input_dim=31, activation='relu'))\nmodel.add(Dropout(0.9))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.9))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.9))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.9))\nmodel.add(Dense(2, activation='softmax')) # With 2 outputs\n\n\n# Let us create X_test with this remaining 20% normal and fraud data\n\n# Compile model using binary crossentropy loss and adam optimizer for loss. Collect accuracy in metric.\n\n# In[26]:\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\n# Fit the compiled model on training data. I am using only 20 epochs to save time with batch_size of 2048.\n\n# In[27]:\n\nepoch = 20\nbatch_size = 2048\nmodel.fit(X_train, Y_train, epochs=epoch, batch_size=batch_size)\n\n\n# In[28]:\n\nscore, acc = model.evaluate(X_test, Y_test)\nprint('Test score:', score)\nprint('Test accuracy:', acc)\n\n\n# We get 99.82% Accuracy!\n\n# # Training and testing accuracy and loss vs epoch\n# \n# Let us plot train and test accuracy and loss vs. epoch collcting the history by running the model again:\n\n# In[29]:\n\nhistory = model.fit(X_train, Y_train, batch_size = 2048, epochs = 20, \n validation_data = (X_test, Y_test), verbose = 2)\n\n\n# In[30]:\n\n# Check the history keys\nhistory.history.keys()\n\n\n# In[31]:\n\nfig, ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"Testing loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history.history['acc'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_acc'], color='r',label=\"Testing accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)\nplt.show()\n\n\n# # Confusion Matrix\n\n# In[32]:\n\n# Let us have a look at the confusion matrix for this 2 classes. I am using the below function to get the confusion matrix. \n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\n# In[33]:\n\n# Predict the values from the validation dataset\nY_pred = model.predict(X_test)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(Y_test,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(2)) \nplt.show()\n\n\n# Basically the model did not predict the Fraud transactions correctly. However, it did not predict any Normal transaction as Fraud. So, Let us try to do it other way\n\n# # Logistic Regression\n\n# In[34]:\n\ndata = pd.read_csv(\"E:/6598/Credit-Card-Fraud-Detection-in-Python-master/creditcard.csv\")\ndata.head()\n\n\n# In[35]:\n\ncount_classes = pd.value_counts(data['Class'], sort = True).sort_index()\ncount_classes.plot(kind = 'bar')\nplt.title(\"Fraud class histogram\")\nplt.xlabel(\"Class\")\nplt.ylabel(\"Frequency\")\nplt.show()\n\n\n# Clearly we can see that data is highly skewed with majority class of normal transactions.\n# \n# Solution is UNDER-sampling, which deletes instances from the over-represented class\n\n# # Set Predictor and Response Variable\n# \n# 1. Normalising the amount column. The amount column is not in line with the anonymised features.\n\n# In[36]:\n\nfrom sklearn.preprocessing import StandardScaler\n\ndata['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1))\ndata = data.drop(['Time','Amount'],axis=1)\ndata.head()\n\n\n# 2. Assigning X and Y. Resampling\n\n# We will use UNDER-sampling. The way we will under sample the dataset will be by creating a 50/50 ratio. This will be done by randomly selecting \"x\" amount of sample from the majority class, being \"x\" the total number of records with the minority class.\n\n# In[37]:\n\nX = data.iloc[:, data.columns != 'Class']\ny = data.iloc[:, data.columns == 'Class']\n\n\n# In[38]:\n\n# Number of data points in the minority class\nnumber_records_fraud = len(data[data.Class == 1])\nfraud_indices = np.array(data[data.Class == 1].index)\n\n# Picking the indices of the normal classes\nnormal_indices = data[data.Class == 0].index\n\n# Out of the indices we picked, randomly select \"x\" number (number_records_fraud)\nrandom_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)\nrandom_normal_indices = np.array(random_normal_indices)\n\n# Appending the 2 indices\nunder_sample_indices = np.concatenate([fraud_indices,random_normal_indices])\n\n# Under sample dataset\nunder_sample_data = data.iloc[under_sample_indices,:]\n\nX_undersample = under_sample_data.iloc[:, under_sample_data.columns != 'Class']\ny_undersample = under_sample_data.iloc[:, under_sample_data.columns == 'Class']\n\n# Showing ratio\nprint(\"Percentage of normal transactions: \", len(under_sample_data[under_sample_data.Class == 0])/len(under_sample_data))\nprint(\"Percentage of fraud transactions: \", len(under_sample_data[under_sample_data.Class == 1])/len(under_sample_data))\nprint(\"Total number of transactions in resampled data: \", len(under_sample_data))\n\n\n# # Set Train and Test Data Set via Cross Validation\n\n# In[39]:\n\nfrom sklearn.cross_validation import train_test_split\n\n# Whole dataset\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)\n\nprint(\"Number transactions train dataset: \", len(X_train))\nprint(\"Number transactions test dataset: \", len(X_test))\nprint(\"Total number of transactions: \", len(X_train)+len(X_test))\n\n# Undersampled dataset\nX_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample\n ,y_undersample\n ,test_size = 0.3\n ,random_state = 0)\nprint(\"\")\nprint(\"Number transactions train dataset: \", len(X_train_undersample))\nprint(\"Number transactions test dataset: \", len(X_test_undersample))\nprint(\"Total number of transactions: \", len(X_train_undersample)+len(X_test_undersample))\n\n\n# In[40]:\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cross_validation import KFold, cross_val_score\nfrom sklearn.metrics import precision_recall_curve,auc,roc_auc_score,roc_curve,recall_score,classification_report \n\n\n# In[41]:\ndef printing_Kfold_scores(x_train_data,y_train_data):\n fold = KFold(len(y_train_data),5,shuffle=False) \n #recall_acss =[] \n\n # Different C parameters\n c_param_range = [0.01,0.1,1,10,100]\n\n results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score'])\n results_table['C_parameter'] = c_param_range\n\n # the k-fold will give 2 lists: train_indices = indices[0], test_indices = indices[1]\n j = 0\n for c_param in c_param_range:\n print('-------------------------------------------')\n print('C parameter: ', c_param)\n print('-------------------------------------------')\n print('')\n\n recall_accs = []\n for iteration, indices in enumerate(fold,start=1):\n\n # Call the logistic regression model with a certain C parameter\n lr = LogisticRegression(C = c_param, penalty = 'l1')\n\n # Use the training data to fit the model. In this case, we use the portion of the fold to train the model\n # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1]\n lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())\n\n # Predict values using the test indices in the training data\n y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)\n\n # Calculate the recall score and append it to a list for recall scores representing the current c_parameter\n recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample)\n recall_accs.append(recall_acc)\n print('Iteration ', iteration,': recall score = ', recall_acc)\n\n # The mean value of those recall scores is the metric we want to save and get hold of.\n results_table.loc[j,'Mean recall score'] = np.mean(recall_accs)\n j += 1\n print('')\n print('Mean recall score ', np.mean(recall_accs))\n print('')\n\n best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']\n \n # Finally, we can check which C parameter is the best amongst the chosen.\n print('*********************************************************************************')\n print('Best model to choose from cross validation is with C parameter = ', best_c)\n print('*********************************************************************************')\n \n return best_c\n\n\n# In[42]:\n \n \nbest_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)\n\n# Confusion Matrix\n\n# In[43]:\n\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=0)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n #print(\"Normalized confusion matrix\")\n else:\n 1#print('Confusion matrix, without normalization')\n\n #print(cm)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\n# # Predictions on test set and plotting confusion matrix\n\n# In[44]:\n\n# Use this C_parameter to build the final model with the whole training dataset and predict the classes in the test\n# dataset\nlr = LogisticRegression(C = best_c, penalty = 'l1')\nlr.fit(X_train_undersample,y_train_undersample.values.ravel())\ny_pred_undersample = lr.predict(X_test_undersample.values)\n\n# Compute confusion matrix\ncnf_matrix = confusion_matrix(y_test_undersample,y_pred_undersample)\nnp.set_printoptions(precision=2)\n\nprint(\"Recall metric in the testing dataset: \", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))\n\n# Plot non-normalized confusion matrix\nclass_names = [0,1]\nplt.figure()\nplot_confusion_matrix(cnf_matrix\n , classes=class_names\n , title='Confusion matrix')\nplt.show()\n\n\n# Model give Recall Accuracy as 93.87. So let's apply the model we fitted and test it on the whole data.\n\n# In[45]:\n\n# Use this C_parameter to build the final model with the whole training dataset and predict the classes in the test\n# dataset\nlr = LogisticRegression(C = best_c, penalty = 'l1')\nlr.fit(X_train_undersample,y_train_undersample.values.ravel())\ny_pred = lr.predict(X_test.values)\n\n# Compute confusion matrix\ncnf_matrix = confusion_matrix(y_test,y_pred)\nnp.set_printoptions(precision=2)\n\nprint(\"Recall metric in the testing dataset: \", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))\n\n# Plot non-normalized confusion matrix\nclass_names = [0,1]\nplt.figure()\nplot_confusion_matrix(cnf_matrix\n , classes=class_names\n , title='Confusion matrix')\nplt.show()\n\n\n# Got Recall Accuracy as 92.5 which is quite decent!\n\n# # Plotting ROC curve and Precision-Recall curve.\n\n# In[46]:\n\n# ROC CURVE\nlr = LogisticRegression(C = best_c, penalty = 'l1')\ny_pred_undersample_score = lr.fit(X_train_undersample,y_train_undersample.values.ravel()).decision_function(X_test_undersample.values)\n\nfpr, tpr, thresholds = roc_curve(y_test_undersample.values.ravel(),y_pred_undersample_score)\nroc_auc = auc(fpr,tpr)\n\n# Plot ROC\nplt.title('Receiver Operating Characteristic')\nplt.plot(fpr, tpr, 'b',label='AUC = %0.2f'% roc_auc)\nplt.legend(loc='lower right')\nplt.plot([0,1],[0,1],'r--')\nplt.xlim([-0.1,1.0])\nplt.ylim([-0.1,1.01])\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\n\n# # One Class SVM Linear\n\n# In[47]:\n\nfrom sklearn import svm\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import classification_report\n\n\n# In[48]:\n\nW_Data=pd.read_csv(\"E:/6598/Credit-Card-Fraud-Detection-in-Python-master/creditcard.csv\")\nW_Data.dropna(thresh=284807)\nData=W_Data\n\n\n# In[49]:\n\nPositives = W_Data[Data['Class']==1]\nNegatives = W_Data[Data['Class']==0]\n\n\n# In[50]:\n\nprint((len(Positives)/len(Data))*100,\"%\")\n\n\n# In[51]:\n\nTrain_Data=Data[1:50000]\nTarget=Train_Data['Class']\nTrain_Data.drop('Class',axis=1,inplace=True)\n\n\n# In[52]:\n\nx_train,x_test,y_train,y_test=train_test_split(Train_Data,Target,test_size=0.5,random_state=0)\n\n\n# In[53]:\n\nfrom sklearn.covariance import EllipticEnvelope \n#An Object for detecting outliers in a Gaussian distributed dataset\n\n\n# In[54]:\n\n#Linear Kernel\nclf_AD_L = svm.OneClassSVM(nu=0.1, kernel=\"linear\", gamma=0.1)\nclf_AD_L.fit(Negatives)\n\n\n# In[55]:\n\ntrain_AD_L=clf_AD_L.predict(Negatives)\ntest_AD_L=clf_AD_L.predict(Positives)\n\n\n# In[56]:\n\ndef Train_Accuracy(Mat):\n \n Sum=0\n for i in Mat:\n \n if(i==1):\n \n Sum+=1.0\n \n return(Sum/len(Mat)*100)\n\ndef Test_Accuracy(Mat):\n \n Sum=0\n for i in Mat:\n \n if(i==-1):\n \n Sum+=1.0\n \n return(Sum/len(Mat)*100)\n\n\n# In[57]:\n\nprint(\"Training: One Class SVM (Linear) : \",(Train_Accuracy(train_AD_L)),\"%\")\nprint(\"Test: One Class SVM (Linear) : \",(Test_Accuracy(test_AD_L)),\"%\")\n\n\n# # Isolation Forest\n\n# In[58]:\n\nfrom sklearn.ensemble import IsolationForest\n\n\n# In[59]:\n\nIFA=IsolationForest()\nIFA.fit(Negatives)\n\n\n# In[60]:\n\ntrain_IFA=IFA.predict(Negatives)\ntest_IFA=IFA.predict(Positives)\n\n\n# In[61]:\n\nprint(\"Training: Isolation Forest: \",(Train_Accuracy(train_IFA)),\"%\")\nprint(\"Test: Isolation Forest: \",(Test_Accuracy(test_IFA)),\"%\")\n\n\n# Isolation Forest has worked way better than one class SVM. Thus, considered as best anomaly detection model.\n","sub_path":"ajith code.py","file_name":"ajith code.py","file_ext":"py","file_size_in_byte":21230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"490101626","text":"# 503. Next Greater Element II\n\n# Given a circular array (the next element of the last element is the first element of the array), \n# print the Next Greater Number for every element. \n# The Next Greater Number of a number x is the first greater number to its traversing-order next in the array,\n# which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.\n\n# Example 1:\n# Input: [1,2,1]\n# Output: [2,-1,2]\n# Explanation: The first 1's next greater number is 2; \n# The number 2 can't find next greater number; \n# The second 1's next greater number needs to search circularly, which is also 2.\n# Note: The length of given array won't exceed 10000.\n\nclass NextGreaterElementsII(object):\n\n\n def doit(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n N = len(nums)\n nums = nums * 2\n st, res = [], [-1 for _ in range(N)]\n \n for n in range(len(nums)):\n \n while st and nums[n] > nums[st[-1]]:\n res[st.pop()] = nums[n]\n \n if n < N:\n st.append(n)\n \n return res\n\n\n\n def doit1(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n ans=[]\n n=len(nums)\n if n==0: \n return []\n \n i = 1\n s = [0]\n ans = [-1] * n\n\n for i in range(1,n):\n while s and nums[i] > nums[s[-1]]:\n ans[s[-1]] = nums[i]\n s.pop()\n s.append(i)\n\n #print s\n for i in range(n):\n while nums[i]> nums[s[-1]]:\n ans[s[-1]] = nums[i]\n s.pop() \n\n return ans\n \n\nif __name__ == \"__main__\":\n\n res = NextGreaterElementsII().doit()","sub_path":"PythonLeetcode/LeetCodeE/503_NextGreaterElementII.py","file_name":"503_NextGreaterElementII.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"129497721","text":"import numpy as np\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\nfrom snpa import snpa\n\n\ndef create_time_resolved_spectra():\n t = np.linspace(0,50,50)\n v = np.linspace(0,40,100)\n trace = np.array([np.exp(-t/10), 1-np.exp(-t/10)]).T\n spectra = np.array([norm.pdf(v, 10, 1), norm.pdf(v, 25, 3)]).T\n spectra3d = trace.dot(spectra.T)\n return (t, trace), (v, spectra), spectra3d\n\ndef check_nmf(trspec, nmf_spectra, nmf_trace):\n \"\"\"\n Check if not nan or inf in nmf_spectra and nmf_trace,\n and print error of decomposition.\n \"\"\"\n \n if not all(np.isfinite(data).all() for data in [nmf_spectra, nmf_trace]):\n print('NMF error')\n mse, max_relerr = 0, 0\n return mse, max_relerr\n \n reconst_trspec = nmf_trace.dot(nmf_spectra)\n mse = np.sqrt(np.mean((reconst_trspec[:] - trspec[:])**2))\n eps = np.max(trspec[:]) * 1e-3\n rel_err = np.abs(1 - (reconst_trspec[:]+eps) / (trspec[:]+eps))\n max_relerr = np.max(rel_err)\n print('max relative error is %.4f'%max_relerr)\n return mse, max_relerr\n \ndef plot_spectra_compare(trspec, v, t, \n nmf_spectra, nmf_trace, \n ref_trace, time_index):\n \n fig, axes = plt.subplots(3,1)\n \n # NMF spectra\n axes[0].plot(v, nmf_spectra.T)\n legend_str = ['spectra_{nmf-sp %d}'%i \n for i in range(nmf_spectra.shape[0])]\n axes[0].legend(legend_str)\n axes[0].set_title('NMF result')\n axes[0].set_xlabel('wavelength')\n \n # Time-resolved spectra\n axes[1].plot(v, trspec[time_index,:].T)\n legend_str = ['t = %.1f us'%t[i] for i in time_index]\n axes[1].legend(legend_str)\n axes[1].set_title('Original spectra')\n axes[1].set_xlabel('wavelength')\n \n # Temporal profile\n\n scale_ref_trace = ref_trace * \\\n (np.max(nmf_trace,axis=0) / np.max(ref_trace,axis=0))\n axes[2].plot(t, nmf_trace)\n axes[2].plot(t, scale_ref_trace,'o')\n legend_str = ['trace_{nmf-sp %d}'%i \n for i in range(nmf_trace.shape[1])]\n legend_str.extend(['trace_{ref-peak %d}'%i \n for i in range(ref_trace.shape[1])])\n axes[2].legend(legend_str)\n axes[2].set_title('comparison of ref_trace and nmf_trace')\n axes[2].set_xlabel('time') \n axes[2].set_ylabel('intensity')\n \n plt.subplots_adjust(hspace=0.5)\n \n return fig, axes\n\ndef plot_trspec(t, v, trspec):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n T, V = np.meshgrid(v, t)\n surf = ax.plot_surface(T, V, trspec, cmap=cm.jet)\n ax.set_title('time-resolved spectra')\n ax.set_xlabel('wavelength')\n ax.set_ylabel('time')\n ax.set_zlabel('intensity')\n fig.colorbar(surf, shrink=0.5, aspect=5)\n return ax\n \n \nif __name__ == '__main__':\n plt.close('all')\n \n # Read excel file for spectral data of Criegee.\n (t, ref_trace), (v, ref_spectra), trspec = create_time_resolved_spectra()\n num_species = ref_spectra.shape[1]\n plt_trspec = plot_trspec(t, v, trspec)\n \n # Execute NMF\n [J, nmf_spectra] = snpa(trspec, num_species)\n nmf_trace = trspec[:, J]\n \n # Check NMF and correct by reference\n mse = check_nmf(trspec, nmf_spectra, nmf_trace)\n rot_spectra = np.linalg.pinv(ref_trace).dot(nmf_trace).dot(nmf_spectra)\n \n # Plot and save result\n time_index = np.linspace(0,trspec.shape[0]-1,4).astype(int)\n plot_spectra_compare(trspec,v,t,nmf_spectra,nmf_trace,ref_trace,time_index)\n # save_nmf_result(v,nmf_spectra,rot_spectra,t,nmf_trace,ref_trace)\n \n plt.show()","sub_path":"spectral_image_NMF.py","file_name":"spectral_image_NMF.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"205525596","text":"import sys\r\n\r\nn = int(input().strip())\r\ntypes = list(map(int, input().strip().split(' ')))\r\ncounts = {}\r\n\r\nfor bird in types:\r\n if bird not in counts:\r\n counts[bird] = 1\r\n else:\r\n counts[bird] += 1\r\n\r\nhighest_count = max(counts.values())\r\nlowest_ID = None\r\n\r\nfor key in counts:\r\n if counts[key] == highest_count:\r\n if lowest_ID == None or int(key) < lowest_ID:\r\n lowest_ID = int(key)\r\n \r\nprint(lowest_ID)\r\n","sub_path":"Challange 1.py","file_name":"Challange 1.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"123294775","text":"# https://leetcode.com/problems/longest-substring-without-repeating-characters/submissions/\n# Sliding Window\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n start = 0\n m = 0\n f = {}\n for end in range(len(s)):\n c = s[end]\n \n if c in f:\n start = max(start, f[c] + 1)\n f[c] = end\n m = max(m, end - start + 1)\n\n return m\n","sub_path":"medium/longest_substr_without_repeating.py","file_name":"longest_substr_without_repeating.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"322014219","text":"import requests\nimport hashlib\n\nclass Nordict():\n\t\"\"\"Nordic-T Python API wrapper\"\"\"\n\t\n\t#VARS\n\tBASEURL = 'https://api.nordic-t.me/api/public/'\n\tAPPID = '' #APP ID provided by staff\n\tAPPSECRET = '' #APP Secret provided by staff\n\n\tdef __init__(self, username, token = \"\"):\n\t\tself.username = username\n\t\tself.usertoken = token\n\t\tself.useragent = '' #Useragent\n\t\tself.client = requests.session(headers={'User-Agent': self.useragent})\n\n\tdef login(self):\n\t\ttry:\n\t\t\tsigned = hashlib.sha1(self.APPSECRET + self.APPID + self.username).hexdigest()\n\t\t\tparams = {'username': self.username, 'appId': self.APPID, 'signed': signed}\n\t\t\tif not self.usertoken == \"\":\n\t\t\t\tparams['token'] = self.usertoken\n\n\t\t\trequest = self.client.post(self.BASEURL + 'authorize', data=params)\n\t\t\tself.usertoken = request.json['data']['token']\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getForums(self):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.get(self.BASEURL + 'forums', params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getSubforum(self, forumid, offset = 0, limit = 60):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken, 'offset': offset, 'limit': limit}\n\t\t\trequest = self.client.get(self.BASEURL + 'forums/' + forumid, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getLatest(self, offset = 0, limit = 60):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken, 'offset': offset, 'limit': limit}\n\t\t\trequest = self.client.get(self.BASEURL + 'forums/topics/last', params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getUser(self, userid):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.get(self.BASEURL + 'user/' + userid, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getuserPosts(self, userid, offset = 0, limit = 60):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken, 'offset': offset, 'limit': limit}\n\t\t\trequest = self.client.get(self.BASEURL + 'user/' + userid + '/posts/', params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef createTopic(self, forumid, subject, message):\n\t\ttry:\n\t\t\tdata = {'subject': subject, 'message': message}\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.post(self.BASEURL + 'forums/' + forumid, data=data, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef createReply(self, topicid, message):\n\t\ttry:\n\t\t\tdata = {'message': message}\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.post(self.BASEURL + 'forums/topic/' + topicid, data=data, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef reportUser(self, userid, reason):\n\t\ttry:\n\t\t\tdata = {'reason': reason}\n\t\t\tparams = {'token': self.usertoken}\t\t\t\n\t\t\trequest = self.client.post(self.BASEURL + 'user/repost/' + userid, data=data, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef reportPost(self, postid, reason):\n\t\ttry:\n\t\t\tdata = {'reason': reason}\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.post(self.BASEURL + 'forums/post/' + postid + '/report/', data=data, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef editPost(self, postid, message):\n\t\ttry:\n\t\t\tdata = {'message': message}\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.post(self.BASEURL + 'forums/post/' + postid + '/edit/', data=data, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef sendPM(self, receiver, msg, save = 'true'):\n\t\ttry:\n\t\t\tdata = {'receiver': receiver, 'msg': msg, 'saveInOutbox': save}\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.post(self.BASEURL + 'privatemessages/', data=data, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getPost(self, postid):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken}\n\t\t\trequest = self.client.get(self.BASEURL + 'forums/post/' + postid, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getTopic(self, topicid, offset = 0, limit = 60):\n\t\ttry:\n\t\t\tparams = {'token': self.usertoken, 'offset': offset, 'limit': limit}\n\t\t\trequest = self.client.get(self.BASEURL + 'forums/topic/' + topicid, params=params)\n\t\t\treturn request\n\t\texcept:\n\t\t\treturn False\n\n\tdef getAuthURL(self, username):\n\t\tsigned = hashlib.sha1(self.APPSECRET + self.APPID + self.username).hexdigest()\n\n\t\tlink = 'https://nordic-t.me/api-auth.php?username=' + username + '&appId=' + self.APPID + \"&signed=\" + signed\n\n\t\treturn link","sub_path":"nordict.py","file_name":"nordict.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"176536207","text":"import pandas as pd\nimport numpy as np\nimport re\n\"\"\"\nwhere the x axis is the value of the observation\nand y axis represents the probability that a\ngiven observation will occur\nif all numbers are equally likely to be drawn\nwhen you sample from it.\nthis should be graphed as a flat horizontal line\nand this flat line is actually called the uniform distribution\ntake the normal distribution which is also called the\nGaussian Distribution or Bell curve\n\"\"\"\n\n\n# with open(\"university_towns.txt\", \"r\") as f:\n# data = []\n# for line in f:\n# m = re.search('(.+)\\[edit\\]', line)\n# if m:\n# state = m.group(1)\n# else:\n# town = line.split('(')[0].strip() # 当没有匹配到state时,上一个在解释器中的state还并没有消失\n# print(data)\n# data.append([state, town])\n# print(data)\n\n\ndef copy(origin):\n \"\"\"\n 实现复制字符串\n \"\"\"\n origin_list = [x for x in origin]\n new = \"\".join(origin_list)\n return new\n\n\ndef flat(origin):\n \"\"\"\n [[['a'],['b'], ['c']]] --> ['a', 'b', 'c']\n \"\"\"\n if len(origin) != 3:\n return flat(origin[0])\n # 递归调用\n else:\n res = []\n for i in origin:\n res.append(i[0])\n return res\n\n\ndef search(a, n, key):\n a.insert(0, key) # 哨兵\n print(a)\n i = n # 列表长度\n while a[i] != key:\n i -= 1\n # 返回0就是查找失败\n return i\n\n\nif __name__ == '__main__':\n # test = copy(\"a cb d\")\n # print(test)\n # test = flat([[['a'], ['b'], ['c']]])\n # print(test)\n test = search([2, 3, 4], 3, 1)\n print(test)\n","sub_path":"Applied-Data-Science-With-Python/Introduction to Data Science in Python/week4/More Distributions.py","file_name":"More Distributions.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"29316258","text":"from ALEFramework.AgentVehicle import AgentVehicle\nclass Fox(AgentVehicle):\n def __init__(self):\n mdNames = ['wheel1', 'wheel2', 'wheel3', 'wheel4']\n turnSpeed = 1.0\n forSpeed = 1.0\n objName = 'Fox'\n super().__init__(mdNames, turnSpeed, forSpeed, objName)\n self.food = ['AdultRabbit','AdultRabbit1','AdultRabbit2','BabyRabbit','BabyRabbit1']\n self.wheels = self.getMotorDevices()\n self.infPos = float('inf')\n self.multiMoveMotorPos(self.wheels, self.infPos)\n self.setMultiMotorVel(self.wheels, 1)\n self.setMaxEnergy(100000)\n self.setEnergy(100000)\n self.setConsumptionEnergy(20000)\n \n def behaviour(self):\n while self.robot.step(self.timestep) != -1:\n if self.energy > 0:\n self.energy = self.energy -1\n self.moveForward()\n if self.energy < 100000:\n isCollision = self.checkEnergyCollision(self.food)\n if isCollision:\n self.eat(isCollision)\n angle = self.checkRecogniseSource()\n if angle < -0.1:\n self.turnSlowLeft()\n \n elif angle > 0.1:\n self.turnSlowRight()\n \n elif angle <= 0.1 and angle >= -0.1:\n self.moveForward()\n \n isObstacle = self.checkObstacle()\n \n if isObstacle:\n self.avoidObstacle(isObstacle)\n \n else:\n self.setMultiMotorVel(self.wheels, 0)\nfox = Fox()\nfox.behaviour()","sub_path":"ALE_Example2/Controllers_For_Example/Fox_Controller/Fox_Controller.py","file_name":"Fox_Controller.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"448591105","text":"#Hello_Github Test\n\nb = 1\ns = 0\na = [int(input(\"digite o primeiro número da lista\"))]\nwhile (b !=0):\n b = int(input(\"digite mais um número da lista, digite 0 para sair\"))\n a.append(b)\n s= s+1\n\ndel(a[s])\n\na.sort()\nt=len(a) - 2\n\ns = 0\nwhile (s < t):\n if (a[s] == a[s+1]):\n del(a[s])\n t=t-1\n s=s-1\n s=s+1\n \nprint(a)\n","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"319807152","text":"# -*- coding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1520541008.222573\n_enable_loop = True\n_template_filename = 'C:/Users/mayaroney/desktop/fomo/homepage/templates/faq.html'\n_template_uri = 'faq.html'\n_source_encoding = 'utf-8'\nimport django_mako_plus\nimport django_mako_plus\n_exports = ['top_center', 'content_left', 'content_right', 'content_center']\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'app_base.html', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n def content_center():\n return render_content_center(context._locals(__M_locals))\n def top_center():\n return render_top_center(context._locals(__M_locals))\n def content_right():\n return render_content_right(context._locals(__M_locals))\n def content_left():\n return render_content_left(context._locals(__M_locals))\n __M_writer = context.writer()\n __M_writer('\\r\\n\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'top_center'):\n context['self'].top_center(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'content_left'):\n context['self'].content_left(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'content_right'):\n context['self'].content_right(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'content_center'):\n context['self'].content_center(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_top_center(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def top_center():\n return render_top_center(context)\n __M_writer = context.writer()\n __M_writer('\\r\\n

Frequently Asked Questions

\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content_left(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def content_left():\n return render_content_left(context)\n __M_writer = context.writer()\n __M_writer('\\r\\n

faq left side

\\r\\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content_right(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def content_right():\n return render_content_right(context)\n __M_writer = context.writer()\n __M_writer('\\r\\n

faq right side

\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content_center(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def content_center():\n return render_content_center(context)\n __M_writer = context.writer()\n __M_writer(\"\\r\\n

Questions

\\r\\n How many instruments do you guys sell?

\\r\\n How long can I rent a flute for?

\\r\\n Who owns this place?

\\r\\n Do you do daily rentals?

\\r\\n What's the cheapest rental?

\\r\\n Do you guys offer music classes?

\\r\\n Do you offer any private piano lessons?

\\r\\n Do you have any locations on the East Coast?

\\r\\n\")\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"C:/Users/mayaroney/desktop/fomo/homepage/templates/faq.html\", \"uri\": \"faq.html\", \"source_encoding\": \"utf-8\", \"line_map\": {\"29\": 0, \"42\": 1, \"47\": 6, \"52\": 11, \"57\": 15, \"62\": 28, \"68\": 4, \"74\": 4, \"80\": 8, \"86\": 8, \"92\": 13, \"98\": 13, \"104\": 18, \"110\": 18, \"116\": 110}}\n__M_END_METADATA\n\"\"\"\n","sub_path":"homepage/templates/.cached_templates/faq.html.py","file_name":"faq.html.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"275065441","text":"# Победители Мировой серии.\n\ndef main():\n filename = 'WorldSeriesWinners.txt'\n\n # Сохраняю в переменую прочитаный файл.\n rf = read_file(filename)\n # Словарь с годами и победителями.\n yw = years_winners(rf)\n # Словарь с командами и кол-вом побед.\n cw = count_winners(yw)\n\n print('Введите год в диапазоне 1903 и 2009 годами.')\n year = input('Год: ')\n if year == '1904' or year == '1994':\n print('В', year, 'г. не проводили чемпионат.')\n elif year in yw:\n print('В этом году побеждала команда:', yw[year])\n comand = yw[year]\n print('У которой за сезон с 1903 - 2009 год -', cw[comand], 'побед(а/ы).')\n\ndef read_file(filename):\n \"\"\"Читаю данные из файла\"\"\"\n\n with open(filename, 'r', encoding='utf-8') as rfile:\n\n winner = rfile.read().split('\\n')\n\n rfile.close()\n\n return winner\n\ndef years_winners(filename):\n \"\"\"Годы и команды побеждающие в них\"\"\"\n\n # Пустой словарь.\n com_win_year = {}\n\n # Перебираю список.\n for f in filename:\n # Если в списке есть значение: 1904\n # 1994 пропускаем их.\n if f[0:4] == '1904' or f[0:4] == '1994':\n continue\n else:\n # Записываем ключ(год):значение(команда)\n com_win_year[f[0:4]] = f[5:]\n\n # Возвращаю словарь.\n return com_win_year\n\ndef count_winners(dict_winner):\n \"\"\"Команды и их победы с 1903 - 2009 г.\"\"\"\n\n # Пустой словарь.\n com_win = {}\n\n # Перебираю словарь.\n for v in dict_winner.values():\n # Если в словаре нет значение, то записываю.\n if v not in com_win:\n # Записываю значение ключ(команда):значение(кол-во побед)\n com_win[v] = list(dict_winner.values()).count(v)\n\n # Возвращаю словарь.\n return com_win\n\nmain()","sub_path":"9/tasks/9.7.py","file_name":"9.7.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"299432121","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/10/11\n# @Author : ywh\n# @Email : yipwinghong@outlook.com\n# @File : Stack\n# @Software: PyCharm\n\nfrom data_structure.LinearList import *\n\nfrom array import array\nimport string\nimport random\n\nMAXSIZE = 10\n\n\nclass SqStack(object):\n \"\"\" 顺序栈 \"\"\"\n\n def __init__(self, elem=None, stack_size=MAXSIZE):\n \"\"\" 初始化 \"\"\"\n\n self.base = 0\n self.top = 0\n self.stack_size = stack_size\n if elem and len(elem) <= self.stack_size:\n self.top += len(elem)\n self.elem = elem\n else:\n self.elem = []\n\n def __len__(self):\n return self.top\n\n @property\n def is_full(self):\n return self.top - self.base == self.stack_size\n\n @property\n def is_empty(self):\n \"\"\" 判断是否空栈 \"\"\"\n return self.top == self.base\n\n @property\n def values(self):\n \"\"\" 取所有元素\"\"\"\n\n return self.elem\n\n def init_stack(self):\n \"\"\" 创建顺序栈 \"\"\"\n\n def push(self, value):\n \"\"\" 入栈 \"\"\"\n\n if self.is_full:\n return False\n\n self.top += 1\n self.elem.append(value)\n\n return True\n\n def pop(self):\n \"\"\" 出栈 \"\"\"\n\n if self.is_empty:\n return False\n\n self.top -= 1\n value = self.elem.pop()\n\n return value\n\n def get_top(self):\n \"\"\" 取栈顶元素 \"\"\"\n\n if self.top == self.base:\n return False\n\n return self.elem[-1]\n\n\nclass StackNode(object):\n \"\"\" 链栈节点 \"\"\"\n\n def __init__(self, elem=None, next=None):\n \"\"\" 初始化 \"\"\"\n\n self.elem = elem\n self.next = next\n\n\nclass LinkStack(object):\n \"\"\" 链栈 \"\"\"\n\n def __init__(self, elem=None):\n \"\"\" 初始化 \"\"\"\n\n self.top = StackNode() # 栈顶指针\n\n if elem:\n for value in elem:\n self.push(value)\n\n @property\n def values(self):\n \"\"\" 取所有元素 \"\"\"\n\n elem_list = []\n p = self.top.next\n while p:\n elem_list.insert(0, p.elem)\n p = p.next\n\n return elem_list\n\n def push(self, value):\n \"\"\" 入栈 \"\"\"\n\n # 新建节点,其next域置为栈顶指针next域,并把栈顶指针next域置为该节点\n self.top.next = StackNode(value, self.top.next)\n\n return True\n\n def pop(self):\n \"\"\" 出栈 \"\"\"\n\n # 取栈顶指针next域所指节点后弹出\n value = self.top.next.elem\n self.top.next = self.top.next.next\n\n return value\n\n\nclass DblStack(object):\n\n def __init__(self):\n self.top_0 = -1\n self.top_1 = MAXSIZE\n self.elem = [None] * MAXSIZE\n\n @property\n def is_empty(self):\n return self.top_0 == -1 and self.top_1 == MAXSIZE\n\n @property\n def is_full(self):\n return self.top_0 + 1 == self.top_1\n\n def push(self, stack_no, elem):\n if self.is_full:\n return False\n if stack_no == 0:\n self.top_0 += 1\n self.elem[self.top_0] = elem\n else:\n self.top_1 -= 1\n self.elem[self.top_1] = elem\n return True\n\n def pop(self, stack_no):\n if (stack_no == 0 and self.top_0 == -1) or (stack_no == 1 and self.top_1 == MAXSIZE):\n return False\n elif stack_no == 0:\n elem = self.elem[self.top_0]\n self.elem[self.top_0] = None\n self.top_0 -= 1\n else:\n elem = self.elem[self.top_1]\n self.elem[self.top_1] = None\n self.top_1 += 1\n\n return elem\n\n\n# 栈应用:数制转换\ndef coversion(num, system):\n \"\"\" 数制转换 \"\"\"\n\n remainder_stack = SqStack()\n while num:\n value = num % system\n remainder_stack.push(value)\n num //= system\n\n value = \"\"\n while not remainder_stack.is_empty:\n value += str(remainder_stack.pop())\n\n return value\n\n\n# 栈应用:符号匹配\ndef maching(symbol_list):\n \"\"\" 符号匹配 \"\"\"\n\n symbol_stack = SqStack()\n\n for item in list(symbol_list):\n if item in [\"(\", \"[\", \"{\"]:\n symbol_stack.push(item)\n elif (item == \")\" and symbol_stack.get_top() == \"(\") \\\n or (item == \"]\" and symbol_stack.get_top() == \"[\") \\\n or (item == \"}\" and symbol_stack.get_top() == \"{\"):\n symbol_stack.pop()\n else:\n break\n\n return True if symbol_stack.is_empty else False\n\n\n# 栈应用:表达式求值\ndef eval_expr(expr):\n \"\"\" 表达式求值 \"\"\"\n\n expr = list(expr)\n\n # 栈底元素\n if expr[0] != \"#\":\n return False\n\n # 算术符优先级\n precede_map = {\n (\"+\", \"+\"): \">\", (\"+\", \"-\"): \">\", (\"+\", \"*\"): \"<\", (\"+\", \"/\"): \"<\",\n (\"+\", \"(\"): \"<\", (\"+\", \")\"): \">\", (\"+\", \"#\"): \">\",\n (\"-\", \"+\"): \">\", (\"-\", \"-\"): \">\", (\"-\", \"*\"): \"<\", (\"-\", \"/\"): \"<\",\n (\"-\", \"(\"): \"<\", (\"-\", \")\"): \">\", (\"-\", \"#\"): \">\",\n (\"*\", \"+\"): \">\", (\"*\", \"-\"): \">\", (\"*\", \"*\"): \">\", (\"*\", \"/\"): \">\",\n (\"*\", \"(\"): \"<\", (\"*\", \")\"): \">\", (\"*\", \"#\"): \">\",\n (\"/\", \"+\"): \">\", (\"/\", \"-\"): \">\", (\"/\", \"*\"): \">\", (\"/\", \"/\"): \">\",\n (\"/\", \"(\"): \"<\", (\"/\", \")\"): \">\", (\"/\", \"#\"): \">\",\n (\"(\", \"+\"): \"<\", (\"(\", \"-\"): \"<\", (\"(\", \"*\"): \"<\", (\"(\", \"/\"): \"<\",\n (\"(\", \"(\"): \"<\", (\"(\", \")\"): \"=\", (\"(\", \"#\"): \"\",\n (\")\", \"+\"): \">\", (\")\", \"-\"): \">\", (\")\", \"*\"): \">\", (\")\", \"/\"): \">\",\n (\")\", \"(\"): \" \", (\")\", \")\"): \">\", (\")\", \"#\"): \">\",\n (\"#\", \"+\"): \"<\", (\"#\", \"-\"): \"<\", (\"#\", \"*\"): \"<\", (\"#\", \"/\"): \"<\",\n (\"#\", \"(\"): \"<\", (\"#\", \")\"): \" \", (\"#\", \"#\"): \"=\",\n }\n\n num_stack = SqStack() # 操作数栈\n op_stack = SqStack() # 操作符栈\n op_stack.push(expr.pop(0)) # 操作栈底置入“#”\n\n # 表达式未结束或符栈非空时执行循环\n ch = expr.pop(0)\n while ch != \"#\" or op_stack.get_top() != \"#\":\n\n # 表达式字符为数字则直接入数栈\n if ch in string.digits:\n num_stack.push(ch)\n ch = expr.pop(0)\n\n # 表达式字符为符\n else:\n # 取符栈顶元素与表达式符比较\n precede = precede_map.get((op_stack.get_top(), ch))\n\n # 栈顶符比表达式符优先级高\n # 弹出栈顶符、弹出数栈顶两个数字,计算结果后置入数栈\n if precede == \">\":\n op = op_stack.pop()\n num2 = num_stack.pop()\n num1 = num_stack.pop()\n res = str(eval(\"{0}{1}{2}\".format(num1, op, num2)))\n num_stack.push(res)\n\n # 栈顶符比表达式符优先级低\n # 表达式符入栈\n elif precede == \"<\":\n op_stack.push(ch)\n ch = expr.pop(0)\n\n # 栈顶符与表达式符优先级相等:左右括号相遇,弹出\n elif precede == \"=\":\n op_stack.pop()\n ch = expr.pop()\n\n else:\n return False\n\n # 数栈顶即为计算结果\n return num_stack.pop()\n\n\ndef eval_expr2(expr):\n \"\"\" 使用逆波兰式计算表达式 \"\"\"\n\n operators = list(\"+-*/()\")\n priority = {\"(\": 1, \"+\": 3, \"-\": 3, \"*\": 5, \"/\": 5, \"%\": 5}\n\n \"\"\" tokenizer:切分中序表达式为字符列表 \"\"\"\n expr = expr.strip()\n index, length = 0, len(expr)\n tokens = []\n\n while index < length:\n\n # 处理操作符\n if expr[index] in operators:\n tokens.append(expr[index])\n index += 1\n\n # 处理整数\n elif expr[index].isdigit():\n val = \"\"\n while index < length and expr[index].isdigit():\n val += expr[index]\n index += 1\n tokens.append(val)\n\n # 处理小数\n elif expr[index] == \".\":\n val = tokens.pop() + expr[index]\n index += 1\n\n while expr[index] not in operators:\n val += expr[index]\n index += 1\n\n tokens.append(val)\n\n # 处理空格(多个空格只保留一个)\n elif expr[index] == \" \":\n tokens.append(\" \")\n while index < length and expr[index] == \" \":\n index += 1\n\n else:\n break\n\n # TODO 处理负指数\n # j = index + 1\n #\n # while j < len(expr) and not expr[j].isspace() and expr[j] not in operators:\n # if (expr[j] == \"e\" or expr[j] == \"E\") and j + 1 < len(expr) and expr[j+1] == \"-\":\n # j += 1\n # j += 1\n #\n # res.append(expr[index:j])\n # index = j\n\n \"\"\" 转换中序表达式为后序表达式 \"\"\"\n op_stack = SqStack()\n suffix_expr = \"\"\n\n for token in tokens:\n # print(op_stack.values)\n\n # 当前字符数字直接加入到结果串\n if token not in operators:\n suffix_expr += \" \" + token\n\n # 左括号无视优先级直���入栈\n elif op_stack.is_empty or token == \"(\":\n op_stack.push(token)\n\n # 当前字符为右括号,把栈中、括号内的所有符号依次加入到结果串\n elif token == \")\":\n while not op_stack.is_empty and op_stack.get_top() != \"(\":\n suffix_expr += \" \" + op_stack.pop()\n\n # 找不到左括号\n if op_stack.is_empty:\n return False\n\n op_stack.pop()\n\n # 当前字符为+、-、*、/\n else:\n # 栈非空且栈顶元素的符号优先级高于等于当前字符,加入到结果串\n while not op_stack.is_empty \\\n and priority[op_stack.get_top()] >= priority[token]:\n\n suffix_expr += \" \" + op_stack.pop()\n\n # 直到栈为空或栈顶元素优先级低于当前字符,把当前字符入栈\n op_stack.push(token)\n\n # 取栈中剩余的元素加入到结果串\n while not op_stack.is_empty:\n\n if op_stack.get_top() == \"(\":\n return False\n\n suffix_expr += \" \" + op_stack.pop()\n\n \"\"\" 计算后序表达式 \"\"\"\n stack = SqStack()\n for char in suffix_expr.strip().split(\" \"):\n\n if char in operators:\n right, left = float(stack.pop()), float(stack.pop())\n if char == \"+\":\n stack.push(left + right)\n elif char == \"-\":\n stack.push(left - right)\n elif char == \"*\":\n stack.push(left * right)\n elif char == \"/\":\n stack.push(left / right)\n elif char == \"%\":\n stack.push(left % right)\n else:\n return False\n\n if char.isdigit():\n stack.push(char)\n\n return round(stack.pop(), 2)\n\n\n\"\"\" 栈与递归:任何一个递归函数都可以通过引入一个栈来保存中间信息、转化为非递归形式 \"\"\"\n\n\ndef hanoi(n, a=\"A\", b=\"B\", c=\"C\"):\n \"\"\" 汉诺塔 \"\"\"\n\n def move(a_, n_, b_):\n print(a_ + \" \" + str(n_) + \" -> \", b_)\n\n if n == 1:\n move(a, n, c)\n else:\n hanoi(n-1, a, c, b)\n move(a, n, c)\n hanoi(n-1, b, a, c)\n\n\ndef norec_fact(n):\n \"\"\" 阶乘函数的非递归形式 \"\"\"\n\n res = 1\n stack = SqStack()\n while n > 0:\n stack.push(n)\n n -= 1\n while not stack.is_empty:\n res *= stack.pop()\n\n return res\n\n\ndef knap_rec(weight, wlist, n):\n \"\"\" \n 背包问题:\n 一个背包可以放入重量为weight的物品,现有n件物品,重量分别为w0, w1, ...wn-1\n 问题是否能从中取出若干件物品,其重量之和正好等于weight\n \"\"\"\n\n # 当物品数量减为0的同时物品总重量也被减为0,表示有解\n if weight == 0:\n return True\n\n if weight < 0:\n return False\n\n if weight > 0 and n < 1:\n return False\n\n # 不计算最后一件物品、总重量减去最后一件物品的重量时有解,即加入最后一件物品时有解\n if knap_rec(weight - wlist[n-1], wlist, n-1):\n print(\"Item \" + str(n) + \":\", wlist[n-1])\n return True\n else:\n return False\n\ndef a_3_1_1(push_order, pop_order):\n # stack_order\n # print(a_3_1_1([1, 2, 3, 4, 5], [2, 3, 5, 4, 1]))\n\n stack = SqStack()\n\n p_pop = 0\n\n for push_v in push_order:\n\n while stack.get_top() == pop_order[p_pop]:\n stack.pop()\n p_pop += 1\n if push_v != pop_order[p_pop]:\n stack.push(push_v)\n else:\n p_pop += 1\n\n while not stack.is_empty:\n if stack.pop() != pop_order[p_pop]:\n return False\n p_pop += 1\n\n return True\n\n\ndef a_3_2_2(string):\n\n stack = SqStack()\n length = len(string)\n\n for i in range(length // 2):\n stack.push(string[i])\n\n for i in range(length // 2 + length % 2, length):\n if stack.pop() != string[i]:\n return False\n\n return True\n\n\ndef a_3_2_3(list_a):\n\n stack = SqStack()\n\n for elem in list_a:\n if elem != -1:\n if stack.is_full:\n print(\"Full!\")\n else:\n stack.push(elem)\n else:\n if stack.is_empty:\n print(\"Empty!\")\n else:\n print(stack.pop())\n\n\ndef a_3_2_4(expr):\n\n num_stack = SqStack()\n digit = \"\"\n for char in expr:\n if char == \"$\":\n break\n if char in string.digits + [\".\"]:\n digit += char\n else:\n s, e = 0, 0\n\n # 小數、整數部分分別處理\n # 如果不存在小數部分,則補上\".0\"\n digit += \".0\" if \".\" not in digit else \"\"\n for i in range(digit.find(\".\") - 1, -1, -1):\n s += int(digit[i]) * 10 ** e\n e += 1\n if \".\" in digit:\n for i in range(len(digit) - 1, digit.find(\".\"), -1):\n s += int(digit[i]) * 10 ** -e\n e -= 1\n\n num_stack.push(s)\n digit = \"\"\n\n if char in [\"+\", \"-\", \"*\", \"/\"]:\n num_2 = num_stack.pop()\n num_1 = num_stack.pop()\n if char == \"+\":\n num_stack.push(num_1 + num_2)\n if char == \"-\":\n num_stack.push(num_1 - num_2)\n if char == \"*\":\n num_stack.push(num_1 * num_2)\n if char == \"/\":\n num_stack.push(num_1 / num_2)\n return num_stack.pop()\n\n\ndef a_3_2_5(list_a):\n\n count = 0\n\n for i in list_a:\n\n if i == \"I\":\n count += 1\n else:\n count -= 1\n\n if count < 0:\n return False\n\n return count == 0\n\n\ndef a_3_2_6():\n\n class LNode(object):\n\n def __init__(self, elem=None, next=None):\n self.elem = elem\n self.next = next\n\n class Queue(object):\n\n def __init__(self, elem=None):\n self.rear = LNode()\n self.rear.next = self.rear\n\n if elem:\n p = first = LNode(elem[0])\n for i in elem[1:]:\n p.next = LNode(i, p.next)\n p = p.next\n self.rear.next = first\n p.next = self.rear\n\n @property\n def is_empty(self):\n return self.rear.next == self.rear\n\n def get(self):\n if self.is_empty:\n return False\n node = self.rear.next\n\n if self.rear.next == self.rear:\n self.rear = None\n else:\n self.rear.next = self.rear.next.next\n\n return node\n\n def put(self, elem):\n self.rear.next = LNode(None, self.rear.next)\n self.rear.elem = elem\n self.rear = self.rear.next\n\n def empty(self):\n self.rear.next = self.rear\n\n\n def print_all(self):\n p = self.rear.next\n\n while p.elem:\n print(p.elem)\n p = p.next\n\n list_1 = Queue([1, 2, 3, 4, 5])\n list_1.put(6)\n list_1.put(7)\n list_1.empty()\n\n list_1.print_all()\n\n\ndef a_3_2_7():\n\n class Queue(object):\n\n def __init__(self):\n self.queue_size = MAXSIZE\n self.tag = self.front = self.rear = 0\n self.elem = [None for _ in range(self.queue_size)]\n\n @property\n def is_empty(self):\n return self.front == self.rear and self.tag == 0\n\n @property\n def is_full(self):\n return self.front == self.rear and self.tag == 1\n\n def put(self, elem):\n if self.is_full:\n return False\n self.rear = (self.rear + 1) % self.queue_size\n self.elem[self.rear] = elem\n if self.tag == 0:\n self.tag = 1\n\n def get(self):\n if self.is_empty:\n return False\n\n self.front = (self.front + 1) % self.queue_size\n elem = self.elem[self.front]\n if self.tag == 1:\n self.tag = 0\n return elem\n\n\ndef a_3_2_8():\n\n class Deque(object):\n\n def __init__(self):\n self.queue_size = MAXSIZE\n self.elem = [None for _ in range(self.queue_size)]\n self.front = self.rear = 0\n\n @property\n def is_empty(self):\n return self.rear == self.front\n\n @property\n def is_full(self):\n return (self.rear + 1) % self.queue_size == self.front\n\n def delqueue(self):\n if self.is_empty:\n return False\n self.rear = (self.rear - 1 + self.queue_size) % self.queue_size\n return self.elem[(self.rear + 1 + self.queue_size) % self.queue_size]\n\n def enqueue(self, elem):\n if self.is_full:\n return False\n\n self.elem[self.front] = elem\n self.front = (self.front - 1 + self.queue_size) % self.queue_size\n\n\ndef a_3_2_9():\n\n def Ackerman(m, n):\n\n if m == 0:\n return n + 1\n\n if m != 0 and n == 0:\n return Ackerman(m - 1, 1)\n\n if m != 0 and n != 0:\n return Ackerman(m - 1, Ackerman(m, n - 1))\n\n def AckermanStack(m, n):\n\n res = [[None for _ in range(n)] for _ in range(m)]\n\n for i in range(n):\n res[0][i] = i\n\n for i in range(1, m):\n res[i][0] = res[i - 1][1]\n\n for i in range(1, m):\n for j in range(1, n):\n res[i][j] = res[i - 1][res[i][j - 1]]\n\n return res[m][n]\n\n\ndef a_3_2_10(list_a):\n\n def max_num(p):\n\n if not p.next:\n return p.elem\n\n max = max_num(p.next)\n return p.elem if p.elem > max else max\n\n def num_count_1(p):\n\n if not p:\n return 0\n return num_count_1(p.next) + 1\n\n def num_count_2(p, count):\n\n if not p:\n return count\n\n return num_count_2(p.next, count + 1)\n\n def avg(p, n, s):\n\n if not p:\n return s / n\n\n return avg(p.next, n + 1, s + p.elem)\n\n print(avg(list_a.head.next, 0, 0))\n\n\nif __name__ == \"__main__\":\n\n # print(coversion(6, 2))\n # print(maching(\"({]})\"))\n # print(evaluate_expression(\"#3*(5-2)#\"))\n # hanoi(3)\n\n # s1 = SqStack([1, 2, 3, 4, 5])\n # v1 = s1.pop()\n # print(v1)\n\n # print(eval_expr2(\"(3-5)*(6+17*4)/3\"))\n\n # a_3_2_4(\"234 34+2*$\")\n\n # print(a_3_2_5(\"IIIOOIOO\"))\n\n # a_3_2_6()\n\n a_3_2_10(LinkList([1, 5, 2, 7, 3]))\n\n print(eval_expr2(\"(3-5)*(6+17*4)/3\"))\n\n # pass\n\"\"\"\nAnswer:\n\n1-1 C 1-2 C 1-3 D 1-4 A 1-5 A\n1-6 D 1-7 A 1-8 B 1-9 D 1-10 D\n1-11 D 1-12 D 1-13 B 1-14 C 1-15 B\n\n\"\"\"\n # s1 = SqStack([1, 2, 3, 4, 5])\n # v1 = s1.pop()\n # print(v1)\n\n\n\n\n","sub_path":"data_structure/Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":19758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"252798331","text":"#!/usr/bin/env python\n\nfrom rospy_message_converter import message_converter\nimport rospy\nimport smach\nimport threading\nfrom std_msgs.msg import String\nfrom dialogflow_ros.msg import *\n\nclass WaitForMsgState(smach.State):\n \"\"\"\n Waits for a message and routes the contents to next State.\n \"\"\"\n\n def __init__(self, topic, msg_type, msg_cb=None, output_keys=[], input_keys=[], latch=False, timeout=None,\n state_name=None):\n smach.State.__init__(self, outcomes=['succeeded', 'aborted'], output_keys=output_keys, input_keys=input_keys)\n self.latch = latch\n self.timeout = timeout\n self.mutex = threading.Lock()\n self.msg = None\n self.message_callback = msg_cb\n self.subscriber = rospy.Subscriber(topic, msg_type, self._callback, queue_size=1)\n self.state_name = state_name\n\n def _callback(self, msg):\n self.mutex.acquire()\n self.msg = msg\n self.mutex.release()\n\n def wait_for_msg(self):\n rospy.loginfo(self.state_name + ' is waiting for message...')\n if self.timeout is not None:\n timeout_time = rospy.Time.now() + rospy.Duration.from_sec(self.timeout)\n while self.timeout is None or rospy.Time.now() < timeout_time:\n self.mutex.acquire()\n if self.msg is not None:\n rospy.loginfo(self.state_name + ' got message.')\n message = self.msg\n\n if not self.latch:\n self.msg = None\n\n self.mutex.release()\n return message\n self.mutex.release()\n\n #TODO: Do we need a preempted out?\n\n # if self.preempt_requested():\n # self.service_preempt()\n # rospy.loginfo('waitForMsg is preempted!')\n # return 'preempted'\n\n rospy.sleep(.1) # TODO: InterruptException? Discuss with Anas\n\n rospy.loginfo(self.state_name + ' experienced a Timeout on waiting for message.')\n return None\n\n def execute(self, ud):\n msg = self.wait_for_msg()\n if msg is not None:\n if msg == 'preempted':\n return 'preempted'\n if self.message_callback is not None:\n ud.publish_msg = self.msg\n cb_result = self.message_callback(msg, ud)\n if cb_result is not None:\n if cb_result:\n return 'succeeded'\n else:\n return 'aborted'\n return 'succeeded'\n else:\n return 'aborted'\n\n\nclass PublishMsgState(smach.State):\n def __init__(self, publisher_name, node_name=None, message_type=String, output_keys=[], input_keys=[],\n state_name=None):\n smach.State.__init__(self, outcomes=['succeeded', 'aborted'], output_keys=output_keys, input_keys=input_keys)\n self.pub = rospy.Publisher(publisher_name, message_type, queue_size=1)\n if node_name is not None:\n rospy.init_node(node_name, anonymous=True)\n self.state_name = state_name\n\n def execute(self, ud):\n rospy.loginfo(\"Publishing \" + self.state_name)\n self.pub.publish(ud.publish_msg)\n return 'succeeded'\n\n\ndef dialogflowresult_format(msg, ud):\n ud.action = msg.action\n ud.parameters = msg.parameters\n ud.publish_msg = msg.action\n rospy.loginfo(ud.action)\n return True\n\n\ndef main():\n rospy.init_node('integration')\n\n sm_top = smach.StateMachine(outcomes=['success'])\n sm_top.userdata.parameters = []\n sm_top.userdata.action = \"\"\n sm_top.userdata.pcl = \"\"\n sm_top.userdata.xyz = \"\"\n sm_top.userdata.publish_msg = {}\n\n with sm_top:\n\n smach.StateMachine.add('NLPsub', WaitForMsgState('/dialogflow_client/results', DialogflowResult,\n msg_cb=dialogflowresult_format, state_name=\"NLPsub\",\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'NLPpub',\n 'aborted': 'NLPsub'})\n\n smach.StateMachine.add('NLPpub', PublishMsgState('/nlp', state_name='NLPpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'AMBERsub',\n 'aborted': 'NLPpub'})\n smach.StateMachine.add('AMBERsub', WaitForMsgState('/nlp', String, state_name=\"AMBERsub\",\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'AMBERpub',\n 'aborted': 'AMBERsub'})\n smach.StateMachine.add('AMBERpub', PublishMsgState('/amber', state_name='AMBERpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'JAKEsub',\n 'aborted': 'AMBERsub'})\n smach.StateMachine.add('JAKEsub', WaitForMsgState('/amber', String, state_name='JAKEsub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'JAKEpub',\n 'aborted': 'JAKEsub'})\n smach.StateMachine.add('JAKEpub', PublishMsgState('/jake', state_name='JAKEpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'ANASpub',\n 'aborted': 'JAKEpub'})\n smach.StateMachine.add('ANASsub', WaitForMsgState('/jake', String, state_name='ANASsub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'ANASpub',\n 'aborted': 'ANASsub'})\n smach.StateMachine.add('ANASpub', PublishMsgState('/anas', state_name='ANASpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'success',\n 'aborted': 'ANASpub'})\n\n\n\n\n\n\n # Execute SMACH plan\n outcome = sm_top.execute()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cap_integration/scripts/state_machines.py","file_name":"state_machines.py","file_ext":"py","file_size_in_byte":7529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"129760388","text":"def value(r):\r\n if (r=='I'):\r\n return 1\r\n if(r=='V'):\r\n return 5\r\n if(r=='X'):\r\n return 10\r\n if(r=='C'):\r\n return 100\r\n if(r=='L'):\r\n return 50\r\n if(r=='D'):\r\n return 500\r\n if(r=='M'):\r\n return 1000\r\n\r\ndef romanToDecimal(str):\r\n res=0\r\n i=0\r\n while(i= s2):\r\n res= res+s1\r\n i=i+1\r\n else:\r\n res = res +s2 -s1\r\n i=i+2\r\n else:\r\n res = res+s1\r\n i=i+1\r\n return res\r\nif __name__=='__main__':\r\n input_string = input()\r\n print(romanToDecimal(input_string))","sub_path":"venv/LeetCode/RomanToDecimal.py","file_name":"RomanToDecimal.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"563802420","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\ndef parsedata(data):\n return float(data[6:14].replace(' ', ''))\n\n# def run(nodeinfo, logger):\n# logger.info('hello, this is a scales mod')\n# # opened serial port and test\n# try:\n# ser = serial.Serial(nodeinfo['devname'],nodeinfo['baudrate'])\n# # flush input\n# ser.flushInput()\n# ser.close()\n# # ingore bad line\n# #ser.readline()\n# except:\n# logger.exception('failed to open or init serial port')\n# exit(1)\n# try:\n# timeinterval = nodeinfo['interval']\n# srvaddr = nodeinfo['srvaddr']\n# scalesid = nodeinfo['scalesid']\n# except:\n# logger.exception('missing config para')\n# exit(1)\n# num = 0\n# while True:\n# num = num + 1\n# #listen and grab data\n# try:\n# time.sleep(timeinterval)\n# ser = serial.Serial(nodeinfo['devname'],nodeinfo['baudrate'])\n# #flush input\n# ser.flushInput()\n# #ingore bad line\n# data = ser.readline()\n# #re_read\n# data = ser.readline()\n# ser.close()\n# data = data.decode('utf-8')\n# except Exception as e:\n# logger.exception('failed to read data from serial port')\n# exit(1)\n# logger.info('#{} data received'.format(num))\n# #parse data\n# try:\n# weight = parsedata(data)\n# except Exception as e:\n# logger.exception('failed to parse data')\n# continue\n# #fork a new thread to post data\n# try:\n# pid = os.fork()\n# except:\n# logger.exception('failed to first fork')\n# if pid == 0:\n# # the child process/the second parent process\n# # do #2 fork\n# try:\n# pid = os.fork()\n# except:\n# logger.exception('failed to do #2 fork')\n# exit(1)#no one cares exit code here\n# if pid == 0:\n# #the second child process\n# try:\n# postdata(srvaddr, scalesid, weight)\n# except:\n# logger.exception('#{} failed to post'.format(num))\n# exit(1)\n# logger.info('#{} data posted'.format(num))\n# exit(0)\n# # the second parent process\n# exit(0)\n# # the parent process\n# ## wait for the second parent process exit\n# os.wait()\n# #end while\n# #shouldn't come here if everything is ok\n# logger.error('unexcept error: fun run in mod scales should not return')\n# return 0\n\n\nimport logging\nimport os\nimport time\nfrom postdata import postdata\nimport serial\n\n\ndef run(nodeinfo, logger, cnt):\n logger.info('hello, this is a scales mod')\n try:\n devname = nodeinfo['devname']\n baudrate = nodeinfo['baudrate']\n srvaddr = nodeinfo['srvaddr']\n scalesid = nodeinfo['scalesid']\n except:\n logger.exception('not enough config parameters')\n exit(1)\n\n # listen and grab data\n try:\n ser = serial.Serial(devname, baudrate)\n # flush input\n ser.flushInput()\n # ingore bad line\n data = ser.readline()\n # re_read\n data = ser.readline()\n ser.close()\n except:\n logger.exception('failed to open or read from serial port')\n exit(1)\n logger.info('#{} data received'.format(cnt))\n\n # parse data\n try:\n data = data.decode('utf-8')\n weight = parsedata(data)\n except Exception as e:\n logger.exception('failed to decode or parse data')\n exit(1)\n # fork a new thread to post data\n try:\n result = postdata(srvaddr, scalesid, weight)\n except:\n logger.exception('#{} failed to post'.format(cnt))\n exit(1)\n logger.info('#{} data posted, result: {}'.format(cnt, str(result)))\n exit(0)\n return 0\n\nimport os\nimport os.path\n\n\ndef fix(nodeinfo, logger, exitcode):\n logger.info('this is func fix of scales mod')\n # get config\n try:\n devname = nodeinfo['devname']\n baudrate = nodeinfo['baudrate']\n srvaddr = nodeinfo['srvaddr']\n scalesid = nodeinfo['scalesid']\n except:\n logger.exception('not enough config parameters')\n exit(1)\n if not os.path.exists(devname):\n logger.error('not such device, failed to fix')\n exit(1)\n exit(0)\n return 0\n\nimport logging\nimport sys\nif __name__ == '__main__':\n logger = logging.getLogger(__name__)\n ch = logging.StreamHandler()\n logger.addHandler(ch)\n logger.setLevel(logging.INFO)\n logger.info('this is test for mod_scales')\n cnt = 9526\n config = {\"devname\": sys.argv[1],\n \"baudrate\": 9600,\n \"scalesid\": 2,\n \"srvaddr\": \"http://211.83.111.245/biaoben/receive.php\"}\n print('try to run it')\n try:\n run(config, logger, cnt)\n except:\n logger.exception('failed to run')\n print('try to fix it')\n fix(config, logger, 1)\n print('finished!')\n","sub_path":"newhub/mods/mod_scales.py","file_name":"mod_scales.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"481574739","text":"# Given a list of numbers and a number k, return whether any two numbers from the list add up to k\n# Example: Given and k of 17, return true since 10 + 7 is 17\n\ndef pairSumToK(nums, k):\n\tcompliments = set()\n\tfor num in nums:\n\t\tif num in compliments:\n\t\t\treturn True\n\t\tcompliments.add(k - num)\n\treturn False\n\nex_nums_true = [10, 15, 3, 7]\nex_nums_false = [10, 15, 3, 8]\nex_k = 17\n\nprint(pairSumToK(ex_nums_true, ex_k))\nprint(pairSumToK(ex_nums_false, ex_k))\n","sub_path":"1_pairSumToK.py","file_name":"1_pairSumToK.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"345194982","text":"mod = 1e9+7\n\nn1 = {2:2,3:1,5:4,23:1}\nn2 = {2:1,5:1,7:2}\n\ndef comb(n1,n2):\n n3 = {}\n for key in n2:\n if key in n1: n3[key] = n2[key]+n1[key]\n else: n3[key] = n2[key]\n for key in n1:\n if key not in n2: n3[key] = n1[key]\n\n return n3\n\ndef nf(n):\n ans = 1\n for key in n:\n ans*=(n[key]+1)\n ans%=mod\n return int(ans)\n\nprint(comb(n1,n2))\nprint(nf(comb(n1, n2)))\n","sub_path":"AprLong/testfctre.py","file_name":"testfctre.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"315201204","text":"#\n# 티켓 객체에 대한 코드\n#\n# @author Seongeun Yu (s3ich4n@gmail.com)\n# @date 2021/06/03 23:55 created.\n#\n\n\nfrom typing import Optional\n\n\nclass Ticket:\n \"\"\" 공연을 관람하려는 사람이 소지해야하는 티켓에 대한 객체\n\n \"\"\"\n def __init__(\n self,\n fee: Optional[int] = None\n ):\n self._fee = fee\n\n @property\n def fee(self):\n return self._fee\n","sub_path":"pt01_object,design/cpt01/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"40541962","text":"def D(a,b,c):\r\n\treturn b ** 2 - 4 * a * c\r\ndef check(x):\r\n\ttry:\r\n\t\tx=float(x)\r\n\t\tglobal i\r\n\t\ti+=1\r\n\t\treturn x\r\n\texcept:\r\n\t\tprint(\" Неверный ввод или вызов помощи. Программа предназначена для решения уравнений вида: ax^2±bx±c=0. \")\r\n\t\tprint(\" Для получения корней уравнения, введите поочередно коэфиценты a,b,c. \")\r\n\t\tprint(\" Коэфиценты необходиы вводить как вещественные числа:\\n Верно: 5; 1; -1; -3.14; 2.16\\n Неверно: 6.23.54; --3; two;\")\r\nfrom math import sqrt\r\nprint(\" Welcom to the programm!\\n Это программа для решения квадратных уравнений. \")\r\nprint(\" Введите коэфиценты уравнения.\\n Для помощи в любом месте введите help \")\r\nwhile True:\r\n\ti = 0\r\n\twhile i<1: value = check(input(\" Press coefficient a: \"));\r\n\ti = 0\r\n\twhile i<1: data = check(input(\" Press coefficient b: \"));\r\n\ti = 0\r\n\twhile i<1: date = check(input(\" Press coefficient c: \"));\r\n\tdate = check( D(value,data,date) )\r\n\tif date == 0:\r\n\t\tx = -data / (2 * value )\r\n\t\tprint(\"Root your equation: \"+str(x))\r\n\telif date > 0:\r\n\t x1 = ( -data + sqrt(date) ) / ( 2 * value )\r\n\t x2 = ( -data - sqrt(date) ) / ( 2 * value )\r\n\t print(\" Roots your equation: \"+str(x1)+\", \"+str(x2))\r\n\telse:\r\n\t print(\"Корней нет.\")\r\n\tinput(\" Press any to continue \")","sub_path":"Quadratic equationInfiniti.py","file_name":"Quadratic equationInfiniti.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"377832966","text":"import os\nimport time\nfrom subprocess import Popen as execute\nfrom twisted.internet.defer import Deferred\n\n#---------------------------------------------------------------------------# \n# configure the client logging\n#---------------------------------------------------------------------------# \nimport logging\nlog = logging.getLogger(__name__)\n\nclass Runner(object):\n '''\n This is the base runner class for all the integration tests\n '''\n\n def initialize(self, service):\n ''' Initializes the test environment '''\n self.fnull = open(os.devnull, 'w')\n self.server = execute(service, stdout=self.fnull, stderr=self.fnull)\n log.debug(\"%s service started: %s\", service, self.server.pid)\n time.sleep(0.2)\n\n def shutdown(self):\n ''' Cleans up the test environment '''\n self.server.kill()\n self.fnull.close()\n log.debug(\"service stopped\")\n\n def testReadWriteCoil(self):\n rq = self.client.write_coil(1, True)\n rr = self.client.read_coils(1,1)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.bits[0] == True)\n \n def testReadWriteCoils(self):\n rq = self.client.write_coils(1, [True]*8)\n rr = self.client.read_coils(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.bits == [True]*8)\n \n def testReadWriteDiscreteRegisters(self):\n rq = self.client.write_coils(1, [False]*8)\n rr = self.client.read_discrete_inputs(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.bits == [False]*8)\n \n def testReadWriteHoldingRegisters(self):\n rq = self.client.write_register(1, 10)\n rr = self.client.read_holding_registers(1,1)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.registers[0] == 10)\n \n def testReadWriteInputRegisters(self):\n rq = self.client.write_registers(1, [10]*8)\n rr = self.client.read_input_registers(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.registers == [10]*8)\n \n def testReadWriteRegistersTogether(self):\n arguments = {\n 'read_address': 1,\n 'read_count': 8,\n 'write_address': 1,\n 'write_registers': [20]*8,\n }\n rq = self.client.readwrite_registers(**arguments)\n rr = self.client.read_input_registers(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.registers == [20]*8)\n\n def __validate(self, result, test):\n ''' Validate the result whether it is a result or a deferred.\n\n :param result: The result to __validate\n :param callback: The test to __validate\n '''\n if isinstance(result, Deferred):\n deferred.callback(lambda : self.assertTrue(test(result)))\n deferred.errback(lambda _: self.assertTrue(False))\n else: self.assertTrue(test(result))\n\n","sub_path":"examples/functional/base_runner.py","file_name":"base_runner.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"19291771","text":"import os\nimport json\nimport base64\nfrom flask import Flask, request, jsonify\nfrom firebase_admin import credentials, firestore, initialize_app\nfrom munch import Munch\n\n# Initialize Flask app\napp = Flask(__name__)\n\n# Initialize Firestore DB\ncred = credentials.Certificate('blazorapp1-50c53-firebase-adminsdk-ucwtd-2117b9c719.json')\ndefault_app = initialize_app(cred)\ndb = firestore.client()\n\n# Utility method for getting a document\ndef document(collName, docName):\n return db.collection(collName).document(docName)\n\n@app.route('/')\ndef index():\n return \"Audio Flashcards Ptyhon API\"\n\n# Get the user data structure\n@app.route('/user/', methods=['GET'])\ndef user(uid):\n try:\n doc = document('users', uid).get()\n if doc and doc.exists:\n return doc.to_dict(), 200\n else:\n return '', 200\n except Exception as e:\n return f\"An Error occurred: {e}\"\n\n# Update or create a user\n@app.route('/saveuser/', methods=['POST'])\ndef saveUser(uid):\n try:\n document('users', uid).set(json.loads(request.data))\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# For playback, get the list of active recordings (active means both prompt and\n# response have been recorded)\n@app.route('/currentpairs//', methods=['GET'])\ndef currentPairs(uid, currentTopicId):\n try:\n query = db.collection('prpairs')\\\n .where('uid', '==', uid)\\\n .where('topicId', '==', int(currentTopicId))\\\n .where('isActive', '==', True)\\\n .order_by('nextDate')\\\n .limit(20)\n docs = query.get()\n list = []\n if docs:\n for doc in docs:\n list.append(doc.to_dict())\n return json.dumps(list) , 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Get a recording\n@app.route('/blob//', methods=['GET'])\ndef blob(uid, promptid):\n try:\n key = f'{uid}_{promptid}'\n doc = document('blobs', key).get()\n if doc and doc.exists:\n return doc.to_dict(), 200\n else:\n return 'error', 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Save a recording\n@app.route('/saveblob//', methods=['POST'])\ndef saveblob(uid, promptid):\n try:\n blob = json.loads(request.data)\n key = f'{uid}_{promptid}'\n document('blobs', key).set(blob)\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Delete a recording\n@app.route('/deleteblob//', methods=['DELETE'])\ndef deleteBlob(uid, promptid):\n try:\n key = f'{uid}_{promptid}'\n document('blobs', key).delete()\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Get the user's topic structure\n@app.route('/gettopics/', methods=['GET'])\ndef getTopics(uid):\n try:\n docs = db.collection('topics').where('uid', '==', uid).get()\n list = []\n if docs:\n for doc in docs:\n list.append(doc.to_dict())\n return json.dumps(list) , 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Save the user's topic structure\n@app.route('/savetopic//', methods=['POST'])\ndef saveTopic(uid, topicid):\n try:\n data = json.loads(request.data)\n key = f'{uid}_{topicid}'\n document('topics', key).set(data)\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Get the prompt-reponse pairs for a deck \n@app.route('/getpairs//', methods=['GET'])\ndef getPairs(uid, deckId):\n try:\n query = db.collection('prpairs')\\\n .where('uid', '==', uid)\\\n .where('deckId', '==', int(deckId))\\\n .order_by('order')\n docs = query.get()\n list = []\n if docs:\n for doc in docs:\n list.append(doc.to_dict())\n return json.dumps(list) , 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Save a prompt-response pair\n@app.route('/savepromptpair//', methods=['POST'])\ndef savepromptpair(uid, pairid):\n try:\n data = json.loads(request.data)\n key = f'{uid}_{pairid}'\n document('prpairs', key).set(data)\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Delete a prompt-response pair\n@app.route('/deletepair//', methods=['DELETE'])\ndef deletePair(uid, pairid):\n try:\n key = f'{uid}_{pairid}'\n document('prpairs', key).delete()\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"326117413","text":"\nimport argparse\nimport sys\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='A Hello World program with arguments.')\n\n parser.add_argument('-m', '--message', type=str, default=\"Hello \",\n help='message to be written')\n\n parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'),\n default=sys.stdout,\n help=\"output file\")\n\n parser.add_argument('-c', '--capitals', action=\"store_true\",\n help='write capitals')\n\n parser.add_argument('name', type=str, nargs='+',\n help='name(s) of the user')\n\n args = parser.parse_args()\n\n message = args.message\n if args.name:\n message = message + ' '.join(args.name)\n if args.capitals: \n message = message.upper()\n args.outfile.write(message + '\\n')\n","sub_path":"structure/argparse/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"63829620","text":"from characters.base import Character\n\nclass Medic(Character):\n def __init__(self): \n self.name = \"Medic\"\n self.health = 10\n self.power = 3\n self.prize = 5\n \n def receive_damage(self, points):\n super(Medic, self).receive_damage(points)\n h_boost = random.random() > 0.8\n if h_boost:\n self.health += 2\n print(\"Medic got health boost and gained 2 health!\")","sub_path":"characters/medic.py","file_name":"medic.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"184653872","text":"'''num = [2,5,6,9]\nnum[2] = 3\nnum.append(70)\nnum.sort(reverse=True)\nnum.insert(2, 2)\nnum.pop(1)\nif 5 in num:\n num.remove(5)\nelse:\n print('não há número 4 ')\nprint(num)\nprint(f'Essa lista tem {len(num)} elementos')'''\n\n'''valores = []\nvalores.append(5)\nvalores.append(10)\nvalores.append(4)\nfor c,v in enumerate(valores):\n print(f'Naposição {c} encontrei o valor {v}!')\nprint('Cheguei ao final da lista')'''\n\n'''valores = list()\nfor cont in range(0, 5):\n valores.append(int(input('Digite um valor:')))\nfor c, v in enumerate( valores ):\n print( f'Naposição {c} encontrei o valor {v}!' )\nprint( 'Cheguei ao final da lista' )'''\n\na = [2, 3, 4, 7]\nb = a[:] #copia para edição\nb[2] = 8\nprint(f'Lista A: {a}')\nprint(f'Lista B: {b}')\n","sub_path":"PYTHON/pythonTeste/aula16.py","file_name":"aula16.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"41396875","text":"# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nimport sqlite3\nimport os\nimport pandas as pd\nimport logging\nimport multiprocessing as mp\n\n__parent_dir__ = os.path.dirname(os.path.dirname(__file__))\n\n\ndef make_page_content(url):\n page = requests.get(url)\n return page.content\n\n\ndef make_soup(url):\n page = requests.get(url)\n return BeautifulSoup(page.content, 'html.parser')\n\n\ndef set_logger(log_file):\n logging.basicConfig(level=logging.DEBUG,\n format=\"%(asctime)s:%(levelname)s:%(message)s\",\n handlers=[logging.StreamHandler(),\n logging.FileHandler('{}.log'.format(log_file))]\n )\n\n\nclass NationalTeams:\n def __init__(self, url, multiprocessor=False):\n self.url = url\n self.page = requests.get(self.url)\n if not os.path.exists(os.path.join(__parent_dir__, 'national_football_teams.db')):\n sqlite3.connect(os.path.join(__parent_dir__, 'national_football_teams.db'))\n self.database = os.path.join(__parent_dir__, 'national_football_teams.db')\n self.multiprocessor = multiprocessor\n\n def fetch_continent_links(self):\n feds = dict()\n pattern = re.compile(r'.*/continent/\\d/(.*)\\.html')\n soup = make_soup(self.url).findAll('a', attrs={'href': pattern})\n for link in soup:\n href = link.get('href')\n feds[re.sub(pattern, r'\\1', href)] = '{}{}'.format(self.url, href)\n return feds\n\n def fetch_country_links(self, continent):\n feds = self.fetch_continent_links()\n countries = dict()\n pattern = re.compile(r'.*/country/\\d*/(.*)\\.html')\n soup = make_soup(feds[continent]).find_all('a', attrs={'href': pattern})\n for link in soup:\n href = link.get('href')\n countries[re.sub(pattern, r'\\1', href)] = '{}{}'.format(self.url, href)\n return countries\n\n def categorize_countries_by_continent(self):\n ref = dict()\n for continent in self.fetch_continent_links().keys():\n for country, link in self.fetch_country_links(continent).items():\n ref[country] = [continent, link]\n print('{} added as a county in {}'.format(country, continent))\n df = pd.DataFrame.from_dict(ref, orient='index', columns=['continent', 'link'])\n df.index.name = 'country'\n conn = sqlite3.connect(self.database)\n df.to_sql('countries_links', con=conn, if_exists='replace')\n conn.commit()\n conn.close()\n return ref\n\n @staticmethod\n def make_link_by_year(country_link, year):\n pattern = re.compile(r'(.*/country/\\d*/)(.*\\.html)')\n return re.sub(pattern, r'\\1[year]/\\2', country_link).replace('[year]', str(year))\n\n def fetch_match_table_content(self, country_link, year=datetime.now().year):\n matches = list()\n while year >= 2000:\n print('collecting data from year {}'.format(year))\n link = self.make_link_by_year(country_link, year)\n print(link)\n soup = make_soup(link).find_all('tr', attrs={'class': re.compile(r'(win|defeat|draw)')})\n pattern = re.compile(r'(teams home|date|teams away|result|event)')\n for tr in soup:\n req_data = filter(lambda x: re.search(pattern, x['class'][0]), tr.find_all('td'))\n req_data = list(map(lambda x: x.text.strip(), req_data))\n req_data.append(tr['class'][0])\n matches.append(req_data)\n year -= 1\n return matches\n\n def extract_results(self, args):\n link = args[0]\n country = args[1]\n logging.info(link)\n logging.debug('collecting data from {}'.format(country))\n matches = self.fetch_match_table_content(link)\n logging.info('{}\\'s Results are being stored in database!'.format(country))\n\n try:\n logging.debug('creating dataframe for {}'.format(country))\n df = pd.DataFrame(\n matches,\n columns=['Date', 'result', 'match_type', 'outcome'],\n index=False\n )\n logging.info('parsing the columns')\n df[['score', 'info', 'home_away']] = df['result'].str.split('\\n\\n', expand=True)\n df[['home', 'away']] = df['home_away'].str.split(' vs. ', expand=True)\n df[['HG', 'AG', 'PR']] = df['score'].str.extract(r'(\\d*):(\\d*)?(\\(\\d*:\\d*\\)|.*)', expand=True)\n df.drop(columns=['result', 'home_away', 'score'], inplace=True)\n\n conn = sqlite3.connect(self.database)\n df.to_sql(str(country), con=conn, index=False)\n logging.info('results have been successfully stored in database for {}!'.format(country))\n conn.commit()\n conn.close()\n\n except Exception as e:\n logging.exception(e)\n pass\n\n def main(self):\n set_logger(os.path.join(__parent_dir__,\n 'scraper_{}.log'.format(datetime.now().strftime('%Y%m%d%H%M'))))\n categories = list()\n for key, val in self.categorize_countries_by_continent().items():\n # making the categories dict iterable in multiprocessing mapping\n data = [val[1], key]\n categories.append(data)\n\n if self.multiprocessor:\n pool = mp.Pool(os.cpu_count() - 2)\n pool.map(\n self.extract_results,\n categories\n )\n else:\n for data in categories:\n self.extract_results(data)","sub_path":"FootballScraper/national_temas_scraper.py","file_name":"national_temas_scraper.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"72976008","text":"\t#!/usr/bin/env python3\n\n\"\"\"\npaperparse.py\n\tA set of functions to deal with pubcrawl data\n\n\"\"\"\n\nimport nltk\nimport os\nfrom segtok.segmenter import split_single as ssplit\ntry:\n\tfrom modules import sent_tokenize as st\nexcept:\n\timport sent_tokenize as st\nimport re\n\n\"\"\"\ngetNames(filePath):\n\tGiven a pubcrawl/pubdip output file, returns the two species terms encoded in the file name, as well as their \n\tabbreviated forms\n\n\tSample pubcrawl output file:\n\t\tEscherichia_coli#Pseudomonas_aeruginosa.compiled\n\t\tEscherichia_coli#Pseudomonas_aeruginosa.sp\n\n\tResultant getNames output:\n\t\t[['escherichia coli', 'e. coli', 'escherichia'], ['pseudomonas aeruginosa', 'p. aeruginosa', 'pseudomonas']]\n\"\"\"\n\n\ndef getNames(filePath):\n\tdef shorten(tup):\n\t\treturn tup[0][0] + '. ' + tup[1]\n\tfilePath = os.path.basename(filePath)\n\tname = os.path.splitext(filePath)[0]\n\t\n\t# print(name)\n\tname = [i.split('_') for i in name.split('#')]\n\tname = [[i.lower() for i in j] for j in name]\n\n\t#check if genus only\n\t# print(name)\n\tif len(name[0]) ==1:\n\t\t\treturn [[i[0]] for i in name]\n\n\treturn [[\" \".join(i), shorten(i), i[0]] for i in name] \n\n\"\"\"\nloadFile(filepath):\n\tgeneric file input. Takes in the file as raw data and returns a list of stripped and lowered lines.\n\"\"\"\n\ndef loadFile(filePath):\n\tholder = []\n\twith open(filePath) as f:\n\t\tfor i in f:\n\t\t\tholder.append(i.strip().lower())\n\treturn holder\n\n\"\"\"\ntagStrip(line):\n\tremoves the medline tag from the line\n\n\"\"\"\n\ndef tagStrip(line):\n\treturn line[6:]\n\n\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n#####################\n# .sp Files #\n#####################\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\"\"\"\nspFile():\n\tClass representation of a single .sp file. Contains the title, abstract, and their respective stemmed and tokenized forms\n\n\tloadSection(section):\n\t\tLoads a .sp section into split {TERM: DATA} dicitonaries.)\n\t\n\treadSpFile(spFIlePath):\n\t\treads a SP file\n\n\tNOTE: Use as base class for all the other paper derivatives\n\tNOTE: For all future pubcrawl outputs, pmid is NECESSARY\n\"\"\"\nclass spFile():\n\tdef __init__(self, spFilePath, purge = False):\n\t\tself.fileName = os.path.basename(spFilePath)\n\t\n\t\tloaded = self.readSpFile(spFilePath)\n\t\t#print(loaded)\n\t\tself.summary = self.loadSection(loaded[\"SUMMARY\"])\n\t\tif purge:\n\t\t\tfor i in self.summary:\n\t\t\t\tself.summary[i] = '0'\n\t\tpapers = loaded['PAPERS'].split('\\n\\n')\n\t\tself.papers = [self.loadSection(i) for i in papers]\n\t\t#print(self.papers)\n\t\tif purge:\n\t\t\tfor i in self.papers:\n\t\t\t\tif i == {}:\n\t\t\t\t\tcontinue\n\t\t\t\ti[\"TIHT\"] = ''\n\t\t\t\ti[\"ABHT\"] = \"\"\n\t\tself.papers = [i for i in self.papers if i != {}]\n\n\n\n\n\tdef loadSection(self, section):\n\t\t#holder = [i.split(\"==\") for i in section.split('\\n') if i != '' and i != '\\n']\n\t\t#HARDCODING \n\t\tholder = []\n\t\tfor i in section.split('\\n'):\n\t\t\tif i == '' or i == '\\n':\n\t\t\t\tcontinue\n\t\t\tholder.append((i[:4], i[6:].strip()))\n\t\ttry:\n\t\t\tresult = {i:j.strip() for i,j in holder}\n\t\texcept ValueError:\n\t\t\tprint(\"ERROR\")\n\t\t\tprint(holder)\n\t\t\tprint(section)\n\t\t\traise\n\t\treturn result\n\n\n\tdef readSpFile(self, spFilePath):\n\n\t\tholder = {}\n\t\ttry:\n\t\t\twith open(spFilePath) as f:\n\t\t\t\tfor i in f:\n\t\t\t\t\t#find the first section\n\t\t\t\t\tif i[0] == '#':\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif i[0] == '@':\n\t\t\t\t\t\tcurrent = i[1:].strip()\n\t\t\t\t\t\tholder[current] = ''\n\t\t\t\t\telse:\n\t\t\t\t\t\t#account for empty lines\n\t\t\t\t\t\tif i == '':\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tholder[current] += i\n\t\texcept:\n\t\t\tprint(spFilePath)\n\t\treturn holder\n\n\t#reads the list of papers, converts them into paper tuples\n\tdef loadPapers(self, rawAbstractList):\n\t\tholder = []\n\t\tres = []\n\t\tfor i in rawAbstractList:\n\t\t\tif i[0] == \">\":\n\t\t\t\tif holder == []:\n\t\t\t\t\tholder = [i[2:]]\n\t\t\t\telse:\n\t\t\t\t\tres.append(holder)\n\t\t\t\t\tholder = [i[2:]]\n\t\t\telse:\n\t\t\t\tholder.append(i)\n\t\treturn res\n\tdef writeSpFile(self, filePath):\n\t\twith open(filePath, 'w') as f:\n\t\t\t#handle the summary\n\t\t\tf.write(\"@SUMMARY\\n\")\n\t\t\tfor i in self.summary:\n\t\t\t\tf.write('== '.join([i, self.summary[i]]) + '\\n')\n\t\t\tf.write(\"@PAPERS\\n\")\n\t\t\tfor paperDict in self.papers:\n\t\t\t\tf.write(\"== \".join([\"PMID\", paperDict[\"PMID\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TI \", paperDict[\"TI \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"AB \", paperDict[\"AB \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TIHT\", paperDict[\"TIHT\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"ABHT\", paperDict[\"ABHT\"]]) + \"\\n\\n\")\n\tdef writeSpFileHits(self, filePath):\n\t\twith open(filePath, 'w') as f:\n\t\t\t#handle the summary\n\t\t\tf.write(\"@SUMMARY\\n\")\n\t\t\tfor i in self.summary:\n\t\t\t\tf.write('== '.join([i, self.summary[i]]) + '\\n')\n\t\t\tf.write(\"@PAPERS\\n\")\n\t\t\tfor paperDict in self.papers:\n\t\t\t\tif not (paperDict[\"TIHT\"] or paperDict[\"ABHT\"]):\n\t\t\t\t\tcontinue\n\t\t\t\tf.write(\"== \".join([\"PMID\", paperDict[\"PMID\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TI \", paperDict[\"TI \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"AB \", paperDict[\"AB \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TIHT\", paperDict[\"TIHT\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"ABHT\", paperDict[\"ABHT\"]]) + \"\\n\\n\")\n\n\n\n\n\nif __name__ == \"__main__\":\n\t#target = '../input/pattern/smalltestann/Actinomyces_sp.#Bacteroides_sp..sp'\n\ttarget = '../input/pattern/smalltestann/Actinomyces_sp.#Bacteroides_coprosuis.sp'\n\toutPath = '../formats_and_standards/tester/tester.sp'\n\ttemp = spFile(target)\n\ttemp.writeSpFile(outPath)","sub_path":"modules/paperparse.py","file_name":"paperparse.py","file_ext":"py","file_size_in_byte":5139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"463110035","text":"# Script to clean pre-process BIOMASS INVENTORY and make spatial\n\n####################################################################\n# First, load packages\nimport pandas as pd\nimport os\nimport geopandas as gpd\nfrom fxns import epsg_meters\nimport shapely as shp\n\ndef MergeInventoryAndCounty(gross_inventory, technical_inventory, county_shapefile, counties_popcen):\n \"\"\"\n Cleans biomass inventory data and merges with county shapefiles\n gross_inventory - gross estimate of biomass inventory\n technical_inventory - technical estimate of biomass inventory\n county_shapefile - shapefile of county polygons\n counties_popcen - csv population-weighted county centroids\n\n Returns: cleaned, spatial biomass data (assigned to pop-weighted \n county centroids and county polygons)\n \"\"\"\n\n ##################################################################\n #read in biomass inventory\n # GROSS inventory\n gbm = pd.read_csv(gross_inventory)\n\n # TECHNIcounty_shapeL inventory\n tbm = pd.read_csv(technical_inventory)\n\n\n gbm.rename(columns={\"biomass.feedstock\":\"feedstock\",\n 'biomass.category':'category',\n 'disposal.yields':'disposal_BDT'}, \n inplace=True)\n\n tbm.rename(columns={\"biomass.feedstock\":\"feedstock\",\n 'biomass.category':'category',\n 'disposal.yields':'disposal_BDT'}, \n inplace=True) \n\n\n # check that all counties in there\n assert len(gbm.COUNTY.unique())==59\n #yup, plus one \"other\"\n\n # gbm[gbm['disposal.yields'] == gbm['disposal.yields'].max()]\n\n # #look at just manure (if feedstock, needs to be capitalized), if category, lower case -- should be equivalent!\n # gbm[(gbm['biomass.feedstock'] == \"MANURE\") & (gbm['year'] == 2014)].head()\n\n # #start grouping by: biomass category\n # gbm.groupby(['biomass.category'])['disposal.yields'].sum()\n # gbm[gbm['biomass.category'] == \"manure\"].groupby(['COUNTY'])['disposal.yields'].sum().head()\n\n fw_mc = 0.7\n gw_mc = 0.5\n manure_mc = 0.85\n\n def bdt_to_wettons(df):\n df['wettons'] = 0.0\n n = len(df.index)\n for i in range(n):\n if df.feedstock[i] == \"FOOD\":\n df.at[i, 'wettons'] = df.disposal_BDT[i] * (1 + fw_mc)\n if df.feedstock[i] == \"GREEN\":\n df.at[i, 'wettons'] = df.disposal_BDT[i] * (1 + gw_mc)\n if df.feedstock[i] == \"MANURE\":\n df.at[i, 'wettons'] = df.disposal_BDT[i] * (1 + manure_mc)\n\n bdt_to_wettons(gbm)\n bdt_to_wettons(tbm)\n\n # turn from wet tons to wet m3\n gbm['disposal_wm3'] = gbm['wettons'] / (1.30795*(1/2.24))\n tbm['disposal_wm3'] = tbm['wettons'] / (1.30795*(1/2.24))\n\n\n # # now load SHAPEFILE for all county_shape COUNTIES to merge this\n # print(\"p Read in county_shape COUNTIES shapefile and reproject\")\n county_shape = gpd.read_file(county_shapefile)\n county_shape.rename(columns = {'NAME': 'COUNTY'}, inplace=True)\n county_shape= county_shape.to_crs(epsg=4326)\n county_shape['county_centroid'] = county_shape['geometry'].centroid \n\n # ALSO LOAD IN CSV of population-weighted county centroids - use this not geographic centroid!!\n counties_popcen = pd.read_csv(counties_popcen) # NEW - population weighted means!\n counties_popcen.rename(columns = {'LATITUDE': 'lat', 'LONGITUDE': 'lon', 'COUNAME': 'COUNTY'}, inplace=True)\n counties_popcen['county_centroid'] = [shp.geometry.Point(xy) for xy in \n zip(counties_popcen.lon, counties_popcen.lat)]\n\n #COUNTY POLYGONS with BIOMASS DATA(mostly for plotting)\n gbm_shp = pd.merge(county_shape, gbm, on = 'COUNTY')\n # Do same for technical biomass\n tbm_shp = pd.merge(county_shape, tbm, on = 'COUNTY')\n\n\n # POPULATION-WEIGHTED COUNTY CENTROIDS with BIOMASS DATA\n gbm_pts = pd.merge(counties_popcen, gbm, on = 'COUNTY')\n tbm_pts = pd.merge(counties_popcen, tbm, on = 'COUNTY')\n\n print(\"p BIOMASS PRE_PROCESSING DONE RUNNING\")\n\n return gbm_pts, tbm_pts\n","sub_path":"scripts/biomass_preprocessing.py","file_name":"biomass_preprocessing.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"206993296","text":"import numpy as np\nimport random\nimport math\nimport copy\n\nboard = np.array([\n [0, 0, 2, 0, 8, 0, 5, 0, 0],\n [8, 0, 1, 2, 5, 7, 0, 4, 9],\n [0, 4, 0, 0, 0, 3, 8, 2, 7],\n [0, 8, 4, 1, 9, 0, 0, 0, 3],\n [3, 0, 0, 7, 0, 5, 2, 0, 0],\n [1, 0, 7, 0, 3, 2, 0, 0, 0],\n [0, 0, 0, 0, 7, 8, 0, 0, 0],\n [0, 6, 0, 0, 0, 9, 1, 0, 0],\n [0, 2, 8, 5, 0, 0, 0, 7, 4]], np.int32)\n\ndef verify(board):\n if (np.where(board == 0)[0]).size == 0:\n return True\n return False\n\ndef getNote(board):\n possible = np.ones((9,9,9))\n occ = np.where(board == 0)\n for i in range(0, occ[0].size):\n bad_values = []\n r = occ[0][i]\n c = occ[1][i]\n for j in range(0, 9):\n if(board[r][j] != 0):\n bad_values.append((board[r][j]))\n if(board[j][c] != 0):\n bad_values.append((board[j][c]))\n\n for m in range(0, 9):\n for n in range(0,9):\n if (math.floor(m/3) == math.floor(r/3) and math.floor(n/3) == math.floor(c/3)):\n if(board[m][n] != 0):\n bad_values.append(board[m][n])\n for value in bad_values:\n possible[value-1][r][c] = 0\n\n return possible\ndef getThrough(p, i, j):\n l = []\n for k in range(0,9):\n l.append(p[k][i][j])\n return l\n\ndef getMax(possible, b):\n max = 0\n x, y = None, None\n for i in range(0,9):\n for j in range(0,9):\n if (getThrough(possible, i,j).count(0) > max and getThrough(possible, i,j).count(0) < 9):\n if (b[i][j] == 0):\n x = i\n y = j\n max = getThrough(possible, i, j).count(0)\n return (max, x, y)\n\n\n\ntrial = 1\npossible = getNote(board)\nboard_static = copy.deepcopy(board)\nboard_sol = np.zeros([9,9])\n\nwhile(not verify(board_sol)):\n\n board_sol, possible_sol = copy.deepcopy(board), copy.deepcopy(possible)\n\n while True:\n max, x, y = getMax(possible_sol, board_sol)[0], getMax(possible_sol, board_sol)[1], getMax(possible_sol, board_sol)[2]\n if (x != None and y != None):\n l = [i for i, pns in enumerate(getThrough(possible_sol, x, y)) if pns == 1]\n occ = np.where(possible_sol[getMax(possible_sol, board_sol)[1]][getMax(possible_sol, board_sol)[2]] == 1)[0].tolist()\n board_sol[x][y] = random.choice(l) + 1\n possible_sol = getNote(board_sol)\n\n if (len(l) == 1):\n board[x][y] = random.choice(l) + 1\n else:\n print(\"Testing trial #\" + str(trial))\n print(board_sol)\n if (verify(board_sol)):\n print(\"Solution found:\")\n print(board_sol)\n break\n\n else:\n board = copy.deepcopy(board_static)\n board_sol = copy.deepcopy(board_static)\n possible_sol = getNote(board_sol)\n\n trial += 1\n\n break","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"247707378","text":"from nose.tools import eq_\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\n\nfrom us_ignite.apps.models import Application\nfrom us_ignite.apps.tests.fixtures import get_application\nfrom us_ignite.challenges.managers import AppEntry\nfrom us_ignite.challenges.models import Challenge, Question, Entry\nfrom us_ignite.challenges.tests import fixtures\nfrom us_ignite.profiles.tests.fixtures import get_user\n\n\nclass TestActiveChallengesManager(TestCase):\n\n def tearDown(self):\n for model in [Challenge, User]:\n model.objects.all().delete()\n\n def test_active_chalenge_is_returned(self):\n user = get_user('us-ignite')\n instance = fixtures.get_challenge(\n user=user, status=Challenge.PUBLISHED)\n eq_(list(Challenge.active.all()), [instance])\n\n def test_removed_challenge_is_not_returned(self):\n user = get_user('us-ignite')\n fixtures.get_challenge(user=user, status=Challenge.REMOVED)\n eq_(list(Challenge.active.all()), [])\n\n\nclass TestQuestionManager(TestCase):\n\n def tearDown(self):\n for model in [Challenge, Question, User]:\n model.objects.all().delete()\n\n def test_questions_are_returned_from_keys(self):\n challenge = fixtures.get_challenge()\n question = fixtures.get_question(challenge, id=3)\n question_list = Question.objects.get_from_keys(['question_3'])\n eq_(list(question_list), [question])\n\n\nclass TestEntryManager(TestCase):\n\n def tearDown(self):\n for model in [Entry, Challenge, Application, User]:\n model.objects.all().delete()\n\n def test_missing_entry_returns_none(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n eq_(Entry.objects.get_entry_or_none(challenge, application), None)\n\n def test_existing_entry_is_returned(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n entry = fixtures.get_entry(\n application, challenge=challenge, status=Entry.SUBMITTED)\n eq_(Entry.objects.get_entry_or_none(challenge, application), entry)\n\n def test_get_entries_for_apps_returns_empty_entries(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n result = Entry.objects.get_entries_for_apps(challenge, [application])\n eq_(result, [AppEntry(application=application, entry=None)])\n\n def test_get_entries_for_apps_returns_entry(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n entry = fixtures.get_entry(application, challenge=challenge)\n result = Entry.objects.get_entries_for_apps(challenge, [application])\n eq_(result, [AppEntry(application=application, entry=entry)])\n","sub_path":"us_ignite/challenges/tests/managers_tests.py","file_name":"managers_tests.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"52013433","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mysite', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='profile',\n old_name='birth_date',\n new_name='birthdate',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='bio',\n ),\n migrations.AddField(\n model_name='profile',\n name='role',\n field=models.PositiveSmallIntegerField(blank=True, null=True, choices=[(1, b'Student'), (2, b'Teacher'), (3, b'Supervisor')]),\n ),\n ]\n","sub_path":"mysite/contributed_by_all/mysite/migrations/0002_auto_20180407_1208.py","file_name":"0002_auto_20180407_1208.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"48473384","text":"\"\"\"\nThis script scrapes the digitalocean.com site and stores the content in a generator\nwith namedtuples for easy handling.\n\"\"\"\n\nfrom collections import namedtuple\nfrom bs4 import BeautifulSoup\nfrom requests import get\nfrom utils import prettify_docean_price, prettify_string\n\n\nURL = \"https://www.digitalocean.com/pricing/\"\nsite = get(URL)\nsoup = BeautifulSoup(site.text, \"lxml\")\n\ntable = soup.find('table', {'class': 'PricingTable'})\nrows = table.find_all('tr')\n\ncomputers = namedtuple(\"PC\", \"memory vCPUs ssd transfer price\")\n\ndef get_data_digital_ocean(rows) -> namedtuple:\n \"\"\"\n Namedtuple generator function.\n Scrapes the digitalocean.com table rows and stores the content in a generator.\n param:\n - rows: Receives table rows from digitalocean.com.\n yield:\n - Generator with namedtuples of computers.\n \"\"\"\n for row in rows[1:]:\n cells = row.find_all('td')\n memory = prettify_string(cells[0].text)\n vcpus = prettify_string(cells[1].text)\n ssd = prettify_string(cells[2].text)\n transfer = prettify_string(cells[3].text)\n price = prettify_docean_price(cells[4].text)\n yield computers(memory, vcpus, ssd, transfer, price)\n\ngenerator_docean_data = get_data_digital_ocean(rows)\n","sub_path":"crawler/digital_ocean.py","file_name":"digital_ocean.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"231483305","text":"import re\nimport glob\nimport os\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef read_dataset_folder(folder_path):\n \"\"\"\n Read the dataset folder and returns a list of datasets.\n Each dataset is a dict of the following format:\n {\n 'stats': a pandas Dataframe containing the simulations statistics,\n 'params': a dict containing the simulation parameters\n }\n :param string folder_path:\n :return: the list of datasets\n :rtype: list\n \"\"\"\n\n # init results\n dataset_list = []\n\n for subfolder in os.listdir(folder_path):\n file_path_list = glob.glob(os.path.join(folder_path, subfolder, '*.dat'))\n merged_params = None\n dataframe_list = []\n\n # read files and concatenate results\n for file_path in file_path_list:\n # read dataset file\n stats, params = read_dataset_file(file_path)\n\n # add cpuId column\n stats['cpuId'] = params['cpuID']\n\n # concatenate stats\n dataframe_list.append(stats)\n\n # merge simulation parameters\n del params['cpuID']\n if merged_params is None:\n merged_params = params\n else:\n assert merged_params == params\n\n merged_stats = pd.concat(dataframe_list)\n merged_stats.sort_values([\"cycle\"], inplace=True)\n dataset_list.append({\n \"stats\": merged_stats,\n \"params\": merged_params,\n \"name\": subfolder\n })\n return dataset_list\n\ndef read_dataset_file(file_path):\n \"\"\"\n Read the dataset and returns the simulation stats and parameters\n :param string file_path:\n :return: A Pandas Dataframe containing the stats and a dict containing the parameters\n :rtype: pandas.Dataframe & dict\n \"\"\"\n\n column_names = None\n parameters = {}\n\n # read column names\n with open(file_path, 'r') as f:\n for line in f:\n # get stats\n if line.startswith('## '):\n key, val = get_parameter_from_line(line)\n if key is not None:\n parameters.update({key: val})\n\n # get columns header\n if line.startswith('# '):\n column_names = line.strip().split(\" \")[1:]\n break\n\n if column_names is None:\n raise Exception(\"Could not read column names from file {0}\".format(file_path))\n\n # read stats (ignoring comment lines)\n stats = pd.read_csv(file_path, sep='[ ^]+', comment='#', names=column_names,\n engine='python')\n\n return stats, parameters\n\ndef get_parameter_from_line(line):\n \"\"\"Split line and return the parameter key and value\"\"\"\n stat_name = None\n stat_value = None\n\n # extract key and value from line\n m = re.findall(r'\\w+\\s+=\\s+.+', line)\n if len(m) > 0:\n m = m[0].replace(\" \", \"\").split(\"=\")\n if len(m) == 2:\n stat_name = m[0]\n stat_value = m[1]\n\n # try to convert the parameter value\n if stat_value.isdigit():\n stat_value = int(stat_value)\n elif isfloat(stat_value):\n stat_value = float(stat_value)\n elif islist(stat_value):\n stat_value = stat_value[1:-1].replace(\"'\", \"\").split(\",\")\n\n return stat_name, stat_value\n\ndef isfloat(str):\n \"\"\"check if the string can be converted to a float\"\"\"\n try:\n float(str)\n return True\n except ValueError:\n return False\n\ndef islist(str):\n \"\"\"check if the string can be converted to a list\"\"\"\n if str[0] == '[' and str[-1] == ']':\n return True\n else:\n return False\n\ndef savefig(output_folder, output_name, output_format=\"png\"):\n # check if output folder exists and create it if not\n if not os.path.isdir(output_folder):\n os.makedirs(output_folder)\n\n # save the figure\n plt.savefig(os.path.join(output_folder, output_name + \".\" + output_format),\n bbox_inches='tight',\n pad_inches=0,\n format=output_format)\n","sub_path":"simulator/bin/datasethelper.py","file_name":"datasethelper.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"236370348","text":"import simpy as si\nimport time as ti\nimport numpy as np\n\nl_np = np.array([0,0,0])\nl = {}\nkey_M = []\n\n'''하나의 드론은 일반 배터리 내장 다른 드론은 지속적인 충전을 구현 '''\n\n#드론 객체 ###################################################################\n\ndef dron_1(env) :\n global battery_1,hight_1,inertia_1,dron_gps_1,restricted_area_1\n battery_1 = 620 * 5 #드론 배터리 용량\n dron_gps_1 = [0,0] #드론 위치(GPS)\n use_b_1 = 2300 * 5 # 배터리 사용량\n timer_1 = battery_1/use_b_1 * 60 #운행시간(분단위)\n\n \"\"\"\n 1번 드론 일반적인 베터리 충전 방식\n \"\"\"\n while timer_1 > 1 :\n timer_1 = timer_1 -1\n dron_gps_1[0] = dron_gps_1[0] + 10\n # print('드론 1이 간 거리' + str(dron_gps_1))\n # print('남은 운행시간 :' + str(timer_1))\n yield env.timeout(1)\n\n\ndef dron_2(env) :\n global battery_2,hight_2,inertia_2,dron_gps_2,restricted_area_2\n battery_2 = 620 * 5 #드론 배터리 용량 mAh\n dron_gps_2 = [0,0] #드론 위치(GPS)\n use_b_2 = 2300 * 5 # 배터리 사용량\n timer_2 = battery_2/use_b_2 * 60 #운행시간(분단위)\n charge_t_1 = 45/use_b_2 * 60 #충전 구현\n\n \"\"\"\n 2번 드론 지속적인 레이져 충전 방식\n \"\"\"\n while timer_2 > 1 :\n timer_2 = timer_2 -1\n timer_2 = timer_2 + charge_t_1\n dron_gps_2[0] = dron_gps_2[0] + 10\n # print('드론 2가 간 거리' + str(dron_gps_2))\n # print('남은 운행 시간 :' + str(timer_2))\n yield env.timeout(1)\n\n\ndef dron_3(env) :\n global battery_3,hight_3,inertia_3,dron_gps_3,restricted_area_3\n battery_3 = 600 * 5 #드론 배터리 용량\n use_b_3 = 2300 * 5 # 배터리 사용량\n charge_t_3 = np.random.randint(3,7)/10 * 0.5#충전 구현(태양광)\n timer_3 = (battery_3 + charge_t_3)/use_b_3 * 60 #운행시간(분단위)\n dron_gps_3 = [0,0] #드론 위치(GPS)\n \"\"\"\n 3번 드론 태양광 충전 방식\n \"\"\"\n while timer_3 > 1 :\n timer_3 = timer_3 - 1\n timer_3 = timer_3 + charge_t_3\n dron_gps_3[0] = dron_gps_3[0] + 10\n # print('드론 3가 간 거리' + str(dron_gps_3))\n # print('남은 배터리 :' + str(timer_3))\n yield env.timeout(1)\n\n#일반 객체 ###################################################################\ndef dic(x):\n return l[x]\n\n#시작 ###################################################################\n\nprint('''\n상황 : 일반적인 배터리를 사용하는 드론과 지속적인 래이져 충전을 사용하는 드론과 태양광 충전을 사용하는 드론 비교\n\n태양광 사용이 불가능한 날은 날씨가 좋지 않아 드론또한 운행이 불가능하므로 제외\n(3초 후 시뮬레이션 시작)\n''')\n\nti.sleep(3)\n\n#시뮬래이션 ###################################################################\n\ni = int(input('반복횟수 입력 >>>'))\n\n","sub_path":"simmulate_going.py","file_name":"simmulate_going.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"604719797","text":"# coding:latin-1\nimport os\nSITE_ROOT = os.path.dirname(os.path.realpath(__file__))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(SITE_ROOT, '../twitalarm.db'),\n },\n}\n\nTIME_ZONE = 'America/Chicago'\n\nLANGUAGE_CODE = 'es'\n\nugettext = lambda s: s\n\nLANGUAGES = (\n ('en', ugettext('English')),\n)\n\n\nSITE_ID = 1\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nMEDIA_ROOT = os.path.join(SITE_ROOT,'../../media')\n\nMEDIA_URL = '/media/'\n\nSTATIC_ROOT = ''\n\nSTATIC_URL = '/static/'\n\nADMIN_MEDIA_PREFIX = os.path.join(STATIC_URL, 'admin/')\n\nSTATICFILES_DIRS = (\n os.path.join(SITE_ROOT,'static'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\nSECRET_KEY = 'w5np!7v*q(^)-4lcma#!ny&au(qh&syitom#et=jc(ns4h9zta'\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.request\",\n \"django.contrib.messages.context_processors.messages\",\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'twitalarm.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n # Contrib\n 'tastypie',\n # Custom\n 'events',\n # Contrib\n 'south',\n)\n\n# Search\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',\n 'PATH': os.path.join(SITE_ROOT, '../whoosh_index'),\n },\n}\n\n# LOGGERS\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'standard': {\n 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(pathname)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%d/%b/%Y %H:%M:%S\"\n },\n },\n 'handlers': {\n 'heartbeat_logfile': {\n 'level':'DEBUG',\n 'class':'logging.handlers.RotatingFileHandler',\n 'filename': os.path.join(SITE_ROOT, '../log', 'heartbeat.log'),\n 'maxBytes': 50000,\n 'backupCount': 2,\n 'formatter': 'standard',\n },\n },\n 'loggers': {\n 'heartbeat': {\n 'handlers': ['heartbeat_logfile'],\n 'level': 'DEBUG',\n },\n }\n}\n","sub_path":"twitalarm/twitalarm/settings_default.py","file_name":"settings_default.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"341477643","text":"import json\nimport jsonschema\nimport os\nimport six\nimport numpy as np\nimport tempfile\nimport tensorflow as tf\nimport zipfile\nfrom six.moves import zip # pylint: disable=redefined-builtin\nfrom utils import ckpts\nfrom collections import OrderedDict, defaultdict\nfrom utils import ckpts\nfrom tensorio_bundler import bundler\nimport time\nimport requests\nimport wget\nfrom tensorflow.python.saved_model import loader\nimport logging\nimport copy\n\n\nCHECKPOINT_BASENAME = \"checkpoint\"\nCHECKPOINT_PB_BASENAME = \"variables\"\nBUNDLE_CHECKPOINT_DIRECTORY = \"checkpoints\"\nRESULT_JSON_BASENAME = \"result.json\"\nSAVED_MODEL_BASENAME = \"saved_model.pb\"\nMODEL_JSON_BASENAME = \"model.json\"\nTIO_PREFIX = \"tio://\"\n\n\nclass AggregatorNotFoundException(Exception):\n pass\n\n\nclass SchemaFailedException(Exception):\n pass\n\n\nclass TensorIOModelsRepositoryException(Exception):\n pass\n\n\nclass Aggregator(object):\n\n def __init__(\n self,\n resource_path,\n output_resource_path,\n repository,\n token,\n export_type,\n aggregator_type,\n temp_dir=\"/tmp/\",\n schema_path=\"./schemas/schema.json\"\n ):\n self.resource_path = resource_path\n self.output_resource_path = output_resource_path\n self.repository = repository\n self.token = token\n self.checkpoint_basename = CHECKPOINT_BASENAME if export_type == 'checkpoint' else CHECKPOINT_PB_BASENAME\n self.temp_dir = temp_dir\n\n # Initialize logger\n self.logger = logging.getLogger('aggregator')\n self.logger.setLevel(logging.DEBUG) # TODO: env var or cli to set this\n self.main_handler = logging.StreamHandler()\n self.main_formatter = logging.Formatter('%(levelname)s - %(asctime)s - %(name)s: %(message)s')\n self.main_handler.setFormatter(self.main_formatter)\n self.logger.addHandler(self.main_handler)\n\n self.logger.info(\"Configured to talk to repository: {0}\".format(repository))\n self.logger.info(\"Checkpoint will be READ from: {0}\".format(resource_path))\n self.logger.info(\"Checkpoint will be WRITTEN to: {0}\".format(output_resource_path))\n self.logger.debug(\"Using temporary directory: {0}\".format(temp_dir))\n self.logger.debug(\"Using schema: {0}\".format(schema_path))\n\n # Cumulative Moving Average, Weighted Cumulative Moving Average\n self.aggregator_step_functions = {\n \"CumulativeMovingAverage\": self._cumulative_moving_average_steps,\n \"WeightedCumulativeMovingAverage\": self._weighted_cumulative_moving_average_steps\n }\n # Aggregated model export type functions\n self.aggregator_export_functions = {\n \"checkpoint\": self._output_checkpoint,\n \"saved_model\": self._output_saved_model,\n \"bundle\": self._output_bundle,\n }\n\n # Get canonical checkpoint and set canonical variables\n self._get_cannonical()\n\n if aggregator_type not in self.aggregator_step_functions.keys():\n raise AggregatorNotFoundException(\"Aggregator of type \\\"{0}\\\" not found.\".format(aggregator_type))\n else:\n self.aggregator_step_fn = self.aggregator_step_functions[aggregator_type]\n\n if export_type not in self.aggregator_export_functions.keys():\n raise AggregatorNotFoundException(\"Aggregator export type \\\"{0}\\\" not found.\".format(export_type))\n else:\n self.export_fn = self.aggregator_export_functions[export_type]\n\n with tf.gfile.Open(schema_path, 'r') as schema_fp:\n self.schema = json.load(schema_fp)\n\n\n def aggregate(self, bundle_paths, output_path):\n update_var_values, update_var_dtypes = self._aggregate_ckpts(bundle_paths)\n self._apply_aggregation(output_path, update_var_values, update_var_dtypes)\n\n\n @staticmethod\n def validate_json_schema(result, schema):\n try:\n jsonschema.validate(instance=result, schema=schema)\n except Exception as e:\n raise SchemaFailedException(str(e))\n\n\n @staticmethod\n def _cumulative_moving_average_steps(steps):\n return 1\n\n\n @staticmethod\n def _weighted_cumulative_moving_average_steps(steps):\n return steps\n\n\n @staticmethod\n def _update_function(current, next_, current_steps, steps):\n if current_steps == 0:\n return next_\n update = ((current * current_steps) + (next_ * steps)) / (current_steps + steps)\n return update\n\n\n def _get_cannonical(self):\n # Initialize: Read canonical json, saved_model, respective variables names/shape, set values to zero\n # Opening in temporary directory, and storing relevant files in memory\n # This way we only need to get canonical files once instead of twice,\n # without changing class structure\n self.canonical_var_values, self.canonical_var_dtypes = {}, {}\n self.canonical_var_set = set([])\n\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as canonical_temp:\n self.canonical_bundle_temppath = self._get_cannonical_bunde(canonical_temp)\n model_json_temppath = os.path.join(self.canonical_bundle_temppath, MODEL_JSON_BASENAME)\n\n # TODO: validate model.json\n with tf.gfile.Open(model_json_temppath, 'r') as model_json_input:\n self.model_json = json.load(model_json_input)\n model_json_spec = self.model_json.get('model', {})\n self.model_json_mode = model_json_spec.get('file')\n\n saved_model_pb_temppath = os.path.join(self.canonical_bundle_temppath, self.model_json_mode, SAVED_MODEL_BASENAME)\n with tf.gfile.Open(saved_model_pb_temppath, 'rb') as saved_model_fp:\n self.saved_model_binary = saved_model_fp.read()\n\n canonical_variables_temppath = os.path.join(self.canonical_bundle_temppath, self.model_json_mode, CHECKPOINT_PB_BASENAME)\n canonical_ckpt = ckpts.find_trained_checkpoints(canonical_variables_temppath)[0]\n # Load checkpoint\n canonical_reader = tf.contrib.framework.load_checkpoint(canonical_ckpt)\n self.canonical_var_list = tf.contrib.framework.list_variables(canonical_ckpt)\n # Initialize variables/weights\n for (canonical_name, canonical_shape) in self.canonical_var_list:\n self.canonical_var_values[canonical_name] = np.zeros(canonical_shape)\n canonical_tensor = canonical_reader.get_tensor(canonical_name)\n self.canonical_var_dtypes[canonical_name] = canonical_tensor.dtype\n self.canonical_var_set.add(canonical_name)\n self.logger.info(\"Initializing aggregated variables from: {0}\".format(canonical_ckpt))\n\n\n def _get_cannonical_bunde(self, tempfile_temp_dir):\n try:\n url = \"{0}{1}\".format(self.repository, self.resource_path)\n headers = {\n \"Authorization\": \"Bearer {0}\".format(self.token)\n }\n response = requests.request(\"GET\", url, data=\"\", headers=headers)\n response_json = response.json()\n self.logger.info(\"Cannonical checkpoint JSON response {0}\".format(response_json))\n url2 = response_json['link']\n bundle_download_filename = wget.download(url2, out=tempfile_temp_dir)\n except Exception as e:\n raise TensorIOModelsRepositoryException(\n \"Failed to get tensorio-models cannonical bundle, error: {0}\".format(str(e))\n )\n\n # Unzip bundle\n bundle_basename = os.path.basename(bundle_download_filename)\n with tf.gfile.Open(bundle_download_filename, 'rb') as bundle_fp:\n with zipfile.ZipFile(bundle_fp) as zf:\n zf.extractall(tempfile_temp_dir)\n os.remove(bundle_download_filename)\n\n bundle_dirname = \".\".join(bundle_basename.split(\".\")[:-1])\n unzipped_bundle_dirs = [dir_name for dir_name in tf.gfile.ListDirectory(tempfile_temp_dir) if dir_name.split(\".\")[-1] != \"zip\"]\n assert len(unzipped_bundle_dirs) == 1\n bundle_path = os.path.join(tempfile_temp_dir, unzipped_bundle_dirs[0])\n return bundle_path\n\n\n def _aggregate_ckpts(self, bundle_paths):\n current_steps = 0\n update_var_values = copy.deepcopy(self.canonical_var_values)\n update_var_dtypes = copy.deepcopy(self.canonical_var_dtypes)\n\n # Load result/update checkpoints and aggregate\n for i, bundle_path in enumerate(bundle_paths):\n var_values, var_dtypes = {}, {}\n self.logger.info(\"Aggregating bundle: {0}\".format(bundle_path))\n self.logger.info(\"Number of steps seen thus far: {0}\".format(current_steps))\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as temp:\n bundle_basename = os.path.basename(bundle_path)\n with tf.gfile.Open(bundle_path, 'rb') as bundle_fp:\n with zipfile.ZipFile(bundle_fp) as zf:\n zf.extractall(temp)\n self.logger.info(\"Unzipping succesful to directory: {0}\".format(temp))\n bundle_dirname = \".\".join(bundle_basename.split(\".\")[:-1])\n model_directory_name = os.path.join(temp, bundle_dirname)\n checkpoint_dir_name = os.path.join(model_directory_name, BUNDLE_CHECKPOINT_DIRECTORY)\n current_ckpt = ckpts.find_trained_checkpoints(checkpoint_dir_name)[0]\n\n # Get result/update checkpoint\n result_filename = os.path.join(model_directory_name, RESULT_JSON_BASENAME)\n with tf.gfile.Open(result_filename, 'r') as result_fp:\n results_dict = json.load(result_fp)\n Aggregator.validate_json_schema(results_dict, self.schema)\n checkpoint_steps = results_dict['numSamples']\n self.logger.debug(\"Number of samples for update {0}: {1}\".format(bundle_path, checkpoint_steps))\n steps = self.aggregator_step_fn(checkpoint_steps)\n self.logger.debug(\"Processed number of steps based on aggregation type: {0}\".format(steps))\n\n # Load checkpoint\n reader = tf.contrib.framework.load_checkpoint(current_ckpt)\n var_list = tf.contrib.framework.list_variables(current_ckpt)\n var_set = set([name for (name, _ ) in var_list])\n var_dict = dict(var_list)\n\n # Verify set differences\n missing_canonical_vars = self.canonical_var_set - var_set\n missing_update_vars = var_set - self.canonical_var_set\n if len(missing_canonical_vars) > 0:\n self.logger.debug(\"Canonical checkpoint variables NOT in Update: {0}\".format(missing_canonical_vars))\n if len(missing_update_vars) > 0:\n self.logger.debug(\"Update checkpoint variables NOT in Canonical: {0}\".format(missing_update_vars))\n\n # Aggregate variables/weights\n for (name, shape) in self.canonical_var_list:\n tensor = reader.get_tensor(name)\n var_values[name] = tensor\n var_dtypes[name] = tensor.dtype\n\n # Do not update variables that are not in result/update checkpoint\n if name not in var_values.keys() and name not in var_dtypes.keys():\n continue\n if shape != var_dict[name]:\n self.logger.info(\"Canonical variable of shape: {0}, Update variable of shape: {1}\".format(shape, var_list_dict[name]))\n # Check dtype match\n if var_dtypes[name] != self.canonical_var_dtypes[name]:\n self.logger.info(\"Canonical variable of type: {0}, Update variable of type: {1}\".format(canonical_var_dtypes[name], var_dtypes[name]))\n\n update_var_values[name] = Aggregator._update_function(update_var_values[name], tensor, current_steps, steps)\n self.logger.info(\"Checkpoint aggregation successful for: {0}\".format(current_ckpt))\n current_steps += steps\n\n return update_var_values, update_var_dtypes\n\n\n def _apply_aggregation(self, output_path, var_values, var_dtypes):\n # Get/Create original Tensorflow variables\n self.logger.info(\"Applying aggregation to export bundle...\")\n tf.reset_default_graph()\n tf_vars = [tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[v]) for v in var_values]\n # Create respective placeholders to feed in Numpy values\n placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars]\n # Assign fed values to original Tensorflow variables\n assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)]\n # Create Saver to execute sync\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)\n # Build a model consisting only of variables and set to average values\n with tf.Session() as session:\n # Initialize computational graph\n session.run(tf.global_variables_initializer())\n # Run built Tensorflow computational graph to assign variables/weights\n for p, assign_op, (name, value) in zip(placeholders, assign_ops, six.iteritems(var_values)):\n session.run(assign_op, {p: value})\n # Export aggregation\n self.export_fn(saver, session, output_path)\n\n\n def _output_checkpoint(self, saver, session, output_path):\n ckpts.check_or_create_dir(output_path)\n aggregated_checkpoint_path = os.path.join(output_path, self.checkpoint_basename)\n save_path = saver.save(session, aggregated_checkpoint_path, write_meta_graph=True)\n self.logger.info(\"Averaged model chackpoints saved in: {0}\".format(save_path))\n\n\n def _output_saved_model(self, saver, session, output_path):\n # Create necessary bundle structure for aggregation\n ckpts.check_or_create_dir(output_path)\n aggregated_checkpoint_directory = os.path.join(output_path, self.checkpoint_basename)\n ckpts.check_or_create_dir(aggregated_checkpoint_directory)\n # `aggregated_checkpoint_path` is not a directory, but basename for variables/ files\n aggregated_checkpoint_path = os.path.join(aggregated_checkpoint_directory, self.checkpoint_basename)\n\n # Unzip and copy necessary files\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as temp:\n bundle_path = self._get_cannonical_bunde(temp)\n saved_model_pb_temppath = os.path.join(bundle_path, self.model_json_mode, SAVED_MODEL_BASENAME)\n saved_model_pb_newpath = os.path.join(output_path, SAVED_MODEL_BASENAME)\n with tf.gfile.Open(saved_model_pb_newpath, 'wb') as saved_model_output:\n saved_model_output.write(self.saved_model_binary)\n\n # No metagraph needed for pb exports\n save_path = saver.save(session, aggregated_checkpoint_path, write_meta_graph=False)\n self.logger.info(\"Averaged saved_model ProtoBuf saved in: {0}\".format(save_path))\n\n\n def _output_bundle(self, saver, session, output_path):\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as temp_bundle:\n # Create necessary bundle structure for aggregation\n ckpts.check_or_create_dir(temp_bundle)\n aggregated_pb_directory = os.path.join(temp_bundle, self.model_json_mode)\n ckpts.check_or_create_dir(aggregated_pb_directory)\n aggregated_checkpoint_directory = os.path.join(aggregated_pb_directory, self.checkpoint_basename)\n ckpts.check_or_create_dir(aggregated_checkpoint_directory)\n # `aggregated_checkpoint_path` is not a directory, but basename for variables/ files\n aggregated_checkpoint_path = os.path.join(aggregated_checkpoint_directory, self.checkpoint_basename)\n\n # No metagraph needed for pb exports\n save_path = saver.save(session, aggregated_checkpoint_path, write_meta_graph=False)\n self.logger.info(\"Averaged saved_model ProtoBuf saved in: {0}\".format(save_path))\n\n # Unzip and copy necessary files\n tio_output_path = \"{0}{1}\".format(TIO_PREFIX, self.output_resource_path)\n saved_model_pb_newpath = os.path.join(aggregated_pb_directory, SAVED_MODEL_BASENAME)\n with tf.gfile.Open(saved_model_pb_newpath, 'wb') as saved_model_output:\n saved_model_output.write(self.saved_model_binary)\n\n model_json_newpath = os.path.join(temp_bundle, MODEL_JSON_BASENAME)\n self.model_json['id'] = tio_output_path\n with tf.gfile.Open(model_json_newpath, 'w') as model_json_output:\n json.dump(self.model_json, model_json_output, indent=4)\n\n # Create bundle\n bundle_basename = os.path.basename(self.canonical_bundle_temppath)\n bundle_name = \".\".join(bundle_basename.split(\".\")[:-1])\n bundle_extension = bundle_basename.split(\".\")[-1]\n # example bundle name: manna-train-aggregated-1520170716.tiobundle.zip\n tiobundle_zip_name = \"{0}-aggregated-{1}.{2}.zip\".format(bundle_name, int(time.time()), bundle_extension)\n tiobundle_output_path = os.path.join(output_path, tiobundle_zip_name)\n bundle_output_path = bundler.tiobundle_build(\n aggregated_pb_directory, # bundler only needs saved_model directory\n model_json_newpath,\n None,\n bundle_basename, # unzipped bundle directory must match canonical\n tiobundle_output_path\n )\n self.logger.info(\"Output bundle stored: {0}\".format(tiobundle_output_path))\n assert tiobundle_output_path == bundle_output_path\n\n # Register bundle\n registration = bundler.register_bundle(bundle_output_path, self.output_resource_path)\n self.logger.info('Bundle registered against repository: {}'.format(registration))\n\n\n\n","sub_path":"aggregator/aggregator.py","file_name":"aggregator.py","file_ext":"py","file_size_in_byte":18089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"332482357","text":"from requests import get\r\nfrom scrapy import Selector\r\nimport re\r\n\r\n\r\ndef catch_URL(URL):\r\n url_emploi = URL\r\n response_emploi = get(url_emploi)\r\n source_emploi = None\r\n\r\n if response_emploi.status_code == 200:\r\n source_emploi = response_emploi.text\r\n return source_emploi\r\n\r\n\r\ndef catch_data(source):\r\n if source:\r\n\r\n # Si le code source existe\r\n selector_emploi = Selector(text=source)\r\n contenus_emploi = selector_emploi.css(\"div.row\")\r\n print(\"N° DATE REGION COMPAGNIE DESCRIPTION\")\r\n print(\"_________________________________________________________________________________\")\r\n cmp = 1\r\n for contenu in contenus_emploi:\r\n if cmp < 2:\r\n date_emploi_x = contenu.css(\"p.job-recruiter::text\").extract_first()\r\n if cmp == 1:\r\n print(type(date_emploi_x))\r\n date_emploi = date_emploi_x.split(' | ')[0]\r\n date_coupee = date_emploi.split('.')\r\n print(date_coupee)\r\n\r\n jour_emploi = date_coupee[0]\r\n mois_emploi = date_coupee[1]\r\n annee_emploi = date_coupee[2]\r\n\r\n region_emploi_x = contenu.css(\"div.search-description + p::text\").extract_first()\r\n region_emploi = re.split(\" : \", region_emploi_x)[1]\r\n\r\n compagnie_emploi = contenu.css(\"p.job-recruiter b *::text\").extract_first()\r\n desc_emploi = contenu.css(\"div.search-description::text\").extract_first()\r\n\r\n link_level = contenu.css(\"h5 a::attr(href)\").extract_first()\r\n\r\n print(cmp, \" | \", jour_emploi, \" | \", mois_emploi, \" | \", annee_emploi, \" | \", region_emploi, \" | \", compagnie_emploi, \" | \", desc_emploi, \" \",\r\n link_level)\r\n cmp += 1\r\n\r\n return contenus_emploi\r\n\r\ndef catch_sec_niv(source):\r\n if source:\r\n\r\n # Si le code source existe\r\n selector_emploi = Selector(text=source)\r\n contenus_emploi = selector_emploi.css(\"body\")\r\n print(\"N° SECTEUR NIVEAU D'ETUDES \")\r\n print(\"_________________________________________________________________________________\")\r\n\r\n for contenu in contenus_emploi:\r\n secteur_emploi = contenu.css(\"div.field.field-name-field-offre-secteur.field-type-taxonomy-term-reference.field-label-hidden div.field-items div.field-item.even::text\").extract_first()\r\n if secteur_emploi == None:\r\n secteur_emploi = \"N/A\"\r\n\r\n niveau_emploi = contenu.css(\"div.field.field-name-field-offre-niveau-etude.field-type-taxonomy-term-reference.field-label-hidden div.field-items div.field-item.even::text\").extract_first()\r\n if niveau_emploi == None :\r\n niveau_emploi = \"N/A\"\r\n\r\n print(\"secteur : \", secteur_emploi)\r\n print(\"niveau d'études requis : \", niveau_emploi)\r\n print(type(secteur_emploi))\r\n print(type(niveau_emploi))\r\n return contenus_emploi\r\n\r\nurl_emploi = \"https://www.emploi.ma/offre-emploi-maroc/consultant-securite-informatique-5948742\"\r\n\r\nsource_emploi_ma = catch_URL(url_emploi)\r\n#data_emploi_ma = catch_data(source_emploi_ma)\r\ndata_emploi_ma = catch_sec_niv(source_emploi_ma)\r\n\r\nprint(data_emploi_ma)\r\n","sub_path":"test_emploima.py","file_name":"test_emploima.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"103312446","text":"import fasttext\nimport prenlp\nfrom prenlp.data import Normalizer\nfrom prenlp.tokenizer import SentencePiece\n\n# Data preparation\nnsmc_train, nsmc_test = prenlp.data.NSMC()\n\n# Corpus preparation for training SentencePiece\ncorpus_path = 'corpus.txt'\nwith open(corpus_path, 'w', encoding='utf-8') as writer:\n for text, label in nsmc_train:\n writer.write(text.strip()+'\\n')\n\n# Preprocessing\ntokenizer = SentencePiece()\ntokenizer.train(input=corpus_path, model_prefix='sentencepiece', vocab_size=10000)\ntokenizer.load('sentencepiece.model')\nnormalizer = Normalizer(url_repl=' ', tag_repl=' ', emoji_repl=' ', email_repl=' ', tel_repl=' ')\n\nfor dataset in [nsmc_train, nsmc_test]:\n for i, (text, label) in enumerate(dataset):\n dataset[i][0] = ' '.join(tokenizer(normalizer.normalize(text.strip())))\n\nprenlp.data.fasttext_transform(nsmc_train, 'nsmc.train')\nprenlp.data.fasttext_transform(nsmc_test, 'nsmc.test')\n \n# Train\nmodel = fasttext.train_supervised(input='nsmc.train', epoch=20)\n\n# Evaluate\nprint(model.test('nsmc.train'))\nprint(model.test('nsmc.test'))\n\n# Inference\nprint(model.predict(nsmc_test[0][0]))","sub_path":"examples/fasttext_nsmc_sentencepiece.py","file_name":"fasttext_nsmc_sentencepiece.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"419721631","text":"# by @f0rizen\n\nfrom .. import loader, utils\n\nimport logging\nimport asyncio\nimport time\n\nlogger = logging.getLogger(__name__)\n\n@loader.tds\nclass HACKMod(loader.Module):\n\t\"\"\"Hack your ass\"\"\"\n\tstrings = {\"name\": \"Hacking\"}\n\tdef __init__(self):\n\t\tself.name = self.strings[\"name\"]\n\tdef config_complete(self):\n\t\tpass\n\tasync def akkcmd(self, message):\n\t\t\"\"\"Hack your ass\"\"\"\n\t\ti = 0\n\t\twhile i <= 99:\n\t\t\tawait message.edit(\"Account telegram hacked for \" + str(i) + \"%\")\n\t\t\ti += 1\n\t\t\ttime.sleep(0.3)\n\t\ttime.sleep(0.3)\n\t\tawait message.edit(\"Account telegram successfully hacked\")\n\t\treturn\n","sub_path":"Vzlom.py","file_name":"Vzlom.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"647590718","text":"#!/usr/bin/env python \nfrom midca import base, rosrun\nfrom midca.modules.perceive import ROSObserver\nfrom midca.modules.plan import AsynchPyhopPlanner\nfrom midca.modules.intend import SimpleIntend\nfrom midca.modules.act import AsynchronousAct\nfrom midca.modules.interpret import InstructionReceiver\nfrom midca.modules.evaluate import EvalPointingFromFeedback\nfrom midca.modules import simulator\nfrom midca.modules._plan.asynch import asynch, operators_sr, methods_sr\nfrom midca.logging import Logger\nimport inspect, os\nfrom std_msgs.msg import String\nfrom midca.examples._gazebo_baxter import Calibrate\nfrom geometry_msgs.msg import Point, PointStamped\n\n\ndef ros_style_midca():\n\tmyMidca = base.MIDCA(None, verbose = 2)\n\tfor phase in [\"Perceive\", \"Interpret\", \"Eval\", \"Intend\", \"Plan\", \"Act\"]:\n\t\tmyMidca.append_phase(phase)\n\n\tmyMidca.append_module(\"Perceive\", ROSObserver.ROSObserver())\n\tmyMidca.append_module(\"Interpret\", InstructionReceiver.InstructionReceiver_sr())\n\tmyMidca.append_module(\"Eval\", EvalPointingFromFeedback.EvalPointingFromFeedback())\n\tmyMidca.append_module(\"Intend\", SimpleIntend.SimpleIntend())\n\tmyMidca.append_module(\"Plan\", AsynchPyhopPlanner.AsynchPyhopPlanner(methods_sr.declare_methods,\n\toperators_sr.declare_ops\n\t\n\t))\n\tmyMidca.append_module(\"Act\", AsynchronousAct.AsynchronousAct())\n\treturn myMidca\n\t\nthisDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\nMIDCA_ROOT = thisDir + \"/../\"\n\nmyMidca = ros_style_midca()\n\n#myMidca.logger.logOutput()\n#myMidca.mem.enableLogging(myMidca.logger)\n\n# calibration\n\n\nrosMidca = rosrun.RosMidca(myMidca, incomingMsgHandlers = [\n\t#rosrun.CalibrationHandler(\"calibrate_done\", myMidca),\n\trosrun.threeObjectsLocationHandler(\"obj_pos\", myMidca),\n\trosrun.UtteranceHandler(\"cmds_received\", myMidca),\n\trosrun.FeedbackHandler(rosrun.FEEDBACK_TOPIC, myMidca)],\n\toutgoingMsgHandlers = [rosrun.OutgoingMsgHandler(asynch.LOC_TOPIC, String), \n\t\t\t\t\t\trosrun.OutgoingMsgHandler(asynch.GRAB_TOPIC, String),\n\t\t\t\t\t\trosrun.OutgoingMsgHandler(asynch.RELEASE_TOPIC, String),\n\t\t\t\t\t\trosrun.OutgoingMsgHandler(asynch.RAISE_TOPIC, String)])\n\nrosMidca.ros_connect()\n\n\nH = Calibrate.calibrate()\n#Z = -0.15113003072395247\n#Z = -0.16113003072395247\nZ=-0.147\nmyMidca.mem.set(myMidca.mem.CALIBRATION_MATRIX, H)\nmyMidca.mem.set(myMidca.mem.CALIBRATION_Z, Z)\n#myMidca.mem.set(myMidca.mem.STACK_Z, 0.018148563732166244)\nmyMidca.mem.set(myMidca.mem.STACK_Z, -0.108833784354784)\nmyMidca.mem.set(myMidca.mem.STACK_3Z, 0.01517833784354784)\nmyMidca.mem.set(myMidca.mem.UNSTACK_Z, -0.11434523370125365)\nmyMidca.mem.set(myMidca.mem.UNSTACK_3Z, -0.05434523370125365)\n\np = Point(x = 0.5682, y = 0.1829 , z = 0.2256)\n#p = \nmyMidca.mem.set(myMidca.mem.RAISING_POINT, p)\n#0.6754473650020971, 0.3487005600746112\n#q = Point(x = 0.6754473650020971, y = 0.3487005600746112, z = -0.14113003072395247)\n#q = Point(x = 0.7596311811530513, y = 0.09691300804254104, z = -0.14113003072395247)\n#lab_q =Point(0.7450848313136519, 0.11634406023548731, -0.15821251824917773)\nq = Point(0.69, 0.01967133208903987, -0.145)\nmyMidca.mem.set(myMidca.mem.PUTTING_POINT, q)\n\n\ninput('Enter ...')\nrosMidca.run_midca()\n","sub_path":"midca/examples/baxter_run_OD_sim.py","file_name":"baxter_run_OD_sim.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"568934761","text":"\nimport pandas as pd\nimport spacy\nimport sys\nspacy.prefer_gpu()\nnlp = spacy.load(\"en_core_web_sm\")\nimport random\nimport re\nfrom random import seed\nimport time\nimport random\nfrom readAndWriteData import write_json, write_csv_from_dict\nfrom sklearn.model_selection import train_test_split\n\ndata = pd.read_csv(\"intermediate_files/new_csv_generated.csv\")\n# data = pd.read_csv(\"balacopa-dev-all.csv\")\n# data = pd.read_csv(\"balacopa-dev-small.csv\")\ncount = 0\n\npronoun_set = set()\noutput_dict = {}\n# output_dict = set()\n\nmale_set = {'her brother', 'his older brother', 'he', 'his brother', 'the man','him', 'the boy'}\nfemale_set = {'her', 'her sister', 'the girl', 'her mother','her daughter','she','the woman','his mother'}\nneutral_set = {'the suspect', 'the police officer','his classmate','the rider', 'the assailant', 'the student', 'the child', \n'a player', 'the physician', 'the scar','his enemy', 'the police', 'the bully', 'the cook', 'i', 'the customer',\n 'the therapist', 'the teacher', 'the caller','the president','her friend','the celebrity','the mayor','the baby'}\nobject_set = {'the gum', 'the computer', 'the door','the puddle', 'it', 'my foot', 'the chair', 'her finger',\n'the bottle', 'the shirt', 'the paperclip', 'the dog', 'the railing', 'her hair', 'college', 'the floor', \n'the book', 'my yard', 'the puzzle', 'the clay','the button', 'his back', 'the church', 'the moon','the disease','the question','his theory','the gift','loose change','the tablecloth','the thread','the room','the jar','the pond',\n'the fabric', 'the desk','the liquid', 'the slide',\"the patient's arm\",'the bill','his toys','the air conditioner','the hamburger','his pocket',\n'the bowling ball','school'}\nplural_set = {'the audience', 'my hands', 'the rules', 'her parents','the parents','the children','they'}\nneutral_self_set = {'i', 'we', 'them'} \n\ndef select_replace_neutral(line, chunk, he_she, word):\n pronoun = he_she\n line = re.sub(word, pronoun, line, flags=re.IGNORECASE)\n return line, word, pronoun\n\ndef select_replace(line, chunk):\n pronoun = \"_\" #\"it\"\n is_neutral=False\n word = random.choice(tuple(chunk))\n if(word in male_set): pronoun = \"_\" #\"he\"\n if(word in female_set): pronoun = \"_\" #\"she\"\n if(word in neutral_set): \n pronoun = \"_\" #\"he\"\n is_neutral = True\n if(word in object_set): pronoun = \"_\" #\"it\"\n if(word in plural_set): pronoun = \"_\" #\"they\"\n if(word in neutral_self_set): pronoun = \"_\" #word\n else: pronoun = \"_\"\n\n line = re.sub(word, pronoun, line, flags=re.IGNORECASE)\n return line, word, pronoun, is_neutral\n\ndef prepare_output(each_output, phrase, option1, option2, ans, pronoun, offset1, offset2, pronoun_offset):\n each_output['video-id'] = \"development_new\"+str(count)\n each_output[\"fold-ind\"] = 1000\n each_output[\"startphrase\"] = phrase\n # print(phrase)\n each_output[\"sent1\"] = phrase.split(\"_\")[0]\n each_output[\"sent2\"] = phrase.split(\"_\")[1]\n each_output[\"gold-source\"] = \"gold\"\n each_output[\"ending0\"] = option1\n each_output[\"ending1\"] = option2\n each_output[\"ending2\"] = \"\"\n each_output[\"ending3\"] = \"\"\n if(ans==option1):\n each_output[\"label\"] = 1\n else:\n each_output[\"label\"] = 2\n\ndef get_values(referring_word, union_set, phrase):\n ans = referring_word\n option1 = ans\n union_set.discard(ans)\n option2 = union_set.pop()\n seed(time.time())\n randval = random.randint(0,1)\n if(randval == 0):\n option1, option2 = option2, option1\n offset1 = phrase.lower().find(option1)\n offset2 = phrase.lower().find(option2)\n return ans, option1, option2, offset1, offset2\n\ndef set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset):\n global count\n global pronoun_set\n global output_dict\n count+=1\n each_output = {}\n prepare_output(each_output, phrase, option1, option2, ans, pronoun, offset1, offset2, pronoun_offset)\n pronoun_set.add(ans)\n output_dict[str(count)] = each_output\n # output_dict.add(each_output)\n\nfor row in data.itertuples(index=True, name='Pandas'):\n # print(row)\n textp = row.p\n docp = nlp(textp)\n chunkp = [chunk.text.lower() for chunk in docp.noun_chunks]\n chunkp = set(chunkp)\n\n texta1 = row.a1\n doca1 = nlp(texta1)\n chunka1 = [chunk.text.lower() for chunk in doca1.noun_chunks]\n chunka1 = set(chunka1)\n\n texta2 = row.a2\n doca2 = nlp(texta2)\n chunka2 = [chunk.text.lower() for chunk in doca2.noun_chunks]\n chunka2 = set(chunka2)\n\n line = row.p+\" \"+row.a1+\" \"+row.a2\n intr1 = chunkp.intersection(chunka1)\n intr2 = chunka1.intersection(chunka2)\n intr3 = chunkp.intersection(chunka2)\n\n total_set = intr1.union(intr2, intr3)\n total_length = len(total_set)\n # print(total_set)\n union_set = chunkp.union(chunka1).union(chunka2)\n # change it >0 afterwards\n if (total_length ==2):\n # print(\"hi\")\n while(len(union_set)>1):\n # print(union_set)\n # print(len(intr1), len(intr2), len(intr3))\n if(len(intr1)>0):\n line, referring_word, pronoun,is_neutral = select_replace(row.a1, intr1)\n if(is_neutral):\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"he\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+line+\" \"+row.a2\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n \n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"she\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word) \n phrase = row.p+\" \"+line+\" \"+row.a2\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n else: \n phrase = row.p+\" \"+line+\" \"+row.a2\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n\n elif(len(intr2)>0):\n line, referring_word, pronoun, is_neutral = select_replace(row.a2, intr2)\n if(is_neutral):\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"he\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"she\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n else:\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n elif(len(intr2)>0):\n line, referring_word, pronoun, is_neutral = select_replace(row.a2, intr2)\n if(is_neutral):\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"he\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"she\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n else:\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset) \n else:\n break\n \n# print(output_dict)\noutput_df = pd.DataFrame.from_dict(output_dict, orient='index')\n # print(output_df)\n # output_df.drop(output_df.columns[[0]], axis=1) \noutput_df = output_df.loc[:, ~output_df.columns.str.contains('^Unnamed')]\n # print(output_df.columns)\n # print(output_df)\ntrain, test = train_test_split(output_df, test_size=0.2)\ntrain.to_csv('output/train.csv')\ntest.to_csv('output/val.csv')\n# write_json(output_dict, \"model_output2.json\")\nprint(\"Check train.csv and val.csv \")\n # write_csv_from_dict(output_dict, \"model_output.csv\")\n\n\n# print(len(male_set)+len(female_set)+len(neutral_set)+len(object_set)+len(plural_set)+len(neutral_self_set))\n# combined_set = (male_set).union(female_set).union(neutral_set).union(object_set).union(plural_set).union(neutral_self_set)\n# print(len(pronoun_set))\n# # pronoun_set.remove(combined_set)\n# # print(pronoun_set)\n# print(combined_set.difference(pronoun_set))\n# print(pronoun_set.difference(combined_set))","sub_path":"code/dataset_generation_new.py","file_name":"dataset_generation_new.py","file_ext":"py","file_size_in_byte":10649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"549857423","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 30 12:19:54 2019\n\n@author: K-D Marie Auriane\n\"\"\"\n\n#programme pour convertir les heures en minute\n\n#variable x designant le nombre d'heures\n#pour afficher la valeur a la ligne (\\n)\nheures=int(input('entrez une valeur: \\n'))\n\nminutes= heures*60\n\nprint(minutes)\n","sub_path":"6.Capstone-I/300116670.py","file_name":"300116670.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"512770069","text":"from typing import Dict\n\nimport numpy as np\nimport torch\n\n\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.models import Model\nfrom allennlp.modules.seq2vec_encoders import Seq2VecEncoder\nfrom allennlp.modules.text_field_embedders import TextFieldEmbedder\nfrom allennlp.nn.util import get_text_field_mask\nfrom allennlp.training.metrics import CategoricalAccuracy, F1Measure\n\nfrom overrides import overrides\n\nEMBEDDING_DIM = 128\nHIDDEN_DIM = 128\n\n\n@Model.register(\"lstm_classifier\")\nclass LstmClassifier(Model):\n def __init__(self,\n word_embeddings: TextFieldEmbedder,\n encoder: Seq2VecEncoder,\n vocab: Vocabulary,\n positive_label: int = 4) -> None:\n super().__init__(vocab)\n \n self.word_embeddings = word_embeddings\n\n self.encoder = encoder\n\n \n self.linear = torch.nn.Linear(in_features=encoder.get_output_dim(),\n out_features=vocab.get_vocab_size('labels'))\n\n \n self.accuracy = CategoricalAccuracy()\n self.f1_measure = F1Measure(positive_label)\n\n \n self.loss_function = torch.nn.CrossEntropyLoss()\n\n \n def forward(self,\n tokens: Dict[str, torch.Tensor],\n label: torch.Tensor = None) -> torch.Tensor:\n \n mask = get_text_field_mask(tokens)\n\n \n embeddings = self.word_embeddings(tokens)\n encoder_out = self.encoder(embeddings, mask)\n logits = self.linear(encoder_out)\n\n \n output = {\"logits\": logits}\n if label is not None:\n self.accuracy(logits, label)\n self.f1_measure(logits, label)\n output[\"loss\"] = self.loss_function(logits, label)\n\n return output\n\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n precision, recall, f1_measure = self.f1_measure.get_metric(reset)\n return {'accuracy': self.accuracy.get_metric(reset),\n 'precision': precision,\n 'recall': recall,\n 'f1_measure': f1_measure}\n","sub_path":"lib/model/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"231915474","text":"import discord\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport socket #used to send UDP packets\r\nimport random\r\nimport colorsys\r\nimport time\r\nimport pickle\r\n\r\n#functions needed to decode the message\r\ndef popString(stack):\r\n length = 1+int.from_bytes(stack[:1],byteorder='big')\r\n string = stack[1:length].decode(\"utf-8\")\r\n return stack[length:], string\r\n\r\ndef popInt(stack):\r\n integer = int.from_bytes(stack[:4],byteorder='big')\r\n return stack[4:],integer\r\n\r\ndef parseResponse(response):\r\n response, _ = popString(response) #msg would be server\r\n response, mapName = popString(response)\r\n response, players = popInt(response)\r\n response, wave = popInt(response)\r\n response, version = popInt(response)\r\n response = {'mapName': mapName,\r\n 'players': players,\r\n 'wave': wave,\r\n 'version': version}\r\n return response\r\n\r\ndef ping(host:str, port:int):\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n sock.settimeout(4) #request timedout\r\n ms = 'ping failed'\r\n try:\r\n sent = sock.sendto(b'\\xFE\\x01',(host, port)) #send [-2,1] (bytes)\r\n start = time.time()\r\n data, server = sock.recvfrom(128)\r\n ms = '%.d ms' %((time.time()-start)*1000) \r\n finally:\r\n response = {'ping':ms} \r\n sock.close()\r\n if (ms!='ping failed'):\r\n response.update(parseResponse(data))\r\n return response\r\n\r\n\r\nclass MindustryCog:\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.servers = [\"mindustry.kr\",\"mindustry.indielm.com\"]\r\n\r\n @commands.group(name='mindustry',aliases=[\"m\"])\r\n async def mindustry(self, ctx):\r\n #Subcommand check\r\n if ctx.invoked_subcommand is None:\r\n await ctx.send(\"You haven't sent a mindustry subcommand. To learn how to use this command say `&&help mindustry`.\")\r\n\r\n #LengthOfHostName HostName, LengthOfMapName MapName, PlayerAmount, Wave, Version\r\n @mindustry.command(name='ping')\r\n async def Mping(self,ctx,server:str=None, port:str='6567'):\r\n print(server)\r\n if server is None:\r\n await ctx.send(\"Please specify a server.\")\r\n return\r\n try:\r\n if ':' in server:\r\n ip, port = server.split(':')\r\n else:\r\n ip = server\r\n response = ping(ip, int(port))\r\n randomColour = [int(x*255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)]\r\n randomColour = discord.Colour.from_rgb(*randomColour)\r\n embed = discord.Embed(title=server,\r\n colour=randomColour)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n for key in response:\r\n embed.add_field(name=key,\r\n value=response[key])\r\n \r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await ctx.send(embed=embed)\r\n print(server, response)\r\n except Exception as e:\r\n print(e)\r\n \r\n @mindustry.command(name='servers')\r\n async def MServers(self,ctx):\r\n randomColour = [int(x*255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)]\r\n randomColour = discord.Colour.from_rgb(*randomColour)\r\n embed = discord.Embed(title=\"Servers:\",\r\n colour=randomColour)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name=\"_*IP*_\",\r\n value=\"*Map*, *Players*, *Wave*\")\r\n for server in self.servers:\r\n try:\r\n if ':' in server:\r\n ip, port = server.split(':')\r\n else:\r\n ip, port = server, '6567'\r\n response = ping(ip, int(port))\r\n if len(response) != 1:\r\n embed.add_field(name=server,\r\n value=f\"{response['mapName']},{response['players']},{response['wave']}\")\r\n else:\r\n embed.add_field(name=server,\r\n value=\"**OFFLINE**\")\r\n\r\n except Exception as e:\r\n print(e)\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await ctx.send(embed=embed)\r\n\r\n @mindustry.command(name='certify',aliases=['verify'])\r\n async def MCertify(self,ctx,ip=None):\r\n await ctx.send('not updated yet might cause a crash')\r\n if ip == None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n else:\r\n servers = pickle.load(open(\"verify.data\", \"rb\"))\r\n try:\r\n print(servers[f'{ip}'])\r\n await ctx.send(f\"{ctx.author.mention}, you have already submitted `{ip}` for verification. Please be patient. We will get to it eventually.\")\r\n return\r\n except KeyError:\r\n servers[f'{ip}'] = {'id':len(servers),'host':ctx.author.id,'timeOfRequest':time.time(),'pings':0}\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"New certification request:\",\r\n colour=0x00FFEE)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Requester',\r\n value=f\"{ctx.author.name}#{ctx.author.discriminator}\")\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Requester\",\r\n value=f\"{ctx.author.mention}\")\r\n await channel.send(embed=embed)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.append(f'{ip}')\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n await ctx.send(f\"I have submitted `{ip}` for verification.\")\r\n for i in range(1,500):\r\n try:\r\n async with websockets.connect(f'ws://{ip}:6568') as websocket:\r\n await websocket.send('ping')\r\n reply = await websocket.recv()\r\n dreply = base64.b64decode(reply)\r\n servers[f'{ip}']['pings'] += 1\r\n except OSError:\r\n adsh = 0\r\n time.sleep(172.8)\r\n if server[f'{ip}']['pings'] < 475:\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"IP Denied:\",\r\n colour=0x990000)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Requester',\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).name+'#'+self.bot.get_user(servers[f\"{ip}\"][\"host\"]).discriminator)\r\n embed.add_field(name='Denier',\r\n value=f\"{self.bot.user.mention}\")\r\n embed.add_field(name='Reason',\r\n value=\"Server failed to have 95% uptime.\")\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Host\",\r\n value=self.bot.get_user(ctx.author.id).mention)\r\n await channel.send(embed=embed)\r\n servers.pop(ip)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.remove(ip)\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n else:\r\n channel = self.bot.get_channel(469612268439601152)\r\n await channel.send(f\"IP `{ip}` has at least 95% uptime.\")\r\n \r\n\r\n @mindustry.command(name='allow',aliases=['approve'])\r\n @commands.has_any_role('Verification Helper')\r\n async def MAllow(self,ctx,ip=None):\r\n if ip == None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n else:\r\n servers = pickle.load(open(\"verify.data\", \"rb\"))\r\n try:\r\n print(servers[f'{ip}'])\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been submitted for verification.\")\r\n return\r\n if (servers[f'{ip}']['timeOfRequest']+(60*60*24)) > time.time():\r\n await ctx.send(f\"Please wait at least 24 hours so that uptime can be measured.\")\r\n return\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"IP Verified:\",\r\n colour=0x008800)\r\n #Difficulty, Catching, obtaining high *, Arena, community\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Host',\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).name+'#'+self.bot.get_user(servers[f\"{ip}\"][\"host\"]).discriminator)\r\n embed.add_field(name='Verifier',\r\n value=f\"{self.bot.get_user(ctx.author.id).mention}\")\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Host\",\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).mention)\r\n await channel.send(embed=embed)\r\n servers.pop(ip)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.remove(ip)\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n \r\n\r\n @mindustry.command(name='queue')\r\n async def MVNext(self,ctx,position=0):\r\n serverList = pickle.load(open(\"verify.list\", \"rb\"))\r\n try: \r\n await ctx.send(serverList[position-1])\r\n except IndexError:\r\n print(serverList)\r\n await ctx.send(\"There isn't an ip at that position\")\r\n\r\n @mindustry.command(name='deny')\r\n @commands.has_any_role('Verification Helper')\r\n async def MDeny(self,ctx,ip=None,*,reason=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n elif reason is None:\r\n await ctx.send(\"Please input a reason.\")\r\n return\r\n else:\r\n servers = pickle.load(open(\"verify.data\", \"rb\"))\r\n try:\r\n print(servers[f'{ip}'])\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been submitted for verification.\")\r\n return\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"IP Denied:\",\r\n colour=0x990000)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Requester',\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).name+'#'+self.bot.get_user(servers[f\"{ip}\"][\"host\"]).discriminator)\r\n embed.add_field(name='Denier',\r\n value=f\"{self.bot.get_user(ctx.author.id).mention}\")\r\n embed.add_field(name='Reason',\r\n value=reason)\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Requester\",\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).mention)\r\n await channel.send(embed=embed)\r\n servers.pop(ip)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.remove(ip)\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n\r\n @mindustry.command(name='position')\r\n async def MVProgress(self,ctx,ip):\r\n servers = pickle.load(open(\"verify.list\", \"rb\"))\r\n for index in range(len(servers)):\r\n if servers[index] == ip:\r\n await ctx.send(f\"Your ip is at position {index+1}.\")\r\n return\r\n await ctx.send(\"I couldn't find that ip in the verification queue.\")\r\n\r\n @mindustry.command(name='v_reset')\r\n @commands.has_any_role('Verification Helper')\r\n async def MVReset(self,ctx):\r\n #{'ip':{'id':0,'host':hostID,'timeOfRequest':time.time,'pings':500}}\r\n servers = {}\r\n serverList = []\r\n pickle.dump(servers, open('verify.data','wb'))\r\n pickle.dump(serverList, open('verify.list','wb'))\r\n\r\n @mindustry.command(name='vote')\r\n async def MVote(self,ctx,ip=None,score=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n if score is None:\r\n await ctx.send(\"Please input a score.\")\r\n return\r\n try:\r\n if int(score) < 0 or int(score) > 10:\r\n await ctx.send(\"Please input a valid score.\")\r\n return\r\n except ValueError:\r\n await ctx.send(\"Please input a valid score.\")\r\n return\r\n servers = pickle.load(open(\"verified.data\", \"rb\"))\r\n try:\r\n currServ = servers[f'{ip}']\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been verified.\")\r\n return\r\n for item in range(len(servers[f'{ip}']['votes'])):\r\n if servers[f'{ip}']['votes'][item][1] == ctx.author.id:\r\n servers[f'{ip}']['votes'][item][0] = score\r\n if len(servers[f'{ip}']['votes']) > 4:\r\n servers[f'{ip}']['score'] = 0\r\n for item in servers[f'{ip}']['votes']:\r\n servers[f'{ip}']['score'] += item[0]\r\n servers[f'{ip}']['score'] = servers[f'{ip}']['score'] / len(servers[f'{ip}']['votes'])\r\n pickle.dump(servers, open('verified.data','wb'))\r\n await ctx.send(\"Vote changed\")\r\n return\r\n servers[f'{ip}']['votes'].append([int(score),ctx.author.id])\r\n if len(servers[f'{ip}']['votes']) > 4:\r\n servers[f'{ip}']['score'] = 0\r\n for item in servers[f'{ip}']['votes']:\r\n servers[f'{ip}']['score'] += item[0]\r\n servers[f'{ip}']['score'] = servers[f'{ip}']['score'] / len(servers[f'{ip}']['votes'])\r\n pickle.dump(servers, open('verified.data','wb'))\r\n await ctx.send(\"Vote submitted\")\r\n\r\n @mindustry.command(name='info')\r\n async def MServerInfo(self,ctx,ip=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n servers = pickle.load(open(\"verified.data\", \"rb\"))\r\n try:\r\n currServ = servers[f'{ip}']\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been verified.\")\r\n return\r\n embed = discord.Embed(title=f\"{ip}'s info:\")\r\n embed.set_author(name=self.bot.get_user(servers[f'{ip}']['host']).display_name,\r\n icon_url=self.bot.get_user(servers[f'{ip}']['host']).avatar_url_as(format='png'))\r\n if servers[f'{ip}']['score'] == -1:\r\n embed.add_field(name='Score',\r\n value='Needs 5 votes to score')\r\n else:\r\n embed.add_field(name='Score',\r\n value=servers[f'{ip}']['score'])\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await ctx.send(embed=embed)\r\n\r\n @mindustry.command(name='add')\r\n @commands.has_any_role('Verification Helper')\r\n async def MServerAdd(self,ctx,ip=None,host:discord.Member=None):\r\n if ip is None or host is None:\r\n await ctx.send(\"Please input __all__ required data.\")\r\n server=pickle.load(open('verified.data','rb'))\r\n server[f'{ip}'] = {'host':host.id,'votes':[],'score':-1}\r\n pickle.dump(server, open('verified.data','wb'))\r\n await ctx.send(\"Server added.\")\r\n\r\n @mindustry.command(name='remove')\r\n @commands.has_any_role('Verification Helper')\r\n async def MServerRemove(self,ctx,ip=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n servers = pickle.load(open(\"verified.data\", \"rb\"))\r\n try:\r\n currServ = servers[f'{ip}']\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been verified.\")\r\n return\r\n servers.pop(f'{ip}')\r\n pickle.dump(servers, open('verified.data','wb'))\r\n await ctx.send(\"Server removed.\")\r\n\r\n @mindustry.command(name='clear')\r\n @commands.has_any_role('Verification Helper')\r\n async def MVServerClear(self,ctx):\r\n servers = {}\r\n pickle.dump(servers, open('verified.data','wb'))\r\n\r\n @mindustry.command(name='edit')\r\n @commands.has_any_role('Verification Helper', 'Verified Host')\r\n async def MServerEdit(self,ctx):\r\n await ctx.send(\"There isn't any data to edit.\")\r\n \r\n# The setup fucntion below is neccesarry. Remember we give bot.add_cog() the name of the class in this case MembersCog.\r\n# When we load the cog, we use the name of the file.\r\ndef setup(bot):\r\n bot.add_cog(MindustryCog(bot))\r\n","sub_path":"cogs/mindustry.py","file_name":"mindustry.py","file_ext":"py","file_size_in_byte":18983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"570161009","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef input_string(st):\n main_dicti = {}\n jj = []\n for i in st:\n if i not in main_dicti:\n main_dicti[i] = 1\n else:\n main_dicti[i]+=1 \n # - sign used to descending order sort in lambda functions\n jj = sorted(main_dicti.items(), key=lambda x:(-x[1],x[0]))\n for k in range(0,3):\n print(jj[k][0],jj[k][1])\n \n\n\nif __name__ == '__main__':\n s = input()\n input_string(s)\n","sub_path":"hackerrank/e_18_company_log.py","file_name":"e_18_company_log.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"238503960","text":"import requests\n\n\nclass Person(object):\n def __init__(self, name=None, email=None, phone=None, website=None):\n self.full_name = name\n self.email = email\n self.phone = phone\n self.website = website\n self.first_name, self.last_name = name.split(' ', 1)\n\n def contact_info(self):\n return self.full_name + ' || ' + self.email + ' || ' + self.phone\n\n @classmethod\n def getAll(self):\n database = requests.get('https://jsonplaceholder.typicode.com/users')\n result = []\n json_list = database.json()\n for item in json_list:\n person = Person(\n item['name'], item['email'],\n item['phone'], item['website']\n )\n result.append(person)\n return result\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391680164","text":"import numpy as np\nimport cv2\nimport imutils\nimport serial\nimport struct\n\nwinName = \"Movement Indicator\"\ncam1= cv2.VideoCapture(1) #Motion Threshold\n\n#setting up 2 cameras in order to\n\nLowercolor = (29, 86, 6)\nUppercolor = (64, 255, 255)\n\n\ndef diffImg(t0, t1, t2):\n d1 = cv2.absdiff(t2, t1)\n d2 = cv2.absdiff(t1, t0)\n added = cv2.add(d1, d2)\n thresholdImage = cv2.threshold(added, 30, 255, cv2.THRESH_BINARY)[1]\n return thresholdImage\n #cv2.bitwise_and\ndef packIntegerAsULong(value):\n \"\"\"Packs a python 4 byte unsigned integer to an arduino unsigned long\"\"\"\n return struct.pack('I', value) #should check bounds\n\n#t_minus = cv2.cvtColor(cam1.read()[1], cv2.COLOR_RGB2GRAY)\n#t = cv2.cvtColor(cam1.read()[1], cv2.COLOR_RGB2GRAY)\n#t_plus = cv2.cvtColor(cam1.read()[1], cv2.COLOR_RGB2GRAY)\nser = serial.Serial(11,9600,timeout =1)\nwhile(True):\n kernel = np.ones((5, 5), np.uint8)\n _,frame = cam1.read()\n mainbase = imutils.resize(frame, width=600)\n # motioncam imageload\n #t_minus = t\n #t = t_plus\n #t_plus = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)\n\n #Colourcam Imageload\n #isol_read_blur = cv2.dilate(mainbase, kernel, iterations=1)\n isol_colour = cv2.cvtColor(mainbase, cv2.COLOR_BGR2HSV)\n ####################################################################\n\n colourcam = cv2.inRange(isol_colour, Lowercolor, Uppercolor)\n\n #motioncam = diffImg(t_minus, t, t_plus)\n\n #motioncam = cv2.erode(motioncam, None, iterations=2)\n colourcam = cv2.erode(colourcam, None, iterations=2)\n #motioncam = cv2.dilate(motioncam, None, iterations=2)\n colourcam = cv2.dilate(colourcam, None, iterations=2)\n\n cnts = cv2.findContours(colourcam.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)[-2]\n center = None\n\n if len(cnts) > 0:\n # find the largest contour in the mask, then use\n # it to compute the minimum enclosing circle and\n # centroid\n c = max(cnts, key=cv2.contourArea)\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n angleHor = int(center[0] / 600 * 60)\n angleVer = int(center[1] / 500 * 60)\n\n\n # only proceed if the radius meets a minimum size\n if radius > 10:\n # draw the circle and centroid on the frame,\n # then update the list of tracked points\n cv2.circle(frame, (int(x), int(y)), int(radius),\n (0, 255, 255), 2)\n cv2.circle(frame, center, 5, (0, 0, 255), -1)\n else:\n angleHor = 30\n angleVer = 30\n\n key = cv2.waitKey(10)\n if key == 27:\n break\n cv2.destroyWindow(winName)\n\n #image, contours, hierarchy = cv2.findContours(Targetcam, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE)\n #Targetcam = cv2.drawContours(Targetcam, contours, -1, (0, 255, 0), 3)\n cv2.imshow(\"Image\", frame)\n cv2.waitKey(10)\n\n #Object coordinate recognition is now complete. Now head on to making servo coordinates\n height, width = frame.shape[:2]\n\n ser.write(struct.pack('>BB',angleHor,angleVer))\n\n# When everything done, release the capture\n\ncv2.destroyAllWindows()","sub_path":"sourceAA.py","file_name":"sourceAA.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"372584664","text":"from grid.Grid import Grid\nfrom cats.astarcat.AstarCat import AstarCat\nfrom cats.catshelper.DistanceCalculator import DistanceTypes\n\nfrom util.Helper import Help\n\n#DO NOT REUSE\n\nclass ScoreCalculator:\n def __init__(self, walls, goals, cat):\n self.walls = set(walls)\n self.goals = set(goals)\n self.cat = cat\n\n self.grid = Grid(goals, walls, (5, 5), rows=11, cols=11)\n\n self.dist = DistanceTypes.HEX\n\n astar_cat = AstarCat(\n max_iterations=200,\n grid=self.grid,\n gWeight=1,\n hWeight=1,\n fWeight=1,\n distanceType=self.dist\n )\n self.cat_obj = astar_cat\n self.score_range = (0, 6)\n\n\n def all_positions(self):\n return [(i,j) for i in range(0,11) for j in range(0,11)]\n\n\n def metadata(self):\n\n cell_set = self.all_positions()\n\n process_data = {\n 'data':{},\n 'normalization':{\n 'min_hits_min': 0,\n 'min_hits_max': 0,\n\n 'path_len_min': 0,\n 'path_len_max': 0,\n\n 'cat_dist_min' : 0,\n 'cat_dist_max' : 0,\n\n 'leads_to_goals_min': 0,\n 'leads_to_goals_max': 0,\n\n 'in_diamond_min': 0,\n 'in_diamond_max': 0,\n\n 'catcher_panic_min': 0,\n 'catcher_panic_max': 0,\n\n 'squares_min': 0,\n 'squares_max': 0,\n }\n }\n\n full_path = []\n full_min_hits = []\n full_cat_dist = [1]\n full_lead_to_goal_count = []\n full_is_diamond = [0,1]\n full_catcher_panic = []\n full_squares = []\n full_cat_trapper = [7]\n \n for elem in cell_set:\n\n local_diff = []\n local_path = []\n\n if elem in self.walls:\n continue\n\n for goal in [goal for goal in self.goals if goal not in self.walls]:\n\n self.cat_obj.reset()\n self.cat_obj.find_path(goal, elem)\n if self.cat_obj.path is None:\n continue\n dist = self.cat_obj.path.get_distance()\n diff = self.cat_obj.path.get_difficulty()\n\n if not elem in Help.valid_goals(goals=self.goals, walls=self.walls):\n local_path.append(dist)\n\n local_diff.append(diff)\n\n\n\n # Aqui local path e diff tem a lista de dados do nó para cada goal\n #local_path.sort()\n #local_diff.sort()\n\n if len(local_path) == 0:\n local_path.append(0)\n\n min_hits_count = Help.count(local_path, [min(local_path)])\n\n if elem not in process_data['data']:\n process_data['data'][elem] = {}\n\n\n process_data['data'][elem]['min_hits'] = min_hits_count\n process_data['data'][elem]['path_len'] = Help.minimum_average(local_path, 5)\n\n lead_to_goals = Help.count_lead_goals(cell=elem, cat=self.cat, goals=self.goals, walls=self.walls)\n\n process_data['data'][elem]['leads_to_goals'] = lead_to_goals\n in_diamond=Help.in_diamond(elem)\n process_data['data'][elem]['in_diamond'] = in_diamond\n\n process_data['data'][elem]['catcher_panic'] = 0\n\n if elem in Help.valid_goals(goals=self.goals, walls=self.walls) and \\\n self.cat in Help.neibs_pos(elem, self.walls, self.cat, False):\n process_data['data'][elem]['catcher_panic'] = 1\n\n process_data['data'][elem]['squares'] = 0\n\n if elem[0] % 3 == 0:\n process_data['data'][elem]['squares'] += 5\n if elem[1] % 3 == 0:\n process_data['data'][elem]['squares'] += 5\n\n if elem[0] % 2 == 0:\n process_data['data'][elem]['squares'] += 1\n if elem[1] % 2 == 0:\n process_data['data'][elem]['squares'] += 1\n\n full_squares.append(process_data['data'][elem]['squares'])\n\n walkables = 0\n n = set(Help.neibs_pos(elem, self.walls, self.cat, exclude_non_walkable = False))\n\n if self.cat in n:\n exitforcat = len(Help.neibs_pos(self.cat, self.walls, self.cat, exclude_non_walkable=True))\n\n if exitforcat == 1:\n walkables = 7\n\n elif exitforcat == 2:\n walkables = 2\n\n elif exitforcat == 3:\n walkables = 1\n\n\n\n process_data['data'][elem]['cat_trap'] = walkables\n full_cat_trapper.append(walkables)\n\n full_path.extend( local_path[ 0:min(len(local_path), 3)] )\n full_min_hits.append( min_hits_count )\n full_lead_to_goal_count.append(lead_to_goals)\n full_is_diamond.append(in_diamond)\n full_catcher_panic.append(process_data['data'][elem]['catcher_panic'])\n\n for position, data in process_data['data'].items():\n self.cat_obj.reset()\n # goal_cell = self.grid.get_cell(goal)\n self.cat_obj.find_path(position, self.cat)\n\n if self.cat_obj.path is None:\n data['cat_dist'] = 20\n full_cat_dist.append(data['cat_dist'])\n continue\n\n dist = self.cat_obj.path.get_distance()\n data['cat_dist'] = dist\n full_cat_dist.append(data['cat_dist'])\n\n process_data['normalization']['min_hits_min'] = min(full_min_hits)\n process_data['normalization']['min_hits_max'] = max(full_min_hits)\n\n process_data['normalization']['path_len_min'] = min(full_path)\n process_data['normalization']['path_len_max'] = max(full_path)\n\n process_data['normalization']['cat_dist_min'] = min(full_cat_dist)\n process_data['normalization']['cat_dist_max'] = max(full_cat_dist)\n\n process_data['normalization']['leads_to_goals_min'] = min(full_lead_to_goal_count)\n process_data['normalization']['leads_to_goals_max'] = max(full_lead_to_goal_count)\n\n process_data['normalization']['in_diamond_min'] = min(full_is_diamond)\n process_data['normalization']['in_diamond_max'] = max(full_is_diamond)\n\n process_data['normalization']['catcher_panic_min'] = min(full_catcher_panic)\n process_data['normalization']['catcher_panic_max'] = max(full_catcher_panic)\n\n process_data['normalization']['squares_min'] = min(full_squares)\n process_data['normalization']['squares_max'] = max(full_squares)\n\n process_data['normalization']['cat_trap_min'] = min(full_cat_trapper)\n process_data['normalization']['cat_trap_max'] = max(full_cat_trapper)\n\n return process_data\n\n\n def scores(self, score_range = (0,50)):\n\n md = self.metadata()\n self.score_range = score_range\n\n norm = md['normalization']\n elems = md['data']\n\n answer = {}\n\n for elem, data in elems.items():\n\n s1_path_len = Help.normalize(\n data['path_len'],\n norm['path_len_min'],\n norm['path_len_max'],\n reversed=True,\n )\n\n s2_min_hits = Help.normalize(\n data['min_hits'],\n norm['min_hits_min'],\n norm['min_hits_max'],\n reversed=False,\n )\n\n s3_cat_dist = Help.normalize(\n data['cat_dist'],\n norm['cat_dist_min'],\n norm['cat_dist_max'],\n reversed=True,\n )\n\n s4_lead_to_goal = Help.normalize(\n data['leads_to_goals'],\n norm['leads_to_goals_min'],\n norm['leads_to_goals_max'],\n reversed=False,\n )\n\n s5_in_diamond = Help.normalize(\n data['in_diamond'],\n norm['in_diamond_min'],\n norm['in_diamond_max'],\n reversed=False,\n )\n\n s6_catcher_panic = Help.normalize(\n data['catcher_panic'],\n norm['catcher_panic_min'],\n norm['catcher_panic_max'],\n reversed=False,\n )\n\n s7_squares = Help.normalize(\n data['squares'],\n norm['squares_min'],\n norm['squares_max'],\n reversed=False,\n )\n\n s8_cat_trap = Help.normalize(\n data['cat_trap'],\n norm['cat_trap_min'],\n norm['cat_trap_max'],\n reversed=False,\n )\n\n #score = (s1_path_len/2) + (s2_min_hits/3) + (s3_cat_dist * 2) + s4_lead_to_goal + (s5_in_diamond/2) + (3*s6_catcher_panic)\n score = ( s3_cat_dist * 20 ) + \\\n ( s2_min_hits * 2 ) + \\\n ( s4_lead_to_goal * .8 ) + \\\n ( s5_in_diamond * 1 ) + \\\n ( s6_catcher_panic * 10 ) + \\\n ( s7_squares * 1 ) + \\\n ( s8_cat_trap * 5 ) + \\\n ( (1+s3_cat_dist*4) * (1+s4_lead_to_goal) * 2 )\n\n if score == -0.0:\n score = 0.0\n\n cell = self.grid.get_cell(elem)\n cell.set_score(score)\n\n\n answer[(elem, cell)] = {\n 's1_path_len':s1_path_len,\n 's2_min_hits':s2_min_hits,\n 's3_cat_dist':s3_cat_dist,\n 'score' : score,\n }\n\n return answer\n","sub_path":"Project4/entrega_final/Pegador_novo/scores_calculator_catcher.py","file_name":"scores_calculator_catcher.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"109574418","text":"\"\"\"\n@author: Duy Le \n\"\"\"\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nimport segmentation_models_pytorch as smp\nimport torch\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import CyclicLR, ReduceLROnPlateau\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nfrom pytorch_toolbelt.utils.catalyst import (\n HyperParametersCallback,\n draw_binary_segmentation_predictions,\n ShowPolarBatchesCallback,\n)\nfrom catalyst.contrib.nn import OneCycleLRWithWarmup\nfrom catalyst import dl, metrics\nfrom catalyst.contrib.callbacks.wandb_logger import WandbLogger\nfrom catalyst.dl import SupervisedRunner, CriterionCallback, EarlyStoppingCallback, SchedulerCallback, MetricAggregationCallback, IouCallback, DiceCallback\nfrom catalyst import utils\nfrom functools import partial\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom typing import List, Union, Tuple\nimport os\nimport json\nimport logging\nlogging.basicConfig(level=logging.INFO, format='')\n\nfrom . import util\nfrom .util import lesion_dict\nfrom ..data import *\nfrom .scheduler import get_scheduler\nfrom .optim import get_optimizer\nfrom .losses import get_loss, WeightedBCEWithLogits\nfrom ..data import OneLesionSegmentation, CLASS_COLORS, CLASS_NAMES\nfrom . import archs\n\ndef get_model(params, model_name):\n \n # Model return logit values\n model = getattr(smp, model_name)(\n **params\n )\n\n return model\n\ndef get_loader(\n images: Union[List[Path], Tuple[List[Path]]],\n is_gray: bool,\n random_state: int,\n masks: Union[List[Path], Tuple[List[Path]]] = None,\n valid_size: float = 0.2,\n batch_size: int = 4,\n val_batch_size: int = 8,\n num_workers: int = 4,\n train_transforms_fn=None,\n valid_transforms_fn=None,\n preprocessing_fn=None,\n ben_method = None,\n mode='binary',\n data_type = 'tile'\n): \n if isinstance(images, List):\n if data_type == 'all':\n indices = np.arange(len(images))\n\n train_indices, valid_indices = train_test_split(\n indices, test_size=valid_size, random_state=random_state, shuffle=True)\n\n np_images = np.array(images)\n train_imgs = np_images[train_indices].tolist()\n valid_imgs = np_images[valid_indices].tolist()\n else:\n train_df = pd.read_csv('data/processed/IDRiD/train/EX/img_mask.csv')\n train_df = train_df.sample(frac=1).reset_index(drop=True)\n train_imgs= train_df.loc[:, 'img'].values.tolist()\n train_imgs = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in train_imgs]\n train_masks = train_df.loc[:, 'mask'].values.tolist()\n train_masks = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in train_masks]\n \n val_df = pd.read_csv('data/processed/IDRiD/val/EX/img_mask.csv')\n val_df = val_df.sample(frac=1).reset_index(drop=True)\n valid_imgs= val_df.loc[:, 'img'].values.tolist()\n valid_imgs = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in valid_imgs]\n valid_masks = val_df.loc[:, 'mask'].values.tolist()\n valid_masks = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in valid_masks]\n else:\n if data_type == 'all':\n train_imgs = images[0]\n valid_imgs = images[1]\n else:\n pass\n \n if mode == 'binary':\n if isinstance(masks, List):\n if data_type == 'all':\n np_masks = np.array(masks)\n train_masks = np_masks[train_indices].tolist()\n valid_masks = np_masks[valid_indices].tolist()\n else:\n pass\n else:\n if data_type == 'all':\n train_masks = masks[0]\n valid_masks = masks[1]\n else:\n pass\n \n train_dataset = OneLesionSegmentation(\n train_imgs,\n is_gray,\n masks=train_masks,\n transform=train_transforms_fn,\n preprocessing_fn=preprocessing_fn,\n ben_transform = ben_method,\n data_type = data_type\n )\n\n valid_dataset = OneLesionSegmentation(\n valid_imgs,\n is_gray,\n masks=valid_masks,\n transform=valid_transforms_fn,\n preprocessing_fn=preprocessing_fn,\n ben_transform = ben_method,\n data_type = data_type\n )\n\n train_loader = DataLoader(\n train_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n shuffle=True,\n pin_memory=True,\n drop_last=True\n )\n\n valid_loader = DataLoader(\n valid_dataset,\n batch_size=val_batch_size,\n num_workers=num_workers,\n shuffle=True,\n pin_memory=True,\n drop_last=False\n )\n\n loaders = OrderedDict()\n loaders['train'] = train_loader\n loaders['valid'] = valid_loader\n\n log_info = [['train', 'valid'], [[len(train_loader), len(valid_loader)], [\n len(train_dataset), len(valid_dataset)]]]\n\n return loaders, log_info\n\n\ndef train_model(exp_name, configs, seed):\n torch.autograd.set_detect_anomaly(True)\n\n TRAIN_IMG_DIRS = configs['train_img_path']\n TRAIN_MASK_DIRS = configs['train_mask_path']\n\n # Get model\n use_smp = True\n if hasattr(smp, configs['model_name']):\n model = get_model(\n configs['model_params'], configs['model_name'])\n elif configs['model_name'] == \"TransUnet\":\n from self_attention_cv.transunet import TransUnet\n model = TransUnet(**configs['model_params'])\n use_smp=False\n else:\n model = archs.get_model(\n model_name=configs['model_name'], \n params = configs['model_params'])\n use_smp = False\n preprocessing_fn, mean, std = archs.get_preprocessing_fn(dataset_name=configs['dataset_name'], grayscale=configs['gray'])\n\n #Define transform (augemntation)\n Transform = get_transform(configs['augmentation'])\n transforms = Transform(\n configs['scale_size'],\n preprocessing_fn=preprocessing_fn\n )\n\n train_transform = transforms.train_transform()\n val_transform = transforms.validation_transform()\n preprocessing = transforms.get_preprocessing()\n\n if configs['data_mode'] == 'binary':\n ex_dirs, mask_dirs = util.get_datapath(\n img_path=TRAIN_IMG_DIRS, mask_path=TRAIN_MASK_DIRS, lesion_type=configs['lesion_type'])\n\n util.log_pretty_table(['full_img_paths', 'full_mask_paths'], [\n [len(ex_dirs), len(mask_dirs)]])\n elif configs['data_mode'] == 'multiclass':\n pass\n else:\n ex_dirs = list(TRAIN_IMG_DIRS.glob('*.jpg'))\n mask_dirs = None\n\n # Get data loader\n if configs['use_ben_transform']:\n ben_transform = load_ben_color\n else:\n ben_transform = None\n\n loader, log_info = get_loader(\n images=ex_dirs,\n is_gray=configs['gray'],\n masks=mask_dirs,\n random_state=seed,\n batch_size=configs['batch_size'],\n val_batch_size=configs['val_batch_size'],\n num_workers=0,\n train_transforms_fn=train_transform,\n valid_transforms_fn=val_transform,\n preprocessing_fn=preprocessing,\n ben_method = ben_transform,\n mode=configs['data_mode'],\n data_type=configs['data_type']\n )\n\n #Visualize on terminal\n util.log_pretty_table(log_info[0], log_info[1])\n\n if use_smp:\n if configs['finetune']:\n #Free all weights in the encoder of model\n for param in model.encoder.parameters():\n param.requires_grad = False\n if configs['model_params']['encoder_weights'] is not None:\n bn_types = nn.BatchNorm2d\n #Disable batchnorm update\n for m in model.encoder.modules():\n if isinstance(m, bn_types):\n m.eval()\n\n param_group = model.get_paramgroup(configs['learning_rate_decode'], configs['weight_decay'])\n trainable, total = model.get_num_parameters()\n # param_group = []\n # if hasattr(model, 'encoder'):\n # encoder_params = filter(lambda p: p.requires_grad, model.encoder.parameters())\n # param_group += [{'params': encoder_params, 'lr': configs['learning_rate']}] \n # if hasattr(model, 'decoder'):\n # decoder_params = filter(lambda p: p.requires_grad, model.decoder.parameters())\n # param_group += [{'params': decoder_params}] \n # if hasattr(model, 'segmentation_head'):\n # head_params = filter(lambda p: p.requires_grad, model.segmentation_head.parameters())\n # param_group += [{'params': head_params}] \n # if hasattr(model, 'supervision'):\n # deep_params = filter(lambda p: p.requires_grad, model.supervision.parameters())\n # param_group += [{'params': deep_params}] \n # if len(param_group) == 0:\n # param_group = [{'params': filter(lambda p: p.requires_grad, model.parameters())}]\n\n # total = int(sum(p.numel() for p in model.parameters()))\n # trainable = int(sum(p.numel() for p in model.parameters() if p.requires_grad))\n count_parameters = {\"total\": total, \"trainable\": trainable}\n\n logging.info(\n f'[INFO] total and trainable parameters in the model {count_parameters}')\n \n #Set optimizer\n optimizer = get_optimizer(\n configs['optimizer'], param_group, configs['learning_rate_decode'], configs['weight_decay'])\n #Set learning scheduler\n scheduler = get_scheduler(\n configs['scheduler'], optimizer, configs['learning_rate'], configs['num_epochs'],\n batches_in_epoch=len(loader['train']), mode=configs['mode']\n )\n #Set loss\n criterion = {}\n for loss_name in configs['criterion']:\n if loss_name == 'wbce':\n pos_weights = torch.tensor(configs['pos_weights'], device=utils.get_device())\n loss_fn = WeightedBCEWithLogits(pos_weights=pos_weights)\n else:\n loss_fn = get_loss(loss_name)\n criterion[loss_name] = loss_fn\n\n #Define callbacks\n callbacks = []\n losses = []\n for loss_name, loss_weight in configs['criterion'].items():\n criterion_callback = CriterionCallback(\n input_key=\"mask\",\n output_key=\"logits\",\n criterion_key=loss_name,\n prefix=\"loss_\"+loss_name,\n multiplier=float(loss_weight)\n )\n\n callbacks.append(criterion_callback)\n losses.append(criterion_callback.prefix)\n\n callbacks += [MetricAggregationCallback(\n prefix=\"loss\",\n mode=\"sum\",\n metrics=losses\n )]\n\n if isinstance(scheduler, (CyclicLR, OneCycleLRWithWarmup)):\n callbacks += [SchedulerCallback(mode=\"batch\")]\n elif isinstance(scheduler, (ReduceLROnPlateau)):\n callbacks += [SchedulerCallback(reduced_metric=configs['metric'])]\n\n hyper_callbacks = HyperParametersCallback(configs)\n\n if configs['data_mode'] == 'binary':\n image_format = 'gray' if configs['gray'] else 'rgb'\n visualize_predictions = partial(\n draw_binary_segmentation_predictions, image_key=\"image\", targets_key=\"mask\", mean=mean, std=std, image_format=image_format\n )\n # elif configs['data_mode'] == 'multilabel':\n # visualize_predictions = partial(\n # draw_multilabel_segmentation_predictions, image_key=\"image\", targets_key=\"mask\", class_colors=CLASS_COLORS\n # )\n\n show_batches_1 = ShowPolarBatchesCallback(\n visualize_predictions, metric=\"iou\", minimize=False)\n\n # show_batches_2 = ShowPolarBatchesCallback(\n # visualize_predictions, metric=\"loss\", minimize=True)\n\n early_stopping = EarlyStoppingCallback(\n patience=20, metric=configs['metric'], minimize=False)\n\n iou_scores = IouCallback(\n input_key=\"mask\",\n activation=\"Sigmoid\",\n threshold=0.5\n )\n\n dice_scores = DiceCallback(\n input_key=\"mask\",\n activation=\"Sigmoid\",\n threshold=0.5\n )\n\n # aucpr_scores = AucPRMetricCallback(\n # input_key=\"mask\",\n # )\n\n # aucroc_scores = RocAucMetricCallback(\n # input_key=\"mask\",\n # )\n #End define\n # if configs['resume'] is not None:\n # exp_name = configs['resume'].split(os.path.sep)[-3]\n\n prefix = f\"{configs['lesion_type']}/{exp_name}\"\n log_dir = os.path.join(\"models/\", configs['dataset_name'], prefix)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n # if configs['kfold']:\n # logger = WandbLogger(project=lesion_dict[configs['lesion_type']].project_name,\n # name=)\n\n logger = WandbLogger(project=lesion_dict[configs['lesion_type']].project_name,\n name=exp_name)\n\n\n #Save config as JSON format\n with open(os.path.join(log_dir, 'config.json'), 'w') as f:\n configs['train_img_path'] = str(configs['train_img_path'])\n configs['train_mask_path'] = str(configs['train_mask_path'])\n json.dump(configs, f)\n\n callbacks += [hyper_callbacks, early_stopping,\n iou_scores, dice_scores]\n\n \n # class CustomRunner(dl.SupervisedRunner):\n # def _handle_batch(self, batch):\n # x, y = batch\n\n # y_pred = self.model(x)\n # pass\n\n if configs['is_fp16']:\n fp16_params = dict(amp=True) # params for FP16\n else:\n fp16_params = None\n \n # model training\n if not configs['deep_supervision']:\n runner = SupervisedRunner(\n device=utils.get_device(), input_key=\"image\", input_target_key=\"mask\")\n\n runner.train(\n model=model,\n criterion=criterion,\n optimizer=optimizer,\n callbacks=callbacks,\n logdir=log_dir,\n loaders=loader,\n num_epochs=configs['num_epochs'],\n scheduler=scheduler,\n main_metric=configs['metric'],\n minimize_metric=False,\n timeit=True,\n fp16=fp16_params,\n resume=configs['resume_path'],\n verbose=True,\n )\n else:\n callbacks = []\n if isinstance(scheduler, (CyclicLR, OneCycleLRWithWarmup)):\n callbacks += [SchedulerCallback(mode=\"batch\")]\n elif isinstance(scheduler, (ReduceLROnPlateau)):\n callbacks += [SchedulerCallback(reduced_metric=configs['metric'])]\n\n hyper_callbacks = HyperParametersCallback(configs)\n\n optim_cb = dl.OptimizerCallback(\n metric_key=\"loss\", \n accumulation_steps=1, \n grad_clip_params=None\n )\n \n callbacks += [optim_cb, hyper_callbacks, early_stopping, logger]\n\n def get_pyramid(mask: torch.Tensor, height, shape_list, include_final_mask=False):\n with torch.no_grad():\n if include_final_mask:\n masks = [mask]\n big_mask = masks[-1]\n else:\n masks = []\n big_mask = mask\n for _, shape in zip(range(height), shape_list):\n small_mask = F.adaptive_avg_pool2d(big_mask, shape)\n masks.append(small_mask)\n big_mask = masks[-1]\n\n targets = []\n for mask in masks:\n targets.append(mask)\n\n return targets\n\n class CustomRunner(dl.Runner):\n def _handle_batch(self, batch):\n results = batch\n x = results['image']\n y = results['mask']\n y_hat, y_hat_levels = self.model(x)\n shape_list =[]\n for level in y_hat_levels:\n shape_list.append(np.array(level.shape[2:]).tolist())\n\n targets = get_pyramid(y, len(y_hat_levels), shape_list, False)\n loss_levels = []\n\n criterion_ds = get_loss(configs['criterion_ds'])\n for y_hat_level, target in zip(y_hat_levels, targets):\n loss_levels.append(criterion_ds(y_hat_level, target))\n\n loss_final = None \n loss_com = {}\n for loss_name, loss_weight in configs['criterion'].items():\n loss_com['loss_' + loss_name] = criterion[loss_name](y_hat, y) \n if loss_final is None:\n loss_final = criterion[loss_name](y_hat, y)*float(loss_weight)\n else:\n loss_final += criterion[loss_name](y_hat,y)*float(loss_weight)\n\n loss_deep_super = torch.sum(torch.stack(loss_levels))\n loss = loss_final + loss_deep_super\n\n target = y\n pred = torch.sigmoid(y_hat)\n dice = metrics.dice(pred, target, threshold=0.5).mean()\n iou = metrics.iou(pred, target, threshold=0.5).mean()\n\n self.batch_metrics = {\n 'loss': loss,\n 'dice': dice,\n 'iou': iou\n }\n\n for key in loss_com:\n self.batch_metrics[key] = loss_com[key]\n \n runner = CustomRunner(device = utils.get_device())\n runner.train(\n model=model,\n optimizer=optimizer,\n callbacks=callbacks,\n logdir=log_dir,\n loaders=loader,\n num_epochs=configs['num_epochs'],\n scheduler=scheduler,\n main_metric=configs['metric'],\n minimize_metric=False,\n timeit=True,\n fp16=fp16_params,\n resume=configs['resume_path'],\n verbose=True,\n )\n\ndef run_cross_validation(fold):\n #@TODO Not doing yet because training with cross validation take so much time \n pass\n","sub_path":"src/main/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":17962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"395784284","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\ninfile = open('perihelion20_8Newton.txt')\n\nnumbers = []\nfor line in infile:\n\tnumbers.append(float(line))\n\n\n\nplt.plot(numbers)\nplt.title('The perihelion precession of Mercury')\nplt.ylabel('Perihelion angle [rad]')\nplt.xlabel('Number of full rotations around the Sun')\nplt.show()\n","sub_path":"plotting/plot_perihelion.py","file_name":"plot_perihelion.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"408237965","text":"import GPUtil\nimport time\nimport psutil\nimport math\nfrom log.log import Logger\nimport sys\n\n\ndef memoryuse():\n gpulist = []\n memory = []\n\n # f = open('./log/2.txt', 'a+')\n # sys.stdout = f\n\n gpuss = GPUtil.getGPUs()\n for gpu in gpuss:\n gpulist.append(gpu.memoryUsed)\n print('总gpu:', gpu.memoryTotal, 'gpuused:', gpu.memoryUsed)\n cpu = psutil.cpu_percent()\n mem = psutil.virtual_memory() #\n\n mem_total = mem[0] / math.pow(1024, 3)\n mem_used = mem[2]\n mem1 = mem[3] / math.pow(1024, 3)\n memory.append(mem_used)\n print('cpu:', str(cpu) + '%,', '总memory:', round(mem_total), '占用率', str(mem_used) + '%,', 'memory used:', str(mem1))\n time.sleep(3)","sub_path":"MemoryUse.py","file_name":"MemoryUse.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"218666631","text":"import pyqtgraph as pg\nimport numpy as np\nfrom PyQt5 import QtCore\nfrom datetime import datetime\n\nfrom MusicalIllusion.Visualizer.VisualizerData import VisualizerData\n\n\nclass Visualizer():\n def __init__(self, plot, parent, defaultSize, defaultGain, connectDots):\n\n self.parent = parent\n self.data = VisualizerData(defaultSize, defaultGain)\n self.frame = 0\n self.connectDots = connectDots\n\n # Timings used for the output file\n self.timings = {}\n\n # Set the plot up for visualization\n self.lines = pg.GraphItem(pos=np.array([(-100, -100)]))\n plot.addItem(self.lines)\n p = plot.getPlotItem()\n p.setXRange(0, 10)\n p.setYRange(0, 10)\n p.showGrid(False, False)\n p.showAxis('left', False)\n p.showAxis('bottom', False)\n p.setMouseEnabled(False, False)\n p.hideButtons()\n\n self.plotTimer = QtCore.QTimer()\n self.plotTimer.setTimerType(QtCore.Qt.PreciseTimer)\n self.plotTimer.timeout.connect(self.plotData)\n\n self.audTimer = QtCore.QTimer()\n self.audTimer.setTimerType(QtCore.Qt.PreciseTimer)\n self.audTimer.timeout.connect(self.playAudio)\n\n self.audComplete = QtCore.QTimer()\n self.audComplete.timeout.connect(self.progressAudio)\n\n def setData(self, data):\n self.data.loadData(data)\n self.frame = 0\n self.timings = {}\n\n def clearPlot(self):\n self.lines.setData(pos=np.array([(-100, -100)]))\n\n def play(self):\n self.plotTimer.start(0)\n if self.data.isAudio:\n self.audTimer.start(self.data.audOffset)\n self.frame = 0\n time = datetime.now()\n self.timings = {\"animationStart\": time, \"animationDelay\": self.data.audOffset,\n \"audioStart\": time, \"audioDelay\": 0}\n\n def playAudio(self):\n self.data.audio.play()\n self.audTimer.stop()\n self.audComplete.start(1000)\n\n def progressAudio(self):\n if not self.data.audio.isPlaying():\n self.audComplete.stop()\n self.parent.state.currentTrialData.update(self.timings)\n if self.parent.data.propertiesVer == 'si.properties':\n self.parent.state.updateState()\n return\n\n def plotData(self):\n\n if self.data.isAnim == False:\n self.plotTimer.stop()\n return\n\n pens = [pg.mkPen(color=[j for j in i]) for i in self.data.pens[self.frame]]\n brushes = [pg.mkBrush(color=[j for j in i]) for i in self.data.pens[self.frame]]\n lines = np.array([(i[0], i[1], i[2], 255, 1) for i in self.data.pens[self.frame]], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)])\n\n # Ugly but the only way it'll let me toggle the lines\n # Pushed a fix for this to matplotlib but not sure when it'll be\n # included in the full version. Ugly will have to do for now\n if self.connectDots:\n self.lines.setData(pos=np.array(self.data.pos[self.frame]),\n adj=self.data.adj,\n pen=lines,\n symbolPen=pens,\n symbolBrush=brushes,\n symbol=self.data.shapes[self.frame],\n size=self.data.sizes[self.frame]\n )\n else:\n self.lines.setData(pos=np.array(self.data.pos[self.frame]),\n pen=lines,\n symbolPen=pens,\n symbolBrush=brushes,\n symbol=self.data.shapes[self.frame],\n size=self.data.sizes[self.frame]\n )\n\n self.frame += 1\n if self.frame < len(self.data.times) - 1:\n dt = int((self.data.times[self.frame] - self.data.times[self.frame - 1]) * 1000)\n self.plotTimer.setInterval(dt)\n else:\n self.plotTimer.stop()\n self.lines.setData(pos=np.array([(-100, -100)]))\n self.parent.state.currentTrialData.update(self.timings)\n self.parent.state.updateState()\n","sub_path":"src/python3/MusicalIllusion/Visualizer/Visualizer.py","file_name":"Visualizer.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"214404034","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import String\nfrom trajectory_msgs.msg import JointTrajectory\nfrom trajectory_msgs.msg import JointTrajectoryPoint\nimport math as mt\nfrom control_msgs.msg import JointTrajectoryControllerState\nfrom han2um_test.srv import *\nimport numpy as np\n\n\ndef Path_move(request):\n #link length\n l1=25\n l2=20\n l3=5\n # go position\n pos_x=request.fpos_x\n pos_y=request.fpos_y\n pos_z=request.fpos_z\n # calculate angle\n r=mt.sqrt(pos_x*pos_x+pos_y*pos_y+pos_z*pos_z)\n if r>50:\n print(\"over max distance\")\n\n #reference=robotarm current joint angle\n rospy.wait_for_service('jointstate')\n word=True\n jointangle=rospy.ServiceProxy('jointstate',jointstate)\n res=jointangle(word) # res.th0~3\n \n res_rx=l1*mt.cos(res.th1)+l2*mt.cos(res.th1+res.th2)\n res_rrx=l1*mt.cos(res.th1)+l2*mt.cos(res.th1+res.th2)+l3*mt.cos(res.th1+res.th2+res.th3)\n res_rz=l1*mt.sin(res.th1)+l2*mt.sin(res.th1+res.th2)\n res_rrz=l1*mt.sin(res.th1)+l2*mt.sin(res.th1+res.th2)+l3*mt.sin(res.th1+res.th2+res.th3)\n\n # circle's dot min distance\n num=8\n t=np.linspace(0,2*mt.pi,num)\n Cx=np.zeros(num)\n Cz=np.zeros(num)\n for i in range(0,num):\n Cx[i]=l3*mt.cos(t[i])+pos_x\n Cz[i]=l3*mt.sin(t[i])+pos_z\n\n distance=np.zeros(num)\n for i in range(0,num):\n distance[i]=mt.sqrt((res_rx-Cx[i])**2+(res_rz-Cz[i])**2)\n min_num=np.argmin(distance)\n Px=Cx[min_num]\n Pz=Cz[min_num]\n print(Px,Pz)\n #IK\n th0=mt.atan(pos_y/pos_x)\n d=mt.sqrt(Px**2+Pz**2)\n th2=-1*mt.acos((d**2-l1**2-l2**2)/(2*l1*l2))\n alpha=mt.atan(Pz/Px)\n th1=mt.acos((d**2+l1**2-l2**2)/(2*d*l1))+alpha\n rx=l1*mt.cos(th1)\n rz=l1*mt.sin(th1)\n th2_m=mt.atan((Pz-rz)/(Px-rx))\n th3_m=mt.atan((pos_z-Pz)/(pos_x-Px))\n th3=(th3_m-th2_m)\n\n # distance error\n de=0.1\n pub = rospy.Publisher('/arm_controller/command', JointTrajectory, queue_size=10)\n print('real')\n print('th0: %f,th1: %f,th2:%f,th3:%f' %(th0,th1,th2,th3))\n #angle error fillter\n \n th1=angle_filter(th1)\n th2=angle_filter(th2)\n th3=angle_filter(th3)\n print('filter')\n print('th0: %f,th1: %f,th2:%f,th3:%f' %(th0,th1,th2,th3))\n print('th0_d:%f,th1_d:%f,th2_d:%f,th3_d:%f' %(th0*180/mt.pi,th1*180/mt.pi,th2*180/mt.pi,th3*180/mt.pi))\n \n\n while not rospy.is_shutdown():\n msg=JointTrajectory()\n msg.joint_names=['base2','link1_joint','link2_joint','link3_joint']\n ptn=JointTrajectoryPoint()\n\n ptn.positions=[th0,th1,th2,th3]\n ptn.time_from_start=rospy.Duration.from_sec(1)\n msg.points.append(ptn)\n pub.publish(msg)\n rate.sleep()\n\n rospy.wait_for_service('jointstate')\n word=True\n jointangle=rospy.ServiceProxy('jointstate',jointstate)\n res=jointangle(word) # res.th0~3\n \n #0<=res.th0<=360degree\n #0<=res.th1<=90degree\n #0<=res.th2<=90degree\n #0<=res.th3<=90degree\n\n if ((res.th0-th0)<=de)and((res.th1-th1)<=de)and((res.th2-th2)<=de)and((res.th3-th3)<=de):\n print('move complete')\n break\n\ndef angle_filter(theta):\n if theta<0:\n theta=-theta\n return theta\n\"\"\"\ndef angle_filter123(theta):\n \n if theta<0:\n theta=-theta\n\n theta=mt.pi/2-theta\n\n if not 0<=theta<=mt.pi/2:\n theta=theta-mt.pi\n return theta\"\"\"\n \n\n\nrospy.init_node('Path_move', anonymous=True)\nservice=rospy.Service('Path_move',path_move,Path_move)\nrate = rospy.Rate(10) # 10hz\nrospy.spin()\n","sub_path":"main/Robot Arm Control/Path_move_server.py","file_name":"Path_move_server.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"196779834","text":"from sklearn import linear_model\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\n\n\n#Function to handle the non-numeric data.\ndef handle_non_numeric_data(df):\n columns=df.columns.values\n \n for column in columns:\n text_digit_vals={}\n def convet_to_int(val):\n return text_digit_vals[val]\n \n if df[column].dtype!=np.int64 and df[column].dtype!=np.float64:\n column_content=df[column].values.tolist()\n unique_element=set(column_content)\n x=0\n for unique in unique_element:\n if unique not in text_digit_vals:\n text_digit_vals[unique]=x\n x+=1\n \n df[column]=list(map(text_digit_vals.get, df[column]))\n return df \n\n\n#Filepath of the training and testing dataset.\ntrain_filepath='/home/shashank/NRP/Linear Regression/train.csv'\ntest_filepath='/home/shashank/NRP/Linear Regression/test.csv'\n\n\n\n#Read the csv file\ntrain_data=pd.read_csv(train_filepath)\ntest_data=pd.read_csv(test_filepath)\n\ny=train_data.SalePrice\nX=train_data.drop(['Id','SalePrice'],axis=1)\n\nX=handle_non_numeric_data(X)\n\n#Split tha data for testing and training.\ntrain_X,test_X,train_y,test_y=train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25)\n\n#Imputer for adding value where data is blank or NaN.\nmy_imputer = Imputer()\ntrain_X = my_imputer.fit_transform(train_X)\ntest_X = my_imputer.transform(test_X)\nX_scaled = preprocessing.scale(train_X)\nregr = linear_model.LinearRegression()\n\n# Train the model using the training sets\nregr.fit(train_X,train_y)\n\n# Make predictions using the testing set\npred_y = regr.predict(test_X)\n\n\n\nprint(mean_squared_error(test_y,pred_y))\nprint(mean_absolute_error(test_y,pred_y))\n\n\n\n\n","sub_path":"Linear Regression/regression_scikit.py","file_name":"regression_scikit.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"598172847","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018, OVENUBE and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\nclass TiposdeTransaccionSunat(Document):\n\tpass\n\n@frappe.whitelist()\ndef get_tipo_transaccion(customer):\n\tcliente = frappe.get_doc(\"Customer\", customer)\n\tif cliente.codigo_tipo_documento in ['-', '1', '4', '6']:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"VENTA INTERNA\")\n\telif cliente.codigo_tipo_documento == \"0\":\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"EXPORTACION\")\n\telse:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"NO DOMICILIADO\")\n\treturn {\"codigo\": transaccion.codigo_tipo_transaccion, \"descripcion\": transaccion.name}\n\n@frappe.whitelist()\ndef get_tipo_transaccion_compras(supplier):\n\tproveedor = frappe.get_doc(\"Supplier\", supplier)\n\tif proveedor.codigo_tipo_documento in ['-', '1', '4', '6']:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"VENTA INTERNA\")\n\telse:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"NO DOMICILIADO\")\n\treturn {\"codigo\": transaccion.codigo_tipo_transaccion, \"descripcion\": transaccion.name}\n\n@frappe.whitelist()\ndef get_tipo_transaccion_fee(student):\n\tstudent = frappe.get_doc(\"Student\", student)\n\tif student.codigo_tipo_documento in ['-', '1', '4', '6']:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"VENTA INTERNA\")\n\telse:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"NO DOMICILIADO\")\n\treturn {\"codigo\": transaccion.codigo_tipo_transaccion, \"descripcion\": transaccion.name}","sub_path":"nubefact_integration/nubefact_integration/doctype/tipos_de_transaccion_sunat/tipos_de_transaccion_sunat.py","file_name":"tipos_de_transaccion_sunat.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"350536725","text":"import json\nimport pytest\nimport requests\nfrom server import *\n\n\n# REQUEST_REQUIRED_KEYS = [[\"patient_id\", \"attending_email\", \"user_age\"],\n# [\"patient_id\", \"heart_rate\"],\n# [\"patient_id\", \"heart_rate_average_since\"]]\n\n\n@pytest.mark.parametrize(\"HR, age, expected, broke\", [\n (200, 2, True, False),\n (120, 2, False, False),\n (110, 6000, True, False),\n (101, 5000, False, False),\n (\"abc\", 5000, False, True)\n])\ndef test_is_tachycardic(HR, age, expected, broke):\n age_years = float(age)/float(365)\n try:\n out = is_tachycardic(HR, age_years)\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n assert out == expected\n\n\n@pytest.mark.parametrize(\"r, broke\", [\n ({\"patient_id\": \"1\", \"attending_email\": \"hi@duke.edu\", \"user_age\": 30},\n False),\n ({\"attending_email\": \"hi@duke.edu\", \"user_age\": 30}, True),\n ({\"patient_id\": \"1\", \"attending_email\": \"hi@duke.edu\"}, True)\n])\ndef test_validate_new_patient_request(r, broke):\n try:\n validate_new_patient_request(r)\n except ValidationError:\n assert broke is True\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n\n\n@pytest.mark.parametrize(\"r, broke\", [\n ({\"patient_id\": \"1\", \"heart_rate\": 30}, False),\n ({\"patient_id\": \"1\"}, True),\n ({\"heart_rate\": 30}, True),\n ({\"patient_id\": \"1\", \"heart_rate\": 30,\n \"attending_email\": \"hi@duke.edu\"}, False),\n])\ndef test_validate_heart_rate_request(r, broke):\n try:\n validate_heart_rate_request(r)\n except ValidationError:\n assert broke is True\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n\n\n@pytest.mark.parametrize(\"r, broke\", [\n ({\"patient_id\": \"1\",\n \"heart_rate_average_since\": \"2018-03-09 11:00:36.372339\"}, False),\n ({\"patient_id\": \"1\"}, True),\n ({\"heart_rate_average_since\": \"2018-03-09 11:00:36.372339\"}, True),\n ({\"patient_id\": \"1\",\n \"heart_rate_average_since\": \"2018-03-09 11:00:36.3\", \"hi\": 0}, False)\n])\ndef test_validate_internal_average_request(r, broke):\n try:\n validate_internal_average_request(r)\n except ValidationError:\n assert broke is True\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n","sub_path":"test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"600449219","text":"import pandas as pd\nimport numpy as np \nimport Utils as utils\nimport kNN as knn\nimport kfold as kfold\nimport OLS as ols\n\nclass CentroidData:\n def __init__(self):\n self.centoid = []\n self.nearestDataPoints = []\n #for performance\n self.nearestDataPointsTempList = []\n #testing data for centroid\n self.testingData = []\n #for performance\n self.nearestDataPointsTempListForTestingData = []\n\nclass CentroidResults:\n def __init__(self):\n self.centroidData = []\n self.olsRuns = []\n\ndef randomN(df):\n return pd.DataFrame( np.random.rand(1,11), columns=df.columns)\n\ndef getKCentroids(k,df):\n list = []\n for i in range(k):\n list.append( randomN(df) )\n return list\n\ndef getKSpacedCentroids(k,df,delta):\n list = []\n for i in np.arange(0.0,1.1,delta):\n for j in np.arange(0,1.1,delta):\n for k in np.arange(0,1.1,delta):\n for l in np.arange(0,1.1,delta):\n centroid = randomN(df)\n centroid.head(1).Health_Expenditure = i\n centroid.head(1).GDP_Per_Capita = j\n centroid.head(1).Unemployment = k\n centroid.head(1).Education = l\n list.append( centroid )\n return list \n\n\ndef getK(delta):\n k = int(1/delta) + 1\n return k**4\n\n\n\ndef getSpacedCentoids(ddf):\n centroidsDF = pd.read_csv(\"clustering-InitialCentroids0.5.csv\")\n l = []\n for i in range(len(centroidsDF)):\n df = pd.DataFrame( columns=ddf.columns)\n df = df.append(centroidsDF.iloc[i])\n l.append(df)\n return l\n\n#sort datapoints according to nearest centroid\n\n\ndef getInitialCentroidDatas(k,df,delta): \n centroidDatas = []\n centroids = getKSpacedCentroids(k,df,delta)\n #centroids = getSpacedCentoids(df)\n for i in range(len(centroids)):\n centroidData = CentroidData()\n centroidData.centoid = centroids[i]\n centroidData.centoid.Country_Name = 'Centroid' + str(i)\n centroidData.nearestDataPoints = pd.DataFrame( columns=df.columns)\n centroidDatas.append(centroidData)\n return centroidDatas\n\n\n#onlySelectCentroidIfNearsestPointsIsEmpty means that thre needs to be nearest points already selected \ndef getClosestCentroid(datapoint,centroidDatas,onlySelectCentroidIfNearsestPointsIsEmpty):\n closestCentroidData = []\n closestDistance = 9999999999.9\n for i in range(len(centroidDatas)):\n #distance = knn.distance(centroidDatas[i].centoid, datapoint)\n distance = utils.GetEuclideanDistanceBetweenFeatureVectors(kfold.getX(centroidDatas[i].centoid),kfold.getX(datapoint) )\n if( distance < closestDistance):\n #this centroid can oly be selected if nearest points exists. This is in the case for selecting centroids for testing data\n if onlySelectCentroidIfNearsestPointsIsEmpty:\n if not centroidDatas[i].nearestDataPoints.empty:\n closestCentroidData = centroidDatas[i]\n closestDistance = distance\n else:\n uu = 0\n #select centroid regardless\n else:\n closestCentroidData = centroidDatas[i]\n closestDistance = distance\n return closestCentroidData\n\n\n\ndef getMeanPoint(nearestDataPoints,trainingData):\n #create new centroid \n meanPoint = randomN(trainingData)\n\n #set values of centroid to mean of each dimension\n meanPoint.head(1).Health_Expenditure = nearestDataPoints['Health_Expenditure'].mean()\n meanPoint.head(1).GDP_Per_Capita = nearestDataPoints['GDP_Per_Capita'].mean()\n meanPoint.head(1).Unemployment = nearestDataPoints['Unemployment'].mean()\n meanPoint.head(1).Education = nearestDataPoints['Education'].mean()\n return meanPoint\n\n\n\ndef CalculateCentroids(trainingData, k, movingThreshold, centroidDatas):\n for j in range(150):\n #assign training data point to closest centroid\n for i in range(len(trainingData)):\n dataRow = trainingData.iloc[i]\n centroidData = getClosestCentroid( dataRow, centroidDatas, onlySelectCentroidIfNearsestPointsIsEmpty = False)\n centroidData.nearestDataPointsTempList.append(dataRow)\n #centroidData.nearestDataPoints = centroidData.nearestDataPoints.append( dataRow, ignore_index=True,sort=False )\n\n numberOfCentroidsThatDidNotMove = 0\n for i in range(len(centroidDatas)):\n #removing all nearest points\n centroidDatas[i].nearestDataPoints.dropna()\n centroidDatas[i].nearestDataPoints = pd.DataFrame(centroidDatas[i].nearestDataPointsTempList, columns=trainingData.columns)\n # centroidDatas[i].nearestDataPoints = pd.concat( [centroidDatas[i].nearestDataPoints, centroidDatas[i].nearestDataPointsTempList])\n #clear temp list \n centroidDatas[i].nearestDataPointsTempList = []\n \n #if no points are assosiated with the centroid then the centroid does not move\n if not centroidDatas[i].nearestDataPoints.empty:\n newCentroid = getMeanPoint(centroidDatas[i].nearestDataPoints,trainingData)\n else:\n newCentroid = centroidDatas[i].centoid\n \n \n \n #calculate mean of data points assigned to the centroid\n #newCentroid = utils.GetMeanPointOfDataset( centroidDatas[i].nearestDataPoints)\n #get the change in position of the centroid\n old = kfold.getX(centroidDatas[i].centoid)\n new = kfold.getX(newCentroid)\n diffrenceInCentroid = old - new \n distanceBetweenOldAndNewCentroid = utils.GetEuclideanDistanceBetweenFeatureVectors(kfold.getX(centroidDatas[i].centoid),kfold.getX(newCentroid) )\n print( \"centroid difference \" + str(i) + ' distance= ' + str(distanceBetweenOldAndNewCentroid) )\n print( diffrenceInCentroid )\n #set new mean of data points as the new centroid\n centroidDatas[i].centoid = newCentroid\n if( distanceBetweenOldAndNewCentroid < movingThreshold ):\n numberOfCentroidsThatDidNotMove = numberOfCentroidsThatDidNotMove +1\n\n #return if none of the centroids have moved\n if( numberOfCentroidsThatDidNotMove >= k):\n print( \"no centroids have moved with threshold=\" + str(movingThreshold) + \" on itteration \" + str(j))\n return centroidDatas\n # return if j itterations have been reached\n print(\"returning after \" + str(j) + \"itterations\")\n return centroidDatas\n\ndef RunClustering(testSet, k, movingThreshold, delta):\n centroidResults = CentroidResults()\n\n centroidDatas = getInitialCentroidDatas(k,testSet.trainingDF, delta) \n\n centroidDatas = CalculateCentroids(testSet.trainingDF, k, movingThreshold, centroidDatas)\n \n #associate testing data to centroids\n for i in range(len(testSet.testingDF)):\n dataRow = testSet.testingDF.iloc[i]\n centroidData = getClosestCentroid( dataRow, centroidDatas, onlySelectCentroidIfNearsestPointsIsEmpty = True)\n centroidData.nearestDataPointsTempListForTestingData.append(dataRow)\n \n for i in range(k):\n centroidDatas[i].testingData = pd.DataFrame(centroidDatas[i].nearestDataPointsTempListForTestingData, columns=testSet.testingDF.columns)\n\n trainingX = kfold.getX(centroidDatas[i].nearestDataPoints).to_numpy()\n trainingY = kfold.getY(centroidDatas[i].nearestDataPoints).to_numpy()\n testingX = kfold.getX(centroidDatas[i].testingData).to_numpy()\n testingY = kfold.getY(centroidDatas[i].testingData).to_numpy()\n \n #training data and testing data has to be available for the OLS regression to run\n results = ols.OLSRun()\n if not centroidDatas[i].nearestDataPoints.empty and not centroidDatas[i].testingData.empty and ols.givesSingularMatrix(trainingX) == False:\n results = ols.RunDataset( trainingY, trainingX, testingY, testingX)\n\n #store centroid data in results\n centroidResults.centroidData.append(centroidDatas[i])\n #store results of running ols on the test data for that centroid\n centroidResults.olsRuns.append( results )\n return centroidResults\n\n\n#l = getKCentroids(2)\n\n#a = randomN()\n\n#dist = utils.GetEuclideanDistanceBetweenFeatureVectors( a, x_df.head(1).to_numpy())\n\n\n\n\n\n\n#b = 1","sub_path":"Hons Project/kMeansClustering.py","file_name":"kMeansClustering.py","file_ext":"py","file_size_in_byte":8431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"251490353","text":"#import asyncio\nimport discord # discord.py rewrite\nfrom discord.ext import commands\nimport os\nfrom pymongo import MongoClient\nimport random\nimport traceback\n\n\n# Load secure environment variables\nBOT_TOKEN = os.environ['BOT_TOKEN']\n#SERVER_ID = os.environ['SERVER_ID']\n\n\nbot = commands.Bot(command_prefix='.')\n\n\n@bot.command(pass_context = True)\nasync def adduser(ctx, user : discord.User, nation):\n \"\"\"Add a user to the users table.\n Requires an @mentioned user and their nation (separated by a space).\"\"\"\n client = MongoClient(MONGODB_URI)\n # As far as I can tell, on the free plan you're only allowed to access the\n # default database created for you by heroku.\n db = client.get_database()\n users = db['users'] # Select or create collection\n\n user_data = {'uid' : user.id, 'username' : user.name,\n 'discriminator' : user.discriminator, 'nation' : nation}\n users.insert_one(user_data)\n client.close() # Clean up\n\n await ctx.send('Added {} playing as {}.'.format(user.name, nation))\n\n\n@bot.command(pass_context = True)\nasync def addnation(ctx, user : discord.User, nation, pres, ind, mil, pop):\n \"\"\"Add a nation to the nation collection.\n\n Requires an @mentioned user, their nation, prestige, industry, and mil\n scores, and the population (separated by spaces, no commas in numbers).\"\"\"\n client = MongoClient(MONGODB_URI)\n db = client.get_database()\n nations = db['nations'] # Select or create collection\n\n n_data = {'nation' : nation, 'uid' : user.id, 'prestige' : pres,\n 'industry' : ind, 'military' : mil, 'pop' : pop}\n nations.insert_one(n_data)\n client.close() # Clean up\n\n await ctx.send('Added {} playing as {}.'.format(user.name, nation))\n\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('-'*max(len(bot.user.name), len(str(bot.user.id))))\n\ncogs = ['cogs.userquery', 'cogs.utility']\n\nif __name__ == '__main__':\n for cog in cogs:\n try:\n bot.load_extension(cog)\n except Exception as e:\n print(f'Failed to load {cog}.')\n traceback.print_exc()\n\n# Actually run the bot\nbot.run(BOT_TOKEN, bot=True, reconnect=True)\n","sub_path":"va.py","file_name":"va.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"549167355","text":"from prog import require\n\n\ndef clitext(f=None):\n require(f, 'str')\n while KeyboardInterrupt:\n with open(f, 'w') as stream:\n data = raw_input('%s->') % f\n stream.write(data)\n\n\ndef searchfile(key, obj):\n require(obj, 'str')\n require(key, 'str')\n\n with open(obj, 'r') as stream:\n d = stream.read()\n if key in d:\n lines = d.splitlines(key)\n return lines\n else:\n return False\n","sub_path":"nstd/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"160297291","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\nfrom ph_plotter.band_sf_plotter import BandSFPlotter\n\n\n__author__ = \"Yuji Ikeda\"\n\n\nclass BandSFContourPlotter(BandSFPlotter):\n def _plot_sf(self, ax, distances, frequencies, sf):\n variables = self._variables\n\n # \"pcolormesh\" is much faster than \"pcolor\".\n quad_contour_set = ax.contour(\n distances,\n frequencies * variables[\"unit\"],\n sf,\n cmap=self._colormap,\n linecolor=\"k\",\n linewidths=variables[\"linewidth\"],\n vmin=variables[\"sf_min\"],\n vmax=variables[\"sf_max\"],\n levels=self._sf_ticks,\n extend=\"both\",\n # rasterized=True, # This is important to make the figure light.\n )\n return quad_contour_set\n","sub_path":"ph_plotter/band_sf_contour_plotter.py","file_name":"band_sf_contour_plotter.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"468430530","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nfrom configparser import ConfigParser\nfrom typing import Union, Tuple\n\n# Typing\nndarray = np.ndarray\nFloatArray = Union[ndarray, float]\n\n# Shortcuts\nABS = np.abs\nARGWHERE = np.argwhere\nSIGN = np.sign\nDIFF = np.diff\n\ndef find_equilibrium_points(heating, cooling, domain, diff_tol=0.1):\n \"\"\" Returns the position of equilibrium points. \"\"\"\n if len(heating.shape) > 1:\n if heating.shape[1] == 1:\n heating = heating[:,0]\n elif heating.shaep[0] == 1:\n heating = heating[0,:]\n else:\n raise Exception('Only 1D Arrays Allowed')\n if len(cooling.shape) > 1:\n if cooling.shape[1] == 1:\n cooling = cooling[:,0]\n elif cooling.shaep[0] == 1:\n cooling = cooling[0,:]\n else:\n raise Exception('Only 1D Arrays Allowed')\n\n index = ARGWHERE(DIFF(SIGN(heating - cooling)) != 0).reshape(-1) + 0\n y = heating[index]\n x = domain[index]\n if len(x) > 1:\n p_i = 0\n possible_points = list()\n for x_i, x in enumerate(domain[index]):\n found = False\n if p_i > 0:\n for p_ii, p in enumerate(possible_points):\n for s in p:\n if abs(x-s) < diff_tol:\n found = True\n break\n if found:\n new_p_loc = p_ii\n break\n if found:\n possible_points[new_p_loc].append(x)\n else:\n possible_points.append([x])\n p_i += 1\n else:\n possible_points.append([x])\n p_i += 1\n # Now combine similar points\n x = []\n y = []\n index = []\n for point_set in possible_points:\n new_x = np.median(point_set)\n ind, real_x = find_nearest(domain, new_x, return_value=True)\n x.append(real_x)\n index.append(ind)\n y.append(heating[ind])\n return x, y, index\n\ndef find_nearest(array: ndarray, value: FloatArray, return_value: bool = False):\n idx = (ABS(array - value)).argmin()\n if return_value:\n output = (idx, array[idx]) # type: Tuple[int, float]\n else:\n output = idx # type: int\n return output\n\ndef find_path(wanted_file_name: str,\n top_level: str = '.',\n ignore_git: bool = True, ignore_python: bool = False) -> str:\n \"\"\" DOC STR\"\"\"\n path = '' # type; str\n if top_level == '.':\n top_level = os.getcwd()\n for dir_name, dir_names, file_names in os.walk(top_level):\n if '__pycache__' in dir_name:\n continue\n if ignore_git and '.git' in dir_name:\n continue\n for file_name in file_names:\n if ignore_python and ('.py' in file_name or '.pyx' in file_name):\n continue\n if file_name == wanted_file_name:\n path = os.path.join(dir_name, file_name)\n break\n if path:\n break\n if not path:\n raise Exception('Can not locate {}'.format(wanted_file_name))\n else:\n return path\n\nBOOL_LIKE_TRUE = ['true', int(1), '1', 'True', 'TRUE', True]\nBOOL_LIKE_FALSE = ['false', int(0), '0', 'False', 'FALSE', False]\nNONE_LIKE = ['none', 'None', '', 'NONE', None]\n\ndef int_float_none(string_: str):\n \"\"\" Attempts to convert to int or float if the string is 'None' it will return a None otherwise it raises an error.\n \"\"\"\n output = None # type: None\n if string_ is not None:\n try:\n output = int(string_) # type: int\n except ValueError:\n try:\n output = float(string_) # type: float\n except ValueError:\n if string_.lower() in BOOL_LIKE_TRUE:\n output = True\n elif string_.lower() in BOOL_LIKE_FALSE:\n output = False\n elif string_.lower() in NONE_LIKE:\n output = None\n else:\n # Leave it as a string.\n pass\n return output\n\ndef pull_cfg_info(cfg_file_name, header_name, var_name, convert: bool = False, starting_dir: str = False):\n \"\"\" Uses the config parser to pull out configuration data information. Converts type if needed.\n\n \"\"\"\n\n if not starting_dir:\n starting_dir = '.'\n cfg_path = find_path(cfg_file_name, top_level=starting_dir, ignore_python=True)\n config = ConfigParser()\n config.read(cfg_path)\n\n value = config[header_name][var_name]\n if convert:\n value = int_float_none(value)\n\n return value\n\n","sub_path":"src/other_funcs/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"496677907","text":"import pprint\nimport re # noqa: F401\n\nimport six\n\nfrom karix.models.whatsapp_account_error import WhatsappAccountError # noqa: F401,E501\n\n\nclass WhatsappAccount(object):\n\n swagger_types = {\n 'uid': 'str',\n 'karix_account_uid': 'str',\n 'name': 'str'\n }\n attribute_map = {\n 'uid': 'uid',\n 'karix_account_uid': 'karix_account_uid',\n 'name': 'name'\n }\n\n def __init__(self, uid=None, karix_account_uid=None, name=None):\n\n self._uid = None\n self._karix_account_uid = None\n self._name = None\n\n if uid is not None:\n self.uid = uid\n if karix_account_uid is not None:\n self.karix_account_uid = karix_account_uid\n if name is not None:\n self.name = name\n\n @property\n def uid(self):\n return self._uid\n\n @uid.setter\n def uid(self, uid):\n self._uid = uid\n\n @property\n def karix_account_uid(self):\n return self._karix_account_uid\n\n @karix_account_uid.setter\n def karix_account_uid(self, karix_account_uid):\n self._karix_account_uid = karix_account_uid\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n def to_dict(self):\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(WhatsappAccount, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n return self.to_str()\n\n def __eq__(self, other):\n if not isinstance(other, WhatsappAccount):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","sub_path":"karix/models/whatsapp_account.py","file_name":"whatsapp_account.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"505112574","text":"import sys\nimport scrabble_best_move as sc\n\n\ndef main(argv):\n if len(argv) == 2:\n input_file = argv[1].strip()\n else:\n print('Please specify the input file')\n exit()\n\n best_move = sc.play(input_file, \"resources/dict.txt\")\n print(best_move)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"315135214","text":"def check_valid_input(s):\n \"\"\" function which check that the input is True or False \"\"\"\n\n if s == \"rock\":\n return True\n elif s == \"paper\":\n return True\n elif s == \"scissors\":\n return True\n else:\n return False\n\n\ndef convert_to_num(s):\n \"\"\" function which tranfer string to a number of choice\n\n >>> convert_to_num(\"scissors\")\n 2\n >>> convert_to_num(\"paper\")\n 1\n \"\"\"\n\n if s == \"rock\":\n return 0\n elif s == \"paper\":\n return 1\n elif s == \"scissors\":\n return 2\n else:\n print(\"Error: should not reach this if input is a valid one\")\n\n\ndef convert_to_string(n):\n \"\"\" function which tranfer number of choice to string\n\n >>> convert_to_string(1)\n \"paper\"\n >>> convert_to_string(2)\n \"scissors\"\n\n \"\"\"\n\n if n == 0:\n return \"rock\"\n elif n == 1:\n return \"paper\"\n elif n == 2:\n return \"scissors\"\n else:\n print(\"Error: should not reach this if input is a valid one\")\n\n\ndef game_decision(player, com):\n \"\"\" function which get a choice from layer and computer then return the winner\n\n >>> game_decision(2,2)\n Both ties!\n >>> game_decision(1,2)\n Player wins!\n >>> game_decision(0,2)\n Computer wins!\n\n \"\"\"\n\n if player == com:\n print(\"Both ties!\")\n if com - player < 0:\n com += 3\n if com - player == 1:\n print(\"Player wins!\")\n elif com - player == 2:\n print(\"Computer wins!\")\n\n\nvalid = False\nwhile valid == False:\n player_choice = input(\"Enter your choice: \")\n valid = check_valid_input(player_choice)\n if valid == False:\n print(\"Invalid choice. Enter again.\")\n\nimport random\n\ncomputer_choice_num = random.randint(0, 2)\ncomputer_choice = convert_to_string(computer_choice_num)\nplayer_choice_num = convert_to_num(player_choice)\nprint(\"Players chooses \", player_choice)\nprint(\"Computer chooses \", computer_choice)\n\ngame_decision(player_choice_num, computer_choice_num)","sub_path":"grader/files_mai/6210546668_task1.py","file_name":"6210546668_task1.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"369717582","text":"# 单调栈问题\n# 给定一个数组, 找到左边第一个比它大的数字,和 右边比它大的数字\n# 核心思想是: 维护一个从大到小的栈, 一个元素进入栈的时候和栈内元素比较, 如比栈内元素大就出栈, 出栈的元素记录左右两边比它大的元素\n# 记得最后栈不为空的时候,清空栈\ndef find_ans(arr):\n if not arr:\n return [], []\n\n stack = []\n left = []\n right = []\n for each in arr:\n if len(stack) >= 1:\n while stack:\n top = stack[-1]\n if top < each:\n stack.pop()\n if stack:\n left.append((top, stack[-1]))\n else:\n left.append((top, -1))\n right.append((top, each))\n else:\n stack.append(each)\n break\n if len(stack) < 1:\n stack.append(each)\n while stack:\n top = stack.pop()\n if stack:\n left.append((top, stack[-1]))\n else:\n left.append((top, -1))\n right.append((top, -1))\n\n return left, right\n\n\nif __name__ == '__main__':\n arr = [3, 5, 2, 4, 6, 0, 1, 5]\n # arr = [1]\n left, right = find_ans(arr)\n print(left)\n print(right)\n","sub_path":"target_offer/栈+队列+堆/单调栈.py","file_name":"单调栈.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"505910179","text":"# %%\nimport pandas as pd\nfrom datetime import date\nfrom os.path import split as split_path\nfrom tqdm import tqdm\nfrom joblib import Parallel, delayed\n\nfrom src.data import trimmed_data_dir\nfrom src.data import parquet_paths\nfrom src.data.constants import PREPAY_STATUSES, DEFAULT_STATUSES, x_cols, y_cols\n\n\n# %%\ndef trim_to_first_60_day_delinq(raw_df):\n raw_df = raw_df.drop(['current_date', 'current_month', 'current_year'], axis=1)\n current_month = (raw_df['orig_month'] + raw_df['month_count'] -1 ) % 12 + 1\n current_year = raw_df['orig_year'] + (raw_df['orig_month'] + raw_df['month_count'] -1) // 12\n current_date = current_year.apply(str) + '-' + current_month.apply('{:02}'.format) + '-01'\n current_date = pd.to_datetime(current_date)\n\n # The current date (year) in the raw data in wrong\n raw_df = raw_df.assign(current_date=current_date, current_year=current_year, current_month=current_month)\n\n post_crisis = (raw_df[raw_df['sr_date_transfer'] >= 20090101])\n post_crisis = post_crisis.set_index(['mcd_loanid', 'sr_unique_id', 'sr_property_id', pd.to_datetime(post_crisis['current_date'])]).sort_index()\n\n # Regard 60-day as absorbing state, and ignore entries with unknown status\n delinq = post_crisis['payment_current_status'].isin(list(DEFAULT_STATUSES))\n first_delinquent_date = (delinq[delinq]\n .reset_index('current_date')\n .groupby('mcd_loanid')['current_date']\n .first()\n .rename('first_delinquent_date'))\n\n post_crisis['first_delinquent_date'] = first_delinquent_date.reindex(delinq.index, level='mcd_loanid')\n\n no_delinq = post_crisis['first_delinquent_date'].isnull()\n before_deliq = post_crisis['current_date'] <= post_crisis['first_delinquent_date']\n missing_status = post_crisis['payment_current_status'] == '-'\n trimmed_df = post_crisis[(no_delinq|before_deliq) & ~missing_status].drop('first_delinquent_date', axis=1)\n \n # Categories to predict\n X = trimmed_df.reindex(x_cols, axis=1)\n X['prepaid'] = trimmed_df['payment_current_status'].isin(list(PREPAY_STATUSES)).astype(int)\n X['default'] = trimmed_df['payment_current_status'].isin(list(DEFAULT_STATUSES)).astype(int)\n X['current'] = 1 - (X['prepaid'] | X['default'])\n return X\n\n\n#%%\ndef trim_and_save(file_path):\n file_name = split_path(file_path)[-1]\n df = pd.read_parquet(file_path)\n t_df = trim_to_first_60_day_delinq(df)\n loanid = t_df.index.get_level_values('mcd_loanid')\n hashkey = pd.util.hash_array(loanid) % 100\n for key, g_df in t_df.groupby(hashkey):\n g_path = trimmed_data_dir + file_name + '.bucket_' + f'{key:02}'\n g_df.to_parquet(g_path)\n return file_name\n#%%\nif __name__ == '__main__':\n Parallel(n_jobs=8)(delayed(trim_and_save)(p) for p in tqdm(parquet_paths))\n\n# %%\n# # %% CHECK if dates are correct\n# g = post_crisis.groupby('mcd_loanid')\n# mono = g['month_count'].is_monotonic_increasing\n# mono","sub_path":"src/data/cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"370510884","text":"#\n# @lc app=leetcode.cn id=20 lang=python3\n#\n# [20] 有效的括号\n#\n# https://leetcode-cn.com/problems/valid-parentheses/description/\n#\n# algorithms\n# Easy (40.85%)\n# Likes: 1385\n# Dislikes: 0\n# Total Accepted: 204.3K\n# Total Submissions: 500K\n# Testcase Example: '\"()\"'\n#\n# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。\n#\n# 有效字符串需满足:\n#\n#\n# 左括号必须用相同类型的右括号闭合。\n# 左括号必须以正确的顺序闭合。\n#\n#\n# 注意空字符串可被认为是有效字符串。\n#\n# 示例 1:\n#\n# 输入: \"()\"\n# 输出: true\n#\n#\n# 示例 2:\n#\n# 输入: \"()[]{}\"\n# 输出: true\n#\n#\n# 示例 3:\n#\n# 输入: \"(]\"\n# 输出: false\n#\n#\n# 示例 4:\n#\n# 输入: \"([)]\"\n# 输出: false\n#\n#\n# 示例 5:\n#\n# 输入: \"{[]}\"\n# 输出: true\n#\n#\n\n# @lc code=start\n\n\nclass Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n val = {'(': 1, '[': 2, '{': 3, ')': -1, ']': -2, '}': -3}\n for i in range(len(s)):\n if val[s[i]] > 0:\n stack.append(val[s[i]])\n else:\n if len(stack) != 0 and stack[-1] + val[s[i]] == 0:\n stack.pop()\n else:\n return False\n return len(stack) == 0\n# @lc code=end\n","sub_path":"20.有效的括号.py","file_name":"20.有效的括号.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"624233858","text":"from typing import List\nfrom cs54_list import nil, head, tail, add, instance_as_list, list_as_str\nfrom cs54_tools import read_instances\n\nfrom dernier import dernier\nfrom sauf_dernier import sauf_dernier\n\n\ndef palindrome(list: List[str]) -> bool:\n if nil(list):\n return True\n elif nil(tail(list)):\n return True\n elif head(list) != dernier(list):\n return False\n else:\n return palindrome(sauf_dernier(tail(list)))\n\n\nif __name__ == \"__main__\":\n # assert palindrome([])\n # assert palindrome(['a'])\n # assert palindrome(['a', 'a'])\n # assert palindrome(['a', 'b']) == False\n # assert palindrome(['a', 'b', 'a']) == True\n # assert palindrome(['a', 'b', 'b', 'a']) == True\n # assert palindrome(['a', 'b', 'c', 'b', 'a']) == True\n\n with open(\"./data/R17.txt\", \"w\") as output_file:\n instances = read_instances(\"./data/T17.txt\")\n output_file.write(f\"{len(instances)}\\n\")\n for num, instance in enumerate(instances, start=1):\n if num >= 4:\n instance = instance.replace(\" \", \"\").replace(\",\", \"\").replace(\"?\", \"\").replace(\"!\", \"\").lower()\n\n l = instance_as_list(instance)\n output_file.write(f\"{palindrome(l)}\\n\")\n","sub_path":"S5/CS54/Algo/Cours/cs54-lab2-solution/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"573296109","text":"from haystack.views import FacetedSearchView\nfrom django.contrib.localflavor.us import us_states\n\nDATE_FIELDS = ('start_date', 'end_date')\n\n\nclass ImprovedFacetedSearchView(FacetedSearchView):\n def __name__(self):\n return \"ImprovedFacetedSearchView\"\n\n def extra_context(self):\n extra = super(ImprovedFacetedSearchView, self).extra_context()\n facet_tuple = tuple([item.split(':') for item in self.request.GET.getlist('selected_facets')])\n facet_dict = dict([(item[0].split('_exact')[0], item[1]) for item in facet_tuple if len(item) > 1])\n extra['selected_facets'] = facet_dict\n extra['date_filters'] = []\n for key, value in self.request.GET.iteritems():\n if key.startswith(DATE_FIELDS):\n extra['date_filters'].append((key, value))\n extra['date_filters'].sort()\n extra['us_states'] = us_states.US_STATES\n extra['sfapp_base_template'] = 'sfapp/base-full.html'\n\n return extra\n","sub_path":"fcc_adtracker/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"105325112","text":"import cv2 as cv\nimport numpy as np\nimport random\nimport math\nimport sys\nimport os\nimport time\nrandom.seed(time.time)\n\nif __name__ == '__main__':\n img_path = sys.argv[1]\n fileName = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) + '/' + img_path\n print(fileName)\n\n # 2a: read and display the image\n # img = cv.imread('../images/bonn.png')\n img = cv.imread(fileName)\n cv.imshow('Original Image', img)\n cv.waitKey(0)\n\n # 2b: display the intenstity image\n intensityImg = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n cv.imshow('Intensity Image', intensityImg)\n cv.waitKey(0)\n\n # 2c: for loop to perform the operation\n diffImg = img.copy()\n\n for y in range(intensityImg.shape[0]):\n for x in range(intensityImg.shape[1]):\n diffImg[y, x, :] -= np.uint8(intensityImg[y, x] * 0.5)\n \n diffImg[diffImg < 0] = 0\n cv.imshow('Difference Image', diffImg)\n cv.waitKey(0)\n\n # 2d: one-line statement to perfom the operation above\n diffImg2 = img - np.uint8(np.expand_dims(intensityImg, axis = 2) * 0.5)\n diffImg2[diffImg2 < 0] = 0\n cv.imshow('Difference Image 2', diffImg2)\n cv.waitKey(0)\n\n\n # 2e: Extract a random patch\n cy = int(img.shape[0]/2)\n cx = int(img.shape[1]/2)\n imgPatch = img[cy - 8 : cy + 8, cx - 8 : cx + 8]\n cv.imshow('Image Patch', imgPatch)\n cv.waitKey(0)\n\n ry = random.randint(0,img.shape[0]-16)\n rx = random.randint(0,img.shape[1]-16)\n imgWithPatch = img.copy()\n imgWithPatch[ry : ry + 16, rx : rx + 16] = imgPatch[:,:]\n cv.imshow('Image with Patch', imgWithPatch)\n cv.waitKey(0)\n\n # 2f: Draw random rectangles and ellipses\n imgRectangles = img.copy()\n for i in range(10):\n ry = random.randint(0,img.shape[0])\n rx = random.randint(0,img.shape[1])\n w = random.randint(1,50)\n h = random.randint(1,50)\n cv.rectangle(imgRectangles, (ry, rx), (ry + w, rx + x), (255, 0, 0), 2)\n \n cv.imshow('Random Rectangles', imgRectangles)\n cv.waitKey(0)\n\n\n # draw ellipses\n imgEllipses = img.copy()\n for i in range(10):\n ry = random.randint(0,img.shape[0])\n rx = random.randint(0,img.shape[1])\n raxisy = random.randint(0,150)\n raxisx = random.randint(0,150)\n cv.ellipse(imgEllipses, (ry, rx), (raxisy, raxisx), 0, 0, 360, (0, 255, 0), 3)\n \n cv.imshow('Random Ellipses', imgEllipses)\n cv.waitKey(0)\n\n\n # destroy all windows\n cv.destroyAllWindows()","sub_path":"Sheet00/src/sheet00.py","file_name":"sheet00.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"604037770","text":"# Introduction to Artificial Intelligence\n# Neural network classifier for credit default using TensorFlow, part 2\n# By Juan Carlos Rojas\n\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport tensorflow as tf\nimport sklearn.metrics\nimport matplotlib.pyplot as plt\n\n# Load the training and test data from the Pickle file\nwith open(\"credit_card_default_dataset.pickle\", \"rb\") as f:\n train_data, train_labels, test_data, test_labels = pickle.load(f)\n\n# Get some lengths\nn_inputs = train_data.shape[1]\nnsamples = train_data.shape[0]\n\n# Training constants\nbatch_size = 60\nlearning_rate = .02\nn_epochs = 500\neval_step = 10\nn_nodes_l1 = 100\n\n# TensorFlow constants\n\n# Input vectors\nX = tf.constant(train_data.values.astype(np.float32))\nY = tf.constant(train_labels.values.reshape(-1,1).astype(np.float32))\n\nn_batches = int(np.ceil(nsamples / batch_size))\n\n# Print the configuration\nprint(\"Batch size: {} Num batches: {} Num epochs: {} Learning rate: {}\".format(batch_size, n_batches, n_epochs, learning_rate))\nprint(\"Num nodes in L1: {} Activation function: ReLU\".format(n_nodes_l1))\n\n# TensorFlow constants\n\n# Input vector placeholders. Length is unspecified.\nX = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\nY = tf.placeholder(tf.float32, shape=(None, 1), name=\"Y\")\n\n# Hidden layer 1:\n# Inputs: n_inputs\n# Outputs: n_nodes_l1\n# Activation: ReLU\nW_L1 = tf.Variable(tf.truncated_normal([n_inputs, n_nodes_l1], stddev=1/np.sqrt(n_inputs)))\nb_L1 = tf.Variable(tf.zeros(n_nodes_l1)) \nY_L1 = tf.nn.relu(tf.add(tf.matmul(X, W_L1), b_L1))\n\n# Output layer:\n# Inputs: n_nodes_l1\n# Outputs: 1\n# Activation: logistic\nW_L2 = tf.Variable(tf.truncated_normal([n_nodes_l1, 1], stddev=1/np.sqrt(n_nodes_l1)))\nb_L2 = tf.Variable(tf.zeros(1)) \nY_L2_linear = tf.add(tf.matmul(Y_L1, W_L2), b_L2)\n\n# Cost function, plus the sigmoid part of the prediction\ncost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( \n logits = Y_L2_linear, labels = Y))\n\n# Optimize cost through gradient descent\noptimizer = tf.train.GradientDescentOptimizer(learning_rate)\nupdate_op = optimizer.minimize(cost)\n\n# Prediction probability values\nY_pred_proba_calc = tf.nn.sigmoid(Y_L2_linear)\n\n# Create TensorFlow session and initialize it\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nepoch = 0\nwhile epoch < n_epochs:\n batch = 0\n\n while batch < n_batches:\n\n # Select the data for the next batch\n dataidx = batch * batch_size\n X_batch = train_data[dataidx:(dataidx+batch_size)]\n Y_batch = train_labels[dataidx:(dataidx+batch_size)].values.reshape(-1,1)\n feed_dict = {X: X_batch, Y: Y_batch}\n\n # Run one iteration of the computation session to update coefficients\n _ = sess.run(update_op, feed_dict=feed_dict)\n batch += 1\n\n # Evaluate the test score every certain number of epochs\n if (epoch % eval_step == 0):\n\n # Compute the test accuracy\n feed_dict = {X: test_data, Y: test_labels.values.reshape(-1,1)}\n Y_pred_proba_test = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n auc_score = sklearn.metrics.roc_auc_score(test_labels, Y_pred_proba_test)\n print(\"Epoch {:4d}: Test AUC score: {:.4f}\".format(epoch, auc_score))\n \n epoch += 1\n\n# Run a session to compute the predictions against the training data\nfeed_dict = {X: train_data, Y: train_labels.values.reshape(-1,1)}\nY_pred_proba_training = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n\n# Run a session to compute the predictions against the test data\nfeed_dict = {X: test_data, Y: test_labels.values.reshape(-1,1)}\nY_pred_proba_test = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n\nauc_score = sklearn.metrics.roc_auc_score(test_labels, Y_pred_proba_test)\nprint(\"Test AUC score: {:.4f}\".format(auc_score))\n\n# Predict new labels for training data\nauc_score_training = sklearn.metrics.roc_auc_score(\\\n train_labels, Y_pred_proba_training)\nprint(\"Training AUC score: {:.4f}\".format(auc_score_training))\n","sub_path":"Week 5/CreditDefault_NN_2.py","file_name":"CreditDefault_NN_2.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"179279478","text":"import logging\nimport json\nimport random\nfrom collections import deque\n\nfrom dungeon.models import Dungeon, DungeonTile, DungeonRoom, DungeonObject, DungeonLevel\nfrom character.models import Character\nfrom item.models import Item\n\nlogger_ = logging.getLogger(\"generator\")\nlogger_.addHandler(logging.StreamHandler())\n\n\nclass DungeonGenerator(object):\n \"\"\"\n Takes a level config and outputs a new dungeon maze.\n \"\"\"\n dungeon_monsters = []\n dungeon_items = []\n num_rooms = 0\n is_final_level = False\n level = None\n maze = []\n monster_rooms = []\n\n def _create_room(self, room):\n # go through the tiles in the rectangle and make them passable\n for x in range(room.x1 + 1, room.x2):\n for y in range(room.y1 + 1, room.y2):\n tile = self.maze[x][y]\n tile.is_blocked = False\n tile.block_sight = False\n tile.is_ground = True\n\n # place the player in the center of the first room\n if self.num_rooms == 0:\n x, y = room.center()\n tile = self.maze[x][y]\n self.place_player(tile)\n else:\n self.monster_rooms.append(room)\n\n def place_monsters_in_rooms(self):\n \"\"\"\n Go through each room and drop a monster in it. Keep\n going until there are no more monsters to place.\n \"\"\"\n while len(self.dungeon_monsters):\n for room in self.monster_rooms:\n tile = self.get_random_room_tile(room)\n self.place_monster(tile)\n\n def place_items_in_rooms(self):\n \"\"\"\n Go through each room and drop an item in it. Keep\n going until there are no more items to place.\n \"\"\"\n for item in self.dungeon_items:\n random_room = random.choice(self.monster_rooms)\n tile = self.get_random_room_tile(random_room)\n self.place_item(tile, item)\n\n def get_random_room_tile(self, room, depth=0):\n \"\"\"\n Get a random ground tile that does not already contain a object\n @param depth: This prevents crash by infinite recursion.\n @param room:\n @return:\n \"\"\"\n x = random.randint(room.x1 + 1, room.x2 - 1)\n y = random.randint(room.y1 + 1, room.y2 - 1)\n tile = self.maze[x][y]\n\n if not tile.contains_object:\n return tile\n\n if depth > 50:\n logger_.debug(\"Could not find appropriate tile to spawn item.\")\n return tile\n\n # if we didn't find an empty tile, try again\n return self.get_random_room_tile(room, depth=depth + 1)\n\n def _create_h_tunnel(self, x1, x2, y):\n # horizontal tunnel. min() and max() are used in case x1>x2\n for x in range(min(x1, x2), max(x1, x2) + 1):\n self.maze[x][y].is_blocked = False\n self.maze[x][y].block_sight = False\n self.maze[x][y].is_ground = True\n\n def _create_v_tunnel(self, y1, y2, x):\n # vertical tunnel\n for y in range(min(y1, y2), max(y1, y2) + 1):\n self.maze[x][y].is_blocked = False\n self.maze[x][y].block_sight = False\n self.maze[x][y].is_ground = True\n\n def generate(self, level):\n \"\"\"\n Generates a new dungeon based the level\n @param level:\n \"\"\"\n width = 80\n height = 45\n max_rooms = level.max_rooms\n max_room_size = level.max_room_size\n min_room_size = level.min_room_size\n\n self.level = level\n self.is_final_level = level.is_final_level\n self.dungeon_monsters = deque([m for m in\n Character\n .select()\n .join(DungeonLevel)\n .where(\n (DungeonLevel.level_id == level.level_id) &\n (Character.name != 'player'))\n ])\n\n self.dungeon_items = deque([item for item in Item\n .select()\n .join(DungeonLevel)\n .where((DungeonLevel.level_id == level.level_id))])\n\n # self.max_num_items = level.max_num_items\n # fill map with \"blocked\" tiles\n self.maze = [[DungeonTile(x, y, True) for y in range(height)] for x in range(width)]\n\n rooms = []\n\n for r in range(max_rooms):\n # random width and height\n w = random.randint(min_room_size, max_room_size)\n h = random.randint(min_room_size, max_room_size)\n # random position without going out of the boundaries of the map\n x = random.randint(0, width - w - 1)\n y = random.randint(0, height - h - 1)\n\n # \"DungeonRoom\" class makes rectangles easier to work with\n new_room = DungeonRoom(x, y, w, h)\n\n # run through the other rooms and see if they intersect with this one\n failed = False\n for other_room in rooms:\n if new_room.intersect(other_room):\n failed = True\n break\n\n if not failed:\n # this means there are no intersections, so this room is valid\n\n # \"paint\" it to the map's tiles\n self._create_room(new_room)\n\n # center coordinates of new room, will be useful later\n new_x, new_y = new_room.center()\n\n if self.num_rooms > 0:\n # connect it to the previous room with a tunnel\n # center coordinates of previous room\n (prev_x, prev_y) = rooms[self.num_rooms-1].center()\n\n # draw a coin (random number that is either 0 or 1)\n if random.randint(0, 1) == 1:\n # first move horizontally, then vertically\n self._create_h_tunnel(prev_x, new_x, prev_y)\n self._create_v_tunnel(prev_y, new_y, new_x)\n else:\n # first move vertically, then horizontally\n self._create_v_tunnel(prev_y, new_y, prev_x)\n self._create_h_tunnel(prev_x, new_x, new_y)\n\n # finally, append the new room to the list\n rooms.append(new_room)\n self.num_rooms += 1\n\n self.place_monsters_in_rooms()\n self.place_items_in_rooms()\n # if not level.final_level:\n # self.place_stairs(rooms)\n\n # connect them with a tunnel\n self._create_h_tunnel(25, 55, 23)\n\n serialized_maze = json.dumps([\n [\n {\n 'x': tile.x,\n 'y': tile.y,\n 'is_blocked': tile.is_blocked,\n 'is_explored': tile.is_explored,\n 'is_ground': tile.is_ground,\n 'contains_object': tile.contains_object,\n 'block_sight': tile.block_sight\n } for tile in row\n ] for row in self.maze\n ])\n\n new_dungeon = Dungeon(level=level, width=width, height=height, maze=serialized_maze)\n new_dungeon.save()\n\n def place_monster(self, tile):\n\n try:\n monster = self.dungeon_monsters.popleft()\n new_dungeon_object = DungeonObject(\n coords=json.dumps((tile.x, tile.y)),\n blocks=True\n )\n new_dungeon_object.save()\n monster.dungeon_object = new_dungeon_object\n monster.save()\n tile.contains_object = True\n except IndexError:\n pass\n\n def place_player(self, tile):\n \"\"\"\n Place the player in the maze.\n \"\"\"\n dungeon_object = DungeonObject(\n coords=json.dumps((tile.x, tile.y)),\n blocks=True\n )\n\n player = Character.get(Character.name == 'player')\n player.level = self.level\n player.dungeon_object = dungeon_object\n\n dungeon_object.save()\n player.save()\n\n tile.contains_object = True\n\n def place_item(self, tile, item):\n item.dungeon_object = DungeonObject(coords=json.dumps((tile.x, tile.y)))\n item.level = self.level\n item.dungeon_object.save()\n item.save()\n\n# def place_stairs(self, tile):\n# TODO: fix this to use new item system\n# room = random.choice(rooms[1::])\n#\n# (x, y) = room.center()\n#\n# if not util.is_blocked(x, y, self):\n# stairs = DungeonObject(x, y, '>', 'Stairs')\n#\n# self.stairs = stairs\n# self.objects.append(stairs)\n# util.send_to_back(stairs, self.objects)\n# else:\n# # if the spot was blocked find another spot to place the item\n# self.place_stairs(rooms)\n","sub_path":"dungeon/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":8884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"488935096","text":"import copy\nimport json\nimport logging\nimport math\nimport multiprocessing\nimport threading\nimport pathlib\nfrom collections import namedtuple\nfrom itertools import count, repeat\nfrom contextlib import AbstractContextManager, contextmanager\n\nfrom music21 import stream, duration, note\n\nfrom db.DbMaster import DbMaster\nfrom gconfig import gconfig\nfrom libs import StreamPackage\nfrom libs.exceptions import dbException\nfrom libs.m21 import melIDsToString\nfrom libs.math import distToMultipleOf\nfrom libs.masterLogger import logger\n\nMeaRange = namedtuple('MeaRange', ['a', 'b'])\n\n# this var is used to monitor progress\n\nclass DbChild(AbstractContextManager):\n \"\"\"\n Each mashup-generating process has one instance of this class to record individually generated mashups.\n The childJson are then sent to dbMaster.\n \"\"\"\n\n def __init__(self):\n # keeps track of threads that are writing musicxml to disk\n self._writeThreads = []\n self._db = {}\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type == dbException:\n return False\n\n # wait for all writeProcess to finish before exit\n for proc in self._writeThreads:\n proc.join()\n\n @property\n def db(self):\n return self._db\n\n @contextmanager\n def startFile(self, melIDs: frozenset):\n # signals that all incoming mashups will be made up of melody with ids in melID\n try:\n # name of db unit will be melIDs joined by @\n # must sort name because otherwise the order of melIDs will be random\n fileName = melIDsToString(melIDs)\n # these attributes will disappear after exiting context\n setattr(self, '_partsList_', [stream.Part() for _ in range(4)])\n setattr(self, '_measureRanges_', [])\n\n yield self\n if self._partsList_: # only write to disk if _partsList_ not empty\n # if no exception happened, write to file\n pathToFile = pathlib.Path(gconfig.db.dbPath).joinpath(fileName)\\\n .with_suffix(f'.{gconfig.db.dbFileFormat}')\n if pathToFile.exists():\n logger.warning(f'Path {pathToFile} already exists. Overwriting...')\n pathToFile.unlink(missing_ok=True)\n\n s = stream.Stream()\n for part in self._partsList_:\n s.insert(0, part)\n\n writer = threading.Thread(target=s.write, args=(gconfig.db.dbFileFormat, pathToFile))\n self._writeThreads.append(writer)\n writer.start()\n\n self._db[melIDs] = {\n 'fileName': fileName,\n 'filePath': str(pathToFile),\n 'measureRanges': self._measureRanges_\n }\n\n except dbException as dbe:\n # do not write to file\n raise dbe\n\n finally:\n delattr(self, '_partsList_')\n delattr(self, '_measureRanges_')\n\n def addMashup(self, mash: StreamPackage):\n mash.parts[0].flat.notesAndRests[0].style.color = '#FF0000'\n assert len(self._partsList_) == 2 * mash.numParts\n for i in range(mash.numParts):\n rst = note.Rest(\n duration=duration.Duration(distToMultipleOf(mash.quarterLength))\n )\n self._partsList_[2 * i].append([e for e in mash.parts[i].flat.notesAndRests])\n self._partsList_[2 * i + 1].append([e for e in mash.parts[i].cf.flat.notesAndRests])\n if rst.duration.quarterLength != 0:\n self._partsList_[2 * i].append(rst)\n self._partsList_[2 * i + 1].append(rst)\n\n endingRstLength = distToMultipleOf(mash.quarterLength)\n measureLength = math.floor((mash.quarterLength + endingRstLength) / 4)\n curMeasureNumber = self._measureRanges_[-1].b + 1 if self._measureRanges_ else 1\n self._measureRanges_.append(MeaRange(curMeasureNumber, curMeasureNumber + measureLength - 1))\n\n\ndef localTest():\n pass\n\n\nif __name__ == '__main__':\n localTest()\n","sub_path":"db/DbChild.py","file_name":"DbChild.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"166368271","text":"#!/usr/bin/env python3\n#coding=utf-8\n#\n# Copyright (c) HiSilicon Technologies Co., Ltd. 2019-2019. All rights reserved.\n# Description: Menuconfig entry\n# Author: HiSilicon\n# Create: 2019-12-31\n#\n\nimport os\nfrom kconfiglib import Kconfig\nfrom menuconfig import menuconfig\n\ndef mconf_set_env(style, conf, header):\n \"\"\"\n These parameters would not be effect unless kconflib supported these.\n \"\"\"\n os.environ[\"MENUCONFIG_STYLE\"] = style\n os.environ[\"KCONFIG_CONFIG\"] = conf\n os.environ[\"KCONFIG_CONFIG_HEADER\"] = header\n\ndef hi_mconfig():\n kconfig = os.path.join(\"tools\", \"menuconfig\", \"Kconfig\")\n display_style = \"default selection=fg:white,bg:red\"\n target_conf = os.path.join(\"build\", \"config\", \"usr_config.mk\")\n header = \"# Generated by HiSilicon menuconfig tool\"\n mconf_set_env(display_style, target_conf, header)\n kconf = Kconfig(filename=kconfig)\n menuconfig(kconf)\n\nif __name__ == \"__main__\":\n hi_mconfig()\n","sub_path":"tools/menuconfig/usr_config.py","file_name":"usr_config.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"627995349","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 19 10:58:04 2019\r\n\r\n@author: Admin\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n# reading the csv file \r\nhousing = pd.read_csv('housing.csv') \r\n#to see the first 5 elements of the table \r\nhousing.head()\r\n# gives the detailed info of the table \r\nhousing.info()\r\n# gives the mean median mode of the quantitative attributes \r\nhousing_describe = housing.describe() \r\n#In a given column It gives the number of unique elements along with its count \r\nhousing['ocean_proximity'].value_counts()\r\n\r\n# plotting histogram to get the overall picture of the data \r\nimport matplotlib.pyplot as plt \r\nhousing.hist(bins=50,figsize=(20,20)) # number of bins is 50 in this case \r\n\r\n# splitting the train test data \r\nfrom sklearn.model_selection import train_test_split \r\ntrain_set,test_set = train_test_split(housing,test_size=0.2,random_state= 42)\r\n\r\nhousing[\"income_cat\"]=np.ceil(housing[\"median_income\"]/1.5)\r\nhousing.hist(column='income_cat')\r\n\r\n#Doubt?\r\nhousing[\"income_cat\"].where(housing[\"income_cat\"]<5,5.0,inplace=True)\r\n\r\nhousing[\"income_cat\"].value_counts()/len(housing)\r\n\r\nfrom sklearn.model_selection import StratifiedShuffleSplit\r\nsplit=StratifiedShuffleSplit(n_splits=1,test_size=0.2,random_state=42)\r\nfor train_index,test_index in split.split(housing,housing[\"income_cat\"]):\r\n strat_train_set=housing.loc[train_index]\r\n strat_test_set=housing.loc[test_index]\r\n \r\n\r\nfor set_ in(strat_train_set,strat_test_set):\r\n set_.drop(\"income_cat\",axis=1,inplace=True)\r\n \r\nhousing = strat_train_set.copy()\r\n\r\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\")\r\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\",alpha=0.1)\r\n\r\n#Why X axis label is not printing?\r\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\",alpha=0.4,\r\n s=housing[\"population\"]/100,label=\"population\",figsize=(10,7),\r\n c=\"median_house_value\",cmap=plt.get_cmap(\"jet\"),colorbar=True,)\r\n#s = size\r\n#c = color\r\n#jet = jet returns the jet colormap as a three-column array\r\n\r\n#why legend?\r\nplt.legend()\r\n\r\n\r\ncorr_matrix=housing.corr()\r\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\r\n\r\nfrom pandas.tools.plotting import scatter_matrix\r\nattributes=[\"median_house_value\",\"median_income\",\"total_rooms\",\r\n \"housing_median_age\"]\r\nscatter_matrix(housing[attributes],figsize=(12,8))\r\n\r\nhousing.plot(kind=\"scatter\",x=\"median_income\",y=\"median_house_value\",alpha=0.1)\r\n\r\nhousing[\"rooms_per_hopusehold\"]=housing[\"total_rooms\"]/housing[\"households\"]\r\nhousing[\"bedrooms_per_room\"]=housing[\"total_bedrooms\"]/housing[\"total_rooms\"]\r\nhousing[\"population_per_household\"]=housing[\"population\"]/housing[\"households\"]\r\n\r\ncorr_matrix=housing.corr()\r\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\r\n\r\nhousing=strat_train_set.drop(\"median_house_value\",axis=1)\r\nhousing_labels=strat_train_set[\"median_house_value\"].copy()\r\n\r\nhousing.dropna(subset=[\"total_bedrooms\"])\r\nhousing.drop(\"total_bedrooms\",axis=1)\r\nmedian=housing[\"total_bedrooms\"].median()\r\nhousing[\"total_bedrooms\"].fillna(median,inplace=True)\r\n\r\nfrom sklearn.preprocessing import Imputer\r\nimputer=Imputer(strategy=\"median\")\r\nhousing_num=housing.drop(\"ocean_proximity\",axis=1)\r\nimputer.fit(housing_num)\r\n\r\nimputer.statistics_ \r\nhousing_num.median().values\r\n\r\nX=imputer.transform(housing_num)\r\nhousing_tr=pd.DataFrame(X,columns=housing_num.columns)\r\n\r\nfrom sklearn.preprocessing import LabelEncoder\r\nencoder=LabelEncoder()\r\nhousing_cat=housing[\"ocean_proximity\"]\r\nhousing_cat_encoded=encoder.fit_transform(housing_cat)\r\nhousing_cat_encoded\r\n\r\nprint(encoder.classes_)\r\n\r\nfrom sklearn.base import BaseEstimator,TransformerMixin\r\nrooms_ix,bedrooms_ix,population_ix,household_ix=3,4,5,6\r\nclass CombinedAttributesAdder(BaseEstimator,TransformerMixin):\r\n def __init__(self,add_bedrooms_per_room=True):\r\n self.add_bedrooms_per_room=add_bedrooms_per_room\r\n def fit(self,X,y=None):\r\n return self\r\n def transform(self,X,y=None):\r\n rooms_per_household=X[:,rooms_ix]/X[:,household_ix]\r\n population_per_household=X[:,population_ix]/X[:,household_ix]\r\n if self.add_bedrooms_per_room:\r\n bedrooms_per_room=X[:,bedrooms_ix]/X[:,household_ix]\r\n return np.c_[X,rooms_per_household,population_per_household,bedrooms_per_room]\r\n else:\r\n return np.c_[X,rooms_per_household,population_per_household]\r\n \r\nattr_adder=CombinedAttributesAdder(add_bedrooms_per_room=False)\r\nhousing_extra_attribs=attr_adder.transform(housing.values)\r\n\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nnum_pipeline=Pipeline([('imputer',Imputer(strategy=\"median\")),('attribs_adder',\r\n CombinedAttributesAdder()),('std_scaler',\r\n StandardScaler()),])\r\nhousing_num_tr=num_pipeline.fit_transform(housing_num)\r\n\r\nfrom sklearn.base import BaseEstimator , TransformerMixin \r\nclass DataFrameSelector(BaseEstimator,TransformerMixin):\r\n def __init__(self,attribute_names):\r\n self.attribute_names=attribute_names\r\n def fit(self,X,y=None):\r\n return self\r\n def transform(self,X):\r\n return X[self.attribute_names].values\r\n \r\nfrom sklearn.preprocessing import LabelBinarizer \r\nnum_attribs=list(housing_num)\r\ncat_attribs=[\"ocean_proximity\"]\r\nnum_pipeline=Pipeline([('selector',DataFrameSelector(num_attribs)),\r\n ('imputer',Imputer(strategy=\"median\")),\r\n ('attribs_adder',CombinedAttributesAdder()),\r\n ('std_scaler',StandardScaler()),])\r\ncat_pipeline=Pipeline([('selector',DataFrameSelector(cat_attribs)),\r\n ('label_binarizer',LabelBinarizer()),])\r\n \r\nfrom sklearn.pipeline import FeatureUnion\r\nfull_pipeline=FeatureUnion(transformer_list=[(\"num_pipeline\",num_pipeline),\r\n (\"cat_pipeline\",cat_pipeline),]) \r\n \r\nhousing_prepared=full_pipeline.fit_transform(housing)\r\nhousing_prepared\r\n\r\nfrom sklearn.linear_model import LinearRegression \r\nlin_reg = LinearRegression()\r\nlin_reg.fit(housing_prepared , housing_labels)\r\nsome_data = housing.iloc[:5]\r\nsome_data_prepared = full_pipeline.transform(some_data)\r\nprint(\"Predictions:\", lin_reg.predict(some_data_prepared))\r\n\r\nfrom sklearn.metrics import mean_squared_error\r\nhousing_predictions= lin_reg.predict(housing_prepared)\r\nlin_mse=mean_squared_error(housing_labels,housing_predictions)\r\nlin_rmse=np.sqrt(lin_mse)\r\nlin_rmse\r\n \r\n#Decision Tree\r\nfrom sklearn.tree import DecisionTreeRegressor\r\ntree_reg=DecisionTreeRegressor()\r\ntree_reg.fit(housing_prepared,housing_labels)\r\n\r\nhousing_predictions=tree_reg.predict(housing_prepared)\r\ntree_mse=mean_squared_error(housing_labels,housing_predictions)\r\ntree_rmse=np.sqrt(tree_mse)\r\ntree_rmse\r\n\r\n#cross validation\r\nlin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels,\r\n scoring=\"neg_mean_squared_error\", cv=10)\r\nlin_rmse_scores = np.sqrt(-lin_scores)\r\ndisplay_scores(lin_rmse_scores) \r\n\r\nfrom sklearn.model_selection import cross_val_score\r\nscores=cross_val_score(tree_reg,housing_prepared,housing_labels,\r\n scoring=\"neg_mean_squared_error\",cv=10) #Doubt?\r\ntree_rmse_scores=np.sqrt(-scores)\r\n\r\ndef display_scores(scores):\r\n print(\"scores:\",scores)\r\n print(\"Mean\",scores.mean())\r\n print(\"Standard deviation:\",scores.std())\r\ndisplay_scores(tree_rmse_scores) \r\n\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nforest_reg = RandomForestRegressor()\r\nforest_reg.fit(housing_prepared, housing_labels)\r\n\r\ndisplay_scores(forest_rmse_scores)\r\n\r\n\r\nfrom sklearn.externals import joblib\r\njoblib.dump(my_model, \"my_model.pkl\")\r\nmy_model_loaded = joblib.load(\"my_model.pkl\") \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Housing Data Analytics.py","file_name":"Housing Data Analytics.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"405611563","text":"import math\nfrom collections import defaultdict, namedtuple\nfrom operator import itemgetter\nfrom pprint import pformat\n\nfrom useful import Graph, input_from, manhattan\n\n\ndef coordinates_from_points(points):\n return [\n tuple(int(coordinate) for coordinate in point)\n for point in map(lambda x: x.split(\",\"), points)\n ]\n\n\n\"\"\"\nFailed attempt at an n log n solution using kdtrees. Left here for posterity.\n\"\"\"\n\n\n# class Node(namedtuple(\"Node\", \"location left_child right_child\")):\n# def __repr__(self):\n# return pformat(tuple(self))\n\n# def points(self):\n# points = []\n# s = []\n# node = self\n# while len(s) > 0 or node is not None:\n# if node is not None:\n# s.append(node)\n# node = node.left_child\n# else:\n# node = s.pop()\n# points.append(node.location)\n# node = node.right_child\n\n# return points\n\n\n# def tree_add(tree, new):\n# \"\"\"\n# Add a new node to this Node tree. For now do it by creating a new\n# kdtree with the new node.\n# \"\"\"\n# new_tree = tree.points()\n# new_tree.append(new)\n# return kdtree_from_points(new_tree)\n\n\n# def tree_insert(new, tree, axis=0):\n# \"\"\"\n# Add a new node to a Node object naively\n# (without regard for tree balance) along the given axis (e.g. x, y, z, etc.)\n\n# Returns a copy of the tree for convenience.\n# TODO: Can't set attributes to new values due to Node being subclassed\n# from namedtuple.\n# Methods using replace only return the tree at that branch of recursion\n# \"\"\"\n# if tree.left_child is None and tree.right_child is None:\n# if new[axis] <= tree.location[axis]:\n# tree.location = tree._replace(\n# location=tree.location,\n# left_child=Node(location=new, left_child=None, right_child=None),\n# right_child=None,\n# )\n# else:\n# tree.location = tree._replace(\n# location=tree.location,\n# left_child=Node(location=new, left_child=None, right_child=None),\n# right_child=None,\n# )\n# elif new[axis] <= tree.location[axis]:\n# tree_insert(new, tree.left_child)\n# else:\n# tree_insert(new, tree.right_child)\n\n\n# def kdtree_from_points(points, depth=0):\n# # print(points)\n# try:\n# k = len(points[0])\n# except IndexError as e:\n# return None\n\n# axis = depth % k\n# sorted_points = sorted(points, key=itemgetter(axis))\n# median = len(points) // 2\n\n# return Node(\n# location=sorted_points[median],\n# left_child=kdtree_from_points(sorted_points[:median], depth + 1),\n# right_child=kdtree_from_points(sorted_points[median + 1 :], depth + 1),\n# )\n\n\n# def nearest_neighbor(tree, point, d=manhattan):\n# \"\"\"\n# Return the nearest node to the input point in the tree of Nodes accoding\n# to the distance function d.\n# \"\"\"\n\n# def nn(tree, point, best_node, best_dist):\n# if tree is None:\n# return best_node\n\n# distance = d(point, tree.location)\n# if distance < best_dist:\n# return min(\n# nn(tree.left_child, point, tree.location, distance),\n# nn(tree.right_child, point, tree.location, distance),\n# key=lambda x: d(point, x),\n# )\n# else:\n# return min(\n# nn(tree.left_child, point, best_node, best_dist),\n# nn(tree.right_child, point, best_node, best_dist),\n# key=lambda x: d(point, x),\n# )\n\n# if tree.location is None or len(tree) < 1:\n# return None\n# else:\n# return nn(tree, point, None, math.inf)\n\n\n# def num_constellations(points):\n# \"\"\"\n# Greedy algorithm to determine number of constellations present in a list\n# of coordinates. Form a constellation (set of points) using the first point\n# encountered. Then add points using nearest neighbor search on a k-d tree\n# of the set to determine set membership until a point can't be added.\n# Then form a new set with the point that cannot be added. Continue until the\n# list of points is exhausted.\n# \"\"\"\n# coordinates = sorted(\n# coordinates_from_points(points), key=lambda x: (x[0], x[1], x[2], x[3])\n# )\n# MAX_DIST = 3\n\n# constellations = [kdtree_from_points(coordinates[:1])]\n# for point in coordinates[1:]:\n# did_add = False\n# for i, constellation in enumerate(constellations):\n# if manhattan(point, nearest_neighbor(constellation, point)) <= MAX_DIST:\n# constellations[i] = tree_add(constellation, point)\n# did_add = True\n# break\n\n# if did_add == False:\n# constellations.append(kdtree_from_points([point]))\n\n# return len(constellations)\n\n\ndef num_constellations(points):\n # Create adjacency list from points if manhattan <= 3\n MAX_DIST = 3\n coordinates = coordinates_from_points(points)\n adjacency_list = defaultdict(list)\n for point_1 in coordinates:\n adjacency_list[point_1] = []\n for point_2 in coordinates:\n if point_1 != point_2 and manhattan(point_1, point_2) <= MAX_DIST:\n adjacency_list[point_1].append(point_2)\n\n G = Graph(adjacency_list=adjacency_list)\n strongly_connected_components = G.Tarjans()\n return len(strongly_connected_components)\n\n\npoints = input_from(25).read().split(\"\\n\")\n\n# We can think of part 1's problem as a subset of the strongly connected\n# components problem. E.g., in trying to find the number of constellations\n# in our set of coordinates/points, we can phrase the problem as finding\n# the number of subgraphs in which each vertex is reachable from every other\n# vertex.\nprint(f\"Part 1: {num_constellations(points)}\")\n\n# TODO: Come back to this once I have 49 stars.\n","sub_path":"day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"377387280","text":"# __init__.py\n# Authors: Yang Lu and Jacob Schreiber \n\nfrom .ledidi import Ledidi\nfrom .ledidi import TensorFlowRegressor\n\n__version__ = '0.2.0'\n\nimport numpy\nimport pyBigWig\n\nfrom tqdm import tqdm\n\ndef sequence_to_ohe(sequence, ignore='N', alphabet=None, dtype='int8', \n\tverbose=False, **kwargs):\n\t\"\"\"Converts a string or list of characters into a one-hot encoding.\n\n\tThis function will take in either a string or a list and convert it into a\n\tone-hot encoding. If the input is a string, each character is assumed to be\n\ta different symbol, e.g. 'ACGT' is assumed to be a sequence of four \n\tcharacters. If the input is a list, the elements can be any size.\n\n\tAlthough this function will be used here primarily to convert nucleotide\n\tsequences into one-hot encoding with an alphabet of size 4, in principle\n\tthis function can be used for any types of sequences.\n\n\tParameters\n\t----------\n\tsequence : str or list\n\t\tThe sequence to convert to a one-hot encoding.\n\n\tignore : str, optional\n\t\tA character to indicate setting nothing to 1 for that row, keeping the\n\t\tencoding entirely 0's for that row. In the context of genomics, this is\n\t\tthe N character. Default is 'N'.\n\n\talphabet : set or tuple or list, optional\n\t\tA pre-defined alphabet. If None is passed in, the alphabet will be\n\t\tdetermined from the sequence, but this may be time consuming for\n\t\tlarge sequences. Default is None.\n\n\tdtype : str or numpy.dtype, optional\n\t\tThe data type of the returned encoding. Default is int8.\n\n\tverbose : bool or str, optional\n\t\tWhether to display a progress bar. If a string is passed in, use as the\n\t\tname of the progressbar. Default is False.\n\n\tkwargs : arguments\n\t\tArguments to be passed into tqdm. Default is None.\n\n\tReturns\n\t-------\n\tone : numpy.ndarray\n\t\tA binary matrix of shape (alphabet_size, sequence_length) where\n\t\talphabet_size is the number of unique elements in the sequence and\n\t\tsequence_length is the length of the input sequence.\n\t\"\"\"\n\n\tname = None if verbose in (True, False) else verbose\n\td = verbose is False\n\n\tif isinstance(sequence, str):\n\t\tsequence = list(sequence)\n\n\talphabet = alphabet or numpy.unique(sequence)\n\talphabet = [char for char in alphabet if char != ignore]\n\talphabet_lookup = {char: i for i, char in enumerate(alphabet)}\n\n\tohe = numpy.zeros((len(sequence), len(alphabet)), dtype=dtype)\n\tfor i, char in tqdm(enumerate(sequence), disable=d, desc=name, **kwargs):\n\t\tif char != ignore:\n\t\t\tidx = alphabet_lookup[char]\n\t\t\tohe[i, idx] = 1\n\n\treturn ohe\n\ndef fasta_to_ohe(filename, include_chroms=None, exclude_chroms=None, \n\tignore='N', alphabet=['A', 'C', 'G', 'T', 'N'], dtype='int8', verbose=True):\n\t\"\"\"Read in a FASTA file and output a dictionary of binary encodings.\n\n\tThis function will take in the path to a FASTA-formatted file and convert\n\tit to a set of one-hot encodings---one for each chromosome. Optionally,\n\tthe user can specify a set of chromosomes to include or exclude from\n\tthe returned dictionary.\n\n\tParameters\n\t----------\n\tfilename : str\n\t\tThe path to the FASTA-formatted file to open.\n\n\tinclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the FASTA file to include, excluding\n\t\tall others. If None, include all chromosomes (except those specified by\n\t\texclude_chroms). Default is None.\n\n\texclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the FASTA file to exclude, including\n\t\tall others. If None, include all chromosomes (or the set specified by\n\t\tinclude_chroms). Default is None.\n\n\tignore : str, optional\n\t\tA character to indicate setting nothing to 1 for that row, keeping the\n\t\tencoding entirely 0's for that row. In the context of genomics, this is\n\t\tthe N character. Default is 'N'.\n\n\talphabet : set or tuple or list, optional\n\t\tA pre-defined alphabet. If None is passed in, the alphabet will be\n\t\tdetermined from the sequence, but this may be time consuming for\n\t\tlarge sequences. Must include the ignore character. Default is\n\t\t['A', 'C', 'G', 'T', 'N'].\n\n\tdtype : str or numpy.dtype, optional\n\t\tThe data type of the returned encoding. Default is int8. \n\n\tverbose : bool or str, optional\n\t\tWhether to display a progress bar. If a string is passed in, use as the\n\t\tname of the progressbar. Default is False.\n\n\tReturns\n\t-------\n\tchroms : dict\n\t\tA dictionary of one-hot encodings where the keys are the names of the\n\t\tchromosomes (exact strings from the header lines in the FASTA file)\n\t\tand the values are the one-hot encodings as numpy arrays.\n\t\"\"\"\n\n\tsequences = {}\n\tname, sequence = None, None\n\tskip_chrom = False\n\n\twith open(filename, \"r\") as infile:\n\t\tfor line in infile:\n\t\t\tif line.startswith(\">\"):\n\t\t\t\tif name is not None and skip_chrom is False:\n\t\t\t\t\tsequences[name] = sequence\n\n\t\t\t\tsequence = []\n\t\t\t\tname = line[1:].strip(\"\\n\")\n\t\t\t\tif include_chroms is not None and name not in include_chroms:\n\t\t\t\t\tskip_chrom = True\n\t\t\t\telif exclude_chroms is not None and name in exclude_chroms:\n\t\t\t\t\tskip_chrom = True\n\t\t\t\telse:\n\t\t\t\t\tskip_chrom = False\n\n\t\t\telse:\n\t\t\t\tif skip_chrom == False:\n\t\t\t\t\tsequence.extend(list(line.rstrip(\"\\n\").upper()))\n\n\tencodings = {}\n\tfor i, (name, sequence) in enumerate(sequences.items()):\n\t\tencodings[name] = sequence_to_ohe(sequence, ignore=ignore, \n\t\t\talphabet=alphabet, dtype=dtype, position=i,\n\t\t\tverbose=name if verbose else verbose)\n\n\treturn encodings\n\ndef bigwig_to_arrays(filename, include_chroms=None, exclude_chroms=None, \n\t fillna=0, dtype='float32'):\n\t\"\"\"Read in a bigWig file and output a dictionary of signal arrays.\n\n\tThis function will take in a filename, open it, and output the\n\tbasepair-resolution signal for the track for all desired chromosomes.\n\n\tParameters\n\t----------\n\tfilename : str\n\t\tThe path to the bigWig to open.\n\n\tinclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the bigWig file to include, excluding\n\t\tall others. If None, include all chromosomes (except those specified by\n\t\texclude_chroms). Default is None.\n\n\texclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the bigWig file to exclude, including\n\t\tall others. If None, include all chromosomes (or the set specified by\n\t\tinclude_chroms). Default is None.\n\n\tfillna : float or None, optional\n\t\tThe value to fill NaN values with. If None, keep them as is. Default is 0.\n\n\tdtype : str or numpy.dtype, optional\n\t\tThe data type of the returned encoding. Default is int8.\n\n\tReturns\n\t-------\n\tsignals : dict\n\t\tA dictionary of signal values where the keys are the names of the\n\t\tchromosomes and the values are arrays of signal values.\n\t\"\"\"\n\n\tsignals = {}\n\tchroms = []\n\n\tbw = pyBigWig.open(filename, \"r\")\n\tfor chrom in bw.chroms().keys():\n\t\tif include_chroms and chrom not in include_chroms:\n\t\t\tcontinue\n\t\telif exclude_chroms and chrom in exclude_chroms:\n\t\t\tcontinue\n\t\telse:\n\t\t\tsignal = bw.values(chrom, 0, -1, numpy=True).astype(dtype)\n\t\t\tif fillna is not None:\n\t\t\t\tsignal = numpy.nan_to_num(signal, nan=fillna, copy=False)\n\n\t\t\tsignals[chrom] = signal\n\n\treturn signals","sub_path":"ledidi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"380724794","text":"import discord\r\n\r\nhelp = discord.Embed(title='도움말', description='도움이 필요할때 ```^도움말 or ^help``` 라고 해줘!!', color = 0x39c5bb)\r\nhelp.add_field(name='```^세카이검색```', value='세카이에 관한 정보를 볼수 있습니다', inline=True)\r\nhelp.set_footer(text='Made By Luen')\r\nhelp.set_thumbnail(url=\"https://media.discordapp.net/attachments/828467375337766962/828581378827485275/1.jpg?width=465&height=491\")\r\n\r\nsk_help = discord.Embed(title='세카이검색', description='세카이에 관한 정보 명령어 모음', color = 0x39c5bb)\r\nsk_help.add_field(name='음악', value='세카이에 수록된 곡 정보를 볼 수 있습니다\\nex)```^세카이검색 음악```', inline=False)\r\nsk_help.add_field(name='유닛', value='세카이에 유닛 정보를 볼 수 있습니다\\nex)```^세카이검색 유닛```', inline=False)\r\nsk_help.set_footer(text='Project SEKAI COLOURFUL STAGE! feat.HATSUNE MIKU')\r\nsk_help.set_thumbnail(url=\"https://cdn.discordapp.com/attachments/828959305478832198/828990365247209482/TMa_FBrjseeE0ZBQa0fve-dyW1j0YZHnNUzJeRR692EyKcNh6SQB04_ytzYE---4xgw512.png\")\r\n\r\nun_help = discord.Embed(title='프로젝트 세카이 유닛', description='유닛 목록',color=0x39c5bb)\r\nun_help.add_field(name='VIRTURE SINGER', value='ㅤ', inline=False)\r\nun_help.add_field(name='MORE MORE JUMP!', value='ㅤ', inline=False)\r\nun_help.add_field(name='Leo/need', value='ㅤ', inline=False)\r\nun_help.add_field(name='Vivid BAD SQUAD', value='ㅤ', inline=False)\r\nun_help.add_field(name='원더랜즈×쇼타임', value='ㅤ', inline=False)\r\nun_help.add_field(name='25시, 나이트코드에서.', value='ㅤ', inline=False)\r\nun_help.add_field(name='명령어', value='ex)```^세카이검색 유닛 모모점```', inline=False)\r\nun_help.set_image(url=\"https://cdn.discordapp.com/attachments/857996994676916234/858001981301850122/65319eabc477e721e6d5dde19508daac108bf74817f79b9061fe00e593d772fcbe7ad1ff333ccf07c36a4f695380d3feee0d.png\")\r\n\r\nms_help = discord.Embed(title='프로젝트 세카이 음악', description='ㅤ', color=0x39c5bb)\r\nms_help.add_field(name='검색하시면 곡의 정보가 나옵니다', value='일본어 검색은 안되요ㅠㅠ', inline=False)\r\nms_help.add_field(name='명령어', value='ex)```^세카이검색 음악 멜트```', inline=False)\r\nms_help.set_image(url=\"https://cdn.discordapp.com/attachments/857996994676916234/858001981301850122/65319eabc477e721e6d5dde19508daac108bf74817f79b9061fe00e593d772fcbe7ad1ff333ccf07c36a4f695380d3feee0d.png\")","sub_path":"help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"166437327","text":"from datetime import datetime\nfrom decimal import Decimal\nfrom typing import TypedDict, List, Tuple, Dict\n\nfrom peewee import fn, Case, Tuple as DBTuple\n\nfrom cockroachdb.modules.models import Customer, Item, Order, OrderLine\nfrom cockroachdb.modules.transactions.base import BaseTransaction\n\n\nclass PopularItemsOutput(TypedDict):\n \"\"\"\n Popular items output dict representation\n \"\"\"\n\n order_id: int\n entry_date: datetime\n first_name: str\n middle_name: str\n last_name: str\n quantity: Decimal\n item_id: int\n item_name: str\n\n\nclass OrderOutput(TypedDict):\n \"\"\"\n Order output dict representation\n \"\"\"\n\n order_id: int\n entry_date: datetime\n customer_name: str\n popular_items: List[str]\n\n\nclass ItemOutput(TypedDict):\n \"\"\"\n Item output dict representation\n \"\"\"\n\n name: str\n orders: set\n\n\nclass PopularItemsTransaction(BaseTransaction):\n \"\"\"\n Transaction for querying popular items\n\n Example:\n popular_items = PopularItemsTransaction(1, 1, 10)\n popular_items.run()\n \"\"\"\n\n def __init__(\n self, warehouse_id: int, district_id: int, orders_to_examine: int\n ):\n \"\"\"\n Initiate a transaction for retrieving popular items\n :param warehouse_id: warehouse identifier\n :param district_id: district identifier\n :param orders_to_examine: number of items to examine\n \"\"\"\n super().__init__()\n self.warehouse_id = warehouse_id\n self.district_id = district_id\n self.orders_to_examine = orders_to_examine\n\n def _execute(self) -> Tuple[List[PopularItemsOutput]]:\n \"\"\"\n Execute new payment transaction\n :return: relevant output information\n \"\"\"\n # Get order table joined with customer table\n order_customer_query = (\n Order.select(\n Order.id.alias(\"order_id\"),\n Order.district_id.alias(\"district_id\"),\n Order.warehouse_id.alias(\"warehouse_id\"),\n Order.entry_date.alias(\"entry_date\"),\n Customer.middle_name.alias(\"middle_name\"),\n Customer.first_name.alias(\"first_name\"),\n Customer.last_name.alias(\"last_name\"),\n )\n .join(\n Customer,\n on=(\n (Order.warehouse_id == Customer.warehouse_id)\n & (Order.district_id == Customer.district_id)\n & (Order.customer_id == Customer.id)\n ),\n )\n .where(\n (Order.warehouse_id == self.warehouse_id)\n & (Order.district_id == self.district_id)\n )\n .order_by(Order.entry_date.desc())\n .limit(self.orders_to_examine)\n .cte(\"order_customer_query\")\n )\n\n # Get order lines with maximum quantity, joined with item table\n OrderLineInner: OrderLine = OrderLine.alias()\n order_line_sum_qty_query = (\n OrderLineInner.select(\n OrderLineInner.warehouse_id.alias(\"warehouse_id\"),\n OrderLineInner.district_id.alias(\"district_id\"),\n OrderLineInner.order_id.alias(\"order_id\"),\n fn.SUM(OrderLineInner.quantity).alias(\"sum_qty\"),\n )\n .where(\n (OrderLineInner.warehouse_id == self.warehouse_id)\n & (OrderLineInner.district_id == self.district_id)\n )\n .group_by(\n OrderLineInner.warehouse_id,\n OrderLineInner.district_id,\n OrderLineInner.order_id,\n OrderLineInner.item_id,\n )\n .cte(\"order_line_sum_qty_query\")\n )\n order_line_max_qty_query = (\n order_line_sum_qty_query.select(\n order_line_sum_qty_query.c.order_id,\n fn.MAX(order_line_sum_qty_query.c.sum_qty),\n )\n .group_by(\n order_line_sum_qty_query.c.warehouse_id,\n order_line_sum_qty_query.c.district_id,\n order_line_sum_qty_query.c.order_id,\n )\n .with_cte(order_line_sum_qty_query)\n )\n\n customer_name_field = Case(\n None,\n (\n (\n order_customer_query.c.middle_name.is_null(),\n fn.CONCAT(\n order_customer_query.c.first_name,\n \" \",\n order_customer_query.c.last_name,\n ),\n ),\n ),\n fn.CONCAT(\n order_customer_query.c.first_name,\n order_customer_query.c.middle_name,\n order_customer_query.c.last_name,\n ),\n ).alias(\"customer_name\")\n\n popular_items_query = (\n OrderLine.select(\n order_customer_query.c.order_id,\n order_customer_query.c.entry_date,\n customer_name_field,\n fn.SUM(OrderLine.quantity).alias(\"quantity\"),\n Item.id.alias(\"item_id\"),\n Item.name.alias(\"item_name\"),\n )\n .join(\n order_customer_query,\n on=(\n (\n OrderLine.warehouse_id\n == order_customer_query.c.warehouse_id\n )\n & (\n OrderLine.district_id\n == order_customer_query.c.district_id\n )\n & (OrderLine.order_id == order_customer_query.c.order_id)\n ),\n )\n .join(Item, on=(OrderLine.item_id == Item.id))\n .group_by(\n order_customer_query.c.order_id,\n order_customer_query.c.entry_date,\n customer_name_field,\n Item.id,\n Item.name,\n )\n .having(\n DBTuple(\n order_customer_query.c.order_id, fn.SUM(OrderLine.quantity)\n ).in_(order_line_max_qty_query)\n )\n .order_by(\n order_customer_query.c.order_id.desc(),\n fn.SUM(OrderLine.quantity).desc(),\n )\n .with_cte(order_customer_query)\n )\n\n # Process query output\n return ([result for result in popular_items_query.dicts()],)\n\n def _output_result(self, popular_items: List[PopularItemsOutput]):\n \"\"\"\n Output execution result\n :param popular_items: list of popular items in PopularItemsOutput format\n :return: None\n \"\"\"\n\n def format_popular_item(name: str, quantity: Decimal):\n \"\"\"\n Format popular item to be printed in console\n :param name: item name\n :param quantity: item quantity\n :return: formatted popular item string\n \"\"\"\n return f\"{name} (QTY: {quantity})\"\n\n self.print(\n f\"Popular Items Summary from {self.orders_to_examine} Orders from Warehouse {self.warehouse_id}, District {self.district_id}:\",\n is_heading=True,\n )\n\n order_table_rows = []\n item_table_rows = []\n\n orders: Dict[int, OrderOutput] = {}\n items: Dict[int, ItemOutput] = {}\n for order_line in popular_items:\n order_id = order_line[\"order_id\"]\n item_id, item_name, item_qty = (\n order_line[\"item_id\"],\n order_line[\"item_name\"],\n order_line[\"quantity\"],\n )\n if item_id not in items.keys():\n items[item_id] = {\"orders\": set(), \"name\": item_name}\n if order_id not in orders.keys():\n orders[order_id] = {\n **order_line,\n \"popular_items\": [\n format_popular_item(item_name, item_qty)\n ],\n }\n else:\n orders[order_id][\"popular_items\"].append(\n format_popular_item(item_name, item_qty)\n )\n items[item_id][\"orders\"].add(order_id)\n\n for order in orders.values():\n order = order\n order_table_rows.append(\n [\n str(order[\"order_id\"]),\n order[\"entry_date\"].strftime(\"%b %d, %Y, %X (UTC)\"),\n order[\"customer_name\"],\n \"\\n\".join(order[\"popular_items\"]),\n ]\n )\n\n for item_id, item_output in sorted(\n items.items(),\n key=lambda item: len(item[1][\"orders\"]) * 1.0 / len(orders),\n reverse=True,\n ):\n percentage = len(item_output[\"orders\"]) * 1.0 / len(orders)\n item_table_rows.append(\n [\n str(item_id),\n item_output[\"name\"],\n \"{:2.2%}\".format(percentage),\n ]\n )\n\n self.print_table(\n columns=[\n {\"header\": \"Order Number\"},\n {\"header\": \"Order Date\"},\n {\"header\": \"Customer Name\"},\n {\"header\": \"Popular Items\"},\n ],\n rows=order_table_rows,\n )\n self.print_table(\n columns=[\n {\"header\": \"Item ID\"},\n {\"header\": \"Item Name\"},\n {\"header\": \"Percentage of Orders Containing This Item\"},\n ],\n rows=item_table_rows,\n )\n\n @property\n def transaction_name(self):\n \"\"\"\n Transaction name\n :return: transaction name\n \"\"\"\n return \"popular_items\"\n","sub_path":"cockroachdb/modules/transactions/popular_item.py","file_name":"popular_item.py","file_ext":"py","file_size_in_byte":9724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"57684126","text":"import discord\nfrom discordbot import betterbot, client\nfrom discord.ext import commands\nimport os\nimport random\nimport re\nimport asyncio\nfrom config import EDITOR_IDS, BASE_URL, ADMIN_IDS, BLACKLIST_IDS\nimport database\nimport utils\nblacklist_wait = 5\n# ACTUAL COMMANDS START HERE\n\n@betterbot.command(name='help',allowed=True)\nasync def help(message, *args):\n\tif message.message.author.id in BLACKLIST_IDS:\n\t\tawait asyncio.sleep(blacklist_wait)\n\tcommands = {\n\t\t'search ': 'Finds entries that match the query',\n\t\t'entry ': 'Shows the matching entry',\n\t\t'random': 'Gets a random entry',\n\t\t'request ': 'Lets noneditors request a Repldex entry',\n\t\t'selfentry': 'Gets your own entry if you have one.'\n\t}\n\tif message.author.id in EDITOR_IDS:\n\t\tcommands['selfentry '] = 'Links you to your entry (editor only)'\n\t\tcommands['newentry '] = 'Sends link to write new entry (editor only)'\n\t\tif message.author.id in ADMIN_IDS:\n\t\t\tcommands['link
'] = 'Manually link non-editors to entries (admin only)'\n\t\t\tcommands['view_selfentry '] = 'View a users selfentry (admin only)'\n\t\t\tcommands['who_is_the_leader'] = 'tells you who the supreme leader is (admin only)'\n\t\t\tcommands['userinfo '] = 'get info on the mentioned user (admin only)'\n\t\t\tcommands['unlist
'] = 'Toggles unlisting of entry (admin only)'\n\t\t\t#commands['neweditor '] = 'Make user editor (admin only)'\n\tcontent = []\n\tprefix = message.prefix\n\tfor command in commands:\n\t\tcontent.append(\n\t\t\tf'{prefix}**{command}** - {commands[command]}'\n\t\t)\n\n\tembed = discord.Embed(\n\t\ttitle='Commands',\n\t\tdescription='\\n'.join(content)\n\t)\n\tawait message.send(embed=embed)\n\nasync def create_entry_embed(entry_data, author_id=None,raw_entry=False):\n\tif(not raw_entry):\n\t\thtml = entry_data['content']\n\t\tcontent = utils.html_to_markdown(html)\n\t\n\t\tcontent_ending = ''\n\t\n\t\tif len(content) > 2048:\n\t\t\tcontent = content[:2045 - len(content_ending)] + '...'\n\t\tcontent += content_ending\n\t\ttitle = utils.url_title(entry_data['title'])\n\t\tview_url = f'{BASE_URL}/entry/{title}'\n\t\tview_url = view_url\n\t\tembed = discord.Embed(\n\t\t\ttitle=entry_data['title'],\n\t\t\tdescription=content,\n\t\t\turl=view_url\n\t\t)\n\t\tif entry_data.get('image'):\n\t\t\tembed.set_thumbnail(url=entry_data['image']['src'])\n\t\n\t\treturn embed\n\telse:\n\t\tentry_data = dict(entry_data)\n\t\tcontent = entry_data['nohtml_content']\n\t\tcontent_ending = ''\n\t\tif len(content) > 1024:\n\t\t\tcontent = content[:1021 - len(content_ending)] + '...'\n\t\ttry: del entry_data['image']\n\t\texcept: pass\n\t\tentry_data['nohtml_content'] = content\n\t\tdel entry_data['content']\n\t\tdel entry_data['history']\n\t\treturn utils.embed_from_dict(entry_data,color=0x00ff00,title=\"raw entry data\")\n\n@betterbot.command(name='search')\nasync def search_entries(message, *args):\n\tnumbers = (\n\t\t'1️⃣',\n\t\t'2️⃣',\n\t\t'3️⃣',\n\t\t'4️⃣',\n\t\t'5️⃣',\n\t\t'6️⃣',\n\t\t'7️⃣',\n\t\t'8️⃣',\n\t\t'9️⃣',\n\t\t'🔟'\n\t)\n\tsearch_query = ' '.join(args)\n\tfound = await database.search_entries(search_query)\n\tif found:\n\t\tcontent = []\n\t\tfor i, result in enumerate(found, 1):\n\t\t\ttitle = result['title']\n\t\t\tcontent.append(f'{i}) {title}')\n\t\tcontent = '\\n'.join(content)\n\telse:\n\t\tcontent = 'No results'\n\tembed = discord.Embed(\n\t\ttitle=f'Results for {search_query}',\n\t\tdescription=content\n\t)\n\t# if found:\n\t# \tembed.set_footer(text=f'React with {one_emoji} to get the first result')\n\tmsg = await message.send(embed=embed)\n\tif found:\n\t\tfor emoji in numbers[:len(found)]:\n\t\t\tawait msg.add_reaction(emoji)\n\t\tdef check(reaction, user):\n\t\t\tmessage_matches = reaction.message.id == msg.id\n\t\t\tuser_matches = user == message.author\n\t\t\temoji_matches = str(reaction.emoji) in numbers\n\t\t\treturn message_matches and user_matches and emoji_matches\n\t\treaction, _ = await client.wait_for('reaction_add', check=check)\n\t\temoji = str(reaction.emoji)\n\t\temoji_pos = numbers.index(emoji)\n\t\tembed = await create_entry_embed(found[emoji_pos], author_id=message.author.id)\n\t\tawait message.send(embed=embed)\n\n@betterbot.command(name='entry', allowed=True)\nasync def show_entry(message, *args):\n\tif message.message.author.id in BLACKLIST_IDS:\n\t\tawait asyncio.sleep(blacklist_wait)\n\tsearch_query = ' '.join(args)\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tembed = await create_entry_embed(found[0], author_id=message.author.id)\n\t\tawait message.send(embed=embed)\n\telse:\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"This entry doesn't exist\"\n\t\t)\n\t\tsearch_query_url_encoded = utils.url_title(search_query)\n\t\tedit_url = f'{BASE_URL}/edit?title={search_query_url_encoded}'\n\t\tedit_url = edit_url\n\t\tif message.author.id in EDITOR_IDS:\n\t\t\tembed.description = f'[Click here to write it!]({edit_url})'\n\t\tawait message.send(embed=embed)\n\n@betterbot.command(name='raw_entry')\nasync def show_raw_entry(message, *args):\n\tif message.author.id not in ADMIN_IDS: return\n\tsearch_query = ' '.join(args)\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tdata = await create_entry_embed(found[0], author_id=message.author.id, raw_entry=True)\n\t\tawait message.send(embed=data)\n\telse:\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"This entry doesn't exist\"\n\t\t)\n\t\tawait message.send(embed=embed)\n\n\n\n@betterbot.command(name='selfentry')\nasync def personal_entry(message, *args):\n\tsearch_query = ' '.join(args)\n\tif not search_query:\n\t\tentry_id = await database.get_personal_entry(message.author.id)\n\t\tif not entry_id:\n\t\t\tif message.author.id not in EDITOR_IDS: \n\t\t\t\treturn await message.send(\"You don't have a personal entry set yet. An admin needs to set one for you\")\n\t\t\telse:\n\t\t\t\treturn await message.send(\"You haven't set a personal entry yet\")\n\t\tentry = await database.get_entry(entry_id)\n\t\tembed = await create_entry_embed(entry, author_id=message.author.id)\n\t\treturn await message.send(embed=embed)\n\tif message.author.id not in EDITOR_IDS: \n\t\treturn await message.send(\"Only editors can set personal entries\")\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tentry = found[0]\n\t\ttitle = entry['title']\n\t\tentry_id = entry['_id']\n\t\tawait database.set_personal_entry(message.author.id, entry_id)\n\t\tawait message.send(f'Set your personal entry to `{title}`')\n\telse:\n\t\tawait message.send('Invalid entry')\n\n@betterbot.command(name='userinfo')\nasync def user_info(message,member:utils.Member):\n\tif message.author.id not in ADMIN_IDS: return\n\tembed = discord.Embed(title='user info',description=f'info on <@{member.id}>',color=0x00ff00)\n\teditor = False\n\tif(member.id in EDITOR_IDS):\n\t\teditor = True\n\tadmin = False\n\tif(member.id in ADMIN_IDS):\n\t\tadmin = True\n\t\n\tentry_id = await database.get_personal_entry(member.id)\n\t\n\tif(entry_id==None):\n\t\tselfentry='None'\n\telse:\n\t\tentry = await database.get_entry(entry_id)\n\t\tselfentry=entry['title']\n\tembed.add_field(name='editor',value=str(editor),inline=True)\n\tembed.add_field(name='admin',value=str(editor),inline=True)\n\tembed.add_field(name='selfentry',value=f'`{selfentry}`',inline=False)\n\tawait message.send(embed=embed)\n\n@betterbot.command(name='view_selfentry')\nasync def view_self_entry(message,member: utils.Member):\n\tif message.author.id not in ADMIN_IDS: return\n\tentry_id = await database.get_personal_entry(member.id)\n\tentry = await database.get_entry(entry_id)\n\ttry:\n\t\tembed = await create_entry_embed(entry, author_id=message.author.id)\n\texcept:\n\t\treturn await message.send(\"no selfentry exists for dis person\")\n\treturn await message.send(embed=embed)\n\t\n@betterbot.command(name='who_is_the_leader')\nasync def leader(message, *args):\n\tif(message.channel.id in utils.auto_delete_channels): return\n\tif message.author.id not in ADMIN_IDS: return\n\tawait message.send('PRUSSIA IS THE SUPREME LEADER')\n\tpass\n\n@betterbot.command(name='request')\nasync def suggest(ctx, *args):\n\tsuggestions_channel = client.get_channel(753331575034347642)\n\tif args != tuple():\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"Entry Suggestion\",\n\t\t\tdescription=' '.join(args)\n\t\t)\n\t\tembed.set_footer(text='Requested by {}'.format(ctx.message.author.name))\n\t\tawait ctx.send(\"Suggestion sent.\")\n\t\treturn await suggestions_channel.send(embed=embed)\n\treturn await ctx.send(\"No suggestion was given\")\n\n'''@betterbot.command(name='role')\nasync def role(message, role):\n\tif message.author.id not in ADMIN_IDS: return\n\tuser = message.author\n\trole = message.guild.get_role(int(role))\n\tawait role.delete()\n\t#await user.remove_roles(role)'''\n\n@betterbot.command(name='unlist')\nasync def unlist(message,entry_id):\n\tif message.author.id not in ADMIN_IDS: return\n\tentry_data = await database.get_entry(entry_id)\n\tif(entry_data==None): return\n\tunlist = not entry_data['unlisted']\n\tawait database.edit_entry(\n\t\ttitle=entry_data['title'],\n\t\tentry_id=entry_id,\n\t\tcontent=entry_data['content'],\n\t\tunlisted=unlist\n\t)\n\tembed = discord.Embed(title='toggle unlist',description='toggling entry being listed/unlisted',color=0x00ff00)\n\tembed.add_field(name='entry name',value=entry_data['title'],inline=True)\n\tembed.add_field(name='entry id',value=entry_id,inline=True)\n\tembed.add_field(name='entry link',value=BASE_URL+'/entry/'+entry_id,inline=True)\n\tembed.add_field(name='unlisted',value=str(unlist),inline=False)\n\tawait message.send(embed=embed)\n\t\n\t\n\n@betterbot.command(name='link')\nasync def link_entry(ctx, *args):\n\tif ctx.message.author.id not in ADMIN_IDS: return\n\ttry:\n\t\tmember = ctx.message.mentions[0]\n\texcept:\n\t\treturn ctx.send('No mentions in command')\n\targs = list(args)\n\tdel args[0]\n\tentry_name = tuple(args)\n\tsearch_query = ' '.join(entry_name)\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tentry = found[0]\n\t\ttitle = entry['title']\n\t\tentry_id = entry['_id']\n\t\tawait database.set_personal_entry(member.id, entry_id)\n\t\tawait ctx.send(\n\t\t\tembed=discord.Embed(\n\t\t\t\tdescription=f'Set {member.mention} personal entry to `{title}`'\n\t\t\t)\n\t\t)\n\telse:\n\t\tawait ctx.send('Invalid entry')\n\t\t\n@betterbot.command(name='newentry')\nasync def new_entry(message, *args):\n\tsearch_query = ' '.join(args)\n\tsearch_query_url_encoded = utils.url_title(search_query)\n\tedit_url = f'{BASE_URL}/edit?title={search_query_url_encoded}'\n\tedit_url = edit_url\n\tif message.author.id in EDITOR_IDS:\n\t\tembed = discord.Embed(\n\t\ttitle=\"Write \"+search_query,\n\t\tdescription=f'[Click here to write it!]({edit_url})'\n\t\t)\n\t\tfound = await database.search_entries(search_query, limit=1)\n\t\tif found:\n\t\t\tembed.set_footer(text='Alert: There may be an entry with the same/similar name or topic.') \n\telse:\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"This command is editor only\"\n\t\t)\n\tawait message.send(embed=embed)\n\t\t\n@betterbot.command(name='random')\nasync def random_entry(message, *args):\n\tentry = await database.get_random_entry()\n\n\tembed = await create_entry_embed(entry, author_id=message.author.id)\n\tawait message.send(embed=embed)\n\n'''@betterbot.command(name=\"neweditor\")\nasync def new_editor(message, member: utils.Member):\n\tprint('new editor command')\n\tif message.author.id not in ADMIN_IDS: return\n\n\twith open(\"editors.txt\") as editors:\n\t\tif str(member.id) in editors.read().split(\"\\n\"):\n\t\t\tawait message.send(embed=discord.Embed(\n\t\t\t\tdescription=\"This user is already an editor!\",\n\t\t\t\tcolour=discord.Colour.red()\n\t\t\t))\n\t\t\treturn\n\n\twith open(\"editors.txt\",\"a\") as editors:\n\t\teditors.write(\"\\n\")\n\t\teditors.write(str(member.id))\n\t\tEDITOR_IDS.append(member.id)\n\t\tawait message.send(embed=discord.Embed(\n\t\t\tdescription=f\"Added {member.mention} as an editor!\",\n\t\t\tcolour=discord.Colour.green()\n\t\t))\n\n@betterbot.command(name=\"removeeditor\")\nasync def new_editor(message, member: utils.Member):\n\tprint('remove editor command')\n\tif message.author.id not in ADMIN_IDS: return\n\n\twith open(\"editors.txt\") as editors:\n\t\teditorlist=editors.read().split(\"\\n\")\n\t\tif str(member.id) not in editorlist:\n\t\t\tawait message.send(embed=discord.Embed(\n\t\t\t\tdescription=\"This user is not an editor!\",\n\t\t\t\tcolour=discord.Colour.red()\n\t\t\t))\n\t\t\treturn\n\n\teditorlist.remove(str(member.id))\n\twith open(\"editors.txt\",\"w\") as editors:\n\t\teditors.write(\"\\n\".join(editorlist))\n\t\tEDITOR_IDS.remove(member.id)\n\t\tawait message.send(embed=discord.Embed(\n\t\t\tdescription=f\"Removed {member.mention} from editors!\",\n\t\t\tcolour=discord.Colour.green()\n\t\t))'''\n","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":12121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"518965053","text":"import argparse\nimport sqlite3\n\nfrom redminelib import Redmine, exceptions\nfrom telegram import Bot, error\nfrom datetime import datetime, timedelta\n\nimport config\n\nDB_PATH = \"database/data.db\"\nMESSAGE_1 = \"Your {0} project debt is {1:.1f} hours!\"\nMESSAGE_2 = \"{0} debts on the {1} project {2:.1f} hours!\"\n\n\ndef hours(info_var):\n return round(sum([h.hours for h in info_var]), 1)\n\n\nparser = argparse.ArgumentParser(description=\"Launch python bot.\")\nparser.add_argument(\"-r\", action=\"store_true\")\nmain_token = parser.parse_args()\nif main_token.r:\n bot = Bot(token=config.main_token)\nelse:\n bot = Bot(token=config.test_token)\n\nconn = sqlite3.connect(DB_PATH)\nc = conn.cursor()\nc.execute(\"SELECT username, password FROM users\")\nusers = c.fetchall()\ninfo = {}\nproject_id = int()\nbad_usernames = []\nfor user in users:\n redmine = Redmine(\"https://ximc.ru\", key=user[1])\n try:\n rm_user = redmine.auth()\n except exceptions.AuthError:\n bad_usernames.append(user[0])\n continue\n c.execute(\"SELECT project, percent, log_id FROM requirements WHERE username='{0}'\".format(user[0]))\n reqs = c.fetchall()\n if reqs is not None:\n debts = {}\n for req in reqs:\n c.execute(\"SELECT date FROM log WHERE id={0}\".format(req[2]))\n date = datetime.strptime(\"{0}\".format(c.fetchone()), \"('%Y-%m-%d %H:%M',)\")\n for project in redmine.project.all():\n if req[0] == project.name:\n project_id = project.id\n info_all = redmine.time_entry.filter(user_id=rm_user.id, from_date=date)\n info_proj = redmine.time_entry.filter(user_id=rm_user.id, from_date=date,\n project_id=\"{0}\".format(project_id))\n info_yesterday = redmine.time_entry.filter(user_id=rm_user.id, from_date=datetime.today() - timedelta(2))\n try:\n hours_all = hours(info_all)\n hours_proj = hours(info_proj)\n hours_yesterday = hours(info_yesterday)\n except exceptions.ForbiddenError:\n continue\n else:\n if hours_yesterday > 1:\n if (hours_all * req[1] / 100) > hours_proj:\n debt = hours_all * req[1] / 100 - hours_proj\n debts[req[0]] = debt\n info[user[0]] = debts.copy()\n for i in range(0, len(debts)):\n debt = debts.popitem()\n c.execute(\"SELECT telegram_id FROM users WHERE username='{0}'\".format(user[0]))\n user_id = c.fetchone()[0]\n try:\n bot.send_message(chat_id=user_id, text=MESSAGE_1.format(debt[0], debt[1]))\n except error.BadRequest:\n bad_usernames.append(user[0])\n continue\n else:\n continue\n\nc.execute(\"SELECT username, subs FROM users\")\nsubs_info = c.fetchall()\nfor user in subs_info:\n if user[0] in bad_usernames:\n continue\n elif user[1] is not None:\n for sub in user[1].split():\n if sub in bad_usernames:\n continue\n else:\n debts = info[sub].copy()\n for i in range(0, len(debts)):\n debt = debts.popitem()\n c.execute(\"SELECT telegram_id FROM users WHERE username='{0}'\".format(user[0]))\n user_id = c.fetchone()[0]\n try:\n bot.send_message(chat_id=user_id, text=MESSAGE_2.format(sub, debt[0], debt[1]))\n except error.BadRequest:\n continue\n","sub_path":"dept_count.py","file_name":"dept_count.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"159681976","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport numpy as np\n\nimport turret\nimport turret.layers as L\n\nfrom util import execute_inference\n\n\nclass ReduceTest(unittest.TestCase):\n def test_sum(self):\n N, C, H, W = 3, 5, 7, 11\n input = np.random.rand(N, C, H, W).astype(np.float32)\n\n def build_network(network):\n h = network.add_input(\"input\", turret.DataType.FLOAT,\n turret.Dimensions.CHW(C, H, W))\n h = L.reduce(h, turret.ReduceOperation.SUM, axes=(0, 1))\n network.mark_output(\"output\", h)\n actual = execute_inference({\"input\": input}, build_network)\n\n expect = np.sum(input, axis=(1, 2), keepdims=False)\n self.assertEqual(expect.shape, actual.shape)\n self.assertTrue(np.allclose(expect, actual))\n","sub_path":"tests/layers/reduce_test.py","file_name":"reduce_test.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"120743037","text":"# Copyright 2018 Jiří Janoušek \n# Licensed under BSD-2-Clause license - see file LICENSE for details.\n\nimport json\nfrom typing import List, Any, Optional, Dict, Type, ClassVar\nimport os\nimport shutil\n\nfrom fxwebgen import imaging\nfrom fxwebgen.context import Context\nfrom fxwebgen.objects import Thumbnail\nfrom fxwebgen.pages import MarkdownPage, HtmlPage, Page\nfrom fxwebgen.postprocessor import PostProcessor\nfrom fxwebgen.resources import ResourceManager\n\nFORCE_ALL = 'all'\nFORCE_PAGES = 'pages'\nFORCE_THUMBNAILS = 'thumbnails'\nFORCE_STATIC_FILES = 'static_files'\nFORCE_TEMPLATE = 'template'\nFORCE_REBUILD_CHOICES: List[str] = [FORCE_ALL, FORCE_PAGES, FORCE_THUMBNAILS, FORCE_STATIC_FILES, FORCE_TEMPLATE]\n\n\nclass Generator:\n ctx: Context\n post_processor: PostProcessor\n page_factories: ClassVar[List[Type[Page]]] = [MarkdownPage, HtmlPage]\n thumbnails: Dict[str, Dict[str, Thumbnail]]\n resources: ResourceManager\n\n def __init__(self, ctx: Context, *,\n post_processor: Optional[PostProcessor] = None,\n resources: Optional[ResourceManager] = None) -> None:\n self.ctx = ctx\n self.post_processor = post_processor or PostProcessor()\n self.thumbnails = {}\n self.resources = resources or ResourceManager()\n self.pages_kind = self.resources.add_kind('pages')\n self.static_files_kind = self.resources.add_kind('static_files')\n self.thumbnails_kind = self.resources.add_kind('thumbnails')\n\n def purge(self) -> None:\n if os.path.isdir(self.ctx.output_dir):\n shutil.rmtree(self.ctx.output_dir, ignore_errors=True)\n\n def build(self, force: Optional[List[str]] = None) -> None:\n if force is None:\n force = []\n elif FORCE_ALL in force:\n force = FORCE_REBUILD_CHOICES\n self.before_building_pages()\n if FORCE_TEMPLATE in force:\n self.ctx.templater.clear_cache()\n force.append(FORCE_PAGES)\n self.build_pages(force=FORCE_PAGES in force)\n self.after_building_pages()\n self.generate_thumbnails(force=FORCE_THUMBNAILS in force)\n self.copy_static_files(force=FORCE_STATIC_FILES in force)\n self.remove_stale_files()\n\n def before_building_pages(self) -> None:\n pass\n\n def after_building_pages(self) -> None:\n pass\n\n def build_pages(self, *, force: bool = False) -> None:\n kind = self.pages_kind\n old_pages = {item.source: item for item in kind.resources}\n old_thumbnails = self.thumbnails\n self.thumbnails = {}\n self.resources.remove_by_kind(kind)\n assert self.ctx.pages_dir\n for root, _dirs, files in os.walk(self.ctx.pages_dir):\n for path in files:\n if path.endswith(('.md', '.html', '.html')):\n path = os.path.join(root, path)\n resource = old_pages.get(path)\n if not force and resource and resource.fresh:\n self.thumbnails[path] = old_thumbnails.get(path, {})\n self.resources.add(kind, resource.source, resource.target)\n else:\n default_path = path[len(self.ctx.pages_dir):]\n page = self.parse_page(path, default_path)\n self.thumbnails[page.source] = page.thumbnails\n assert page.target\n resource = self.resources.add(kind, page.source, page.target)\n if force or not resource.fresh:\n self.build_page(page)\n\n def parse_page(self, source: str, default_path: str) -> Page:\n page = self._process_source(source, default_path)\n self._process_metadata(page)\n return page\n\n def build_page(self, page: Page) -> Page:\n self._load_datasets_for_page(page)\n self._process_page(page)\n self._write_page(page)\n return page\n\n def _process_source(self, source: str, default_path: str) -> Page:\n page = None\n for factory in self.page_factories:\n if factory.test(source):\n page = factory(self.ctx, source, default_path)\n break\n assert page, f'No page factory for \"{source}\".'\n page.process()\n return page\n\n def _process_metadata(self, page: Page) -> None:\n path_prefix = self.ctx.path_prefix\n meta = page.metadata\n meta.setdefault('title', os.path.splitext(os.path.basename(page.source))[0])\n meta.setdefault('template', self.ctx.default_template)\n\n url_deprecated = None\n if 'url' in meta:\n url_deprecated = meta['url']\n print(f'Warning: \"URL: {url_deprecated}\" meta directive is deprecated.')\n if not url_deprecated.startswith('/'):\n url_deprecated = '/' + url_deprecated\n\n save_as_deprecated = None\n if 'save_as' in meta:\n save_as_deprecated = meta['save_as']\n print(f'Warning: \"save_as: {save_as_deprecated}\" meta directive is deprecated.')\n\n path = meta.get('path', url_deprecated or page.default_path)\n if not path.startswith('/'):\n path = '/' + path\n if not path.endswith(('/', '.html', '.htm')):\n path += '/'\n meta['canonical_path'] = meta['path'] = '/' + path_prefix + path if path_prefix else path\n\n if save_as_deprecated:\n filename = save_as_deprecated\n else:\n filename = (path + 'index.html' if path.endswith('/') else path)[1:]\n\n root = ('../' * filename.count('/')).rstrip('/') or '.'\n meta['filename'] = filename\n meta['webroot'] = root\n meta['path_prefix'] = '/' + path_prefix if path_prefix else ''\n page.target = os.path.join(self.ctx.output_dir, page.filename)\n\n def _load_datasets_for_page(self, page: Page) -> None:\n meta = page.metadata\n\n datasets = {}\n for name in meta.get('datasets', '').split(','):\n name = name.strip()\n if name:\n name = name.lower().replace(' ', '_').replace('-', '_')\n datasets[name] = self.get_dataset(name)\n meta['datasets'] = datasets\n\n snippets: Dict[str, str] = {}\n if self.ctx.enable_snippets:\n for original_name in meta.get('snippets', '').split(','):\n original_name = original_name.strip()\n normalized_name = original_name.lower().replace(' ', '_').replace('-', '_')\n if original_name and normalized_name not in snippets:\n snippets[original_name] = snippets[normalized_name] = self.ctx.templater.render(\n [f'snippets/{normalized_name}.html'], meta)\n meta['snippets'] = snippets\n\n def _process_page(self, page: Page) -> None:\n meta = page.metadata\n body = page.body or ''\n if self.ctx.enable_snippets:\n snippets: Dict[str, str] = meta['snippets']\n for name, content in snippets.items():\n body = body.replace(f'[Snippet: {name}]', content)\n body = body.replace(f'[snippet: {name}]', content)\n page.body = body\n self.post_processor.process_page(self.ctx, page)\n\n def _write_page(self, page: Page) -> None:\n template = page.metadata['template']\n target = page.target\n assert target\n print(f'Page: \"{page.source}\" → \"{target}\" = {page.path} {page.webroot}')\n variables = {}\n variables.update(page.metadata)\n variables['body'] = page.body\n variables['toc'] = page.toc\n os.makedirs(os.path.dirname(target), exist_ok=True)\n with open(target, \"wt\") as fh:\n fh.write(self.ctx.templater.render(template + '.html', variables))\n\n def copy_static_files(self, *, force: bool = False) -> None:\n kind = self.static_files_kind\n self.resources.remove_by_kind(kind)\n for static_dir in self.ctx.static_dirs:\n target_dir = os.path.join(self.ctx.output_dir, os.path.basename(static_dir))\n print(f'Dir: \"{static_dir}\" → \"{target_dir}\"')\n os.makedirs(target_dir, exist_ok=True)\n prefix_len = len(static_dir) + 1\n for source_root, dirs, files in os.walk(static_dir):\n target_root = os.path.join(target_dir, source_root[prefix_len:])\n for path in files:\n source = os.path.join(source_root, path)\n target = os.path.join(target_root, path)\n resource = self.resources.add(kind, source, target)\n if force or not resource.fresh:\n shutil.copy2(source, target)\n for path in dirs:\n target = os.path.join(target_root, path)\n os.makedirs(target, exist_ok=True)\n\n def get_dataset(self, name: str) -> Any:\n try:\n return self.ctx.datasets[name]\n except KeyError:\n if self.ctx.datasets_dir:\n path = os.path.join(self.ctx.datasets_dir, name + \".json\")\n with open(path) as fh:\n dataset = json.load(fh)\n else:\n dataset = None\n self.ctx.datasets[name] = dataset\n return dataset\n\n def generate_thumbnails(self, *, force: bool = False) -> None:\n kind = self.thumbnails_kind\n self.resources.remove_by_kind(kind)\n static_dirs = self.ctx.static_dirs\n output_dir = self.ctx.output_dir\n for thumbnails in self.thumbnails.values():\n for thumbnail in thumbnails.values():\n for static_dir in static_dirs:\n prefix = os.path.basename(static_dir) + '/'\n if thumbnail.original_url.startswith(prefix):\n source = os.path.join(static_dir, thumbnail.original_url[len(prefix):])\n target = os.path.join(output_dir, thumbnail.filename)\n resource = self.resources.add(kind, source, target)\n if force or not resource.fresh:\n print(f'Thumbnail: {source} → {target}.')\n os.makedirs(os.path.dirname(target), exist_ok=True)\n imaging.create_thumbnail(source, target, thumbnail.width, thumbnail.height)\n break\n else:\n raise ValueError(f'Cannot find {thumbnail.original_url}.')\n\n def remove_stale_files(self) -> None:\n self.resources.remove_stale_files(self.ctx.output_root)\n","sub_path":"fxwebgen/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":10662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"166766648","text":"# valuefy/method4-shell.py\n# Creates a file named method4.txt containing a list of internal URLs\n\nfrom subprocess import check_output, CalledProcessError\nfrom valuefy import URL, write_to_file\n\nset_of_urls = set()\n\n\ndef run_command(url):\n\n \"\"\"\n This is a recursive function which runs the 'lynx' shell command\n for a URL and returns the standard output as a list.\n \"\"\"\n\n command = 'lynx -dump -listonly \"{}\" | grep -o \"https:.*\"' \\\n '| sort -u | grep -vwE \"(osd.xml|plus.google.com)\"'.format(url)\n std_out = check_output(command, shell=True)\n\n return std_out.decode().split('\\n')\n\n\ndef internal_url_scraper(url):\n\n \"\"\"\n This function recursively calls itself for each unique URL returned\n by the run_command() function.\n \"\"\"\n\n global set_of_urls\n\n # stopping condition\n if len(set_of_urls) > 100:\n return\n\n try:\n urls = run_command(url)\n for _url in urls:\n\n if _url not in set_of_urls:\n\n set_of_urls.add(_url)\n write_to_file('method4.txt', _url)\n\n if 'medium.com' in _url:\n internal_url_scraper(_url)\n\n except CalledProcessError:\n pass\n\nif __name__ == '__main__':\n\n internal_url_scraper(URL)\n","sub_path":"scraper/method4-shell.py","file_name":"method4-shell.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"124120623","text":"fname=input(\"enter file name\")\ntry_count=3\nwith open(fname) as file:\n lines = file.readlines()\n lines = [line.rstrip() for line in lines]\nwhile(try_count):\n line_no=int(input(\"Enter line number to read \"))\n try:\n print(lines[line_no-1])\n try_count=0\n except:\n print('Line number exceeded length of file')\n try_count-=1\nfreq={}\nfor i in lines:\n words=i.split(\" \")\n for word in words:\n if (word in freq):\n freq[word]+=1\n else:\n freq[word]=1\ngoing=True\nwhile(going):\n check=input(\"Enter word to see frequency \")\n try:\n print(freq[check])\n going=False\n except:\n print(\"Word in not available in file\")\n finally:\n still_going=\"Y\"\n if(going):\n still_going=input(\"Do you want to continue irrespective of the error? Y/N? \")\n if(still_going==\"N\"):\n going=False\n \n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"637913458","text":"\n\nfrom xai.brain.wordbase.nouns._ligament import _LIGAMENT\n\n#calss header\nclass _LIGAMENTS(_LIGAMENT, ):\n\tdef __init__(self,): \n\t\t_LIGAMENT.__init__(self)\n\t\tself.name = \"LIGAMENTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"ligament\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_ligaments.py","file_name":"_ligaments.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"98644482","text":"from typing import Dict, List\n\nfrom jina.executors.rankers import Match2DocRanker\nfrom jina.executors.decorators import batching\n\n\nclass DummyRanker(Match2DocRanker):\n \"\"\"\n :class:`LevenshteinRanker` Computes the negative Levenshtein distance\n between a query and its matches. The distance is negative, in order to\n achieve a bigger=better sorting in the respective driver.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.match_required_keys = ['tags__dummy_score']\n\n @batching(slice_nargs=3)\n def score(\n self,\n old_match_scores: List[Dict],\n queries_metas: List[Dict],\n matches_metas: List[List[Dict]],\n ) -> List[List[float]]:\n return [\n [m['tags__dummy_score'] for m in match_meta] for match_meta in matches_metas\n ]\n","sub_path":"tests/integration/evaluation/rank/yaml/dummy_ranker.py","file_name":"dummy_ranker.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"273939001","text":"#!/usr/bin/python\n\nimport heapq\nimport math \nimport numpy as np\nimport rtreelib\nimport time\n\n \nclass SingleDimensionalQuery():\n \"\"\"The 'Single Dimensional Query Intervals' algorithm\"\"\"\n\n def __init__(self, query_start, query_end, dimension, rtree, logfile):\n \"\"\"\n The constructor of the class\n\n Parameters: query_start -> [x, y]\n query_end -> [x, y]\n dimension -> int that refers to the dimension the query took place\n rtree -> reference to the implementation of the Rtree with the \n data points\n logfile -> reference to the logfile object\n \"\"\"\n \n self.qs = query_start\n self.qe = query_end\n self.dim = dimension\n self.rtree = rtree\n self.logfile = logfile\n # Range Skyline Set\n self.RSS = []\n \n # The priority heaps\n self.main = []\n self.secondary = [] \n\n self.garbage_time = 0\n self.maximum_main_size = 0\n self.maximum_secondary_size = 0\n self.domination_checks = 0\n \n\n def range_skyline_computation(self):\n \"\"\"\n The backbone of the algorithms implementation\n \"\"\"\n\n # Get the Root node's entries\n for entry in self.rtree.root.entries:\n segment = [self.qs, self.qe]\n self.insert_into_main_heap(entry, segment)\n\n if len(self.main) > self.maximum_main_size:\n self.maximum_main_size = len(self.main)\n \n secondary_heap_empty = False\n while not secondary_heap_empty:\n while len(self.main) != 0:\n e, Le = self.remove_top_entry(self.main)\n \n e_mbr_mindist = self.get_mbr_mindist(e)\n Lee = self.iterate_RSS_for_nonDomination_segment(e_mbr_mindist, Le)\n try: \n # Different starting points\n if Lee[0] != Le[0]:\n # Check if data point or mbr and insert analogously\n if e.is_leaf:\n # Data Point\n self.insert_into_secondary_heap(e, Lee)\n else:\n # MBR\n #self.insert_into_secondary_heap(e, Le)\n for ee in e.child.entries:\n self.insert_into_secondary_heap(ee, Le)\n # Check maximum heap size\n if len(self.secondary) > self.maximum_secondary_size:\n self.maximum_secondary_size = len(self.secondary)\n \n # Same starting points\n else:\n # MBR \n if not e.is_leaf: \n Lee = Le\n for ee in e.child.entries:\n ee_mbr_mindist = self.get_mbr_mindist(ee)\n Leee = self.iterate_RSS_for_nonDomination_segment(ee_mbr_mindist, Lee)\n try: \n # Different starting points\n if Leee[0] != Lee[0]:\n if ee.is_leaf:\n # Data Point\n self.insert_into_secondary_heap(ee, Leee)\n else:\n # MBR\n #self.insert_into_secondary_heap(ee, Lee)\n for eee in ee.child.entries:\n self.insert_into_secondary_heap(eee, Lee)\n # Check maximum heap size\n if len(self.secondary) > self.maximum_secondary_size:\n self.maximum_secondary_size = len(self.secondary)\n else:\n if ee.is_leaf:\n # Data Point\n self.insert_into_main_heap(ee, Leee)\n else:\n # MBR\n #self.insert_into_main_heap(ee, Lee)\n for eee in ee.child.entries:\n self.insert_into_main_heap(eee, Lee)\n # Check maximum heap size\n if len(self.main) > self.maximum_main_size:\n self.maximum_main_size = len(self.main)\n except TypeError:\n pass\n # Leaf - Data Point\n else:\n for index, rss_entry in enumerate(self.RSS):\n rss_point, Lp = rss_entry[0], rss_entry[1]\n # Check for intersection\n Lp_inter_Lee = self.segment_intersection(Lp, Lee)\n if Lp_inter_Lee != None:\n Lpp = self.point_domination(e.data, rss_point, Lp_inter_Lee) \n if Lpp != None:\n # Lp - Lpp\n new_Lp = self.segment_difference(Lp, Lpp)\n self.RSS[index] = [rss_point, new_Lp]\n # Insert the new entry into RSS\n self.RSS.append([e.data, Lee])\n # Clean entries with None as rectangle area\n self.RSS = self.clean_RSS(self.RSS)\n except TypeError:\n pass\n \n if len(self.secondary) == 0:\n secondary_heap_empty = True\n else:\n # Move entries from secondary into main\n self.push_to_main()\n\n\n def priority_main(self, e_mindist, e_segment) -> float:\n \"\"\"\n Calculate the priority of an Rtree entry for the main heap.\n The priority is the distance between the mindist point of Rtree entry\n and the left most point of entry's non dominational segment.\n\n Parameters: e_mindist -> point (x, y)\n e_segment -> segment [(x1, y1), (x2, y2)]\n \n Output: float \n \"\"\"\n \n # Euclidean distance\n x, y = e_mindist[0], e_mindist[1]\n x1, y1 = e_segment[0][0], e_segment[0][1]\n\n return math.sqrt((x-x1)**2 + (y-y1)**2)\n\n\n def priority_secondary(self, segment) -> float:\n \"\"\"\n Calculate the priority of an Rtree entry for the secondary heap.\n The priority is the distance of segment's left starting point (qes)\n from query's left starting point (qs)\n\n Parameters: segment -> line segment [(qes_x, qes_y), (qee_x, qee_y)]\n\n Output : float\n \"\"\"\n\n # The non dominational segment and the query segment are the same segments\n # with the only difference that the non dominational segment might be smaller\n # if a dominational segment has been found previously\n # Therefore the distance of the starting points is the difference qes - qs\n # on the axes the query has taken place\n seg_start = segment[0]\n return seg_start[self.dim - 1] - self.qs[self.dim - 1] \n\n\n def get_mbr_mindist(self, entry) -> (float, float):\n \"\"\"\n Every Rtree Entry represents an MBR.\n The mindist point of an MBR is the point with the \n minimum distance from query's start point qs.\n\n Parameters: entry -> RTreeEntry object, \n entry.rect -> Represents the MBR, \n rect.min_x & rect.min_y is the lower left corner\n rect.max_x & rect.max_y is the top right corner\n \n Output: Point, (x,y)\n \"\"\"\n \n # Query's start point\n qs_x, qs_y = (self.qs[0], self.qs[1])\n # MBR lower left and top right corners\n min_x, min_y = entry.rect.min_x, entry.rect.min_y\n max_x, max_y = entry.rect.max_x, entry.rect.max_y\n\n # Find the relative position of qs to the MBR\n is_top = qs_y > max_y\n is_bottom = qs_y < min_y\n is_left = qs_x < min_x\n is_right = qs_x > max_x\n\n # Return the qs's projection onto the MBR\n if is_top and is_left:\n return [min_x, max_y]\n elif is_top and is_right:\n return [max_x, max_y]\n elif is_bottom and is_left:\n return [min_x, min_y]\n elif is_bottom and is_right:\n return [max_x, min_y]\n elif is_top:\n return [qs_x, max_y]\n elif is_bottom:\n return [qs_x, min_y]\n elif is_left:\n return [min_x, qs_y]\n elif is_right:\n return [max_x, qs_y]\n else:\n # Inside the MBR\n return [qs_x, qs_y]\n\n\n def insert_into_main_heap(self, entry, segment):\n \"\"\"\n Insert into the main heap a new entry \n\n Parameters: entry -> RTreeEntry object\n segment -> segment [(x1, y1), (x2, y2)]\n \"\"\"\n\n mindist_point = self.get_mbr_mindist(entry)\n priority = self.priority_main(mindist_point, segment)\n\n # Use id() in case of priority collision\n heapq.heappush(self.main, [priority, id(entry), entry, segment])\n\n\n def insert_into_secondary_heap(self, entry, segment):\n \"\"\"\n Insert into the secondary heap a new entry\n\n Parameters: entry -> RTreeEntry object\n segment -> segment [(x1,y1), (x2,y2)]\n \"\"\"\n\n priority = self.priority_secondary(segment)\n\n # Use id() in case of priority collision\n heapq.heappush(self.secondary, [priority, id(entry), entry, segment])\n\n\n def remove_top_entry(self, heap) -> [rtreelib.rtree.RTreeEntry , [(float,float),(float,float)]]:\n \"\"\"\n Return the RTreeEntry object and the segment and\n exclude the priority and the id()\n\n Parameters: heap -> list with heap framework\n\n Output: list -> [RTreeEntry, segment]\n segment -> [(x1,y1), (x2,y2)]\n \"\"\"\n \n heap_top_entry = heapq.heappop(heap)\n # Keep only the RtreeEntry and the segment\n return heap_top_entry[2:]\n\n\n def iterate_RSS_for_nonDomination_segment(self, r_point, r_segm) -> [(float,float),(float,float)]:\n \"\"\"\n Checks if there is a non dominational sub segment for r_point, \n in comparison to every point of RSS\n\n Parameters: r_point -> (xr,yr) \n r_segm -> [(xs,ys), (xe,ye)]\n\n Output: segment -> [(x1,y1), (x2,y2)] or None\n \"\"\"\n \n for rss_entry in self.RSS:\n rss_point, rss_segm = rss_entry[0], rss_entry[1]\n\n # I have to check if the r_nonDomination_segm is not None, due to previous function call\n # if it is not I call again the funtion\n # if it is None the for the rest of RSS points I will not process further\n if r_segm != None:\n r_nonDomination_seg = self.nonDomination_segment(rss_point, r_point, rss_segm, r_segm)\n r_segm = r_nonDomination_seg\n else:\n pass\n\n return r_segm\n\n \n def nonDomination_segment(self, p_point, r_point, p_segm, r_segm) -> [(float,float),(float,float)]:\n \"\"\"\n The non domination segment is the current r_segm differentiated by the\n domination segment of p to r in relation to p_segm \n\n Parameters: p_point -> (xp,yp)\n r_point -> (xr,yr)\n p_segm -> [(xp_s,yp_s),(xp_e,yp_e)]\n r_segm -> [(xr_s,yr_s),(xr_e,yr_e)]\n\n Output: segment -> [(x1,y1),(x2,y2)] or None\n \"\"\"\n \n domination_segment = self.point_domination(p_point, r_point, p_segm)\n # To differentiate, the domination_segment has to be != None\n if domination_segment != None:\n non_domination_segment = self.segment_difference(r_segm, domination_segment)\n else:\n non_domination_segment = r_segm\n\n return non_domination_segment\n\n\n def point_domination(self, p_point, r_point, ref_segm) -> [(float,float),(float,float)]:\n \"\"\"\n Calculate the domination segment and if the non query dimensions\n meet the requirements for domination\n\n Parameters: p -> [x1,y1] \n r -> [x2,y2]\n ref_seg -> [(qs_x, qs_y), (qe_x,qe_y)]\n\n Output: Line segment -> [(x, y), (x, y)] or None\n \"\"\"\n # Add a domination check\n self.domination_checks += 1\n \n # Get the dominational segment\n dominational_segm = self.domination_segment(p_point, r_point, ref_segm)\n\n domination = True\n # Check if the domination holds for the rest dimensions\n for indx in range(len(p_point)):\n # Do not take into account the query dimension\n if indx != self.dim -1:\n p_point_dist = abs(self.qs[indx] - p_point[indx])\n r_point_dist = abs(self.qs[indx] - r_point[indx])\n if r_point_dist < p_point_dist:\n domination = False\n \n # Return\n if (dominational_segm != None) and (domination):\n return dominational_segm\n else:\n return None\n\n\n def domination_segment(self, p_point, r_point, ref_segm) -> [(float,float),(float,float)]: \n \"\"\"\n Specifying the range of the coordinate values on the i-axis \n of all the points q that belong to hte ref_seg in relation\n to which p dominates r\n\n Input: p -> [x1,y1] \n r -> [x2,y2]\n ref_seg -> [(qs_x, qs_y), (qe_x,qe_y)]\n\n Output: Line segment -> [(x1, y1), (x2, y2)] or None\n \"\"\"\n \n # Get the points' values on the axis the query took place\n p_val = list(p_point).pop(self.dim - 1)\n r_val = list(r_point).pop(self.dim - 1)\n qs_val = list(ref_segm[0]).pop(self.dim - 1)\n qe_val = list(ref_segm[1]).pop(self.dim - 1)\n\n # Find the relative position of the values\n range_values= None\n if (p_val < r_val):\n # No.2\n if (p_val <= qs_val <= r_val <= qe_val) and (2*qs_val <= p_val + r_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n # No.3\n elif (p_val <= qs_val <= qe_val <= r_val):\n if (2*qs_val <= p_val + r_val <= 2*qe_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n elif (2*qe_val <= p_val+r_val):\n range_values= [qs_val, qe_val]\n # No.4\n elif (qs_val <= p_val <= qe_val <= r_val):\n if (p_val+r_val <= 2*qe_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n else:\n range_values= [qs_val, qe_val]\n # No.5\n elif (qs_val <= p_val < r_val <= qe_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n # No.6\n elif (qs_val <= qe_val <= p_val < r_val):\n range_values= [qs_val, qe_val]\n elif (r_val < p_val):\n # No.7\n if (r_val < p_val <= qs_val <= qe_val):\n range_values= [qs_val, qe_val]\n # No.8\n elif (r_val <= qs_val <= p_val <= qe_val):\n if ( 2*qs_val <= p_val+r_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n else:\n range_values= [qs_val, qe_val]\n # No.9\n elif (r_val <= qs_val <= qe_val <= p_val):\n if (2*qe_val <= p_val+r_val):\n pass\n elif (2*qs_val <= p_val+r_val <= 2*qe_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n else:\n range_values= [qs_val, qe_val]\n # No.10\n elif (qs_val <= r_val <= qe_val <= p_val) and (p_val+r_val <= 2*qe_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n # No.11\n elif (qs_val <= r_val < p_val <= qe_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n elif (r_val == p_val):\n range_values= [qs_val, qe_val]\n \n # Construct the segment by adding the other dimensions\n if range_values!= None:\n segment = []\n # range(2), cause start and end points\n for indx1 in range(2):\n segment_point = []\n for indx2 in range(len(self.qs)):\n if indx2 != self.dim - 1:\n segment_point.append(self.qs[indx2])\n else:\n segment_point.append(range_values[indx1])\n segment.append(tuple(segment_point))\n else:\n segment = None\n\n # Return the segment\n return segment\n\n\n def segment_difference(self, segm_a, segm_b) -> [(float,float),(float,float)]:\n \"\"\"\n Given two segments, the difference between segm_a and segm_b is \n segm_a - segm_b\n\n Parameters: segm_a -> [(xa1,ya1),(xa2,ya2)]\n segm_b -> [(xb1,yb1),(xb2,yb2)]\n \n Output: segment -> [(x1,y1),(x2,y2)]\n \"\"\"\n\n # Garbage time\n start_time = time.time()\n\n # Take the values on the axis that the query took place\n segm_a_start = segm_a[0][self.dim - 1]\n segm_a_end = segm_a[1][self.dim - 1]\n segm_b_start = segm_b[0][self.dim - 1]\n segm_b_end = segm_b[1][self.dim - 1]\n\n # Create a range from start to end for the segments\n segm_a_range = [round(float(item), 3) for item in np.arange(segm_a_start, segm_a_end + 0.001, 0.001) if round(float(item), 3) <= segm_a_end]\n segm_b_range = [round(float(item), 3) for item in np.arange(segm_b_start, segm_b_end + 0.001, 0.001) if round(float(item), 3) <= segm_b_end]\n\n # Take the difference of the two ranges/segments\n diff = list(set(segm_a_range) - set(segm_b_range))\n # Sort the difference\n diff.sort()\n\n # Construct the new segment\n if diff:\n # Keep only the first and last element\n diff = [diff[0], diff[len(diff)-1]]\n final_segment = []\n for indx1 in range(2):\n segment_point = []\n for indx2 in range(len(self.qs)):\n if indx2 != self.dim - 1:\n segment_point.append(self.qs[indx2])\n else:\n segment_point.append(diff[indx1])\n final_segment.append(tuple(segment_point))\n else:\n final_segment = None\n \n self.garbage_time += time.time() - start_time\n\n # Return\n return final_segment\n\n\n def segment_intersection(self, segm_a, segm_b) -> [(float,float),(float,float)]:\n \"\"\"\n Calculate the intersection of two segments\n\n Parameters: segm_a -> [(xa1,ya1),(xa2,ya2)]\n segm_b -> [(xb1,yb1),(xb2,yb2)]\n \n Output: segment -> [(x1,y1),(x2,y2)] \n \"\"\"\n\n # Garbage time\n start_time = time.time()\n\n # Take the values on the axis that the query took place\n segm_a_start = segm_a[0][self.dim - 1]\n segm_a_end = segm_a[1][self.dim - 1]\n segm_b_start = segm_b[0][self.dim - 1]\n segm_b_end = segm_b[1][self.dim - 1]\n \n # Create a range from start to end for the segments\n segm_a_range = [round(float(item), 3) for item in np.arange(segm_a_start, segm_a_end + 0.001, 0.001) if round(float(item), 3) <= segm_a_end]\n segm_b_range = [round(float(item), 3) for item in np.arange(segm_b_start, segm_b_end + 0.001, 0.001) if round(float(item), 3) <= segm_b_end]\n\n # Take the difference of the two ranges/segments\n diff = list(set(segm_a_range) & set(segm_b_range))\n # Sort the difference\n diff.sort()\n\n # Construct the new segment\n if diff:\n # Keep only the first and last element\n diff = [diff[0], diff[len(diff)-1]]\n final_segment = []\n for indx1 in range(2):\n segment_point = []\n for indx2 in range(len(self.qs)):\n if indx2 != self.dim - 1:\n segment_point.append(self.qs[indx2])\n else:\n segment_point.append(diff[indx1])\n final_segment.append(tuple(segment_point))\n else:\n final_segment = None\n \n self.garbage_time += time.time() - start_time\n\n # Return\n return final_segment\n\n\n def push_to_main(self):\n \"\"\"\n Pushes the entries with higher priority into the queue from the secondary heap \n to the main heap\n \"\"\"\n\n # Take top entry \n rtree_entry, segment = self.remove_top_entry(self.secondary)\n self.insert_into_main_heap(rtree_entry, segment)\n\n backup_list = []\n for index in range(len(self.secondary)):\n next_rtree_entry, next_segment = self.remove_top_entry(self.secondary)\n if next_segment[0] == segment[0]:\n self.insert_into_main_heap(next_rtree_entry, next_segment)\n else:\n backup_list.append([next_rtree_entry, next_segment])\n\n # Put back to secondary heap \n for pair in backup_list:\n self.insert_into_secondary_heap(pair[0], pair[1]) \n\n # Check maximum heap size\n if len(self.main) > self.maximum_main_size:\n self.maximum_main_size = len(self.main)\n if len(self.secondary) > self.maximum_secondary_size:\n self.maximum_secondary_size = len(self.secondary)\n\n\n def clean_RSS(self, RSS) -> list:\n \"\"\"\n Takes away the entries that have None as a rectangle area\n\n Parameters: list -> [ [point, rectangle area], [point, None], ... ]\n\n Output: list -> [ [point1, rectangle area1], [point2, rectangle area2], ...]\n \"\"\"\n clean_RSS = []\n for item in RSS:\n rectangle_area = item[1]\n if rectangle_area != None:\n clean_RSS.append(item)\n \n # Return\n return clean_RSS","sub_path":"implementation/algorithms/algos_without_logs/single_dimensional_query.py","file_name":"single_dimensional_query.py","file_ext":"py","file_size_in_byte":23048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"616191867","text":"import random\r\n\r\n#Variables\r\n#Main game loop\r\nplayingGame = 1\r\n\r\n#Tictactoe game loop\r\nstartingGame = 0\r\n\r\n#Tictactoe board array\r\nboardArr = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\r\n\r\n#Player Turn\r\nplayerTurn = 1\r\n\r\n#Check if players action is correct\r\nswitchPlayer = -1\r\n\r\n#Total turns of all players\r\ntotalPlayerTurns = 0\r\n\r\n#Error checks in choosing human or computer\r\nerrorTypeCheck1 = 0\r\n\r\n#Functions\r\ndef showBoard():\r\n #Start counting from the first index of the array\r\n sType = 1\r\n while sType <= 9:\r\n print(boardArr[sType-1],\"|\", end='') #Print the boxes, sType-1 since array starts with 0\r\n if(sType % 3 == 0): #If the counting is divisible by 3 then add a new line(since the are only 3 boxes per row)\r\n print(\"\")\r\n print(\"---------\")\r\n sType += 1 #proceed to the next index of the array\r\n\r\ndef placeTurn(loc, player): #Give the function the location of the turn and the player\r\n if loc.isdigit():\r\n #check if the numbers are between 1-9\r\n loc = int(loc)\r\n if loc > 9 or loc < 1:\r\n print(\"Please enter numbers between 1-9\")\r\n global switchPlayer\r\n switchPlayer = -1\r\n return\r\n else:\r\n #check if the entered value is an integer\r\n print(\"Please enter numbers between 1-9\")\r\n switchPlayer = -1\r\n return\r\n \r\n #If the choosen location has already a place\r\n if boardArr[loc-1] == \"X\" or boardArr[loc-1] == \"O\":\r\n print(\"Place already set! Please choose another number!\")\r\n switchPlayer = -1\r\n else:\r\n #if no errors then place the turn\r\n switchPlayer = 0\r\n if player == 1:\r\n boardArr[loc-1] = \"X\"\r\n else:\r\n boardArr[loc-1] = \"O\"\r\n global totalPlayerTurns\r\n totalPlayerTurns += 1 #add the total player turns\r\n\r\ndef checkWin():\r\n #if playerWinner is 0, it is tie\r\n #if playerWinner is 1, then player 1 wins\r\n #if 2 then player 2 wins\r\n \r\n playerWinner = 0\r\n \r\n #Player 1\r\n shape = \"X\"\r\n \r\n #Horizontal Win Check\r\n if boardArr[0] == shape and boardArr[1] == shape and boardArr[2] == shape: playerWinner = 1\r\n if boardArr[3] == shape and boardArr[4] == shape and boardArr[5] == shape: playerWinner = 1\r\n if boardArr[6] == shape and boardArr[7] == shape and boardArr[8] == shape: playerWinner = 1\r\n\r\n #Vertical Win Check\r\n if boardArr[0] == shape and boardArr[3] == shape and boardArr[6] == shape: playerWinner = 1\r\n if boardArr[1] == shape and boardArr[4] == shape and boardArr[7] == shape: playerWinner = 1\r\n if boardArr[2] == shape and boardArr[5] == shape and boardArr[8] == shape: playerWinner = 1\r\n\r\n #Diagonal Win Check\r\n if boardArr[0] == shape and boardArr[4] == shape and boardArr[8] == shape: playerWinner = 1\r\n if boardArr[2] == shape and boardArr[4] == shape and boardArr[6] == shape: playerWinner = 1\r\n\r\n #Player 2\r\n shape = \"O\"\r\n \r\n #Horizontal Win Check\r\n if boardArr[0] == shape and boardArr[1] == shape and boardArr[2] == shape: playerWinner = 2\r\n if boardArr[3] == shape and boardArr[4] == shape and boardArr[5] == shape: playerWinner = 2\r\n if boardArr[6] == shape and boardArr[7] == shape and boardArr[8] == shape: playerWinner = 2\r\n\r\n #Vertical Win Check\r\n if boardArr[0] == shape and boardArr[3] == shape and boardArr[6] == shape: playerWinner = 2\r\n if boardArr[1] == shape and boardArr[4] == shape and boardArr[7] == shape: playerWinner = 2\r\n if boardArr[2] == shape and boardArr[5] == shape and boardArr[8] == shape: playerWinner = 2\r\n\r\n #Diagonal Win Check\r\n if boardArr[0] == shape and boardArr[4] == shape and boardArr[8] == shape: playerWinner = 2\r\n if boardArr[2] == shape and boardArr[4] == shape and boardArr[6] == shape: playerWinner = 2\r\n\r\n global startingGame\r\n if playerWinner == 1:\r\n print(\"PLAYER 1 WINS!\")\r\n showBoard()\r\n startingGame = 0 #End the game\r\n if playerWinner == 2:\r\n print(\"PLAYER 2 WINS!\")\r\n showBoard()\r\n startingGame = 0 #End the game\r\n \r\n #if all the board is placed and there is no winner, then it is a tie\r\n if totalPlayerTurns == 9 and playerWinner == 0:\r\n print(\"Its a tie!!\")\r\n showBoard()\r\n startingGame = 0 #End the game\r\n\r\ndef resetVariables():\r\n global playingGame, startingGame, boardArr, playerTurn, switchPlayer, totalPlayerTurns, errorTypeCheck1\r\n playingGame = 1\r\n startingGame = 0\r\n boardArr = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\r\n playerTurn = 1\r\n switchPlayer = -1\r\n totalPlayerTurns = 0\r\n errorTypeCheck1 = 0\r\n\r\n#Main Loop\r\nwhile playingGame == 1:\r\n\r\n #if playerType is 0, human vs human\r\n #if 1, comp vs human\r\n playerType = -1\r\n\r\n #the selected place turn of the player\r\n playerChoose = -1\r\n \r\n print(\"Tic-tac-toe Game\")\r\n playerType = input(\"Enter 0 for human vs human and 1 for Computer vs human: \")\r\n \r\n if playerType == \"0\":\r\n errorTypeCheck1 = 0\r\n startingGame = 1\r\n print(\"Human vs Human\")\r\n \r\n while startingGame == 1: #Nested loop\r\n showBoard()\r\n print(\"Player\", playerTurn, \": \")\r\n #Ask for the turn\r\n playerChoose = input(\"Please choose a number to place your mark: \")\r\n placeTurn(playerChoose, playerTurn)\r\n\r\n #If the player is good to switch turn with player 2 or 1, then switch\r\n if switchPlayer == 0:\r\n if playerTurn == 1:\r\n playerTurn = 2\r\n elif playerTurn == 2:\r\n playerTurn = 1\r\n checkWin()\r\n \r\n elif playerType == \"1\":\r\n errorTypeCheck1 = 0\r\n startingGame = 1\r\n print(\"Computer vs Human\")\r\n \r\n while startingGame == 1: #Nested loop\r\n showBoard()\r\n print(\"Player\", playerTurn, \": \", end='')\r\n\r\n if playerTurn == 1:\r\n playerChoose = input(\"Please choose a number to place your mark: \")\r\n else:\r\n playerChoose = str(random.randint(1,9)) #computer will choose a number between 1-9, convert it to string since there will be a checker and str to int converter\r\n print(playerChoose)\r\n #if the random number has already a place, then continue to choose a random number until there is none placed on the selected place\r\n while boardArr[int(playerChoose)-1] == \"X\" or boardArr[int(playerChoose)-1] == \"O\":\r\n playerChoose = str(random.randint(1,9))\r\n \r\n placeTurn(playerChoose, playerTurn)\r\n \r\n #If the player is good to switch turn with player 2 or 1, then switch\r\n if switchPlayer == 0:\r\n if playerTurn == 1:\r\n playerTurn = 2\r\n elif playerTurn == 2:\r\n playerTurn = 1\r\n checkWin()\r\n else:\r\n print(\"Please enter 0 or 1.\")\r\n errorTypeCheck1 = 1\r\n\r\n #If no errors\r\n if errorTypeCheck1 == 0:\r\n #Game End\r\n playAgain = input(\"Do you want to play again? y/n: \")\r\n \r\n if playAgain == \"n\" or playAgain == \"N\":\r\n print(\"Thank you for playing! Goodbye!\")\r\n playingGame = 0 #End the main loop\r\n \r\n if playAgain == \"y\" or playAgain == \"Y\":\r\n resetVariables()\r\n startingGame == 1 #Start again the nested loop\r\n","sub_path":"Tictactoe_Game.py","file_name":"Tictactoe_Game.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"597473390","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.utils.data import DataLoader, Dataset, random_split\nfrom sklearn.preprocessing import QuantileTransformer, StandardScaler, MinMaxScaler\nimport pytorch_lightning as pl\nimport pickle\nfrom random import randint, sample\nfrom ExpressiveDataset import ExpressiveDataset\nfrom utils import *\n\n\nclass LinearBlock(nn.Module):\n def __init__(self, in_size, out_size, norm=True, act=True):\n super().__init__()\n self.linear = nn.Linear(in_size, out_size)\n self.norm = nn.LayerNorm(out_size) if norm else None\n self.act = act\n\n def forward(self, x):\n x = self.linear(x)\n if self.norm is not None:\n x = self.norm(x)\n if self.act:\n x = nn.functional.leaky_relu(x)\n return x\n\n\nclass ModelCategorical(pl.LightningModule):\n def __init__(self, in_size, hidden_size, out_size, scalers):\n super().__init__()\n self.save_hyperparameters()\n self.scalers = scalers\n self.loudness_nbins = 30\n self.ddsp = torch.jit.load(\"results/ddsp_debug_pretrained.ts\").eval()\n\n self.pre_lstm = nn.Sequential(\n LinearBlock(in_size, hidden_size),\n LinearBlock(hidden_size, hidden_size),\n )\n\n self.lstm = nn.GRU(\n hidden_size,\n hidden_size,\n num_layers=1,\n batch_first=True,\n )\n\n self.post_lstm = nn.Sequential(\n LinearBlock(hidden_size, hidden_size),\n LinearBlock(\n hidden_size,\n out_size,\n norm=False,\n act=False,\n ),\n )\n\n def configure_optimizers(self):\n return torch.optim.Adam(\n self.parameters(),\n lr=1e-4,\n weight_decay=.01,\n )\n\n def forward(self, x):\n x = self.pre_lstm(x)\n x = self.lstm(x)[0]\n x = self.post_lstm(x)\n return x\n\n def split_predictions(self, prediction):\n pred_f0 = prediction[..., :100]\n pred_cents = prediction[..., 100:200]\n pred_loudness = prediction[..., 200:]\n return pred_f0, pred_cents, pred_loudness\n\n def cross_entropy(self, pred_f0, pred_cents, pred_loudness, target_f0,\n target_cents, target_loudness):\n pred_f0 = pred_f0.permute(0, 2, 1)\n pred_cents = pred_cents.permute(0, 2, 1)\n pred_loudness = pred_loudness.permute(0, 2, 1)\n\n target_f0 = target_f0.squeeze(-1)\n target_cents = target_cents.squeeze(-1)\n target_loudness = target_loudness.squeeze(-1)\n\n loss_f0 = nn.functional.cross_entropy(pred_f0, target_f0)\n loss_cents = nn.functional.cross_entropy(pred_cents, target_cents)\n loss_loudness = nn.functional.cross_entropy(\n pred_loudness,\n target_loudness,\n )\n\n return loss_f0, loss_cents, loss_loudness\n\n def training_step(self, batch, batch_idx):\n model_input, target = batch\n prediction = self.forward(model_input.float())\n\n pred_f0, pred_cents, pred_loudness = self.split_predictions(prediction)\n target_f0, target_cents, target_loudness = torch.split(target, 1, -1)\n\n loss_f0, loss_cents, loss_loudness = self.cross_entropy(\n pred_f0,\n pred_cents,\n pred_loudness,\n target_f0,\n target_cents,\n target_loudness,\n )\n\n self.log(\"loss_f0\", loss_f0)\n self.log(\"loss_cents\", loss_cents)\n self.log(\"loss_loudness\", loss_loudness)\n\n return loss_f0 + loss_cents + loss_loudness\n\n def sample_one_hot(self, x):\n n_bin = x.shape[-1]\n sample = torch.distributions.Categorical(logits=x).sample()\n sample = nn.functional.one_hot(sample, n_bin)\n return sample\n\n @torch.no_grad()\n def generation_loop(self, x, infer_pitch=False):\n context = None\n\n for i in range(x.shape[1] - 1):\n x_in = x[:, i:i + 1]\n\n x_out = self.pre_lstm(x_in)\n x_out, context = self.lstm(x_out, context)\n x_out = self.post_lstm(x_out)\n pred_f0, pred_cents, pred_loudness = self.split_predictions(x_out)\n\n if infer_pitch:\n f0 = self.sample_one_hot(pred_f0)\n else:\n f0 = x[:, i + 1:i + 2, :100].float()\n\n cents = self.sample_one_hot(pred_cents)\n loudness = self.sample_one_hot(pred_loudness)\n\n cat = torch.cat([f0, cents, loudness], -1)\n ndim = cat.shape[-1]\n\n x[:, i + 1:i + 2, -ndim:] = cat\n\n pred = x[..., -ndim:]\n pred_f0, pred_cents, pred_loudness = self.split_predictions(pred)\n\n pred_f0 = pred_f0[:, 1:]\n pred_loudness = pred_loudness[:, 1:]\n pred_cents = pred_cents[:, :-1]\n\n out = map(lambda x: torch.argmax(x, -1),\n [pred_f0, pred_cents, pred_loudness])\n\n return list(out)\n\n def apply_inverse_transform(self, x, idx):\n scaler = self.scalers[idx]\n x = x.cpu()\n out = scaler.inverse_transform(x.reshape(-1, 1))\n out = torch.from_numpy(out).to(\"cuda\")\n out = out.unsqueeze(0)\n return out.float()\n\n def get_audio(self, model_input, target):\n\n model_input = model_input.unsqueeze(0).float()\n f0, cents, loudness = self.generation_loop(model_input)\n cents = cents / 100 - .5\n\n f0 = pctof(f0, cents)\n\n loudness = loudness / (self.loudness_nbins - 1)\n f0 = self.apply_inverse_transform(f0.squeeze(0), 0)\n loudness = self.apply_inverse_transform(loudness.squeeze(0), 1)\n y = self.ddsp(f0, loudness)\n return y\n\n def validation_step(self, batch, batch_idx):\n model_input, target = batch\n prediction = self.forward(model_input.float())\n\n pred_f0, pred_cents, pred_loudness = self.split_predictions(prediction)\n target_f0, target_cents, target_loudness = torch.split(target, 1, -1)\n\n loss_f0, loss_cents, loss_loudness = self.cross_entropy(\n pred_f0,\n pred_cents,\n pred_loudness,\n target_f0,\n target_cents,\n target_loudness,\n )\n\n self.log(\"val_loss_f0\", loss_f0)\n self.log(\"val_loss_cents\", loss_cents)\n self.log(\"val_loss_loudness\", loss_loudness)\n self.log(\"val_total\", loss_f0 + loss_cents + loss_loudness)\n\n ## Every 100 epochs : produce audio\n\n if self.current_epoch % 200 == 0:\n\n audio = self.get_audio(model_input[0], target[0])\n # output audio in Tensorboard\n tb = self.logger.experiment\n n = \"Epoch={}\".format(self.current_epoch)\n tb.add_audio(tag=n, snd_tensor=audio, sample_rate=16000)\n\n\nif __name__ == \"__main__\":\n\n trainer = pl.Trainer(\n gpus=1,\n callbacks=[pl.callbacks.ModelCheckpoint(monitor=\"val_total\")],\n max_epochs=50000,\n )\n list_transforms = [\n (Identity, ), # u_f0 \n (MinMaxScaler, ), # u_loudness\n (Identity, ), # e_f0\n (Identity, ), # e_cents\n (MinMaxScaler, ), # e_loudness\n ]\n\n dataset = ExpressiveDataset(n_sample=512, list_transforms=list_transforms)\n val_len = len(dataset) // 20\n train_len = len(dataset) - val_len\n\n train, val = random_split(dataset, [train_len, val_len])\n\n model = ModelCategorical(360, 1024, 230, scalers=dataset.scalers)\n\n trainer.fit(\n model,\n DataLoader(train, 32, True),\n DataLoader(val, 32),\n )\n","sub_path":"models/LSTMCategorical.py","file_name":"LSTMCategorical.py","file_ext":"py","file_size_in_byte":7574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"295195123","text":"'''\nCreated on Oct 24, 2016\n\n@author: Titus\n'''\ndef ui_add_expense(expenses, params):\n ''' \n Adds an expense to the expenses list\n \n Input - expenses : the list of all the expenses\n params : the list of parameters ( sum, category )\n \n Output - \n '''\n day = 0\n sum = int(params[0])\n category = params[1]\n expenses.append(add_expense(day,sum,category))\n\n\ndef ui_insert_expense(expenses, params):\n '''\n Inserts an expense to the expenses list\n \n Input - expenses : the list of all the expenses\n params : the list of parameters ( day, sum, category )\n \n Output - \n '''\n day = int(params[0])\n sum = int(params[1])\n category = params[2]\n expenses.append(add_expense(day,sum,category))\n\n\ndef ui_remove_expense(expenses, params):\n '''\n Removes expenses from the expenses list depending on the parameters\n \n Input - expenses : the list of all the expenses\n params : the list of paramaters ( day ) or ( starting day , ending day ) or ( category )\n \n Output - \n '''\n if len(params) is 1:\n try:\n day = int(params[0])\n remove_day(expenses, day)\n except ValueError:\n category = params[0]\n remove_category(expenses, category)\n if len(params) is 3:\n if params[1] == 'to':\n startDay = int(params[0])\n endDay = int(params[2])\n remove_day_to_day(expenses, startDay, endDay)\n \n\ndef ui_list_expense(expenses, params):\n '''\n Prints the expenses from the expenses list depending on the parameters\n \n Input - expenses : the list of all the expenses\n params : the list of paramaters ( ) or ( category ) or ( category, operand, value )\n \n Output - \n '''\n if len(params) is 0:\n list_all(expenses)\n \n if len(params) is 1:\n category = params[0]\n list_category(expenses, category)\n \n if len(params) is 3:\n category = params[0]\n operant = params[1]\n value = params[2]\n if operant == '<':\n list_category_lower(expenses, category, value)\n if operant == '>':\n list_category_upper(expenses, category, value)\n if operant == '=':\n list_category_equal(expenses, category, value)\n \n \ndef ui_sum_category(expenses, params):\n '''\n Prints the total expense for a given category\n \n Input - expenses : the list of all the expenses\n params : the list of parameters, expected only one ( category )\n \n Output - \n '''\n if len(params) is 1:\n category = params[0]\n print('The total expense for', category, 'is', sum_category(expenses, category))\n\n\ndef ui_max_day(expenses, params):\n pass\n# '''\n# Prints the category with the maximum expenses from the expenses list\n# \n# Input - expenses : the list of all the expenses\n# params : the list of parameters, expected only one ( day )\n# \n# Output - \n# '''\n# if len(params) is 1:\n# day = params[0]\n# print('The category with most expenses for the day', day, 'is', maximum_expense_day(expenses, day))\n\n\ndef ui_sort_expense(expenses, params):\n '''\n Prints the sorted expenses ( by the amount of money spend ) from the expenses list\n depending on the parameters\n \n Input - expenses : the list of all the expenses\n params : the list of parameters ( day ) or ( category )\n \n Output - \n '''\n if len(params) is 1:\n try:\n day = int(params[0])\n sort_expense_day(expenses, day)\n except ValueError:\n category = params[0]\n sort_expense_category(expenses, category)\n \n","sub_path":"2-4/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"490790666","text":"import sys\nimport threading\nfrom NLP import *\nfrom DB import *\nfrom GEO import *\nimport time\n\n\ndef GEOJOB():\n db = DBO()\n maps = GEO()\n table_tweets = Tweets(db)\n table_locations = Locations(db)\n while True:\n places = table_tweets.get_place()\n for place in places:\n (p,) = place\n cordinate = maps.geocode(p)\n if cordinate is not None:\n table_locations.insert(p,cordinate['lat'],cordinate['lng']) \n time.sleep(120)\n\ndef NLPJOB():\n db = DBO()\n nlp = NLPEngine()\n table_tweets = Tweets(db)\n while True:\n tweets = table_tweets.get_tweets_wo_sentiment()\n for tweet in tweets:\n TWTID = tweet[0]\n text = tweet[5]\n score = nlp.sentiment(text)\n place = nlp.place(text)\n table_tweets.update_sentiment(TWTID, score)\n if place is not None:\n table_tweets.update_place(TWTID, place)\n time.sleep(60)\n\ndef main(argv):\n GEOThread = threading.Thread(target = GEOJOB)\n \n NLPThread = threading.Thread(target = NLPJOB)\n GEOThread.start()\n NLPThread.start()\n\n GEOThread.join()\n NLPThread.join()\n \nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"Analyst.py","file_name":"Analyst.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"488948667","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('attendance', '0005_auto_20151231_1702'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ClockRecord',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('time', models.DateTimeField(verbose_name='\\u65f6\\u95f4')),\n ('place', models.ForeignKey(to='attendance.Place')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': '\\u6253\\u5361\\u8bb0\\u5f55',\n 'verbose_name_plural': '\\u6253\\u5361\\u8bb0\\u5f55',\n },\n ),\n migrations.CreateModel(\n name='Setting',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n options={\n 'verbose_name': '\\u8003\\u52e4\\u8bbe\\u7f6e',\n 'verbose_name_plural': '\\u8003\\u52e4\\u8bbe\\u7f6e',\n },\n ),\n ]\n","sub_path":"Documents/backupCode/allapps/attendance/migrations/0006_clockrecord_setting.py","file_name":"0006_clockrecord_setting.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"456257931","text":"# ballot/controllers.py\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\nfrom .models import BallotItemListManager, OFFICE, CANDIDATE, MEASURE\nfrom candidate.models import CandidateCampaignList\nfrom config.base import get_environment_variable\nfrom exception.models import handle_exception\nfrom measure.models import ContestMeasureList\nfrom office.models import ContestOfficeList\nfrom voter.models import fetch_voter_id_from_voter_device_link\nimport wevote_functions.admin\nfrom wevote_functions.functions import is_voter_device_id_valid, positive_value_exists\n\nlogger = wevote_functions.admin.get_logger(__name__)\n\nGOOGLE_CIVIC_API_KEY = get_environment_variable(\"GOOGLE_CIVIC_API_KEY\")\n\n\ndef voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):\n \"\"\"\n\n :param voter_device_id:\n :param google_civic_election_id: This variable either was stored in a cookie, or passed in explicitly so we can\n get the ballot items related to that election.\n :return:\n \"\"\"\n # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer\n results = is_voter_device_id_valid(voter_device_id)\n if not results['success']:\n json_data = {\n 'status': 'VALID_VOTER_DEVICE_ID_MISSING',\n 'success': False,\n 'voter_id': 0,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': [],\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'success': False,\n 'json_data': json_data,\n 'google_civic_election_id': 0, # Force the clearing of google_civic_election_id\n }\n return results\n\n voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)\n if not positive_value_exists(voter_id):\n json_data = {\n 'status': \"VALID_VOTER_ID_MISSING\",\n 'success': False,\n 'voter_id': voter_id,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': [],\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'success': False,\n 'json_data': json_data,\n 'google_civic_election_id': 0, # Force the clearing of google_civic_election_id\n }\n return results\n\n ballot_item_list_manager = BallotItemListManager()\n # If we get here without a google_civic_election_id, we need to choose one from the ballot items that are already\n # stored. If we proceed to retrieve_all_ballot_items_for_voter without a google_civic_election_id, we will get\n # ballot items from a variety of elections.\n # This logic looks for all of the elections we have ballot information for, and displays the most recent election\n # (not counting the test election)\n if not positive_value_exists(google_civic_election_id):\n google_civic_election_id = ballot_item_list_manager.fetch_most_recent_google_civic_election_id()\n\n # If an election id STILL wasn't found, then we probably don't have any ballot items stored locally, so we\n # need to go out to google civic. BUT we will proceed and attempt to retrieve ballot items without an election_id\n\n ballot_item_list = []\n ballot_items_to_display = []\n try:\n results = ballot_item_list_manager.retrieve_all_ballot_items_for_voter(voter_id, google_civic_election_id)\n success = results['success']\n status = results['status']\n ballot_item_list = results['ballot_item_list']\n except Exception as e:\n status = 'FAILED voter_ballot_items_retrieve. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n success = False\n\n if success:\n for ballot_item in ballot_item_list:\n if ballot_item.contest_office_we_vote_id:\n kind_of_ballot_item = OFFICE\n ballot_item_id = ballot_item.contest_office_id\n we_vote_id = ballot_item.contest_office_we_vote_id\n try:\n candidate_list_object = CandidateCampaignList()\n results = candidate_list_object.retrieve_all_candidates_for_office(ballot_item_id, we_vote_id)\n candidates_to_display = []\n if results['candidate_list_found']:\n candidate_list = results['candidate_list']\n for candidate in candidate_list:\n # This should match values returned in candidates_retrieve_for_api\n one_candidate = {\n 'id': candidate.id,\n 'we_vote_id': candidate.we_vote_id,\n 'ballot_item_display_name': candidate.candidate_name,\n 'candidate_photo_url': candidate.fetch_photo_url(),\n 'order_on_ballot': candidate.order_on_ballot,\n 'kind_of_ballot_item': CANDIDATE,\n }\n candidates_to_display.append(one_candidate.copy())\n except Exception as e:\n # status = 'FAILED candidates_retrieve. ' \\\n # '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))\n candidates_to_display = []\n one_ballot_item = {\n 'ballot_item_display_name': ballot_item.ballot_item_display_name,\n 'google_civic_election_id': ballot_item.google_civic_election_id,\n 'google_ballot_placement': ballot_item.google_ballot_placement,\n 'local_ballot_order': ballot_item.local_ballot_order,\n 'kind_of_ballot_item': kind_of_ballot_item,\n 'id': ballot_item_id,\n 'we_vote_id': we_vote_id,\n 'candidate_list': candidates_to_display,\n }\n ballot_items_to_display.append(one_ballot_item.copy())\n elif ballot_item.contest_measure_we_vote_id:\n kind_of_ballot_item = MEASURE\n ballot_item_id = ballot_item.contest_measure_id\n we_vote_id = ballot_item.contest_measure_we_vote_id\n one_ballot_item = {\n 'ballot_item_display_name': ballot_item.ballot_item_display_name,\n 'google_civic_election_id': ballot_item.google_civic_election_id,\n 'google_ballot_placement': ballot_item.google_ballot_placement,\n 'local_ballot_order': ballot_item.local_ballot_order,\n 'kind_of_ballot_item': kind_of_ballot_item,\n 'id': ballot_item_id,\n 'we_vote_id': we_vote_id,\n }\n ballot_items_to_display.append(one_ballot_item.copy())\n\n json_data = {\n 'status': 'VOTER_BALLOT_ITEMS_RETRIEVED',\n 'success': True,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': ballot_items_to_display,\n 'google_civic_election_id': google_civic_election_id,\n }\n else:\n json_data = {\n 'status': status,\n 'success': False,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': [],\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'success': success,\n 'google_civic_election_id': google_civic_election_id, # We want to save google_civic_election_id in cookie\n 'json_data': json_data,\n }\n return results\n\n\ndef ballot_item_options_retrieve_for_api(google_civic_election_id=0):\n \"\"\"\n This function returns a normalized list of candidates and measures so we can pre-populate form fields\n :param google_civic_election_id:\n :return:\n \"\"\"\n\n status = \"\"\n try:\n candidate_list_object = CandidateCampaignList()\n results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(google_civic_election_id)\n candidate_success = results['success']\n status += results['status']\n candidate_list = results['candidate_list_light']\n except Exception as e:\n status += 'FAILED ballot_item_options_retrieve_for_api, candidate_list. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n candidate_list = []\n candidate_success = False\n\n try:\n office_list_object = ContestOfficeList()\n results = office_list_object.retrieve_all_offices_for_upcoming_election(google_civic_election_id)\n office_success = results['success']\n status += ' ' + results['status']\n office_list = results['office_list_light']\n except Exception as e:\n status += 'FAILED ballot_item_options_retrieve_for_api, office_list. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n office_list = []\n office_success = False\n\n try:\n measure_list_object = ContestMeasureList()\n results = measure_list_object.retrieve_all_measures_for_upcoming_election(google_civic_election_id)\n measure_success = results['success']\n status += ' ' + results['status']\n measure_list = results['measure_list_light']\n except Exception as e:\n status += 'FAILED ballot_item_options_retrieve_for_api, measure_list. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n measure_list = []\n measure_success = False\n\n ballot_items_to_display = []\n if candidate_success and len(candidate_list):\n for candidate in candidate_list:\n ballot_items_to_display.append(candidate.copy())\n\n if office_success and len(office_list):\n for office in office_list:\n ballot_items_to_display.append(office.copy())\n\n if measure_success and len(measure_list):\n for measure in measure_list:\n ballot_items_to_display.append(measure.copy())\n\n json_data = {\n 'status': status,\n 'success': candidate_success or measure_success,\n 'ballot_item_list': ballot_items_to_display,\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'status': status,\n 'success': candidate_success or measure_success,\n 'google_civic_election_id': google_civic_election_id, # We want to save google_civic_election_id in cookie\n 'json_data': json_data,\n }\n return results\n","sub_path":"ballot/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":11071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"147118374","text":"\r\nimport numpy as np\r\n\r\nfrom utils import read_variable\r\n\r\n\r\ntest_Y = np.zeros(1183748)\r\nrow_start = 0\r\nrow_end = 0\r\nfor chunk_id in range(1184):\r\n \r\n path = 'final/test_votes_1L/'+str(chunk_id)\r\n votes = read_variable(path)\r\n\r\n chunk_Y_pred = (np.sum(votes,axis=1)>=1).astype(np.int)\r\n print(chunk_id,'1s:',sum(chunk_Y_pred))\r\n \r\n row_end = row_start+len(chunk_Y_pred)\r\n\r\n test_Y[row_start:row_end] = chunk_Y_pred\r\n row_start = row_end\r\n \r\nprint('FINAL 1s:',sum(test_Y))\r\n#%%\r\nimport pandas as pd\r\n# saving to CSV\r\ntest_ids = read_variable('outputs/test_ids.pkl')\r\ntest_y_ids = pd.DataFrame(test_ids,columns=['Id'])\r\ntest_y_y = pd.DataFrame(test_Y,columns=['Response'])\r\ntest_y = pd.concat([test_y_ids,test_y_y],axis=1)\r\ntest_y = test_y.set_index('Id')\r\ntest_y.to_csv('submissions/submission_1130.csv',float_format='%.0f')\r\n\r\n\r\n","sub_path":"10_model_2L_test_SUBMISSION.py","file_name":"10_model_2L_test_SUBMISSION.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"393121600","text":"\"\"\"Main entry point\n\"\"\"\nfrom pyramid.config import Configurator\n\n\ndef main(global_config, **settings):\n config = Configurator(settings=settings)\n config.include(\"cornice\")\n# config.include('pyramid_mako')\n config.add_static_view('static', 'static', cache_max_age=3600)\n config.add_static_view('/index', 'lightapp:templates')\n config.scan(\"lightapp.views\")\n return config.make_wsgi_app()\n","sub_path":"lightapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"473032289","text":"import sys\nimport os\n\noutput_dir = sys.argv[1]\n\ndef filename(num_duplications):\n return os.path.join(output_dir, \"output_%s.csv\" % (str(num_duplications),))\n\ndef time_for_method(fname):\n with open(fname) as f:\n lines = f.readlines()[1:]\n lines = [line.replace(\"\\n\", \"\").split(\", \") for line in lines]\n lines = [(l[0].strip(), float(l[1].strip())) for l in lines]\n return lines\n\ntimes_for_method = {}\nfor num_duplications in (1, 5, 10, 20, 40, 60, 80, 100, 140, 160, 180, 250, 300, 350, 400):\n fname = filename(num_duplications)\n if os.path.isfile(fname):\n for (method, time) in time_for_method(fname):\n if method not in times_for_method:\n times_for_method[method] = []\n times_for_method[method].append((num_duplications, time))\n\nfor (method, times) in times_for_method.iteritems():\n for (num_duplications, time) in times:\n print(method + \", \" + str(num_duplications) + \", \" + str(time))\n","sub_path":"scripts/evaluation/process_api_performance_files.py","file_name":"process_api_performance_files.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"70684741","text":"#!/usr/bin/env python3\n#-*-coding:utf-8-*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport mysql\nimport mysql.connector\nimport ast\nimport os\nimport sys\nsys.path.insert(1,\"/Users/joel/Archetype/Tobi\")\nfrom Library.TBook import Tools\nmagicWords = Tools().getModuleData(\"localDbPassword\",\"Tobias\")\n\nUtilisateur=os.environ[\"USER\"]\ndef MyConverter(mydata):\n def cvt(data):\n try : \n return ast.litteral_eval(data)\n except Exception:\n return str(data)\n return tuple(map(cvt,mydata))\n\nclass updateWindow(object):\n\n def LoadData(self):\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=magicWords,\n )\n\n Command = mydb.cursor()\n Command.execute(\"USE tobiasdb\") \n Command.execute(\"SELECT * FROM knownIps\")\n data = Command.fetchall()\n\n for row in data : \n self.addTable(MyConverter(row))\n\n Command.close()\n \n def addTable(self,columns):\n rowPosition = self.tableWidget.rowCount()\n self.tableWidget.insertRow(rowPosition)\n\n for i, column in enumerate(columns):\n self.tableWidget.setItem(rowPosition, i , QtWidgets.QTableWidgetItem(str(column)))\n\n def stocker(self): \n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=magicWords,\n )\n\n Command=mydb.cursor()\n Command.execute(\"USE tobiasdb\")\n\n Ins=\"INSERT INTO knownIps (id,hostname,address) VALUES (NULL , '{}' , '{}')\".format(self.lineEdit_2.text(),self.lineEdit.text()) \n \n Command.execute(Ins)\n mydb.commit()\n\n def init(self):\n self.LoadData()\n self.stocker()\n self.LoadData()\n \n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(810, 371)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)\n self.tableWidget.setGeometry(QtCore.QRect(40, 10, 691, 231))\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setRowCount(0)\n self.tableWidget.setColumnCount(3)\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit.setGeometry(QtCore.QRect(40, 280, 251, 32))\n self.lineEdit.setObjectName(\"lineEdit\")\n self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit_2.setGeometry(QtCore.QRect(330, 280, 251, 32))\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(610, 280, 88, 34))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.clicked.connect(self.init)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 810, 30))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Tobias\\'s Update Hosts Page\"))\n self.lineEdit.setPlaceholderText(_translate(\"MainWindow\", \"Adresse ip à rajouter\"))\n self.lineEdit_2.setPlaceholderText(_translate(\"MainWindow\", \"Nom \"))\n self.pushButton.setText(_translate(\"MainWindow\", \"Update\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = updateWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","sub_path":"Gui/UpdateHosts.py","file_name":"UpdateHosts.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"339383845","text":"import sys\nimport os\nsys.path.insert(0, os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..')))\n\nfrom matplotlib import pyplot as plt # NOQA\nfrom collections import OrderedDict # NOQA\n\nfrom nik_sm.nik_sm_strategy import NikSelfishMining # NOQA\nfrom nik_sm.learning_automata_type import LearningAutomataType # NOQA\nfrom sm1.sm1_strategy import SelfishMiningOne # NOQA\n\niteration_number = 10000\n\ntow_number = 10\nmin_tow_block_number = 4\nmax_tow_block_number = 6\n\nreward_rate = 0.01\npenalty_rate = 0.01\n\nmin_k_1 = 1\nmax_k_1 = 3\nnik_defense_1 = NikSelfishMining(\n tow_number, min_tow_block_number, max_tow_block_number, reward_rate, penalty_rate, min_k_1, max_k_1, LearningAutomataType.AVDHLA, False)\nnik_defense_1.gamma = 0.5\n\nmin_k_2 = 2\nmax_k_2 = 4\nnik_defense_2 = NikSelfishMining(\n tow_number, min_tow_block_number, max_tow_block_number, reward_rate, penalty_rate, min_k_2, max_k_2, LearningAutomataType.AVDHLA, False)\nnik_defense_2.gamma = 0.5\n\nmin_k_3 = 1\nmax_k_3 = 5\nnik_defense_3 = NikSelfishMining(\n tow_number, min_tow_block_number, max_tow_block_number, reward_rate, penalty_rate, min_k_3, max_k_3, LearningAutomataType.AVDHLA, False)\nnik_defense_3.gamma = 0.5\n\n\nalpha_values = [x / 100 for x in range(25, 51) if x % 5 == 0]\n\nnik_defense_1_revenue = []\nnik_defense_1_stale_block = []\n\nnik_defense_2_revenue = []\nnik_defense_2_stale_block = []\n\nnik_defense_3_revenue = []\nnik_defense_3_stale_block = []\n\nideal_defense_revenue_value = []\nupper_bound_value = []\n\n\nfor alpha in alpha_values:\n nik_defense_1.reset()\n\n nik_defense_1.alpha = alpha\n nik_defense_1.start_simulate(iteration_number)\n nik_defense_1.print_final_result()\n nik_defense_1_revenue.append(nik_defense_1.revenue)\n nik_defense_1_stale_block.append(nik_defense_1.stale_block)\n\nfor alpha in alpha_values:\n nik_defense_2.reset()\n\n nik_defense_2.alpha = alpha\n nik_defense_2.start_simulate(iteration_number)\n nik_defense_2.print_final_result()\n nik_defense_2_revenue.append(nik_defense_2.revenue)\n nik_defense_2_stale_block.append(nik_defense_2.stale_block)\n\nfor alpha in alpha_values:\n nik_defense_3.reset()\n\n nik_defense_3.alpha = alpha\n nik_defense_3.start_simulate(iteration_number)\n nik_defense_3.print_final_result()\n nik_defense_3_revenue.append(nik_defense_3.revenue)\n nik_defense_3_stale_block.append(nik_defense_3.stale_block)\n\nfor alpha in alpha_values:\n ideal_defense_revenue_value.append(alpha * 100)\n\nfor alpha in alpha_values:\n upper_bound_value.append(alpha / (1 - alpha) * 100)\n\n\nlinestyles_dict = OrderedDict(\n [('solid', (0, ())),\n ('loosely dotted', (0, (1, 10))),\n ('dotted', (0, (1, 5))),\n ('densely dotted', (0, (1, 1))),\n\n ('loosely dashed', (0, (5, 10))),\n ('dashed', (0, (5, 5))),\n ('densely dashed', (0, (5, 1))),\n\n ('loosely dashdotted', (0, (3, 10, 1, 10))),\n ('dashdotted', (0, (3, 5, 1, 5))),\n ('densely dashdotted', (0, (3, 1, 1, 1))),\n\n ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),\n ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),\n ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])\n\n\nplt.plot(\n alpha_values, nik_defense_1_revenue, color='r', label='K=[1,3]', linestyle=linestyles_dict['densely dotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_2_revenue, color='b', label='K=[2,4]', linestyle=linestyles_dict['densely dashdotdotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_3_revenue, color='y', label='K=[1,5]', linestyle=linestyles_dict['densely dashed'], linewidth=1.5)\n\nplt.plot(alpha_values, ideal_defense_revenue_value,\n color='k', label='Ideal Defense', linestyle=linestyles_dict['densely dashed'], linewidth=1.5)\nplt.plot(\n alpha_values, upper_bound_value, color='g', label='Upper Bound', linestyle=linestyles_dict['dashdotdotted'], linewidth=1.5)\n\nplt.title('ُNik Defense(AVDHLA) K Based Revenue Comparison-Ex2.3')\nplt.xlabel('Pool size')\nplt.ylabel('Relative Revenue')\n\nplt.legend(loc=\"upper left\")\n\nplt.show()\n\n\nplt.plot(\n alpha_values, nik_defense_1_stale_block, color='r', label='K=[1,3]', linestyle=linestyles_dict['densely dotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_2_stale_block, color='b', label='K=[2,4]', linestyle=linestyles_dict['densely dashdotdotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_3_stale_block, color='y', label='K=[1,5]', linestyle=linestyles_dict['densely dashed'], linewidth=1.5)\n\n\nplt.title('ُNik Defense(AVDHLA) K Based Stale Block Comparison-Ex2.3')\nplt.xlabel('Pool size')\nplt.ylabel('ُStale Block Number')\n\nplt.legend(loc=\"upper left\")\n\nplt.show()\n","sub_path":"tests/nik_selfish_mining_k_comparison_test.py","file_name":"nik_selfish_mining_k_comparison_test.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"397628635","text":"#!/usr/bin/env python\nimport argparse\nfrom igf_data.task_tracking.igf_slack import IGF_slack\nfrom igf_data.utils.seqrunutils import load_new_seqrun_data\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-p','--seqrun_data', required=True, help='Seqrun data json file')\nparser.add_argument('-d','--dbconfig_path', required=True, help='Database configuration json file')\nparser.add_argument('-s','--slack_config', required=True, help='Slack configuration json file')\nargs = parser.parse_args()\n\ndbconfig_path = args.dbconfig_path\nslack_config = args.slack_config\nseqrun_data = args.seqrun_data\n\nslack_obj = IGF_slack(slack_config=slack_config)\n\nif __name__=='__main__':\n try:\n load_new_seqrun_data(data_file=seqrun_data, dbconfig=dbconfig_path)\n except Exception as e:\n message = 'Failed to load data to seqrun table, error: {0}'.format(e)\n slack_obj.post_message_to_channel(message,reaction='fail')\n raise ValueError(message)\n else:\n slack_obj.post_message_to_channel(message='Loaded new seqrun info to db',reaction='pass')","sub_path":"scripts/db_scripts/load_seqrun_data.py","file_name":"load_seqrun_data.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"574412655","text":"#!/usr/bin/env python\n#!-*-coding:utf-8 -*-\n#!@Create :2019/3/20 14:20\n#!@Author : zyy\n#!@File : DataTransforBigDatalog.py\n\nfilename='D:\\Datasets\\\\testcircle.txt'\nfileNew = 'D:\\Datasets\\\\testcircle.csv'\n\n#filename='D:\\Datasets\\com-friendster.ungraph\\com-friendster.ungraph.txt'\n#fileNew = 'D:\\Datasets\\\\friBDL.csv'\nfobj = open(fileNew, 'wb+')\nwith open(filename,'r') as f:\n next(f)\n next(f)\n next(f)\n next(f)\n #skip first four lines\n for line in f:\n line = line.replace('\\n', '') # 去掉换行符,需要注意\n print(line)\n res = line.split()\n srcid = res[0]\n dstid = res[1]\n input = srcid+','+dstid+'\\n'\n input1 = bytes(input,encoding=\"utf8\")\n fobj.write(input1)\n\n\n\n\nf.close()\nfobj.close()\n","sub_path":"DataTransforBigDatalog.py","file_name":"DataTransforBigDatalog.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"342741013","text":"# -*- coding:utf-8 -*-\n#--\n# Copyright (c) 2012-2014 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should have received as part of\n# this distribution.\n#--\n\nfrom nagare import presentation, var, security\nfrom nagare.i18n import _\n\nfrom .comp import Title\n\n\n@presentation.render_for(Title, 'tabname')\ndef render(self, h, comp, *args):\n h.head << h.head.title(self.text)\n return h.root\n\n\n@presentation.render_for(Title)\ndef render(self, h, comp, *args):\n \"\"\"Render the title of the associated object\n\n Used by column title and card title on popin\n \"\"\"\n with h.div(class_='title'):\n kw = {}\n if not security.has_permissions('edit', self):\n kw['style'] = 'cursor: default'\n a = h.a(self.text, **kw)\n if security.has_permissions('edit', self):\n a.action(comp.answer)\n h << a\n return h.root\n\n\n@presentation.render_for(Title, model='edit')\ndef render(self, h, comp, *args):\n \"\"\"Render the title of the associated object\"\"\"\n text = var.Var(self.text)\n with h.form(class_='title-form'):\n id_ = h.generate_id()\n if self.field_type == 'textarea':\n h << h.textarea(self.text, id_=id_).action(text)\n elif self.field_type == 'input':\n h << h.input(type='text', value=self.text,\n id_=id_).action(text)\n else:\n raise ValueError(_('Unsupported field_type %r') % self.field_type)\n h << h.button(_('Save'), class_='btn btn-primary btn-small').action(\n lambda: comp.answer(self.change_text(text())))\n h << ' '\n h << h.button(_('Cancel'), class_='btn btn-small').action(comp.answer)\n h << h.script('YAHOO.kansha.app.selectElement(%r);YAHOO.kansha.app.hideCardsLimitEdit(%s)' % (id_, self.parent.id))\n return h.root\n","sub_path":"kansha/title/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"228672955","text":"#!/usr/bin/env python\nimport os\n\nfrom django.conf import settings\nfrom django.core.management import call_command\n\nTHIS_DIR = os.path.dirname(__file__)\n\n\ndef main():\n \"\"\"Dynamically configure the Django settings with the\n minimum necessary to get Django running tests\"\"\"\n settings.configure(\n INSTALLED_APPS=(\n 'rtl_django_tools',\n 'django.contrib.sites',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django_nose',\n 'registration',\n ),\n TEST_RUNNER = 'django_nose.NoseTestSuiteRunner',\n DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': '/tmp/registration.db',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': ''}},\n NOSE_ARGS=['--with-xunit', '-s'],\n ROOT_URLCONF=None,\n TEMPLATE_DIRS = (\n os.path.join(THIS_DIR, 'templates'),\n ),\n FIXTURES_DIR=(\n os.path.join(THIS_DIR, 'fixtures'),\n ),\n SITE_ID=1,\n )\n\n call_command('test', 'registration')\n\nif __name__ == '__main__':\n main()\n","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"552925870","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom datetime import datetime, timedelta\nimport os\nimport sys\n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nfrom DataUpdate.updateDataStockForAdjQuote import airflowCallable as updateDataStockForAdjQuote\nfrom DataUpdate.updateDataStockDescription import airflowCallable as updateDataStockDescription\nfrom DataUpdate.updateDataStockUnadjustedQuote import airflowCallable as updateDataStockUnadjustedQuote\nfrom DataUpdate.updateDataStockIndex import airflowCallable as updateDataStockIndex\nfrom DataUpdate.updateDataStockFundamental import airflowCallable as updateDataStockFundamental\nfrom DataUpdate.updateDataFundIndex import airflowCallable as updateDataFundIndex\nfrom DataUpdate.updateDataStockFlag import airflowCallable as updateDataStockFlag\nfrom DataUpdate.updateDataTushareDailyQuotes import airflowCallable as updateDataStockTushareQuotes\n\nfrom Basic.calForwardAdjAreaIndex import airflowCallable as calForwardAdjAreaIndex\nfrom Basic.calForwardAdjIndustryIndex import airflowCallable as calForwardAdjIndustryIndex\n\nfrom Derivatives.calStockFeatures import airflowCallableStockTechnicalInicators as calStockTechnicalInicators, \\\n airflowCallableStockExcessiveReturnArea as calStockExcessiveReturnArea, \\\n airflowCallableStockExcessiveReturnIndustry as calStockExcessiveReturnIndustry, \\\n airflowCallableStockExcessiveReturnHS300 as calStockExcessiveReturnHS300, \\\n airflowCallableStockExcessiveReturnMarket as calStockExcessiveReturnMarket, \\\n airflowCallableStockStationaryTechnicalIndicators as calStockStationaryTechnicalIndicators, \\\n airflowCallableStockStationaryFundamentalIndicators as calStockStationaryFundamentalIndicators\nfrom Derivatives.calStockMarketFeatures import airflowCallableArea as calAreaRiseRatio, \\\n airflowCallableIndustry as calIndustryRiseRatio, \\\n airflowCallableMarket as calMarketRiseRatio, \\\n airflowCallableAllStock as calAllStockRiseRatio\nfrom Derivatives.calStockBeta import airflowCallable as calStockBeta\nfrom Derivatives.calStockValue import airflowCallable as calStockValue\nfrom Derivatives.calStockDayNum import airflowCallable as calStockDayNum\nfrom Derivatives.calIndexFeatures import airflowCallableHS300Technical as calHS300TechnicalIndicator, \\\n airflowCallableStockIndexTechnical as calStockIndexTechnicalIndicators, \\\n airflowCallableStockIndexStationaryTechnical as calStockIndexStationaryTechnical, \\\n airflowCallableHS300StationaryTechnical as calHS300StationaryTechnical\nfrom Derivatives.calNonStockFeatures import airflowCallableFundIndex as calFundIndexFeatures\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': datetime(2015, 1, 1),\n 'email': ['13602819622@163.com'],\n 'email_on_failure': True,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n# ========= dag =========\n# UTC time\ndag = DAG('afternoon_dag', catchup=False, schedule_interval='35 18 * * *', default_args=default_args)\n\n# ========= task ==========\n# update data\nt_stock_for_adj_quote = PythonOperator(\n task_id='data_stock_for_adj_quote',\n python_callable=updateDataStockForAdjQuote,\n dag=dag)\n\nt_stock_unadj_quote = PythonOperator(\n task_id='data_stock_unadj_quote',\n python_callable=updateDataStockUnadjustedQuote,\n dag=dag)\n\nt_stock_description = PythonOperator(\n task_id='data_stock_description',\n python_callable=updateDataStockDescription,\n dag=dag)\n\nt_stock_ts_quotes = PythonOperator(\n task_id='data_stock_ts_quotes',\n python_callable=updateDataStockTushareQuotes,\n dag=dag)\n\nt_stock_index = PythonOperator(\n task_id='data_stock_index',\n python_callable=updateDataStockIndex,\n dag=dag)\n\n# =============== boundary ============= (update source data first, and later update final data from different sources)\ndata_boundary_data_source = DummyOperator(task_id='data_boundary_afternoon_data_source', dag=dag)\ndata_boundary_data_source.set_upstream([t_stock_ts_quotes])\n\nt_fund_index = PythonOperator(\n task_id='data_fund_index',\n python_callable=updateDataFundIndex,\n dag=dag)\n\nt_stock_fundamental = PythonOperator(\n task_id='data_stock_fundamental',\n python_callable=updateDataStockFundamental,\n dag=dag)\n\ndata_boundary_data_source.set_downstream([t_fund_index, t_stock_fundamental])\n\n# =============== boundary ============= (dervative on stock quote and public index, composite customized index)\ndata_boundary = DummyOperator(task_id='data_boundary_afternoon', dag=dag)\ndata_boundary.set_upstream([t_stock_for_adj_quote, t_stock_unadj_quote, t_stock_description, t_stock_index, t_stock_fundamental, t_fund_index])\n\n# calculate features\nt_stock_technical = PythonOperator(\n task_id='feature_stock_technical',\n python_callable=calStockTechnicalInicators,\n dag=dag)\n\nt_stock_stat_technical = PythonOperator(\n task_id='feature_stock_stat_technical',\n python_callable=calStockStationaryTechnicalIndicators,\n dag=dag)\n\nt_stock_stat_fundamental = PythonOperator(\n task_id='feature_stock_stat_fundamental',\n python_callable=calStockStationaryFundamentalIndicators,\n dag=dag)\n\nt_stock_beta = PythonOperator(\n task_id='feature_stock_beta',\n python_callable=calStockBeta,\n dag=dag)\n\nt_stock_value = PythonOperator(\n task_id='feature_stock_value',\n python_callable=calStockValue,\n dag=dag)\n\nt_stock_daynum = PythonOperator(\n task_id='feature_stock_daynum',\n python_callable=calStockDayNum,\n dag=dag)\n\nt_HS300_technical = PythonOperator(\n task_id='feature_HS300_technical',\n python_callable=calHS300TechnicalIndicator,\n dag=dag)\n\nt_HS300_stat_technical = PythonOperator(\n task_id='feature_HS300_stat_technical',\n python_callable=calHS300StationaryTechnical,\n dag=dag)\n\nt_area_index_for_adj_quote = PythonOperator(\n task_id='data_area_index_for_adj_quote',\n python_callable=calForwardAdjAreaIndex,\n dag=dag)\n\nt_industry_index_for_adj_quote = PythonOperator(\n task_id='data_industry_index_for_adj_quote',\n python_callable=calForwardAdjIndustryIndex,\n dag=dag)\n\nt_fund_index_technical = PythonOperator(\n task_id='feature_fund_index',\n python_callable=calFundIndexFeatures,\n dag=dag)\n\nt_stock_flag = PythonOperator(\n task_id='data_stock_flag',\n python_callable=updateDataStockFlag,\n dag=dag)\n\ndata_boundary.set_downstream([t_stock_technical, t_stock_stat_technical, t_stock_stat_fundamental,\n t_stock_beta, t_stock_value, t_stock_daynum, t_HS300_technical, t_HS300_stat_technical,\n t_area_index_for_adj_quote, t_industry_index_for_adj_quote, t_fund_index_technical, t_stock_flag])\n\n# ================= boundry 2 =============== (derivative on customized index quote)\ndata_boundary2 = DummyOperator(task_id='data_boundary_afternoon_2', dag=dag)\ndata_boundary2.set_upstream([t_area_index_for_adj_quote, t_industry_index_for_adj_quote])\n\nt_stock_index_technical = PythonOperator(\n task_id='feature_stock_index_technical',\n python_callable=calStockIndexTechnicalIndicators,\n dag=dag)\n\nt_stock_index_stat_technical = PythonOperator(\n task_id='feature_stock_index_stat_technical',\n python_callable=calStockIndexStationaryTechnical,\n dag=dag)\n\ndata_boundary2.set_downstream([t_stock_index_technical, t_stock_index_stat_technical])\n\n# ============== boundry 3 ================== excessive return (stock derivatives over index derivatives)\ndata_boundary3 = DummyOperator(task_id='data_boundary_afternoon_3', dag=dag)\ndata_boundary3.set_upstream([t_stock_technical, t_stock_index_technical, t_HS300_technical])\n\nt_exc_ret_area = PythonOperator(\n task_id='feature_stock_excessive_return_area',\n python_callable=calStockExcessiveReturnArea,\n dag=dag)\n\nt_exc_ret_industry = PythonOperator(\n task_id='feature_stock_excessive_return_industry',\n python_callable=calStockExcessiveReturnIndustry,\n dag=dag)\n\nt_exc_ret_hs300 = PythonOperator(\n task_id='feature_stock_excessive_return_HS300',\n python_callable=calStockExcessiveReturnHS300,\n dag=dag)\n\nt_exc_ret_market = PythonOperator(\n task_id='feature_stock_excessive_return_market',\n python_callable=calStockExcessiveReturnMarket,\n dag=dag)\n\nt_rise_ratio_area = PythonOperator(\n task_id='feature_stock_rise_ratio_area',\n python_callable=calAreaRiseRatio,\n dag=dag)\n\nt_rise_ratio_industry = PythonOperator(\n task_id='feature_stock_rise_ratio_industry',\n python_callable=calIndustryRiseRatio,\n dag=dag)\n\nt_rise_ratio_market = PythonOperator(\n task_id='feature_stock_rise_ratio_market',\n python_callable=calMarketRiseRatio,\n dag=dag)\n\nt_rise_ratio_all_stock = PythonOperator(\n task_id='feature_stock_rise_ratio_all',\n python_callable=calAllStockRiseRatio,\n dag=dag)\n\ndata_boundary3.set_downstream([t_exc_ret_area, t_exc_ret_industry, t_exc_ret_market, t_exc_ret_hs300,\n t_rise_ratio_area, t_rise_ratio_industry, t_rise_ratio_market, t_rise_ratio_all_stock])","sub_path":"AirFlow/afternoonDAG.py","file_name":"afternoonDAG.py","file_ext":"py","file_size_in_byte":9402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"443780512","text":"#!/usr/bin/env python3\n\n\"\"\"\n Compare to scoring matrix, extract highest affinity binding site\n\n usage: highest_affinity_binding_site.py -m\n\"\"\"\nimport argparse\nimport os\nimport sys\n\ndef main(argv):\n \"\"\"\n main method\n \"\"\"\n args = parseArgs(argv)\n\n # create scoring matrix from file\n scoring_matrix = create_scoring_matrix_from_file(args.matrix)\n\n # retrieve highest scoring sequence and score\n sequence, score = get_highest_score_sequence(scoring_matrix)\n\n print(\"The highest scoring sequence is {} with a score of {}\".format(sequence, score))\n\n\n\ndef parseArgs(argv):\n \"\"\"\n cmd line input\n \"\"\"\n parser = argparse.ArgumentParser(description=\"This script generates sbatch script and submits sbatch job.\")\n parser.add_argument(\"-m\", \"--matrix\", required=True,\n help=\"[Required] Path to scoring matrix. matricies must be in nucleotide x (sequence length) format.\")\n\n # remove script call from list (this is passed as list of cmd line input with script at position 0)\n args = parser.parse_args(argv[1:])\n return args\n\ndef create_scoring_matrix_from_file(matrix_file):\n \"\"\"\n Reads columnar data from file, returns a dictionary representation of a matrix with {nucleotide: score}\n representing the columns in the data\n Args: matrix_file\n Returns: a dictionary representation of a 4 x p matrix where the rows are the 4 nucleotide bases\n and p is the length of the sequence\n \"\"\"\n file_data = [ x.split() for x in open(matrix_file).readlines() ]\n scoring_matrix = [ dict(A=float(a_score), C=float(c_score), G=float(g_score),\n T=float(t_score)) for a_score, c_score, g_score, t_score in\n zip(file_data[0], file_data[1], file_data[2], file_data[3])\n ]\n\n return scoring_matrix\n\ndef get_highest_score_sequence(matrix):\n \"\"\"\n modified create_scoring_matrix_from_file() from scan_sequence.py\n based on https://stackoverflow.com/a/268285/9708266\n Args: a matrix with columns represented as dictionaries where the key is the rowname\n Returns: a string length p representing the sequence with the highest score across the n x p matrix\n \"\"\"\n sequence_score_tuple = [[max(col, key=lambda key: col[key]), col[max(col, key=lambda key: col[key])]] for col in\n matrix]\n sequence = ''.join([x[0] for x in sequence_score_tuple])\n score = sum([x[1] for x in sequence_score_tuple])\n\n return sequence, score #''.join([max(col, key=lambda key: col[key]) for col in matrix])\n\n\n# call main method\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"assignment6/highest_affinity_binding_site.py","file_name":"highest_affinity_binding_site.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"350659161","text":"import sympy as sy \nimport numpy as np \nimport matplotlib.pyplot as plt\nimport autograd.numpy as anp \nimport timeit \nfrom autograd import grad \nfrom autograd import elementwise_grad\nimport numpy.linalg as la \nimport scipy.sparse as sparse\n\n#############\n# Iterative solvers - QUESTION 1&2:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 1&2\\n########\\n\".format(section))\n\ndef jacobi(A, b, tol, maxiters, plot=False):\n\n\n\titer_count = 0\n\terror = np.inf \n\n\tD = np.diag(A)\t\n\tL = np.tril(A, k=-1)\n\tU = np.triu(A, k=1)\n\n\terror_tracker = np.empty(maxiters)\n\n\tassert np.allclose(A, np.diag(D) + L + U)\n\n\tD_inv = 1/D \n\tD_inv = D_inv.reshape((D_inv.size, 1))\n\n\tcur_x = np.zeros((A.shape[1],1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tnew_x = cur_x + D_inv*(b-A@cur_x)\n\n\t\terror = np.max(np.abs(new_x - cur_x))\n\t\terror_tracker[iter_count] = error \n\t\titer_count += 1\n\n\n\t\tcur_x = new_x \n\n\terror_tracker = error_tracker[0:iter_count]\n\tif plot:\n\t\tplt.semilogy(range(iter_count), error_tracker)\n\t\tplt.xlabel(\"Iteration\")\n\t\tplt.ylabel(\"Absolute error of approx\")\n\t\tplt.title(\"Covergence of Jacobi Method\")\n\t\tplt.savefig('jacobi_covergence.png')\n\n\n\treturn cur_x \n\n\ndef diag_dom(n, num_entries=None):\n\t\"\"\"Generate a strictly diagonally dominant (n, n) matrix.\n\tParameters:\n\tn (int): The dimension of the system.\n\tnum_entries (int): The number of nonzero values.\n\tDefaults to n^(3/2)-n.\n\tReturns:\n\tA ((n,n) ndarray): A (n, n) strictly diagonally dominant matrix.\n\t\"\"\"\n\tif num_entries is None:\n\t\tnum_entries = int(n**1.5) - n\n\tA = np.zeros((n,n))\n\trows = np.random.choice(np.arange(0,n), size=num_entries)\n\tcols = np.random.choice(np.arange(0,n), size=num_entries)\n\tdata = np.random.randint(-4, 4, size=num_entries)\n\tfor i in range(num_entries):\n\t\tA[rows[i], cols[i]] = data[i]\n\tfor i in range(n):\n\t\tA[i,i] = np.sum(np.abs(A[i])) + 1\n\treturn A\n\ndef test_part1(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = jacobi(A, b, 10e-10, 200, plot=True)\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\t#assert test_part1(n)\n\tassert True\nprint(\"Passed test #1\")\n\n#############\n# Iterative solvers - QUESTION 3:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 3\\n########\\n\".format(section))\n\ndef Gauss_Seidel(A, b, tol, maxiters, plot=False):\n\n\tn = A.shape[1]\n\titer_count = 0\n\terror = np.inf \n\n\terror_tracker = np.empty(maxiters)\n\n\tcur_x = np.zeros((n,1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tpreserve_x = np.copy(cur_x)\n\t\tfor i in range(n):\n\t\t\tcur_x[i,0] += (1/A[i,i]) * (b[i,0] - A[i,:].T @ cur_x)\n\n\t\terror = np.max(np.abs(preserve_x - cur_x))\n\t\terror_tracker[iter_count] = error \n\t\titer_count += 1\n\n\n\terror_tracker = error_tracker[0:iter_count]\n\tif plot:\n\t\tplt.semilogy(range(iter_count), error_tracker)\n\t\tplt.xlabel(\"Iteration\")\n\t\tplt.ylabel(\"Absolute error of approx\")\n\t\tplt.title(\"Covergence of Gauss_Seidel Method\")\n\t\tplt.savefig('Gauss_Seidel_covergence.png')\n\n\n\treturn cur_x \n\ndef test_part3(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = Gauss_Seidel(A, b, 10e-10, 200, plot=True)\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\tassert test_part3(n)\n\tassert True\nprint(\"Passed test #3\")\n\n#############\n# Iterative solvers - QUESTION 4:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 4\\n########\\n\".format(section))\n\ndef Gauss_Seidel_sparse(A, b, tol, maxiters):\n\t'''\n\tNOTE: matrix A is a sparse matrix\n\t'''\n\n\tn = A.shape[1]\n\titer_count = 0\n\terror = np.inf \n\n\tcur_x = np.zeros((n,1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tpreserve_x = np.copy(cur_x)\n\t\tfor i in range(n):\n\t\t\trowstart = A.indptr[i]\n\t\t\trowend = A.indptr[i+1]\n\n\t\t\tAix = A.data[rowstart:rowend] @ cur_x[A.indices[rowstart:rowend]]\n\t\t\tcur_x[i,0] += (1/A[i,i]) * (b[i,0] - Aix)\n\n\t\terror = np.max(np.abs(preserve_x - cur_x))\n\t\titer_count += 1\n\n\treturn cur_x \n\ndef test_part4(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = Gauss_Seidel_sparse(sparse.csr_matrix(A), b, 10e-10, 200)\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\tassert test_part4(n)\n\tassert True\nprint(\"Passed test #4\")\n\n\n#############\n# Iterative solvers - QUESTION 5:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 5\\n########\\n\".format(section))\n\ndef Gauss_Seidel_SOR(A, b, tol, maxiters, omega):\n\t'''\n\tNOTE: matrix A is a sparse matrix\n\t'''\n\n\tn = A.shape[1]\n\titer_count = 0\n\terror = np.inf \n\n\tcur_x = np.zeros((n,1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tpreserve_x = np.copy(cur_x)\n\t\tfor i in range(n):\n\t\t\trowstart = A.indptr[i]\n\t\t\trowend = A.indptr[i+1]\n\n\t\t\tAix = A.data[rowstart:rowend] @ cur_x[A.indices[rowstart:rowend]]\n\t\t\tcur_x[i,0] += (omega/A[i,i]) * (b[i,0] - Aix)\n\n\t\terror = np.max(np.abs(preserve_x - cur_x))\n\t\titer_count += 1\n\n\treturn cur_x, iter_count\n\ndef test_part5(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = Gauss_Seidel_SOR(sparse.csr_matrix(A), b, 10e-10, 200, .5)[0]\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\tassert test_part5(n)\n\tassert True\nprint(\"Passed test #5\")\n\n#############\n# Iterative solvers - QUESTION 6:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 6\\n########\\n\".format(section))\n\ndef laplace(n, omega, tol=10e-8, maxiters=100, plot=False):\n\n\tb_n = np.zeros(n)\n\tb_n[0] = -100\n\tb_n[n-1] = -100\n\tb = np.tile(b_n, n)\n\tb = b.reshape((n**2,1))\n\n\tA = np.tile(np.identity(n), (n,n) )\n\tnp.fill_diagonal(A, -4)\n\n\tones = np.ones( (n**2, n**2) )\n\tones_diag_upper = np.triu(np.tril(ones, 1), 1)\n\tones_diag_lower = np.triu(np.tril(ones, -1), -1)\n\n\tA = A + ones_diag_lower + ones_diag_upper\n\n\tx, iters = Gauss_Seidel_SOR(sparse.csr_matrix(A), b, tol, maxiters, omega)\n\n\tx = x.reshape((n,n))\n\n\tif plot:\n\t\tplt.pcolormesh(x, cmap=\"coolwarm\")\n\t\tplt.savefig('Laplace.png')\n\nlaplace(10, 1, plot=True)\n\n","sub_path":"ProbSets/Comp/Week6/solvers.py","file_name":"solvers.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"310986910","text":"# Phi Vision, Inc.\n# __________________\n\n# [2020] Phi Vision, Inc. All Rights Reserved.\n\n# NOTICE: All information contained herein is, and remains\n# the property of Phi Vision Incorporated and its suppliers,\n# if any. The intellectual and technical concepts contained\n# herein are proprietary to Phi Vision, Inc\n# and its suppliers and may be covered by U.S. and Foreign Patents,\n# patents in process, and are protected by trade secret or copyright law.\n# Dissemination of this information or reproduction of this material\n# is strictly forbidden unless prior written permission is obtained\n# from Phi Vision, Inc.\n\n\"\"\"\nload K2HPD serialized TFRecords format.\nBy Fanghao Yang, 12/21/2020\n\"\"\"\n\nimport click\nfrom datasets.dataset_loader import load_dataset, parse_tfr_tensor\nfrom utilities.image_utils import generate_blended_heatmap\nfrom pathlib import Path\nimport pylab\n\n\n@click.command()\n@click.option('--input_file', help='input TFRecords file')\n@click.option('--image_type', help='Type of image loading from the dataset')\ndef load_k2hpd_test(input_file: str, image_type: str):\n dataset = load_dataset(Path(input_file), image_type=image_type)\n for element in dataset.take(5):\n example = parse_tfr_tensor(element, image_type=image_type)\n print(f\"Loading data for image: {example['name'].numpy().decode('ascii')}\")\n pylab.figure()\n depth_map = example['depth'].numpy()\n pylab.imshow(depth_map)\n # list heat maps\n blended_map = generate_blended_heatmap(example['heat_map'])\n pylab.figure()\n pylab.imshow(blended_map)\n pylab.show()\n\n\nif __name__ == '__main__':\n load_k2hpd_test()\n","sub_path":"test/load_k2hpd_test.py","file_name":"load_k2hpd_test.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"386152170","text":"# SPDX-FileCopyrightText: 2020 Phillip Burgess for Adafruit Industries\n#\n# SPDX-License-Identifier: MIT\n\n\"\"\"\nRASTER EYES for Adafruit Matrix Portal: animated spooky eyes.\n\"\"\"\n\n# pylint: disable=import-error\nimport math\nimport random\nimport time\nimport displayio\nimport adafruit_imageload\nfrom adafruit_matrixportal.matrix import Matrix\n\n# TO LOAD DIFFERENT EYE DESIGNS: change the middle word here (between\n# 'eyes.' and '.data') to one of the folder names inside the 'eyes' folder:\nfrom eyes.werewolf.data import EYE_DATA\n#from eyes.cyclops.data import EYE_DATA\n#from eyes.kobold.data import EYE_DATA\n#from eyes.adabot.data import EYE_DATA\n#from eyes.skull.data import EYE_DATA\n\n# UTILITY FUNCTIONS AND CLASSES --------------------------------------------\n\n# pylint: disable=too-few-public-methods\nclass Sprite(displayio.TileGrid):\n \"\"\"Single-tile-with-bitmap TileGrid subclass, adds a height element\n because TileGrid doesn't appear to have a way to poll that later,\n object still functions in a displayio.Group.\n \"\"\"\n def __init__(self, filename, transparent=None):\n \"\"\"Create Sprite object from color-paletted BMP file, optionally\n set one color to transparent (pass as RGB tuple or list to locate\n nearest color, or integer to use a known specific color index).\n \"\"\"\n bitmap, palette = adafruit_imageload.load(\n filename, bitmap=displayio.Bitmap, palette=displayio.Palette)\n if isinstance(transparent, (tuple, list)): # Find closest RGB match\n closest_distance = 0x1000000 # Force first match\n for color_index, color in enumerate(palette): # Compare each...\n delta = (transparent[0] - ((color >> 16) & 0xFF),\n transparent[1] - ((color >> 8) & 0xFF),\n transparent[2] - (color & 0xFF))\n rgb_distance = (delta[0] * delta[0] +\n delta[1] * delta[1] +\n delta[2] * delta[2]) # Actually dist^2\n if rgb_distance < closest_distance: # but adequate for\n closest_distance = rgb_distance # compare purposes,\n closest_index = color_index # no sqrt needed\n palette.make_transparent(closest_index)\n elif isinstance(transparent, int):\n palette.make_transparent(transparent)\n super(Sprite, self).__init__(bitmap, pixel_shader=palette)\n\n\n# ONE-TIME INITIALIZATION --------------------------------------------------\n\nMATRIX = Matrix(bit_depth=6)\nDISPLAY = MATRIX.display\n\n# Order in which sprites are added determines the 'stacking order' and\n# visual priority. Lower lid is added before the upper lid so that if they\n# overlap, the upper lid is 'on top' (e.g. if it has eyelashes or such).\nSPRITES = displayio.Group()\nSPRITES.append(Sprite(EYE_DATA['eye_image'])) # Base image is opaque\nSPRITES.append(Sprite(EYE_DATA['lower_lid_image'], EYE_DATA['transparent']))\nSPRITES.append(Sprite(EYE_DATA['upper_lid_image'], EYE_DATA['transparent']))\nSPRITES.append(Sprite(EYE_DATA['stencil_image'], EYE_DATA['transparent']))\nDISPLAY.show(SPRITES)\n\nEYE_CENTER = ((EYE_DATA['eye_move_min'][0] + # Pixel coords of eye\n EYE_DATA['eye_move_max'][0]) / 2, # image when centered\n (EYE_DATA['eye_move_min'][1] + # ('neutral' position)\n EYE_DATA['eye_move_max'][1]) / 2)\nEYE_RANGE = (abs(EYE_DATA['eye_move_max'][0] - # Max eye image motion\n EYE_DATA['eye_move_min'][0]) / 2, # delta from center\n abs(EYE_DATA['eye_move_max'][1] -\n EYE_DATA['eye_move_min'][1]) / 2)\nUPPER_LID_MIN = (min(EYE_DATA['upper_lid_open'][0], # Motion bounds of\n EYE_DATA['upper_lid_closed'][0]), # upper and lower\n min(EYE_DATA['upper_lid_open'][1], # eyelids\n EYE_DATA['upper_lid_closed'][1]))\nUPPER_LID_MAX = (max(EYE_DATA['upper_lid_open'][0],\n EYE_DATA['upper_lid_closed'][0]),\n max(EYE_DATA['upper_lid_open'][1],\n EYE_DATA['upper_lid_closed'][1]))\nLOWER_LID_MIN = (min(EYE_DATA['lower_lid_open'][0],\n EYE_DATA['lower_lid_closed'][0]),\n min(EYE_DATA['lower_lid_open'][1],\n EYE_DATA['lower_lid_closed'][1]))\nLOWER_LID_MAX = (max(EYE_DATA['lower_lid_open'][0],\n EYE_DATA['lower_lid_closed'][0]),\n max(EYE_DATA['lower_lid_open'][1],\n EYE_DATA['lower_lid_closed'][1]))\nEYE_PREV = (0, 0)\nEYE_NEXT = (0, 0)\nMOVE_STATE = False # Initially stationary\nMOVE_EVENT_DURATION = random.uniform(0.1, 3) # Time to first move\nBLINK_STATE = 2 # Start eyes closed\nBLINK_EVENT_DURATION = random.uniform(0.25, 0.5) # Time for eyes to open\nTIME_OF_LAST_MOVE_EVENT = TIME_OF_LAST_BLINK_EVENT = time.monotonic()\n\n\n# MAIN LOOP ----------------------------------------------------------------\n\nwhile True:\n NOW = time.monotonic()\n\n # Eye movement ---------------------------------------------------------\n\n if NOW - TIME_OF_LAST_MOVE_EVENT > MOVE_EVENT_DURATION:\n TIME_OF_LAST_MOVE_EVENT = NOW # Start new move or pause\n MOVE_STATE = not MOVE_STATE # Toggle between moving & stationary\n if MOVE_STATE: # Starting a new move?\n MOVE_EVENT_DURATION = random.uniform(0.08, 0.17) # Move time\n ANGLE = random.uniform(0, math.pi * 2)\n EYE_NEXT = (math.cos(ANGLE) * EYE_RANGE[0], # (0,0) in center,\n math.sin(ANGLE) * EYE_RANGE[1]) # NOT pixel coords\n else: # Starting a new pause\n MOVE_EVENT_DURATION = random.uniform(0.04, 3) # Hold time\n EYE_PREV = EYE_NEXT\n\n # Fraction of move elapsed (0.0 to 1.0), then ease in/out 3*e^2-2*e^3\n RATIO = (NOW - TIME_OF_LAST_MOVE_EVENT) / MOVE_EVENT_DURATION\n RATIO = 3 * RATIO * RATIO - 2 * RATIO * RATIO * RATIO\n EYE_POS = (EYE_PREV[0] + RATIO * (EYE_NEXT[0] - EYE_PREV[0]),\n EYE_PREV[1] + RATIO * (EYE_NEXT[1] - EYE_PREV[1]))\n\n # Blinking -------------------------------------------------------------\n\n if NOW - TIME_OF_LAST_BLINK_EVENT > BLINK_EVENT_DURATION:\n TIME_OF_LAST_BLINK_EVENT = NOW # Start change in blink\n BLINK_STATE += 1 # Cycle paused/closing/opening\n if BLINK_STATE == 1: # Starting a new blink (closing)\n BLINK_EVENT_DURATION = random.uniform(0.03, 0.07)\n elif BLINK_STATE == 2: # Starting de-blink (opening)\n BLINK_EVENT_DURATION *= 2\n else: # Blink ended,\n BLINK_STATE = 0 # paused\n BLINK_EVENT_DURATION = random.uniform(BLINK_EVENT_DURATION * 3, 4)\n\n if BLINK_STATE: # Currently in a blink?\n # Fraction of closing or opening elapsed (0.0 to 1.0)\n RATIO = (NOW - TIME_OF_LAST_BLINK_EVENT) / BLINK_EVENT_DURATION\n if BLINK_STATE == 2: # Opening\n RATIO = 1.0 - RATIO # Flip ratio so eye opens instead of closes\n else: # Not blinking\n RATIO = 0\n\n # Eyelid tracking ------------------------------------------------------\n\n # Initial estimate of 'tracked' eyelid positions\n UPPER_LID_POS = (EYE_DATA['upper_lid_center'][0] + EYE_POS[0],\n EYE_DATA['upper_lid_center'][1] + EYE_POS[1])\n LOWER_LID_POS = (EYE_DATA['lower_lid_center'][0] + EYE_POS[0],\n EYE_DATA['lower_lid_center'][1] + EYE_POS[1])\n # Then constrain these to the upper/lower lid motion bounds\n UPPER_LID_POS = (min(max(UPPER_LID_POS[0],\n UPPER_LID_MIN[0]), UPPER_LID_MAX[0]),\n min(max(UPPER_LID_POS[1],\n UPPER_LID_MIN[1]), UPPER_LID_MAX[1]))\n LOWER_LID_POS = (min(max(LOWER_LID_POS[0],\n LOWER_LID_MIN[0]), LOWER_LID_MAX[0]),\n min(max(LOWER_LID_POS[1],\n LOWER_LID_MIN[1]), LOWER_LID_MAX[1]))\n # Then interpolate between bounded tracked position to closed position\n UPPER_LID_POS = (UPPER_LID_POS[0] + RATIO *\n (EYE_DATA['upper_lid_closed'][0] - UPPER_LID_POS[0]),\n UPPER_LID_POS[1] + RATIO *\n (EYE_DATA['upper_lid_closed'][1] - UPPER_LID_POS[1]))\n LOWER_LID_POS = (LOWER_LID_POS[0] + RATIO *\n (EYE_DATA['lower_lid_closed'][0] - LOWER_LID_POS[0]),\n LOWER_LID_POS[1] + RATIO *\n (EYE_DATA['lower_lid_closed'][1] - LOWER_LID_POS[1]))\n\n # Move eye sprites -----------------------------------------------------\n\n SPRITES[0].x, SPRITES[0].y = (int(EYE_CENTER[0] + EYE_POS[0] + 0.5),\n int(EYE_CENTER[1] + EYE_POS[1] + 0.5))\n SPRITES[2].x, SPRITES[2].y = (int(UPPER_LID_POS[0] + 0.5),\n int(UPPER_LID_POS[1] + 0.5))\n SPRITES[1].x, SPRITES[1].y = (int(LOWER_LID_POS[0] + 0.5),\n int(LOWER_LID_POS[1] + 0.5))\n","sub_path":"Matrix_Portal_Eyes/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":9267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"299617010","text":"from flask_jwt import jwt_required\nfrom flask import request\nfrom . import rest\nfrom app import utils\nfrom app.model import User as UserModel\nfrom app.model import AbstractUser as AUserModel\nimport logging, datetime\n#from logging.config import fileConfig\n#fileConfig('conf/log-app.conf')\n#logger = logging.getLogger(__name__)\n\n\n#query all users\n@rest.route('users/privilege/', methods=['GET'])\n@jwt_required()\ndef get_privilege(loginUser):\n # default is lowest privilege\n privilege = 3\n errcode = 1\n ## here, need verify if loginUser has privilege to get user list\n user = AUserModel.IsExist(loginUser)\n logging.debug(\"user is %s\"%user)\n if user:\n privilege =user.privilege\n errcode = 0\n return utils.jsonresp(jsonobj={'errcode':errcode,'privilege':privilege})\n\n@rest.route('users/blgadmin/', methods=['GET'])\n@jwt_required()\ndef get_blgAdmins(loginUser):\n errcode = 1\n blgAdmins = []\n user = UserModel.IsExist(loginUser)\n if user:\n if user.privilege == '0': # only super admin can return all admin users\n blgAdmins = UserModel.GetBlgAdmins()\n errcode = 0\n return utils.jsonresp(jsonobj={'errcode':errcode,'blgAdmins':blgAdmins})\n\n@rest.route('users/blgqmuser/', methods=['GET'])\n@jwt_required()\ndef get_blgQMUsers(loginUser):\n errcode = 1\n blgQMUsers = []\n user = UserModel.IsExist(loginUser)\n if user:\n blgQMUsers = UserModel.GetBlgQMUsers(user.privilege, loginUser)\n errcode = 0\n\n return utils.jsonresp(jsonobj={'errcode':errcode,'blgQMUsers':blgQMUsers})\n\n\n@rest.route('users/blgquser/', methods=['GET'])\n@jwt_required()\ndef get_blgQUsers(loginUser):\n errcode = 1\n blgQUsers = []\n user = UserModel.IsExist(loginUser)\n if user:\n blgQUsers = UserModel.GetBlgQUsers(user.privilege, loginUser)\n errcode = 0\n\n return utils.jsonresp(jsonobj={'errcode':errcode,'blgQUsers':blgQUsers})\n\n\n\n#query all users\n@rest.route('users/', methods=['GET'])\n@jwt_required()\ndef get_users():\n limit = int(request.args.get('limit'))\n page = int(request.args.get('page'))\n # this name allow none, if no value, it mean query all user list under this amdin\n name = request.args.get('name')\n # \n total, users = 0, \"null\"\n loginUser = request.args.get('loginUser')\n ## here, need verify if loginUser has privilege to get user list\n if loginUser:\n user = UserModel.IsExist(loginUser)\n if user:\n if user.privilege == '0': # super admin\n if name:\n total, users = UserModel.SearchUserByName(page, limit, name)\n else:\n total, users = UserModel.GetUsers(page, limit)\n \n if user.privilege == '1': # admin \n if name:\n total, users = UserModel.SearchUserByName(page, limit, name, loginUser)\n else:\n total, users = UserModel.GetUsers(page, limit, loginUser) \n \n\n\n return utils.jsonresp(jsonobj={'total':total, 'limit':limit, 'users':users})\n\n\n\n# create one user\n@rest.route('users/', methods=['POST'])\n#@jwt_required()\ndef create_user():\n data = request.get_json('content')\n print(type(data))\n print(data)\n # need check if username already exist\n username = data.get('username')\n if username:\n user = UserModel.IsExist(username)\n if user:\n errcode = 2 # 2 mean username already exist\n else:\n errcode = UserModel.CreateUser(**data)\n else:\n errcode = 1\n\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n# update one user\n@rest.route('users/', methods=['PUT'])\n#@jwt_required()\ndef update_user(userid):\n data = request.get_json(force=True) \n print(data)\n print(type(data))\n errcode = UserModel.UpdateUser(userid, **data)\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n# delete one user\n@rest.route('users/', methods=['DELETE'])\n#@jwt_required()\ndef delete_user(username):\n errcode = UserModel.DeleteUser(username)\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n# patch del users\n@rest.route('users/batch/', methods=['DELETE'])\n#@jwt_required()\ndef delete_users(usernames):\n errcode = 0\n #nameList = names.split(',')\n for username in usernames.split(','):\n ret = UserModel.DeleteUser(username)\n if ret != 0:\n errcode = 1\n\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n\n# change password\n@rest.route('users/password/', methods=['PUT'])\n#@jwt_required()\ndef change_password(username):\n data = request.get_json(force=True) \n oldpwd = data.get('oldpwd')\n newpwd = data.get('newpwd')\n errcode = 1\n # check if username is exist\n #\n # check privi\n errcode = AUserModel.ChangePwd(username, oldpwd, newpwd )\n #errcode = UserModel.UpdateUser(userid, **data)\n return utils.jsonresp(jsonobj={'errcode':errcode})\n","sub_path":"server/app/rest/userapi.py","file_name":"userapi.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"443145744","text":"import random\r\nimport time\r\nimport sys\r\n\r\ndef d_p(s):\r\n for c in s:\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n time.sleep(0.03)\r\n print(\"\")\r\n\r\ndef bad_input():\r\n print(\"Bad input.\")\r\n time.sleep(1)\r\n print(\"Please try again when prompted.\")\r\n time.sleep(1)\r\n\r\nclass Character:\r\n def __init__(self, name, race, cls, attack, defense, magic, range, hp, stealth, speed, luck, inv):\r\n self.name = name\r\n self.race = race\r\n self.cls = cls\r\n self.attack = attack\r\n self.defense = defense\r\n self.magic = magic\r\n self.range = range\r\n self.hp = hp\r\n self.stealth = stealth\r\n self.speed = speed\r\n self.luck = luck\r\n self.inv = inv\r\n\r\n def get_char_info(Character):\r\n print(Character.name.capitalize(), Character.race.capitalize(), Character.cls.capitalize(),f\"Inventory:{Character.inv}\")\r\n time.sleep(2)\r\n\r\n def get_char_stats(Character):\r\n d_p(f\"Attack = {Character.attack}, Defense = {Character.defense}, Magic = {Character.magic}, Range = {Character.range}\")\r\n d_p(f\"HP = {Character.hp}, Stealth = {Character.stealth}, Speed = {Character.speed}, Luck = {Character.luck}\")\r\n time.sleep(2)\r\n\r\n def dragon_base(Character):\r\n Character.race = \"dragon\"\r\n Character.attack = 150\r\n Character.defense = 150\r\n Character.magic = 1\r\n Character.range = 1\r\n Character.hp = 100\r\n Character.stealth = 2\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def orc_base(Character):\r\n Character.race = \"orc\"\r\n Character.attack = 75\r\n Character.defense = 75\r\n Character.magic = 50\r\n Character.range = 00\r\n Character.hp = 75\r\n Character.stealth = 1\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def human_base(Character):\r\n Character.race = \"human\"\r\n Character.attack = 50\r\n Character.defense = 50\r\n Character.magic = 50\r\n Character.range = 50\r\n Character.hp = 60\r\n Character.stealth = 5\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def elf_base(Character):\r\n Character.race = \"elf\"\r\n Character.attack = 40\r\n Character.defense = 50\r\n Character.magic = 75\r\n Character.range = 75\r\n Character.hp = 50\r\n Character.stealth = 6\r\n Character.speed = 6\r\n Character.inv = ['']\r\n\r\n def dwarf_base(Character):\r\n Character.race = \"dwarf\"\r\n Character.attack = 100\r\n Character.defense = 100\r\n Character.magic = 1\r\n Character.range = 1\r\n Character.hp = 100\r\n Character.stealth = 2\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def shaman(Character):\r\n d_p(\"A shaman uses magic to cripple an opponent's speed, while sapping life from them.\")\r\n d_p(\"Shaman's use wards to prevent enemies from harming them, and spirit energy to attack them.\")\r\n d_p(\"You have gained stats towards magic and defense, and your hp will randomly recover during fights.\")\r\n d_p(\"You have lost all stats in attack and range.\")\r\n\r\n Character.cls = \"shaman\"\r\n Character.magic += 60\r\n Character.defense += 30\r\n Character.attack = 1\r\n Character.range = 1\r\n\r\n def berserker(Character):\r\n d_p(\"A berserker cares nothing for defense and relies on reflexes to avoid damage during a relentless attack.\")\r\n d_p(\"Berserkers gain speed and attack bonuses during fights at the cost of defense.\")\r\n d_p(\"You have gained a massive attack bonus, and a slight speed bonus, but your defense has dropped.\")\r\n d_p(\"You have lost all stats in range and magic.\")\r\n\r\n Character.cls = \"berserker\"\r\n Character.attack += 75\r\n Character.defense -= 25\r\n Character.speed += 2\r\n Character.range = 1\r\n Character.magic = 1\r\n\r\n def rogue(Character):\r\n d_p(\"A rogue uses range to attack from afar and speed to attack quickly in near quarters.\")\r\n d_p(\"Due to a rogue's stealth, they often are successful in one attack assassinations.\")\r\n d_p(\"You have gained bonuses in stealth, speed, and range, and a slight bonus in attack.\")\r\n\r\n Character.cls = \"rogue\"\r\n Character.attack += 10\r\n Character.range += 30\r\n Character.speed += 4\r\n Character.stealth += 5\r\n\r\n def warrior(Character):\r\n d_p(\"A warrior uses speed with attack and defense skills to handle opponents head on.\")\r\n d_p(\"You have gained bonuses in attack, defense, and hp, but have lost all stats in range and mage\")\r\n\r\n Character.cls = \"warrior\"\r\n Character.attack += 40\r\n Character.defense += 40\r\n Character.hp += 10\r\n Character.magic = 1\r\n Character.range = 1\r\n Character.speed += 1\r\n\r\n def ranger(Character):\r\n d_p(\"A ranger uses ranged weapons to handle enemies from afar.\")\r\n d_p(\"Often, rangers are able to get off two attacks before an enemy can attack.\")\r\n d_p(\"You have gained bonuses in range at the cost of attack and magic.\")\r\n\r\n Character.cls = \"ranger\"\r\n Character.range += 75\r\n Character.speed += 1\r\n Character.attack = 1\r\n Character.magic = 1\r\n\r\n def mage(Character):\r\n d_p(\"A mage uses energy to bend reality, especially the elements, to fight.\")\r\n d_p(\"You have gained a massive magic bonus, at the cost of attack and range.\")\r\n\r\n Character.cls = \"mage\"\r\n Character.magic += 75\r\n Character.speed +=1\r\n Character.attack = 1\r\n Character.range = 1\r\n def hunter(Character):\r\n d_p(\"So you have chosen to be a dragon.\")\r\n d_p(\"You are the last of your people, and have thus raised yourself by hunting in the wild.\")\r\n d_p(\"You start with massive stats, but your story will unfold with many mysteries.\")\r\n d_p(\"Be on the lookout for those like you as the story unfolds.\")\r\n\r\n Character.cls = \"hunter\"\r\n\r\n\r\n def player_creation(Character):\r\n ### build race attributes and class attributes\r\n ### Add fancy stuff around mechanics\r\n print(\"Let's build your character.\")\r\n time.sleep(1)\r\n print(\"Please do NOT type until the text has finished displaying.\")\r\n time.sleep(1)\r\n print(\"Typing beforehand will cause return errors, and your character will not be properly built.\")\r\n time.sleep(1)\r\n Character.name = input(\"What is your name? \").lower()\r\n\r\n races = [\"dragon\", \"orc\", \"elf\", \"dwarf\", \"human\"]\r\n print(\"let's select your race. You can be {} or {}.\".format(\", \".join(races[0:-1]), races[-1]))\r\n Character.race = \"\"\r\n while Character.race == \"\":\r\n Character.race = input(\"What race would you like to be: \").lower()\r\n if not Character.race in races:\r\n bad_input()\r\n Character.race = \"\"\r\n getattr(Character, Character.race + \"_base\")()\r\n\r\n classes = (\"mage\", \"ranger\", \"warrior\", \"rogue\", \"berserker\", \"shaman\")\r\n Character.cls = \"\"\r\n while Character.cls == \"\":\r\n if Character.race == \"dragon\":\r\n Character.hunter()\r\n else:\r\n print(\"let's select your race. You can be {} or {}.\".format(\", \".join(classes[0:-1]), classes[-1]))\r\n Character.cls = input(\"What class would you like to be: \").lower()\r\n if not Character.cls in classes:\r\n bad_input()\r\n Character.cls = \"\"\r\n getattr(Character, Character.cls)()\r\n\r\n\r\n luck = random.randint(1, 10)\r\n Character.luck = luck\r\n\r\n def fightIntro(Character):\r\n time.sleep(.5)\r\n print(\"\\n\" * 10)\r\n d_p(\"We are going to quickly simulate a fight between you and a robber before going on.\")\r\n d_p(\"You will be able to do an accurate attack, strong attack, or very aggressive attack.\")\r\n d_p(\"Type the respective number when prompted, and you will attack respective of your class.\")\r\n d_p(\"As the fight goes on, you will see the left over health of your character and the opponent character.\")\r\n d_p(\"If you lose: GAME OVER\")\r\n d_p(\"Let's begin!\")\r\n time.sleep(1.5)\r\n print(\"\\n\" * 10)\r\n\r\n def fight(Character, NPC):\r\n ### To do tasks\r\n ### continue loop so that NPC.speed > character plays...\r\n ### finish the loop without -hp showing\r\n ### create a class based fighting style, so that robbers don't use magic... lol\r\n # create functions that can be called in fights based on character class\r\n\r\n def char_fight_attack():\r\n d_p(\"You can make an accurate attack, a strong attack, or a very aggressive attack.\")\r\n d_p(\"At the prompt, type the number corresponding to your desired attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] accurate, [2] strong, [3] very aggressive: \")\r\n if a == \"1\":\r\n attack = (Character.attack * random.randint(1, 2))\r\n b = 0\r\n elif a == \"2\":\r\n attack = (Character.attack * random.randint(1, 3))\r\n b = 1\r\n elif a == \"3\":\r\n attack = (Character.attack * random.randint(0, 6))\r\n b = 2\r\n else:\r\n bad_input()\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n attack_tuple = (\"Accurate\", \"Strong\", \"Very Aggressive\")\r\n d_p(\"{} used {} attack.\".format(Character.name.capitalize(), attack_tuple[b]))\r\n if total < NPC.hp:\r\n print(f\"{Character.name.capitalize()} did {int(total)} damage!\")\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n elif NPC.hp < 0:\r\n print(f\"{NPC.name} died!\")\r\n def char_fight_mage():\r\n d_p(\"You can use an elemental spell of water, fire, or lightening.\")\r\n d_p(\"At the prompt, type the number corresponding to your desired attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] (water) accurate, [2] (fire) strong, [3] (lightening) very aggressive: \")\r\n if a == \"1\":\r\n attack = (Character.magic * random.randint(1, 2))\r\n b = 0\r\n elif a == \"2\":\r\n attack = (Character.magic * random.randint(1, 3))\r\n b = 1\r\n elif a == \"3\":\r\n attack = (Character.magic * random.randint(0, 6))\r\n b = 2\r\n else:\r\n bad_input()\r\n magic_tuple = (\"water\", \"fire\", \"lightening\")\r\n print(\"{} used {}\".format(Character.name.capitalize(), magic_tuple[b]))\r\n attack = (Character.magic * 2 * random.randint(1, 2))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n\r\n def char_fight_range():\r\n print(\"You used a ranged attack.\")\r\n attack = (Character.range * random.randint(1, 4))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n (int(NPC.hp))\r\n elif NPC.hp <= 0:\r\n print(f\"{NPC.name} died!\")\r\n if ((Character.speed - NPC.speed) > NPC.speed) and NPC.hp > 0:\r\n d_p(f\"{Character.name.capitalize()} was twice as fast as {NPC.name}, and was able to get off an extra shot\")\r\n attack = (Character.attack * random.randint(1, 4))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n\r\n def char_fight_rogue():\r\n if Character.speed > NPC.speed:\r\n first_move = True\r\n while first_move == True:\r\n d_p(\"You make the first move. You can use a stealth attack, a regular attack, or a ranged attack.\")\r\n first_move = input(\"Choose your move [1] stealth [2] regular [3] ranged: \")\r\n if first_move == \"1\":\r\n if Character.stealth < NPC.speed:\r\n attack = 0\r\n elif Character.stealth > NPC.speed:\r\n attack = (Character.attack * random.randint(2, 10))\r\n b = 0\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n first_move = False\r\n elif first_move == \"2\":\r\n attack = (Character.attack * random.randint(1, 2))\r\n b = 1\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n first_move = False\r\n elif first_move == \"3\":\r\n attack = (Character.attack * random.randint(0, 6))\r\n b = 2\r\n attack = (Character.range * random.randint(1, 4))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n first_move = False\r\n else:\r\n bad_input()\r\n first_move = True\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n npc_fight()\r\n while first_move == False:\r\n while Character.hp > 0 and NPC.hp > 0:\r\n d_p(\"You can use a ranged attack or a physical attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] ranged attack [2] physical attack: \")\r\n if a == \"1\":\r\n char_fight_range()\r\n elif a == \"2\":\r\n char_fight_attack()\r\n else:\r\n bad_input()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp < 0:\r\n first_move = \"\"\r\n def char_fight_shaman():\r\n d_p(\"You can use a spirit attack, a defensive ward, or an hp boost.\")\r\n d_p(\"At the prompt, type the number corresponding to your desired attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] spirit attack, [2] defensive ward, [3] hp boost: \")\r\n if a == \"1\":\r\n attack = (Character.magic * random.randint(1, 3) + (Character.hp/NPC.hp))\r\n print(\"You stole your opponent's spirit energy to attack them.\")\r\n attack = (Character.magic * 2 * random.randint(1, 2))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n print(NPC.hp)\r\n elif a == \"2\":\r\n defense = ((Character.defense * (1 + random.random())) // 1)\r\n Character.defense = defense\r\n print(\"You create a defensive ward.\")\r\n print(int(Character.defense))\r\n\r\n elif a == \"3\":\r\n sha_health = (Character.hp + random.randint(10, 100))\r\n Character.hp = sha_health\r\n print(f\"Your hp is now {Character.hp}.\")\r\n else:\r\n bad_input()\r\n\r\n\r\n def npc_fight():\r\n if NPC.cls == \"fighter\":\r\n print(f\"{NPC.name} attacked!\")\r\n attack = (NPC.attack * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n elif NPC.cls == \"mage\":\r\n d_p(f\"{NPC.name} used magic to attack!\")\r\n attack = (NPC.magic * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n elif NPC.cls == \"ranger\":\r\n d_p(f\"{NPC.name} used a ranged attack!\")\r\n attack = (NPC.attack * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n if (NPC.speed - Character.speed) > Character.speed:\r\n d_p(f\"{NPC.name} was twice as fast as {Character.name}, and was able to get off an extra shot\")\r\n attack = (NPC.attack * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense) - 1\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n\r\n a_health = Character.hp\r\n a_defense = Character.defense\r\n while Character.hp > 0 and NPC.hp > 0:\r\n if Character.speed >= NPC.speed:\r\n print(f\"{Character.name.capitalize()}'s turn.\")\r\n time.sleep(1)\r\n if Character.cls in (\"berserker\", \"warrior\", \"hunter\"):\r\n fight_sequence = True\r\n while fight_sequence == True:\r\n char_fight_attack()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp <= 0:\r\n print(f\"{NPC.name} lost.\")\r\n fight_sequence = False\r\n if Character.cls == \"mage\":\r\n fight_sequence = True\r\n while fight_sequence == True:\r\n char_fight_mage()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp <= 0:\r\n print(f\"{NPC.name} lost.\")\r\n fight_sequence = False\r\n if Character.cls == \"rogue\":\r\n char_fight_rogue()\r\n if Character.cls == \"shaman\":\r\n fight_sequence = True\r\n while fight_sequence == True:\r\n char_fight_shaman()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp <= 0:\r\n print(f\"{NPC.name} lost.\")\r\n fight_sequence = False\r\n\r\n\r\n elif NPC.speed > Character.speed:\r\n pass\r\n if Character.hp > 0:\r\n Character.hp = a_health\r\n Character.defense = a_defense\r\n if Character.hp < 0:\r\n print(\"GAME OVER\")\r\n exit()\r\n\r\n\r\n\r\n\r\nclass NPC:\r\n def __init__(self, name, race, cls, attack, defense, magic, range, hp, stealth, speed, luck):\r\n self.name = name\r\n self.race = race\r\n self.cls = cls\r\n self.attack = attack\r\n self.defense = defense\r\n self.magic = magic\r\n self.range = range\r\n self.hp = hp\r\n self.stealth = stealth\r\n self.speed = speed\r\n self.luck = luck\r\n\r\n ### define robber, mage, boss, and other NPC stats\r\n#ignore below this line... testing\r\n# \r\n# player = Character(\"A\", \"human\", \"shaman\", 100, 100, 100, 100, 100, 100, 100, 100, \"\")\r\n# robber = NPC(\"Robber\", \"human\", \"fighter\", 50, 10, 1, 1, 50, 1, 1, random.random())\r\n# rogue_mage = NPC(\"Rogue Mage\", \"human\", \"mage\", 0, 10, 15, 0, 25, 0, 110, 10)\r\n# NPC1 = robber\r\n# NPC2 = rogue_mage\r\n# \r\n# print(\"random dooooog\")\r\n# Character.player_creation(player)\r\n# Character.get_char_stats(player)\r\n# Character.get_char_info(player)\r\n# Character.fightIntro(player)\r\n# Character.fight(player, robber)\r\n# print(player.hp)","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":21392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"7808370","text":"\n#=================================================\n#\n#File Name \t\t: 1.py\n#\n#Purpose \t\t: A func() that return a decimal \n# string from a fraction\n#\n#Creation Date : 22=2=008\n#\n#Last Modified : Mon 22 Dec 2008 10:36:49 PM PST\n#\n#Created By : Prathu Baronia, 14D070046 \n#\n#=================================================\n\nclass Solution:\n # @param A : integer\n # @param B : integer\n # @return a strings\n \n def fractionToDecimal(self, A, B):\n \n def fractional_part(A,B):\n \n rem = abs_A%abs_B\n d = []\n res = \"\"\n \n while(rem!=0 & ~(rem in d)):\n d.append(rem)\n rem = rem*10\n res = res + str(rem//B)\n rem = rem%B\n \n if(rem==0):\n return res\n else:\n return (\"(\" + res + \")\")\n \n if(A==0):\n return 0\n \n sign = 1\n \n if((A<0)^(B<0)):\n sign = -1\n \n abs_A = abs(A)\n abs_B = abs(B)\n \n integer_part = abs_A//abs_B\n \n res = \"\"\n if(sign==-1):\n res = \"-\" + str(integer_part)\n else:\n res = \"\" + str(integer_part)\n \n res = res + fractional_part(abs_A,abs_B)\n \n return res\n\n","sub_path":"Hashing/fraction.py","file_name":"fraction.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"548872990","text":"from protein import Protein\n\nclass BlastMatch():\n\n\tdef __init__(self, target_protein=None, protein_name=None, evalue=None, accession_number=None, description=None, aaseq=None, tags=None):\n\t\tself.target_protein = target_protein\n\t\tself.protein = Protein.from_name_and_sequence(protein_name, aaseq)\n\t\tself.protein.accession_number = accession_number\n\t\tself.protein.description = description\n\t\tself.evalue = evalue\n\t\tself.tags = tags\n\n\tdef __str__(self):\n\t\tretstring = \"Target Protein Name: \" + self.target_protein.name + '\\n'\n\t\tretstring += \"Description: \" + self.protein.description + '\\n'\n\t\tretstring += \"eValue: \" + self.evalue + '\\n'\n\t\tretstring += \"Tags: \" + self.tags + '\\n'\n\t\treturn retstring\n\n\tdef to_csv_line(self):\n\t\tvalues = [self.protein.name, self.evalue, self.protein.accession_number, self.protein.description, self.protein.aaseq, self.tags]\n\t\treturn ','.join(values)\n\nclass BlastInfo():\n\n\tdef __init__(self, target_protein, matches=None):\n\t\tself.target_protein = target_protein\n\t\tself.matches = []\n\t\tif matches:\n\t\t\tself.top_matches = top_matches\n\n\tdef has_result(self):\n\t\treturn self.matches != []\n\n\tdef get_target_protein_name(self):\n\t\treturn self.target_protein.name\n\n\tdef add_match(self, match):\n\t\tself.matches.append(match)\n\n\tdef num_matches(self):\n\t\treturn len(self.matches)\n\n\tdef to_csv_lines(self):\n\t\tretstring = \"\"\n\t\tif self.has_result():\n\t\t\tfor match in self.matches:\n\t\t\t\tretstring += match.to_csv_line() + '\\n'\n\t\telse:\n\t\t\tretstring += self.target_protein.name + ',NO BLAST RESULT\\n'\n\t\treturn retstring\n\n\tdef __str__(self):\n\t\tretstring = \"Blast Info for Target Protein: \" + self.target_protein.name +'\\n'\n\t\tif not self.has_result():\n\t\t\tretstring += \"No matches.\\n\"\n\t\telse:\n\t\t\tfor match in self.matches:\n\t\t\t\tretstring += str(match)\n\t\treturn retstring\n\n\t@staticmethod\n\tdef construct_from_csv(filename):\n\t\tblastinfo_list = []\n\t\twith open(filename) as fp:\n\t\t\tline = fp.readline()\n\t\t\twhile line:\n\t\t\t\tline = line.replace('\\n', '')\n\t\t\t\ttokens = line.split(',')\n\t\t\t\tblastinfo = None\n\t\t\t\tfor item in blastinfo_list:\n\t\t\t\t\tif item.get_target_protein_name() == tokens[0]:\n\t\t\t\t\t\tblastinfo = item\n\t\t\t\t\t\tbreak\n\t\t\t\tif not blastinfo:\n\t\t\t\t\ttarget_protein = Protein.from_name_and_sequence(tokens[0], \"UNKNOWN\")\n\t\t\t\t\tblastinfo = BlastInfo(target_protein)\n\t\t\t\t\tblastinfo_list.append(blastinfo)\n\t\t\t\tif tokens[1].strip() != \"NO BLAST RESULT\":\n\t\t\t\t\tif len(tokens) != 6:\n\t\t\t\t\t\traise ValueError(\"Not enough arguments in data line.\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tblastmatch = BlastMatch(blastinfo.target_protein, tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5])\n\t\t\t\t\t\tblastinfo.add_match(blastmatch)\n\t\t\t\tline = fp.readline()\n\t\treturn blastinfo_list\n\n# blast_results = BlastInfo.construct_from_csv(\"Data/SampleData/SAMPLE_C_BLAST_RESULTS.csv\")\n# print(blast_results[0].to_csv_lines())\n\n\n\n\n\t\t","sub_path":"blast.py","file_name":"blast.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"588773035","text":"\nimport pytest\nimport numpy as np\nimport cntk as C\n\ndef test_outputs():\n fwd_state = C.placeholder(\"placeholder\")\n prev_state = C.sequence.past_value(fwd_state, name=\"prev_state\")\n z = C.abs(prev_state, \"abs\")\n output = z.output\n z = z.replace_placeholders({fwd_state: z.output})\n\n fwd_state = None\n prev_state = None\n z = None\n\n for arg in output.owner.arguments:\n print(\"Argument name: {}, argument owner name {}\".format(arg.name, arg.owner.name))\n\ndef test_0d_data_1d_sample_shape():\n x = C.input_variable(shape=(1,))\n op = x + x\n\n with pytest.raises(ValueError):\n op.eval({x : [np.asarray(2)]})\n\ndef test_1d_NDArrayView_copy():\n x = C.input_variable(shape=(1,))\n op = x + 1\n result = op.eval({x : [np.asarray([1])]}, as_numpy=False)\n result_slice = result.data.slice_view((0, 0), (1,))\n\n w = C.parameter(init=np.asarray([1]))\n w.set_value(result_slice)\n \n assert np.array_equal(w.value, result_slice.asarray())\n\ndef test_sequences_packed_in_single_ndarray():\n dim = 2\n input_with_sequence_axis = C.sequence.input_variable(shape=(dim,))\n\n data = np.asarray([[1, 2], [2, 3]])\n op = C.sequence.last(input_with_sequence_axis)\n result = op.eval({input_with_sequence_axis : data})\n assert np.array_equal(result, [[2., 3.]])\n\n result = op.eval({input_with_sequence_axis : (data, [True, True])})\n assert np.array_equal(result, [[1., 2.], [2., 3.]])\n\n \n","sub_path":"tests/function_test.py","file_name":"function_test.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"40446345","text":"\nfrom collections import defaultdict as dd\n\ndef list_features(input_file, output_file):\n f_cnt = dd(int)\n for line in open(input_file):\n inputs = line.strip().split()\n for t in inputs[1:]:\n f_cnt[t] += 1\n t_len = len(f_cnt.keys())\n f_set = sorted([(k, v) for k, v in f_cnt.iteritems() if v > 1], key = lambda x: x[1], reverse = True)\n\n f2ind = {}\n for i, k in enumerate(f_set):\n f2ind[k[0]] = i\n\n fout = open(output_file, 'w')\n for line in open(input_file):\n inputs = line.strip().split()\n s = inputs[0]\n for t in inputs[1:]:\n if t not in f2ind: continue\n s += \" {}\".format(f2ind[t])\n fout.write(s + '\\n')\n fout.close()\n\nlist_features('../diel/all_list_ALL.tok_feat', 'list_features.txt')","sub_path":"theano/list_features.py","file_name":"list_features.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"236250861","text":"import bottle\nimport pymongo\n\n@bottle.route('/')\ndef index():\n\tconnection = pymongo.MongoClient('localhost')\n\t\n\tdb = connection.test\n\t\n\tnames = db.names\n\t\n\titem = names.find_one()\n\t\n\treturn bottle.template('Hello {{name}}!', name=item['name'])\n\nbottle.run(host='localhost', port=8080)\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"406939481","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.distributions.normal import Normal\nfrom torch.distributions.kl import kl_divergence\n\n# Hyper-parameters \ninput_size = 784\nnum_classes = 10\nnum_epochs = 5\nbatch_size = 100\nlearning_rate = 1e-4\n\n# MNIST dataset (images and labels)\ntrain_dataset = torchvision.datasets.MNIST(root='/Users/sunpeiquan/data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='/Users/sunpeiquan/data',\n train=False,\n transform=transforms.ToTensor())\n\n# Data loader (input pipeline)\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\n# Logistic regression model\nclass Encoder(nn.Module):\n def __init__(self):\n super().__init__()\n self.model = nn.Sequential(\n nn.Linear(input_size, 1024),\n nn.ReLU(),\n nn.Linear(1024, 1024),\n nn.ReLU()\n )\n self.mu = nn.Linear(1024, 256)\n self.sigma = nn.Linear(1024, 256)\n self.decoder = nn.Linear(256, num_classes)\n\n def forward(self, x):\n hidden = self.model(x)\n mu = self.mu(hidden)\n sigma = self.sigma(hidden)\n std = nn.functional.softplus(sigma)\n dist = Normal(mu, std)\n z = dist.rsample()\n return z, dist, mu\n\nencoder = Encoder()\n\n# model = nn.Linear(input_size, num_classes)\n\n# Loss and optimizer\n# nn.CrossEntropyLoss() computes softmax internally\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(encoder.parameters(), lr=learning_rate)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1, 28*28)\n\n # Forward pass\n z, dist, mu = encoder(images)\n prior = Normal(torch.zeros_like(z), torch.ones_like(z))\n kl = 0.001 * kl_divergence(dist, prior).sum(1).mean()\n loss = criterion(z, labels) + kl\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1) % 100 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n\n# Test the model\n# In test phase, we don't need to compute gradients (for memory efficiency)\nwith torch.no_grad():\n correct = 0.\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, 28*28)\n _, _, outputs = encoder(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n\n print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))\n\n# Save the model checkpoint\ntorch.save(encoder.state_dict(), 'model.ckpt')\n","sub_path":"tutorials/01-basics/logistic_regression/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"618641333","text":"# This code if a part of the HPM library for rapid hypersonic modelling.\n# Heads up! This software most likely still contains errors.\n# It is therefore distributed without warranty of merchantability.\n#\n#\n# HPM_read.py: here, all functions for reading of the input data and save data are defined. \n#\n# Developed/ made available: 19/10/2020 by M. Brchnelova\n# Questions? michaela.brchnelova@kuleuven.be\n\n\n\n\nfrom HPM_import import *\n\n\n\n\n\n\ndef ReadNullSpace(filename):\n j = 0.\n null_spaces = []\n with open(filename, \"r\") as ins:\n nullspace_array = []\n for line in ins:\n line = line.strip()\n line = line.split()\n if len(line) == 1:\n nullspace_array.append(float(line[0]))\n if len(line) > 1:\n null_spaces.append(nullspace_array)\n nullspace_array = []\n\n j += 1\n null_spaces.append(nullspace_array)\n\n null_spaces_formatted = []\n for i in range(0, len(null_spaces)):\n null_spaces_formatted.append(null_spaces[i])\n\n return null_spaces_formatted[1:]\n\n\n\n###############################################################################\n\n\n\ndef ReadInviscidData(filename):\n data = []\n nodes = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n nodes.append([x, y, z])\n data.append(float(line[3]))\n\n return data, nodes\n\n\n\n###############################################################################\n\n\n\ndef ReadCentroids(filename):\n centroids = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n centroids.append([x, y, z])\n\n return centroids\n\n\n\n###############################################################################\n\n\n\ndef ReadNormals(filename):\n normals = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n normals.append([x, y, z])\n\n return normals\n\n\n\n###############################################################################\n\n\n\ndef ReadStagPointData(filename):\n stag_points = []\n stg_idxs = []\n epss = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n stag_point = [float(line[0]), float(line[1]), float(line[2])]\n stg_idx = int(line[3])\n eps = float(line[4])\n\n stag_points.append(stag_point)\n stg_idxs.append(stg_idx)\n epss.append(eps)\n\n return stag_points, stg_idxs, epss\n\n\n\n###############################################################################\n\n\n\ndef ReadConnectivity(filename):\n connectivity = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = int(line[0])\n y = int(line[1])\n z = int(line[2])\n\n connectivity.append([x, y, z])\n\n return connectivity\n\n\n\n###############################################################################\n\n\n\ndef ReadSolvedFitting(filename):\n j = 0.\n vectors = []\n with open(filename, \"r\") as ins:\n vector_array = []\n for line in ins:\n line = line.strip()\n line = line.split()\n if len(line) == 1:\n vector_array.append(float(line[0]))\n if len(line) > 1:\n vectors.append(vector_array)\n vector_array = []\n\n j += 1\n vectors.append(vector_array)\n\n solutions_formatted = []\n for i in range(0, len(vectors)):\n solutions_formatted.append(vectors[i])\n\n return solutions_formatted[1:]\n\n\n\n###############################################################################\n\n\n\ndef ReadBacktracingData(filename_intersections, filename_nodepaths, filename_nodecoords, filename_nodesresolved, filename_epsilonnodes):\n intersections = []\n node_paths_elem = []\n node_paths_coord = []\n epsilon_nodes = []\n nodes_resolved_idxs = []\n\n with open(filename_epsilonnodes, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n epsilon_nodes.append([x, y, z])\n\n with open(filename_intersections, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n intersections.append([x, y, z])\n\n with open(filename_nodesresolved, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n node_idx = int(line[0])\n\n nodes_resolved_idxs.append(node_idx)\n\n\n with open(filename_nodepaths, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n node_path = []\n for i in range(0, len(line)):\n node_path.append(int(line[i]))\n\n node_paths_elem.append(node_path)\n\n with open(filename_nodecoords, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n node_path_coord = []\n coord = []\n for i in range(0, len(line)):\n #print line\n if line[i][0] != ',':\n if line[i] != '' and line[i] != ' ' and line[i] != '\\n':\n coord_cur = float(line[i])\n coord.append(coord_cur)\n else:\n if line[i] != '' and line[i] != ' ' and line[i] != '\\n':\n node_path_coord.append(coord)\n if len(line[i][1:]) > 1:\n new_coord = line[i][1:]\n coord = [float(new_coord)]\n\n node_paths_coord.append(node_path_coord)\n\n\n return intersections, node_paths_elem, node_paths_coord, epsilon_nodes, nodes_resolved_idxs\n\n","sub_path":"single_SP/HPM_read.py","file_name":"HPM_read.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"597317139","text":"from pymongo import MongoClient\r\ndef displayCursor(cursor):\r\n words = ''\r\n for doc in cursor:\r\n words += doc[\"word\"] + \",\"\r\n if len(words) > 65:\r\n words = words[:65] + \"...\"\r\n print (words)\r\ndef pageResults(collection, skip):\r\n query = {'first': 'w'} \r\n cursor = collection.find(query)\r\n cursor.limit(10)\r\n cursor.skip(skip)\r\n print (\"Page \" + str(skip+1) + \" to \" + \\\r\n str(skip + cursor.count(True)) + \":\")\r\n displayCursor(cursor);\r\n if(cursor.count(True) == 10):\r\n pageResults(collection, skip+10);\r\nif __name__==\"__main__\":\r\n mongo = MongoClient('mongodb://localhost:27017/')\r\n db = mongo['words']\r\n collection = db['word_stats']\r\n pageResults(collection, 0)","sub_path":"hour17/PythonFindPaging.py","file_name":"PythonFindPaging.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"592529135","text":"import requests\nimport json\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass OpenBD:\n def __init__(self):\n pass\n\n def get_json(self, isbn: str) -> dict:\n api_data = self.__call_api(isbn)\n if api_data == {}:\n return {}\n if api_data[0] == None:\n return {}\n json_data = {}\n json_data['isbn'] = api_data[0]['summary']['isbn']\n json_data['title'] = api_data[0]['summary']['title']\n json_data['series'] = api_data[0]['summary']['series']\n json_data['publisher'] = api_data[0]['summary']['publisher']\n json_data['pubdate'] = self.modify_datetime(api_data[0]['summary']['pubdate'])\n json_data['cover'] = api_data[0]['summary']['cover']\n json_data['author'] = self.clean_author(api_data[0]['summary']['author'])\n return json_data\n\n def __call_api(self, isbn: str) -> dict:\n url = 'https://api.openbd.jp/v1/get?isbn=' + isbn\n response = requests.get(url)\n if response.status_code != 200:\n return {}\n return json.loads(response.text)\n\n def modify_datetime(self, date: str) -> str:\n \"\"\"\n OpenBDのAPIで取得した出版日を整形する\n :param date:\n :return:\n \"\"\"\n return date.replace('c', '')\n\n def clean_author(self, author: str) -> str:\n \"\"\"\n OpenBDのAPIで取得した著者名を修正\n :param author:\n :return:\n \"\"\"\n return author.replace('/著', '')\n","sub_path":"api/book/openbd.py","file_name":"openbd.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"53857233","text":"#!/usr/bin/python\nimport Image\nimport tesseract\n\ndef extractText(pPath):\n lImage = Image.open(pPath) \n lResult = tesseract.image_to_string(lImage, lang=\"deu\")\n print (lResult)\n if (lResult != None):\n \treturn 1, pPath\n else:\n \treturn 0, pPath\n\n","sub_path":"BastelPython/src/Code-Snipels/OpenCV/src/prog/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"635139629","text":"#!/usr/bin/env python\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import column_property\n# cancerhermit\nfrom pg_catalog import pg_namespace, pg_type\nfrom pgvcs import ddl_object, constraint, label, range_params\n\nclass regtype(pg_type,ddl_object):\n __table__ = pg_type.__table__\n _regtype = column_property(\n func.regtypeout(pg_type.oid)\n )\n #format_type = column_property(\n # func.format_type(pg_type.oid,pg_type.typtypmod)\n #)\n parent_cls = [pg_namespace]\n filter = not_(pg_type.typname.like('%pg_toast_%'))\n child_cls = [constraint,label,range_params]\n required = True\n __synonyms__ = dict(\n name = \"typname\",\n default = \"typdefault\"\n )\n unused = [\n \"typlen\",\n \"typbyval\",\n \"typispreferred\",\n \"typisdefined\",\n \"typdelim\",\n \"typarray\",\n \"typalign\",\n \"typstorage\",\n \"typtypmod\",\n \"typndims\",\n \"typdefaultbin\"\n ]\n\n @property\n def regtype(self):\n regtype = self._regtype\n if regtype.find(\".\")>0:\n return regtype[regtype.find(\".\")+1:]\n else:\n return regtype\n\n @property \n def null(self):\n return not self.typnotnull\n\n @property\n def composite(self):\n return self.typtype=='c'\n\n @property\n def domain(self):\n return self.typtype=='d'\n\n @property\n def enum(self):\n return self.typtype=='e'\n\n @property\n def range(self):\n return self.typtype=='r'\n\n @property\n def basetype(self):\n return self.db[self.typbasetype]\n\n @classmethod\n def get_filter(cls,db):\n \"\"\"return SQLAlchemy filter for class\"\"\"\n # required for generate SQL\n required_oids = db.required_pg_type_oids\n schema_oids = map(\n lambda s:s.oid,\n filter(lambda s:s.included,db.schemas)\n )\n return and_(\n cls.filter,\n or_(\n pg_type.typnamespace.in_(schema_oids),\n pg_type.oid.in_(required_oids) if required_oids else None\n )\n )\n\n","sub_path":"pgvcs/ddl/regtype.py","file_name":"regtype.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"233417872","text":"import pandas as pd\nimport pymysql\npymysql.install_as_MySQLdb()\nimport MySQLdb\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nimport warnings\nimport pandas as pd\nimport FinanceDataReader as fdr\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport time\nwarnings.filterwarnings(action='ignore')\nimport user\n\nquerys = pd.read_csv('investing_query.csv')\nsymbol_list = querys['symbol'].values\n\n\n# %%time\ntoday = datetime.today()\n\ndfs = fdr.DataReader(\"US500\",end=today) # fdr 기존 양식에 symbol_list를 추가하기 위해 base_table 생성\ndfs['Symbol'] = \"AAPL\"\nfor i in symbol_list:\n try:# apple data frame에 symbol_list 추가작업 진행\n data = fdr.DataReader(i, end=today)\n df = pd.DataFrame(data)\n df['Symbol'] = i\n dfs = pd.concat([df,dfs])\n except:\n pass\n\ndfs = dfs[['Symbol', 'Close', \"Open\", \"High\", \"Low\", \"Volume\", \"Change\"]]\ndfs = dfs.reset_index() # reset_index()를 사용해 date column에 위치하게 정렬\ndfs = dfs.drop_duplicates(['Symbol', 'Close', \"Open\", \"High\", \"Low\", \"Volume\", \"Change\"]) # 상단에 생성한 중복된 apple 정보 삭제\n# print(dfs)\n# print(\"time :\", time.time() - start) # 현재시각 - 시작시간 = 실행시간\n\nus_stock_basedata = pd.read_csv('./amount_to_be registered.csv') # frd에 없는 data csv로 import\n# us_stock_basedata\n\ndaily = pd.merge(dfs,us_stock_basedata, how='left', on='Symbol') # frd와 csv merge 작업 기준은 symbol로 잡아 왼쪽으로 정렬\n# daily\n\ndaily[\"market_capitalization\"] = daily[\"Close\"]*daily[\"amount_to_be_registered\"]\n# daily\na=daily.rename(columns={\"Change\":\"Changee\"})\nb=a.rename(columns={'index':'Date'})\nb.to_csv('daily_210730_3.csv')\n\n#1. mysqldb 접속객체 세팅(연결하기)\nconnect_datas = {\n 'host': user.host,\n 'user': user.user,\n 'passwd': user.pw,\n 'db': user.db,\n 'charset': 'utf8'\n}\ndb = MySQLdb.connect(**connect_datas)\n# db\n\n#2. 주가데이터 csv파일 불러오기\nstock = pd.DataFrame(b)\nstock_df = stock.drop(columns='Unnamed: 0')\nstock.rename(columns={'Change':'Changee'})\nstock_df.rename(columns={'index':'Date'})\n\n# MYsqldb로 테이블 생성하기\nQUERY = \"\"\"\n CREATE TABLE daily (\n Date DATE,\n Symbol Varchar(5) NOT NULL,\n Close INT(30) NOT NULL,\n Open INT(30)NOT NULL,\n High INT(30) NOT NULL,\n Low INT(30)NOT NULL,\n Volume DOUBLE,\n Changee Varchar(30),\n amount_to_be_registered INT(100),\n market_capitalization DOUBLE,\n FOREIGN KEY (Symbol) REFERENCES company(Symbol)\n )\n\"\"\"\n# cursor객체 생성후 쿼리 실행\ncurs = db.cursor()\ncurs.execute(QUERY)\n\n#3. sqlalchemy 클라이언트 설정\nclient = create_engine('mysql://{}:{}@{}/{}?charset=utf8'.format(user.user, user.pw, user.host, user.db),encoding=\"utf-8\")\nconn = client.connect()\n\n#4. csv파일 db에 담기(Daily file)\nstock.to_sql(name='daily',con=client, if_exists='append',index=False)\nconn.close()","sub_path":"US_stock/Dev/daily_starting.py","file_name":"daily_starting.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"148825287","text":"class Tacotron2Config(object):\n \"\"\"Initialize Tacotron-2 Config.\"\"\"\n\n def __init__(\n self,\n max_len_seq=200,\n max_input_length=1000,\n embedding_hidden_size=64,\n\n # encoder层数\n n_conv_encoder=3,\n encoder_conv_filters=256,\n encoder_conv_kernel_sizes=5,\n encoder_conv_activation=\"relu\",\n encoder_conv_dropout_rate=0.1,\n encoder_lstm_units=256,\n\n # decode(限制条件:initial_hidden_size==2*encoder_lstm_units)\n attention_rnn_dim=512,\n decoder_lstm_dim=512,\n decoder_lstm_rate=0.1,\n initial_hidden_size=512,\n\n # Attention parameters\n attention_dim=128,\n # Location Layer parameters\n attention_filters=32,\n attention_kernel=31,\n\n # Mel-post processing network parameters\n n_prenet_layers=2,\n prenet_units=256,\n prenet_dropout_rate=0.1,\n gate_threshold=0.5,\n\n #postnet-conv1d层数\n n_conv_postnet=3,\n postnet_conv_filters=256,\n postnet_conv_kernel_sizes=5,\n postnet_dropout_rate=0.1,\n postnet_conv_activation=\"tanh\",\n checkpoingt_dir=r\"./checkpoints\",\n\n # ljspeech的path\n wave_train_path=r\"../data/LJSpeech-1.1/train/wavs/\",\n wave_test_path=r\"../data/LJSpeech-1.1/test/wavs/\",\n csv_dir=r\"../data/LJSpeech-1.1/metadata.csv\",\n save_path_dictionary=r\"../data/LJSpeech-1.1/dictionary.json\",\n\n # number的path\n wave_train_path_number=r\"../data/number/train/wavs/\",\n wave_test_path_number=r\"../data/number/test/wavs/\",\n csv_dir_number=r\"../data/number/metadata.csv\",\n save_path_dictionary_number=r\"../data/number/dictionary.json\",\n\n # 关于音频的参数\n sr=22050,\n n_fft=2048,\n frame_shift=0.0125,\n frame_length=0.05,\n hop_length=275,\n win_length=1102,\n n_mels=80,\n power=1.2,\n n_iter=100,\n preemphasis=.97,\n max_db=100,\n ref_db=20,\n top_db=15,\n # 其他\n batch_size=2,\n test_batch_size=1,\n #最大检查点保存数目\n max_to_keep=2,\n ):\n \"\"\"tacotron2参数.\"\"\"\n self.max_len_seq = max_len_seq\n self.max_input_length = max_input_length\n self.embedding_hidden_size = embedding_hidden_size\n self.n_conv_encoder = n_conv_encoder\n self.encoder_conv_filters = encoder_conv_filters\n self.encoder_conv_kernel_sizes = encoder_conv_kernel_sizes\n self.encoder_conv_activation = encoder_conv_activation\n self.encoder_conv_dropout_rate = encoder_conv_dropout_rate\n self.encoder_lstm_units = encoder_lstm_units\n\n # 解码器参数\n self.n_prenet_layers = n_prenet_layers\n self.prenet_units = prenet_units\n self.prenet_dropout_rate = prenet_dropout_rate\n self.attention_dim = attention_dim\n self.attention_filters = attention_filters\n self.attention_kernel = attention_kernel\n self.n_mels = n_mels\n self.attention_rnn_dim = attention_rnn_dim\n self.decoder_lstm_dim = decoder_lstm_dim\n self.decoder_lstm_rate = decoder_lstm_rate\n self.gate_threshold = gate_threshold\n self.initial_hidden_size = initial_hidden_size\n\n # postnet网络\n self.n_conv_postnet = n_conv_postnet\n self.postnet_conv_activation = postnet_conv_activation\n self.postnet_conv_filters = postnet_conv_filters\n self.postnet_conv_kernel_sizes = postnet_conv_kernel_sizes\n self.postnet_dropout_rate = postnet_dropout_rate\n\n # 检查点路径\n self.checkpoingt_dir = checkpoingt_dir\n\n # ljspeech路径\n self.wave_train_path = wave_train_path\n self.wave_test_path = wave_test_path\n self.save_path_dictionary = save_path_dictionary\n self.csv_dir = csv_dir\n\n # number路径\n self.wave_train_path_number = wave_train_path_number\n self.wave_test_path_number = wave_test_path_number\n self.save_path_dictionary_number = save_path_dictionary_number\n self.csv_dir_number = csv_dir_number\n\n # 声音参数\n self.sr = sr\n self.n_fft = n_fft\n self.frame_shift = frame_shift\n self.frame_length = frame_length\n self.hop_length = hop_length\n self.win_length = win_length\n self.n_mels = n_mels\n self.power = power\n self.n_iter = n_iter\n self.preemphasis = preemphasis\n self.max_db = max_db\n self.ref_db = ref_db\n self.top_db = top_db\n\n # 其他\n self.batch_size = batch_size\n self.test_batch_size = test_batch_size\n self.max_to_keep = max_to_keep\n","sub_path":"hlp/tts/tacotron2/config2.py","file_name":"config2.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"172912426","text":"class Node():\n def __init__(self,data):\n self.data = data\n self.next = next\n\nclass myQueue():\n def __init__(self,head = None,tail = None):\n self.head = head\n self.tail = tail\n \n def enqueue(self,data):\n node = Node(data)\n self.head, node.next = node, self.head\n def dequeue(self):\n pos = self.head\n while pos.next!=None:\n prev_pos = pos\n pos = pos.next\n prev_pos.next = None\n return pos.data\n \n def printQueue(self):\n if self.head == None: return\n cur_pos = self.head\n l = []\n while cur_pos.next != None:\n l.append(cur_pos.data)\n cur_pos = cur_pos.next\n l.append(cur_pos.data)\n return l\nq = myQueue()\nq.enqueue(2)\nq.enqueue(4)\nq.enqueue(6)\nprint(q.printQueue())\nprint(q.dequeue())\nprint(q.printQueue())\n","sub_path":"03_queues.py","file_name":"03_queues.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"55362352","text":"import json\n\nfrom digs.raaka_bed.decoder import Decoder\nfrom tools import format as FORM\n\n\n# Nothing in the code ... best we can do is make lists here\nOBJECT_SHORT_NAMES = {\n \n 0x01 : 'BOTTLE', # Word is not in CoCo version \n 0x02 : 'POTION',\n 0x03 : 'RUG',\n 0x04 : 'DOOR_RUG',\n 0x05 : 'FOOD',\n 0x06 : 'STATUE_FACING_EAST',\n 0x07 : 'STATUE_FACING_WEST',\n 0x08 : 'RING',\n 0x09 : 'SWORD',\n 0x0A : 'GARGOYLE_STONE',\n 0x0B : 'ALTAR_STAINED',\n 0x0C : 'IDOL',\n 0x0D : 'GATE',\n 0x0E : 'LEVER_UNPULLED',\n 0x0F : 'LEVER_PULLED',\n \n 0x10 : 'PLAQUE_LEVER',\n 0x11 : 'CANDLE_UNLIT',\n 0x12 : 'CANDLE_LIT',\n 0x13 : 'PLAQUE_TUNNEL',\n 0x14 : 'LAMP_LIT',\n 0x15 : 'SERPENT_LIVE',\n 0x16 : 'SERPENT_DEAD',\n 0x17 : 'HANDS',\n 0x18 : 'COIN',\n 0x19 : 'SLOT',\n 0x1A : 'PLAQUE_SLOT',\n 0x1B : 'DOOR_CLOSED',\n 0x1C : 'DOOR_OPEN',\n 0x1D : 'PLAYER',\n 0x1E : 'GARGOYLE_LIVE',\n 0x1F : 'GARGOYLE_DEAD',\n \n 0x20 : 'WALL',\n 0x21 : 'VINE',\n 0x22 : 'CHOPSTICK',\n 0x23 : 'GUARD',\n 0x24 : 'GUARD_REPORTER',\n 0x25 : 'GEM_MOVER',\n 0x26 : 'GEM_TREASURE',\n 0x27 : 'ROOM',\n 0x28 : 'LAMP_UNLIT',\n 0x29 : 'FLOOR',\n 0x2A : 'EXIT',\n 0x2B : 'PASSAGE',\n 0x2C : 'HOLE',\n 0x2D : 'CORRIDOR',\n 0x2E : 'CORNER',\n 0x2F : 'BOW',\n \n 0x30 : 'ARROW',\n 0x31 : 'HALLWAY',\n 0x32 : 'CHAMBER',\n 0x33 : 'VAULT',\n 0x34 : 'ENTRANCE',\n 0x35 : 'TUNNEL',\n 0x36 : 'JUNGLE',\n 0x37 : 'TEMPLE',\n 0x38 : 'SERPENTS',\n 0x39 : 'PIT',\n 0x3A : 'CEILING',\n 0x3B : 'ALTAR_UNDER',\n 0x3C : 'AMBIENT_SOUNDS', \n \n 0xFF : '??255',\n}\n\nchkr = []\nfor k in OBJECT_SHORT_NAMES:\n if OBJECT_SHORT_NAMES[k] in chkr:\n raise Exception('DUPLICATE '+OBJECT_SHORT_NAMES[k])\n chkr.append(OBJECT_SHORT_NAMES[k])\n\nROOM_SHORT_NAMES = {\n 0x00 : 'NOWHERE',\n 0xFF : 'EVERYWHERE',\n 0x81 : 'Small room granite walls',\n 0x82 : 'Oriental rug',\n 0x83 : 'Dark passage',\n 0x84 : 'Top of a passage',\n 0x85 : 'T-shaped room 1',\n 0x86 : 'Gray stone walls 1',\n 0x87 : 'Round room high walls 1',\n 0x88 : 'Triangular room',\n 0x89 : 'South end central hall',\n 0x8A : 'T-shaped room 2',\n 0x8B : 'Grey stone walls 2', # Not the 'GRAY stone walls'\n 0x8C : 'Round room high walls 2',\n 0x8D : 'Petite chamber',\n 0x8E : 'Smells of decaying flesh',\n 0x8F : 'Tall room',\n 0x90 : 'North end central hall',\n 0x91 : 'Vault',\n 0x92 : 'Entrance long dark tunnel west',\n 0x93 : 'Dark tunnel',\n 0x94 : 'Entrance long dark tunnel east',\n 0x95 : 'Large room',\n 0x96 : 'Dense dark damp jungle',\n 0x97 : 'Dark dense damp jungle',\n 0x98 : 'See east wall',\n 0x99 : 'Stands south wall',\n 0x9A : 'See bronze gates',\n 0x9B : 'See north wall',\n 0x9C : 'Standing west entrance',\n 0x9D : 'At north wall',\n 0x9E : 'At east wall',\n 0x9F : 'At south wall',\n 0xA0 : 'Very small room',\n 0xA1 : 'Small room',\n 0xA2 : 'Dark damp dense jungle',\n 0xA3 : 'Dense damp dark jungle',\n 0xA4 : 'Damp dark dense jungle',\n 0xA5 : 'Secret passage',\n 0xA6 : 'End of the passage',\n}\n\nHELPER_SHORT_NAMES = {\n 0x81: 'ResetGame',\n 0x82: 'DeathByStatue',\n 0x83: 'Manipulate',\n 0x84: 'PrintPeriod',\n 0x85: 'PrintGuardsMarchRight',\n 0x86: 'PrintGuardsAroundCorner',\n 0x87: 'PrintGuardsDisappearLeft', \n 0x88: 'PrintTheNOUNIsNotBurning', \n 0x89: 'PrintCantJumpThatFar',\n 0x8A: 'DeathByRugSpike',\n 0x8B: 'DeathByHiddenRugSpike',\n 0x8C: 'PrintDiscoverPit',\n 0x8D: 'PrintStatueTooHeavy',\n 0x8E: 'PrintMoveAlter',\n 0x8F: 'EnterSecretPassage',\n 0x90: 'PrinteAlterMovesBack',\n 0x91: 'SealUpHole',\n 0x92: 'PrintScore',\n 0x93: 'InvalidClimbInOrOut',\n 0x94: 'PrintUseDirections',\n 0x95: 'ResetDungeon',\n 0x96: 'PrintGoodWayToLoseHand',\n 0x97: 'PrintMouthImGame',\n 0x98: 'PrintGiantLeapForYou' \n}\n \nINFO_TRS80 = {\n 'binfile' : '../../../content/TRS80/RaakaTu/RAAKA.bin',\n 'codefile' : '../../../content/TRS80/RaakaTu/Code.md',\n 'origin' : 0x4300,\n 'word_data' : 0x52C2,\n 'phrase_data' : 0x50B9,\n 'object_data' : 0x5651,\n 'general_commands_data' : 0x73FB,\n 'helper_commands_data' : 0x7BCD,\n 'room_descriptions_data' : 0x681F,\n 'command_table': 0x5066,\n}\n\nINFO_COCO = {\n 'binfile' : '../../../content/CoCo/RaakaTu/RaakaTu.bin',\n 'codefile' : '../../../content/CoCo/RaakaTu/Code.md',\n 'origin' : 0x0600,\n 'word_data' : 0x3C29,\n 'phrase_data' : 0x135B,\n 'command_table': 0x12E5,\n \n 'object_data' : 0x20FF, \n 'general_commands_data' : 0x323C,\n 'helper_commands_data' : 0x37FA,\n 'room_descriptions_data' : 0x1523, # same for coco/trs80 \n}\n\ncoco = Decoder(INFO_COCO,OBJECT_SHORT_NAMES,ROOM_SHORT_NAMES,HELPER_SHORT_NAMES)\ntrs80 = Decoder(INFO_TRS80,OBJECT_SHORT_NAMES,ROOM_SHORT_NAMES,HELPER_SHORT_NAMES)\n\ndef make_original_json(plat,name_tag):\n with open('rooms_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_room_descriptions()\n js = json.dumps(js,indent=2)\n f.write(js)\n with open('objects_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_objects()\n js = json.dumps(js,indent=2)\n f.write(js) \n with open('general_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_general()\n js = json.dumps(js,indent=2)\n f.write(js) \n with open('helper_raakas_'+name_tag+'.json','w') as f:\n js = plat.tojson_helpers()\n js = json.dumps(js,indent=2)\n f.write(js) \n with open('words_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_words()\n js = json.dumps(js,indent=2)\n f.write(js)\n with open('phrases_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_phrases()\n js = json.dumps(js,indent=2)\n f.write(js)\n \nmake_original_json(trs80,'trs80')\n\n\"\"\"\nplat = coco\nout = []\nplat.print_general_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_helper_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_room_descriptions(out)\nplat.merge_into(out)\nout = []\nplat.print_object_data(out)\nplat.merge_into(out)\nout = []\nplat.print_words(out)\nplat.merge_into(out)\nout = []\nplat.print_phrases(out)\nplat.merge_into(out)\n\nplat.fix_command_names()\n\nplat = trs80\nout = []\nplat.print_general_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_helper_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_room_descriptions(out)\nplat.merge_into(out)\nout = []\nplat.print_object_data(out)\nplat.merge_into(out)\nout = []\nplat.print_words(out)\nplat.merge_into(out)\nout = []\nplat.print_phrases(out)\nplat.merge_into(out)\n\nplat.fix_command_names()\n\nwith open('rooms_raaka_trs80.json','w') as f:\n js = plat.tojson_room_descriptions()\n js = json.dumps(js,indent=2)\n f.write(js)\nwith open('objects_raaka_trs80.json','w') as f:\n js = plat.tojson_objects()\n js = json.dumps(js,indent=2)\n f.write(js) \nwith open('general_raaka_trs80.json','w') as f:\n js = plat.tojson_general()\n js = json.dumps(js,indent=2)\n f.write(js) \nwith open('helper_raakas_trs80.json','w') as f:\n js = plat.tojson_helpers()\n js = json.dumps(js,indent=2)\n f.write(js) \nwith open('words_raaka_trs80.json','w') as f:\n js = plat.tojson_words()\n js = json.dumps(js,indent=2)\n f.write(js)\nwith open('phrases_raaka_trs80.json','w') as f:\n js = plat.tojson_phrases()\n js = json.dumps(js,indent=2)\n f.write(js)\n\"\"\"\n \n\"\"\"\nin_trs80 = []\nfor t in trs80._words:\n for w in trs80._words[t]:\n in_trs80.append(FORM.shex2(w['num'])+' '+w['text'])\n \nin_coco = []\nfor t in coco._words:\n for w in coco._words[t]:\n in_coco.append(FORM.shex2(w['num'])+' '+w['text'])\n\"\"\"\n\n\"\"\"\nin_trs80 = []\nfor ph in trs80._phrases:\n in_trs80.append(trs80.phrase_to_string(ph,True))\n \nin_coco = []\nfor ph in coco._phrases:\n in_coco.append(coco.phrase_to_string(ph,True)) \n\"\"\"\n\n\"\"\"\nin_coco=[]\nobs = coco.tojson_objects(False)\nfor o in obs:\n in_coco.append(str(o))\n \nin_trs80=[]\nobs = trs80.tojson_objects(False)\nfor o in obs:\n in_trs80.append(str(o))\n \n\nprint('In CoCo but not TRS80')\nfor i in in_coco:\n if not i in in_trs80:\n print(i)\n \nprint('In TRS80 but not CoCo')\nfor i in in_trs80:\n if not i in in_coco:\n print(i)\n\"\"\"","sub_path":"computerarcheology/digs/raaka_bed/decode_raakatu_data.py","file_name":"decode_raakatu_data.py","file_ext":"py","file_size_in_byte":8345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"336192729","text":"# import paho.mqtt.client as mqtt\r\nimport json\r\nimport time\r\nimport os\r\n\r\nfrom helper import get_logger\r\n\r\n\r\nclass MqttClient:\r\n \"\"\"\r\n It deals with MQTT Broker directly.\r\n \"\"\"\r\n def __init__(self, client_mqtt):\r\n self.mqtt_client = client_mqtt\r\n self._connection_ok = False \r\n self._pub_result = False\r\n self._sub_result = False\r\n self._sub_msgs = []\r\n self._qos = 0\r\n\r\n self.logger = get_logger(name=__name__, _type=\"mqtt\")\r\n\r\n def on_connect(self, client, userdata, flags, rc):\r\n if rc != 0:\r\n raise RuntimeError(\"MQTT Broker connection failed.\")\r\n else:\r\n self._connection_ok = True\r\n \r\n def on_disconnect(self, client, userdata, flags):\r\n self.mqtt_client.loop_stop()\r\n self._connection_ok = False\r\n\r\n def on_log(self, client, userdata, level, buf): \r\n self.logger.debug(\"Client: %s -- %s\" % client, buf)\r\n\r\n def on_publish(self, client, userdata, mid):\r\n self._pub_result = True\r\n \r\n def on_subscribe(self, client, userdata, mid, granted_qos):\r\n self._sub_result = True\r\n self.logger(\"Ready to receive Signal\")\r\n\r\n def on_message(self, client, userdata, message):\r\n logger = get_logger(_type=\"cloud_rx\", name=__name__)\r\n time.sleep(0.1)\r\n logger.info(\"Signal Received.\")\r\n self._sub_msgs.append(str(message.payload))\r\n \r\n from cloud import SignalReception\r\n SignalReception().process_signal(message.payload)\r\n \r\n logger.info(\"Signal Processed Successfully\")\r\n\r\n def get_connection_details(self):\r\n try:\r\n path = \"/opt/app/arduino_app/CutiePi/\"\r\n with open(os.path.join(path, 'config/mqtt_config.json'), \"r\") as config_file:\r\n connection = json.load(config_file)\r\n self._qos = int(connection[\"qos\"])\r\n return connection\r\n except Exception as e:\r\n self.logger.exception(\"Error in getting Broker details\")\r\n raise RuntimeError(\"Could not get Broker details.\") \r\n \r\n def connect_target(self):\r\n \"\"\"\r\n Connects to MQTT broker and returns a MQTT Client object.\r\n \"\"\"\r\n\r\n connection_details = self.get_connection_details()\r\n\r\n self.mqtt_client.username_pw_set(connection_details['USERNAME'], connection_details['PASSWORD'])\r\n\r\n self.mqtt_client.on_connect = self.on_connect\r\n self.mqtt_client.on_disconnect = self.on_disconnect\r\n self.mqtt_client.on_publish = self.on_publish\r\n self.mqtt_client.on_subscribe = self.on_subscribe\r\n self.mqtt_client.on_message = self.on_message\r\n self.mqtt_client.on_log = self.on_log\r\n \r\n try:\r\n self.mqtt_client.connect(\r\n connection_details['HOST'],\r\n connection_details['PORT'],\r\n connection_details['keepalive'])\r\n except Exception as e: \r\n # del self.mqtt_client\r\n self.logger.exception(\"Error in connection...!!!\")\r\n raise RuntimeError(\"MQTT Broker connection failed.\")\r\n \r\n time.sleep(0.2)\r\n\r\n def transmit_signal(self, topic, message):\r\n self.connect_target()\r\n \r\n self.mqtt_client.loop_start()\r\n time.sleep(0.5)\r\n self.mqtt_client.publish(topic=topic, payload=str(message), qos=self._qos)\r\n time.sleep(0.1)\r\n self.logger.info(\"Signal transmitted successfully.\")\r\n \r\n if self._connection_ok or self._pub_result:\r\n self.disconnect_from_broker()\r\n\r\n def receive_signal(self, channel):\r\n self.connect_target()\r\n try:\r\n self.mqtt_client.subscribe(channel, qos=self._qos)\r\n except:\r\n self.logger.exception(\"Error in Recieving Signal\")\r\n raise RuntimeError(\"Unable to receive from channel: \", channel)\r\n\r\n self.mqtt_client.loop_forever()\r\n\r\n def disconnect_from_broker(self):\r\n self.mqtt_client.disconnect()\r\n time.sleep(0.1)\r\n","sub_path":"libraries/mqtt_engine.py","file_name":"mqtt_engine.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"496517411","text":"def citanjeIzFajla(_file, _separator):\n final_list = []\n temp_list = []\n file = open(_file, \"r\")\n separator = _separator\n lines = file.readlines()\n for line in lines:\n temp_list = line.strip(\"\\n\").split(separator)\n final_list.append(temp_list)\n\n file.close()\n return final_list\n\nif __name__ == \"__main__\":\n print(citanjeIzFajla(\"korisnici.txt\",\"|\"))\n\n","sub_path":"vezba5/zadatak3.py","file_name":"zadatak3.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"26877307","text":"def sequentialSearch(myList, item):\n count = 0\n found = False\n\n while count < len(myList) and not found:\n if myList[count] == item:\n found = True\n else:\n count = count+1\n return found\n\ntestlist=[1,2,32,8,17,19,42,13,0]\nprint(sequentialSearch(testlist, 3))\nprint(sequentialSearch(testlist, 13))\n\ndef orderedSequentialSearch(myList,item):\n count = 0\n found = False\n stop = False\n while count < len(myList) and not found and not stop:\n if myList[count] == item:\n found = True\n else:\n if myList[count] > item:\n stop = True\n else:\n count = count+1\n return found\n\ntestlist = [0,1,2,8,13,17,19,32,42]\nint(orderedSequentialSearch(testlist, 3))","sub_path":"Python/sequentialSearch.py","file_name":"sequentialSearch.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"414948258","text":"import unittest\n\n\nclass Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n return any(i == target for row in matrix for i in row)\n\n\nclass Test(unittest.TestCase):\n def test(self):\n matrix = [\n [1, 4, 7, 11, 15],\n [2, 5, 8, 12, 19],\n [3, 6, 9, 16, 22],\n [10, 13, 14, 17, 24],\n [18, 21, 23, 26, 30]\n ]\n self._test(matrix, 5, True)\n self._test(matrix, 20, False)\n\n def _test(self, matrix, target, expected):\n actual = Solution().searchMatrix(matrix, target)\n self.assertEqual(expected, actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"problems/test_0240_bruteforce.py","file_name":"test_0240_bruteforce.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"278933261","text":"import asyncio\nimport sys\n\n# cette constante est utile pour déclarer qu'on a l'intention\n# de lire les sorties (stout et stderr)\n# de nos sous-process par l'intermédiaire de pipes\nfrom subprocess import PIPE\n\nclass Scheduler:\n\n def __init__(self, script, fut):\n\n #future object\n self.fut = fut\n # on trie le script par ordre chronologique\n self.script = list(script)\n self.script.sort(key = lambda time_predef : time_predef[0])\n\n # juste pour donner un numéro à chaque processus\n self.counter = 1\n # combien de processus sont actifs\n self.running = 0\n # nombre de processus à executer et nombre de processus terminés\n self.to_be_run = len(script)\n self.finished = 0\n\n\n async def run(self):\n \"\"\"\n fait tout le travail, c'est-à-dire :\n * lance tous les sous-processus à l'heure indiquée\n * et aussi en préambule, pour le mode avec clavier,\n arme une callback sur l'entrée standard\n \"\"\"\n # pour le mode avec clavier (pas fonctionnel dans le notebook)\n # on arme une callback sur stdin\n asyncio.get_running_loop().add_reader(\n # il nous faut un file descriptor, pas un objet Python\n sys.stdin.fileno(),\n # la callback\n Scheduler.read_keyboard_line,\n # les arguments de la callback\n # cette fois c'est un objet Python\n self, sys.stdin\n )\n \n # le scénario prédéfini\n epoch = 0\n for tick, predef in self.script:\n # attendre le bon moment\n await asyncio.sleep(tick - epoch)\n # pour le prochain\n epoch = tick\n asyncio.ensure_future(self.fork_players(predef))\n\n\n async def fork_players(self, predef):\n \"\"\"\n lance maintenant une instance de players.py avec cette config\n\n puis\n écoute à la fois sdtout et stderr, et les imprime\n (bon c'est vrai que players n'écrit rien sur stderr)\n attend la fin du sous-processus (avec wait())\n et retourne son code de retour (exitcode) du sous-processus\n\n par commodité on décide d'arrêter la boucle principale\n lorsqu'il n'y a plus aucun process actif\n \"\"\"\n\n # la commande à lancer pour forker une instance de players.py\n # l'option python -u sert à désactiver le buffering sur stdout\n command = f\"python3 -u players.py {predef}\".split()\n \n # pour afficher un nom un peu plus parlant\n worker = f\"ps#{self.counter} (predef {predef})\"\n\n # housekeeping\n self.counter += 1\n self.running += 1\n\n # c'est là que ça se passe : on forke\n print(8 * '>', f\"worker {worker}\")\n process = await asyncio.create_subprocess_exec(\n *command,\n stdout=PIPE, stderr=PIPE,\n )\n # et on lit et écrit les canaux du sous-process\n stdout, stderr = await asyncio.gather(\n self.read_and_display(process.stdout, worker),\n self.read_and_display(process.stderr, worker))\n # qu'il ne faut pas oublier d'attendre pour que l'OS sache\n # qu'il peut nettoyer\n retcod = await process.wait()\n \n # le process est terminé\n self.running -= 1\n self.finished += 1\n print(8 * '<', f\"worker {worker} - exit code {retcod}\"\n f\" - {self.running} still running\")\n \n # si c'était le dernier on sort de la boucle principale\n # if self.running == 0:\n # Plus de processus en cours d'execution ET tous les processus executés\n if self.running == 0 and self.finished == self.to_be_run:\n print(\"no process left - bye\")\n # On donne un résultat à l'objet pour le set à done\n self.fut.set_result(\"end\")\n # sinon on retourne le code de retour\n return retcod\n\n\n async def read_and_display(self, stream, worker):\n \"\"\"\n une coroutine pour afficher les sorties d'un canal\n stdout ou stderr d'un sous-process\n elle retourne lorsque le processus est terminé\n \"\"\"\n while True:\n bytes = await stream.readline()\n # l'OS nous signale qu'on en a terminé\n # avec ce process en renvoyant ici un objet bytes vide\n if not bytes:\n break\n \n # bien qu'ici players n'écrit que de l'ASCII\n # readline() nous renvoie un objet `bytes`\n # qu'il faut convertir en str \n line = bytes.decode().strip()\n print(8 * ' ', f\"got `{line}` from {worker}\")\n\n\n # ceci est seulement fonctionnel si vous exécutez\n # le programme localement sur votre ordinateur\n # car depuis un notebook le clavier est intercepté\n # par le serveur web\n def read_keyboard_line(self, stdin):\n \"\"\"\n ceci est une callback; eh oui :)\n c'est pourquoi d'ailleurs ce n'est pas une coroutine\n cependant on est sûr qu'elle n'est appelée\n que lorsqu'il y a réellement quelque chose à lire\n \"\"\"\n line = stdin.readline().strip()\n # ici je triche complètement\n # lorsqu'on est dans un notebook, pour bien faire\n # on ne devrait pas regarder stdin du tout\n # mais pour garder le code le plus simple possible\n # je choisis d'ignorer les lignes vides ici\n # comme ça mon code marche dans les deux cas\n if not line:\n return\n # on traduit la ligne tapée au clavier\n # en un entier entre 1 et 4\n try:\n predef = int(line)\n if not (1 <= predef <= 4):\n raise ValueError('entre 1 et 4')\n except Exception as e:\n print(f\"{line} doit être entre 1 et 4 {type(e)} - {e}\")\n return\n asyncio.ensure_future(self.fork_players(predef))\n # Un nouveau processus à executer\n self.to_be_run += 1\n\nclass Clock:\n\n def __init__(self, fut):\n self.clock_seconds = 0\n self.fut = fut\n\n async def run(self):\n while not self.fut.done():\n print(f\"clock = {self.clock_seconds:04d}s\")\n await asyncio.sleep(1)\n self.clock_seconds += 1\n\n\nclass Game:\n\n def __init__(self, script):\n self.script = script\n\n async def mainloop(self):\n loop = asyncio.get_running_loop()\n fut = loop.create_future()\n\n # on met ensemble une clock et un scheduler\n clock = Clock(fut)\n scheduler = Scheduler(self.script, fut)\n\n # et on fait tourner le tout\n asyncio.ensure_future(clock.run())\n asyncio.ensure_future(scheduler.run())\n await fut\n\n# nous allons juxtaposer 3 instances de players.py\n# et donc avoir 6 joueurs dans le jeu\n# La dernière instance se déroulera alors que les 2 premières sont terminées\ngame = Game( [(0.5, 1), (1., 2), (6., 3)])\n\n# si vous êtes dans un notebook\n# await game.mainloop()\nasyncio.run(game.mainloop())\n","sub_path":"games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"444524231","text":"from tkinter import *\nimport sqlite3 as sq\nfrom tkinter import ttk\nimport books as books\nimport datetime\n\nclass Rental():\n def __init__(self, master):\n\n ####### Master #############\n self.rent_master=master\n style = ttk.Style()\n style.configure(\"Treeview.Heading\", font=(None, 10))\n\n self.mainFrame=_mainFrame(self.rent_master, row=0, column=0)\n self.message=_message(self.mainFrame.frame, row=1, column=0)\n self.rentFrame=_rentFrame(self.mainFrame.frame, row=2, column=0)\n self.searchFrame=_searchFrame(self.mainFrame.frame, self.message, self.rentFrame, row=0, column=0)\n self.menuFrame =_menuFrame(self.rent_master, self.searchFrame, row=0, column=1, sticky=NS)\n\nclass _mainFrame():\n def __init__(self, parent, *args, **kwargs):\n self.frame=Frame(parent)\n print(kwargs['row'])\n self.frame.grid(row=kwargs['row'], column=kwargs['column'], padx=3)\n\nclass _message():\n def __init__(self, parent, *args, **kwargs):\n self.frame=Frame(parent)\n self.frame.grid(row=kwargs['row'], column=kwargs['column'], pady=10, sticky=W, padx=10)\n\n self.status_message=Label(self.frame, text='', fg='red', width=15)\n self.status_message.grid(row=0, column=0)\n\n self.member_info=Frame(self.frame)\n self.member_info.grid(row=0, column=1)\n\n Label(self.member_info, text='이름:', fg='blue').grid(row=0, column=0, sticky=W, padx=10 )\n self.name=Label(self.member_info, text='', fg='blue')\n self.name.grid(row=0, column=1, sticky=W, padx=10 )\n\n Label(self.member_info, text='휴대폰:', fg='blue').grid(row=1, column=0, sticky=W, padx=10 )\n self.phone=Label(self.member_info, text='', fg='blue')\n self.phone.grid(row=1, column=1, sticky=W, padx=10 )\n\n Label(self.member_info, text='주소:', fg='blue').grid(row=2, column=0, sticky=W, padx=10 )\n self.address=Label(self.member_info, text='', fg='blue')\n self.address.grid(row=2, column=1, sticky=W, padx=10 )\n\n def update_status_info(self, message):\n self.status_message['text']=message\n\n def update_member_info(self, row):\n self.name['text']=row[1]\n self.phone['text']=row[2]\n self.address['text']=row[3]\n\nclass _rentFrame():\n def __init__(self, parent, *args, **kwargs):\n ############# Tree ###################\n self.tree = ttk.Treeview(parent, height=15, column=('rent_date', 'title', 'vol', 'genre', 'author', 'days'),\n show='headings', selectmode=\"browse\")\n self.tree.grid(row=kwargs['row'], column=kwargs['column'], pady=10)\n\n # scrollbar\n ysb = ttk.Scrollbar(parent, orient='vertical', command=self.tree.yview)\n ysb.grid(row=2, column=1, sticky='ns', pady=10)\n self.tree.configure(yscroll=ysb.set)\n\n self.tree.heading('#1', text='대여일')\n self.tree.heading('#2', text='제목')\n self.tree.heading('#3', text='권')\n self.tree.heading('#4', text='장르')\n self.tree.heading('#5', text='저자')\n self.tree.heading('#6', text='경과일')\n\n self.tree.column('rent_date', width=150, anchor=CENTER)\n self.tree.column('title', width=170, anchor=CENTER)\n self.tree.column('vol', width=40, anchor=CENTER)\n self.tree.column('genre', width=40, anchor=CENTER)\n self.tree.column('author', width=40, anchor=CENTER)\n self.tree.column('days', width=50, anchor=CENTER)\n #####################################\n\n def update_rent_info(self, member_id):\n con = sq.connect('guelbang.db')\n c = con.cursor()\n query = 'SELECT RentDate, Title, Vol, Genre, AUthor FROM RENT join BOOK on BOOK.Id=RENT.BookId where MemberId=?'\n parameters = (member_id,)\n c.execute(query, parameters)\n\n rows = c.fetchall()\n for row in rows:\n delta = datetime.datetime.now() - datetime.datetime.strptime(row[0], \"%Y-%m-%d %H:%M:%S\")\n row=row + (delta.days,)\n self.tree.insert(\"\", END, values=row)\n\n c.close()\n\n def clear_rent_info(self):\n self.tree.delete(*self.tree.get_children())\n\nclass _searchFrame():\n def __init__(self, parent, message, tree, *args, **kwargs):\n\n # setting Frame\n self.searchFrame = Frame(parent)\n self.searchFrame.grid(row=kwargs['row'], column=kwargs['column'], sticky=W)\n # search bar\n self.searchMember = Entry(self.searchFrame, width=20)\n self.searchMember.grid(row=0, column=0, padx=10, sticky=W)\n # connected Frame\n self.message=message\n self.tree=tree\n # button\n Button(self.searchFrame, text='검색', command= lambda:self.search_members(self.searchMember.get())).grid(row=0,column=1)\n\n def search_validation(self, parameters):\n return len(parameters)!=0\n\n def search_members(self, parameters):\n if self.search_validation(parameters):\n\n member_row=self.search_query_return(parameters)\n\n if len(member_row)==0:\n self.message.update_status_info('검색결과가 없습니다')\n\n elif len(member_row)==1:\n self.message.update_member_info(member_row[0])\n self.tree.clear_rent_info()\n self.selected_id=member_row[0][0]\n self.tree.update_rent_info(self.selected_id)\n\n else:\n self.popup=PopupMember(self.searchFrame, self.message, self.tree, member_row)\n\n\n else:\n self.message.update_status_info('글자를 입력하세요')\n\n def search_query_return(self, parameters):\n con = sq.connect('guelbang.db')\n c = con.cursor()\n query = 'select Id, Name,Phone,Address from MEMBER where Name like ?'\n c.execute(query, ('%{}%'.format(parameters),))\n rows=c.fetchall()\n c.close()\n return rows\n\nclass PopupMember():\n def __init__(self, parent, message, tree, fetch_rows):\n\n self.parent=parent\n ## popup new window\n self.win_master =Toplevel(parent)\n\n # connected widget\n self.message=message\n self.rentFrame=tree\n\n # determine popup position\n x_axis = parent.winfo_x()\n y_axis = parent.winfo_y()\n self.win_master.geometry('+{}+{}'.format(x_axis + 600, y_axis + 400))\n\n # generate Frame within windows\n self.mainFrame = Frame(self.win_master)\n self.mainFrame.grid(row=0, column=0)\n\n # generate treeviews\n self.tree = ttk.Treeview(self.mainFrame, height=5, column=('no','name','mobile','address'),show='headings', selectmode='browse')\n self.tree.grid(row=0, column=0)\n\n self.tree.heading('#1', text='번호')\n self.tree.heading('#2', text='이름')\n self.tree.heading('#3', text='핸드폰')\n self.tree.heading('#4', text='주소')\n\n self.tree.column('no',width=40, anchor=CENTER)\n self.tree.column('name',width=80, anchor=CENTER)\n self.tree.column('mobile', width=120, anchor=CENTER)\n self.tree.column('address', width=200, anchor=CENTER)\n\n for row in fetch_rows:\n self.tree.insert(\"\",END,values=row)\n\n # button\n Button(self.mainFrame, text='선택', command=self.proceed).grid(row=1, column=0)\n\n def proceed(self):\n self.selected_row=tuple(self.tree.item(self.tree.selection())['values'])\n self.message.update_member_info(self.selected_row)\n self.rentFrame.clear_rent_info()\n self.rentFrame.update_rent_info(self.selected_row[0])\n self.parent.selected_id=self.selected_row[0]\n self.win_master.destroy()\n return self.selected_row\n\nclass _menuFrame():\n def __init__(self, parent, searchFrame, *args, **kwargs):\n\n # create Frame\n self.menuFrame=Frame(parent)\n self.menuFrame.grid(row=kwargs['row'],column=kwargs['column'], padx=3, pady=40, sticky=N)\n\n # connected widget\n self.searchFrame=searchFrame\n\n Button(self.menuFrame, text='대여',command=self.pop_add_rent, width=10).grid(row=5, padx=3, pady=10)\n Button(self.menuFrame, text='회수',command=self.return_rent, width=10).grid(row=6, padx=3, pady=10)\n Button(self.menuFrame, text='대여기록',command=self.view_history, width=10).grid(row=7, padx=3, pady=10)\n\n def pop_add_rent(self):\n add_rent(self.menuFrame)\n\n def return_rent(self):\n return\n\n def view_history(self):\n return\n\nclass add_rent():\n def __init__(self,parent,**kwargs):\n\n ## popup new window\n self.win_master = Toplevel(parent)\n\n # generate Frame within windows\n self.mainFrame = Frame(self.win_master)\n self.mainFrame.grid(row=0, column=0,padx=10, pady=5)\n\n # generate Entry\n self.entryFrame = Frame(self.mainFrame)\n self.entryFrame.grid(row=0, column=0)\n\n Label(self.entryFrame, text='도서검색: ').grid(row=0, column=0, pady=5)\n self.entry=Entry(self.entryFrame, width=20)\n self.entry.grid(row=0,column=1)\n Button(self.entryFrame, text='검색', command=self.button_pressed).grid(row=0, column=2, padx=5)\n Button(self.entryFrame, text='대여목록추가', command=self.add_pressed).grid(row=0, column=3, padx=5)\n\n # generate treeviews\n self.tree = ttk.Treeview(self.mainFrame, height=20, column=('id','title','vol','genre','author'),show='headings')\n self.tree.grid(row=1, column=0)\n\n self.tree.heading('#1', text='Id')\n self.tree.heading('#2', text='제목')\n self.tree.heading('#3', text='권')\n self.tree.heading('#4', text='장르')\n self.tree.heading('#5', text='저자')\n\n self.tree.column('id',width=40, anchor=CENTER)\n self.tree.column('title',width=200, anchor=CENTER)\n self.tree.column('vol',width=40, anchor=CENTER)\n self.tree.column('genre', width=80, anchor=CENTER)\n self.tree.column('author', width=80, anchor=CENTER)\n\n def button_pressed(self):\n self.keyword=self.entry.get()\n self.get_query_result()\n self.update_tree()\n\n def get_query_result(self):\n con=sq.connect('guelbang.db')\n c=con.cursor()\n query='SELECT Id, Title, Vol, Genre, Author FROM BOOK WHERE Title like ?'\n c.execute(query, ('%{}%'.format(self.keyword),))\n self.rows=c.fetchall()\n c.close()\n\n def update_tree(self):\n for row in self.rows:\n self.tree.insert(\"\",END,values=row)\n\n def clear_rent_info(self):\n self.tree.delete(*self.tree.get_children())\n\n def add_pressed(self):\n\n params=[]\n for i in self.tree.selection():\n id=self.tree.item(i)['values']\n print(id)\n params.append((id,))\n\n query='INSERT INTO BOOK VALUES ()'\n\n\n\n return\n\n\n\n\ndef main():\n root=Tk()\n myGUIWelcome=Rental(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"rental.py","file_name":"rental.py","file_ext":"py","file_size_in_byte":10981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"493932258","text":"from PyQt5.QtWidgets import QGridLayout, QWidget, QPushButton, QFileDialog\nfrom PyQt5 import QtCore\n\nfrom gcode_viewer.gcode.layer_parser import Layer_Parser\nfrom gcode_viewer.gui.left_side.left_side import Left_Side\nfrom gcode_viewer.gui.menu_bar.menu_bar import Menu_Bar\nfrom gcode_viewer.gui.right_side.right_side import Right_Side\nfrom gcode_viewer.gui.startup_window.startup_window import Startup_Window\nfrom gcode_viewer.util.file_handler import File_Handler\n\n\nclass Central_Widget(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.file_handler = File_Handler()\n self.settings = self.file_handler.read_settings()\n\n self.initUI()\n\n def initUI(self):\n\n self.grid = QGridLayout()\n\n self.menu_bar = Menu_Bar(self.settings)\n self.grid.addWidget(self.menu_bar, 0, 0, 1, 2)\n self.menu_bar.observer = self\n\n self.left_side = Left_Side()\n self.grid.addWidget(self.left_side, 1, 0)\n\n self.right_side = Right_Side(self.settings)\n self.grid.addWidget(self.right_side, 1, 1)\n\n bottom_grid = QGridLayout()\n self.grid.addLayout(bottom_grid, 2, 0, 1, 2)\n\n self.load_file_button = QPushButton(\"Load Different GCode File\")\n bottom_grid.addWidget(self.load_file_button, 0, 1)\n self.load_file_button.clicked.connect(self.get_path_to_file)\n\n bottom_grid.setColumnStretch(0, 1)\n bottom_grid.setColumnStretch(2, 1)\n\n self.setLayout(self.grid)\n\n def start(self):\n test = Startup_Window()\n file_path = test.get_initial_file_path()\n\n if file_path:\n self.load_gcode_file(file_path)\n\n def get_path_to_file(self):\n file_path, _ = QFileDialog(self).getOpenFileName(caption=\"Select A GCode File That You Want To Load\",\n filter=\"GCode (*.gcode)\", initialFilter=\"GCode (*.gcode)\")\n\n if file_path:\n self.load_gcode_file(file_path)\n\n def load_gcode_file(self, file_path):\n\n line_list = self.file_handler.read_gcode_file(file_path)\n temp_layer_parser = Layer_Parser()\n layer_list = temp_layer_parser.parse_layer_list(line_list)\n\n self.load_new_file_on_screen(layer_list)\n\n def load_new_file_on_screen(self, layer_list):\n self.right_side.load_new_gcode(layer_list)\n self.right_side.gcode_loaded = True\n\n self.left_side.gcode_3d_viewer.load_gcode(layer_list)\n\n def update(self, type, par1, par2 = None):\n\n if type == \"new_settings\":\n new_settings = par1\n\n self.settings = new_settings\n #self.left_side.settings = new_settings\n self.menu_bar.settings = new_settings\n\n self.file_handler.settings_to_file(self.settings)\n","sub_path":"src/gcode_viewer/gui/central_widget.py","file_name":"central_widget.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"129243279","text":"from random import randint\r\n\r\n# set up variables to keep score and set number of non-tie matches\r\nplayer_wins = 0\r\ncomputer_wins = 0\r\nwinning_score = 5\r\n\r\n# loop to keep game going until winning_score condition is met\r\nwhile player_wins < winning_score and computer_wins < winning_score:\r\n\tprint(f\"Player Score: {player_wins} Computer Score: {computer_wins}\")\r\n\tprint(\"Rock...\")\r\n\tprint(\"Paper...\")\r\n\tprint(\"Scissors...\")\r\n\r\n# sets rock, paper, and scissors as the number equivalents and gives players option to quit early\r\n\tplayer = input(\"What is your move?: \").lower()\r\n\tif player == \"quit\" or player == \"q\":\r\n\t\tbreak\r\n\trandom_int = random.randint(0,2)\r\n\tif random_int == 0:\r\n\t\tcomputer = \"rock\"\r\n\telif random_int == 1:\r\n\t\tcomputer = \"paper\"\r\n\telse:\r\n\t\tcomputer = \"scissors\"\r\n\r\n# indicates what the computer plays so player knows\r\n\tprint(f\"The computer plays: {computer}\")\r\n\r\n\tif player == computer:\r\n\t\tprint(\"You tied!\")\r\n\telif player == \"rock\":\r\n\t\tif computer == \"scissors\":\r\n\t\t\tprint(\"player wins!\")\r\n\t\t\tplayer_wins += 1\r\n\t\telse:\r\n\t\t\tprint(\"computer wins!\")\r\n\t\t\tcomputer_wins += 1\r\n\telif player == \"paper\":\r\n\t\tif computer == \"rock\":\r\n\t\t\tprint(\"player wins!\")\r\n\t\t\tplayer_wins += 1\r\n\t\telse:\r\n\t\t\tprint(\"computer wins!\")\r\n\t\t\tcomputer_wins += 1\r\n\telif player == \"scissors\":\r\n\t\tif computer == \"paper\":\r\n\t\t\tprint(\"player wins!\")\r\n\t\t\tplayer_wins += 1\r\n\t\telse:\r\n\t\t\tprint(\"computer wins!\")\r\n\t\t\tcomputer_wins += 1\r\n\telse:\r\n\t\tprint(\"Somethin ain't right\")\r\n\r\nif player_wins > computer_wins:\r\n\tprint(\"Well done, you won!\")\r\nelif player_wins == computer_wins:\r\n\tprint(\"It's a tie!\")\r\nelse:\r\n\tprint(\"Computer won.\")","sub_path":"RPS_v2.py","file_name":"RPS_v2.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"449082846","text":"\"\"\"\n\nA basic linear classifer example that uses the pyoplot library to help us visualize the data classification.\n\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass points:\n def __init__(self, arr=None, x=None, y=None, category = None):\n self.x = []\n self.y = []\n self.category = category\n if (arr == None and x != None and y != None):\n self.x.append(x)\n self.y.append(y)\n elif (arr == None and x == None and y == None):\n return\n else:\n for pair in arr:\n self.x.append(pair[0])\n self.y.append(pair[1])\n\n def add_cordinate(self, x=None, y=None, arr=None):\n if (x != None and y != None):\n self.x.append(x)\n self.y.append(y)\n elif (arr != None):\n print(\"printing arr\" + format(arr))\n for pair in arr:\n self.x.append(pair[0])\n self.y.append(pair[1])\n\n def isEmpty(self):\n if(len(self.x) == 0):\n return True\n else:\n return False\n\n def print_pairs(self):\n for el in range(0, len(self.x)):\n print(\"x= \" + str(self.x[el]) + \" y = \" + str(self.y[el]))\n\n\ndef calculate_errors(c1, c2, threshold):\n #true positives and true negatives\n tp = 0\n tn = 0\n fp = 0\n fn = 0\n\n for ind in range (0, len(c1.x)):\n #get points from both groups\n x_1 = c1.x[ind]\n y_1 = c1.y[ind]\n \n\n x_2 = c2.x[ind]\n y_2 = c2.y[ind]\n\n print(\"x_1 = \"+str(x_1))\n print(\"threshold x = \"+str(threshold.x[0]))\n\n #test against the threshold\n\n if(x_1 > threshold.x[0] and y_1 > threshold.y[0]):\n category_1 = \"C1\"\n else:\n category_1 = \"C2\"\n \n if(x_2 > threshold.x[0] and y_2 > threshold.y[0]):\n category_2 = \"C1\"\n else:\n category_2 = \"C2\"\n\n if(category_1 == \"C1\"):\n tp += 1\n else:\n fp += 1\n \n if(category_2 == \"C2\"):\n tn += 1\n else:\n fn += 1\n \n result = 100 * ( (float (tn+ tp) ) / (float (tn+tp+fp+fn)) )\n print(\"Accuracy of threshold is... \" + str(result))\n\n#THRESHOLD setting function / General x and y input getting function\ndef get_xy(argument,msg = \"Enter the X and Y Value\"):\n if(argument == \"XY\" or argument == \"xy\"):\n print(msg)\n x = get_xy(\"X\")\n y = get_xy(\"Y\")\n return x, y\n \n if(argument == \"X\" or argument == \"x\"):\n x_in = input(\"\"\"Enter the X value :\\n\"\"\")\n try:\n x_in = float(x_in)\n except:\n print(\"error!\")\n if(isinstance(x_in, int) or isinstance(x_in,float)):\n return float(x_in)\n else:\n return get_xy(\"X\")\n \n if(argument == \"Y\" or argument == \"y\"):\n y_in = input(\"\"\"Enter the Y value : \\n\"\"\")\n try:\n y_in = float(y_in)\n except:\n print(\"error!\")\n if(isinstance(y_in, int) or isinstance(y_in,float)):\n return float(y_in)\n else:\n return get_xy(\"Y\")\n\n\ndef display_graph(group1, group2, threshold, container1, container2):\n plt.xlim([0, 5])\n plt.ylim([0, 5])\n\n plt.plot(group1.x, group1.y, \"ro\", label = group1.category)\n plt.plot(group2.x, group2.y, \"bv\", label = group2.category)\n\n if(container1.isEmpty() == False):\n plt.plot(container1.x, container1.y, \"r*\", label = container1.category)\n if(container2.isEmpty() == False):\n plt.plot(container2.x, container2.y, \"b*\", label = container2.category)\n\n plt.plot(threshold.x[0], threshold.y[0], \"g*\", label = \"threshold\")\n plt.xlabel(\"X\")\n plt.ylabel(\"Y\")\n plt.legend()\n plt.show()\n\n#This function takes a points and categorizes them according to the category passed.\ndef classify (p, threshold, category1, category2):\n categorized_group1 = points()\n categorized_group1.category = category1\n categorized_group2 = points()\n categorized_group2.category = category2\n for i in range(0,len(p.x)):\n if(p.x[i] > threshold.x[0] and p.y[i] > threshold.y[0]):\n categorized_group1.add_cordinate(x = p.x[i], y = p.y[i])\n else:\n categorized_group2.add_cordinate(x = p.x[i], y = p.y[i])\n \n return categorized_group1, categorized_group2\n\n\ndef main():\n\n #Our C1 and C2 coordinate arrays\n C1_test = points({(2, 2), (3, 2), (2, 3)}, category = \"C1\")\n C2_test = points({(1, 2), (1, 1), (2, 1)} , category = \"C2\")\n \n #set threshold\n xth = yth = 0\n threshold = points(x = xth, y = yth)\n exit = False\n user_data_points = points()\n\n while exit == False:\n\n\n main_menu = \"\"\n main_menu += \"MAIN MENU \\n\"\n main_menu += \"\"\"Press \"d\" to display graph (Part a) \\n\"\"\"\n main_menu += \"\"\"Press \"s\" to set the threshold and test it's accuracy (Part b and c) \\n\"\"\"\n main_menu += \"\"\"Press \"n\" to add data points (Part d) \\n\"\"\" \n main_menu += \"\"\"Press \"x\" to exit the program \\n \\n \\n\"\"\" \n\n main_input = input(main_menu)\n\n if(main_input == \"d\"):\n if(not(user_data_points.isEmpty())):\n print(\"Array is not empty\")\n C1_training , C2_training = classify(user_data_points, threshold, \"C1 Detected\", \"C2 Detected\")\n display_graph(C1_test, C2_test, threshold, C1_training , C2_training )\n else:\n C1_training=points()\n C2_training=points()\n display_graph(C1_test, C2_test, threshold, C1_training , C2_training )\n\n if(main_input == \"s\"):\n in_x, in_y = get_xy(\"XY\", \"SET THRESHOLD\")\n threshold.x[0] = in_x\n threshold.y[0] = in_y\n calculate_errors(C1_test, C2_test, threshold)\n\n if(main_input == \"n\"):\n while True:\n in_x, in_y = get_xy( \"XY\", \"Enter Data point\")\n user_data_points.add_cordinate(x = in_x, y = in_y)\n inn = input(\"\"\" To enter another point press \"y\" \\n Else press any other button to exit this menu \"\"\")\n\n if(inn != \"y\"):\n break;\n\n if(main_input == \"x\"):\n break;\n\n\n\nif __name__== \"__main__\":\n main()\n","sub_path":"LS.py","file_name":"LS.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"37904636","text":"class Date:\n __slots__ = [\"year\", \"month\", \"day\"]\n\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def __repr__(self):\n return 'year:{d.year}month:{d.month}day:{d.day}'.format(d=self)\n\n\nd = Date(2018, 7, 9)\nprint(d)\n","sub_path":"chapter-8/8.4.py","file_name":"8.4.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"58732775","text":"from datetime import datetime\nimport os\n\ndt = datetime.today().strftime('%y%m%d')\ndirectory = \"D:/MEGA/\"\n\noutfile_name = \"merged_{}.txt\".format(datetime.today().strftime('%y%m%d'))\n\nout_file = open(outfile_name,'w')\nfiles = os.listdir(directory)\n\nfor filename in files:\n if \".txt\" not in filename:\n continue\n file = open(directory+filename)\n for line in file:\n out_file.write(line)\n print(filename)\n\n out_file.write(\"\\n\\n\")\n\n file.close()\nout_file.close()\n\n","sub_path":"python/automation/automation_text.py","file_name":"automation_text.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"398425114","text":"n = int(input())\na = []\nfor _ in range(n):a.append(int(input()))\n\nmax_ = max(a)\nmax2 = sorted(a)[-2]\nfor i in range(n):\n if a[i] != max_:\n print(max_)\n else:\n print(max2)","sub_path":"Python_codes/p02971/s928146171.py","file_name":"s928146171.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"545925715","text":"import os\nimport redis\n\n\n# configurationb\nDATABASE = 'dashboard.db'\nDEBUG = True\nSECRET_KEY = 'my_precious'\n\n# grabs the folder where the script runs\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# REDIS_HOST = '43.82.163.74'\n# REDIS_PORT = 6379\n# REDIS = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)\n\n# defines the full path for the database\nDATABASE_PATH = os.path.join(basedir, DATABASE)\n\n# database config\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\n# celery\nCELERY_BROKER_URL = 'redis://localhost:6379/0'\nCELERY_RESULT_CACKEND = 'redis://localhost:6379/0'","sub_path":"_settings.py","file_name":"_settings.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"224238304","text":"import lightgbm as lgb\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\ndef add_community_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['communityName'].unique():\n trademoney_ave = df_ret[df_ret['communityName'] == i]['tradeMoney'].mean()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['communityName']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'community_ave_trademoney': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_region_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['region'].unique():\n trademoney_ave = df_ret[df_ret['region'] == i]['tradeMoney'].mean()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['region']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'region_ave_trademoney': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_plate_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['plate'].unique():\n trademoney_ave = df_ret[df_ret['plate'] == i]['tradeMoney'].mean()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['plate']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'plate_ave_trademoney': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_pv_div_uv(df_origin):\n df_ret = df_origin.copy()\n list_pv_div_uv = []\n for index, row in df_ret.iterrows():\n pv = row['pv']\n uv = row['uv']\n pv_div_uv = float(pv) / float(uv)\n list_pv_div_uv.append(pv_div_uv)\n dict_pv_div_uv = {'pv_div_uv': list_pv_div_uv}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_pv_div_uv)], axis=1)\n return df_ret\n\n\ndef add_month_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_month_ave_money = {}\n for i in df_ret['tradeMonth'].unique():\n trademoney_ave = df_ret[df_ret['tradeMonth'] == i]['tradeMoney'].mean()\n dict_month_ave_money[i] = trademoney_ave\n list_trademoney_month_ave = []\n for index, row in df_ret.iterrows():\n month = row['tradeMonth']\n trademoney = dict_month_ave_money[month]\n list_trademoney_month_ave.append(trademoney)\n dict_trademoney_final = {'month_ave_trademoney': list_trademoney_month_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_totalfloor_times_housefloor(df_origin):\n df_ret = df_origin.copy()\n list_totalfloor_times_housefloor = []\n for index, row in df_ret.iterrows():\n housefloor = row['houseFloor']\n totalfloor = row['totalFloor']\n if housefloor == 0:\n ratio = 0.5\n elif housefloor == 1:\n ratio = 1.5\n else:\n ratio = 2.5\n list_totalfloor_times_housefloor.append(ratio * totalfloor)\n dict_totalfloor_times_housefloor = {'totalfloor_times_housefloor': list_totalfloor_times_housefloor}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_totalfloor_times_housefloor)], axis=1)\n return df_ret\n\n\ndef add_housetype_to_num(df_origin):\n df_ret = df_origin.copy()\n list_num = []\n for index, row in df_ret.iterrows():\n bedroom = row['bedroom']\n livingroom = row['livingroom']\n bathroom = row['bathroom']\n num = 14 * bedroom + 14 * livingroom + 3 * bathroom\n list_num.append(num)\n dict_num = {'housetype_to_num': list_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_num)], axis=1)\n return df_ret\n\n\ndef add_tradeyear_minus_buildyear(df_origin):\n df_ret = df_origin.copy()\n list_year = []\n tradeyear=2018\n list_buildyear = df_ret['buildYear'].tolist()\n for buildyear in list_buildyear:\n list_year.append(tradeyear - buildyear)\n dict_year = {'tradeyear_minus_buildyear': list_year}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_year)], axis=1)\n return df_ret\n\n\ndef add_plate_num_in_region(df_origin):\n df_ret = df_origin.copy()\n dict_plate_num = {}\n list_region = list(df_ret['region'].unique())\n list_plate_num_in_region = []\n for region in list_region:\n plate_num = len(df_ret[df_ret['region'] == region]['plate'].unique())\n dict_plate_num[region] = plate_num\n for index, row in df_ret.iterrows():\n region = row['region']\n plate_num = dict_plate_num[region]\n list_plate_num_in_region.append(plate_num)\n dict_plate_num_in_region = {'plate_num_in_region': list_plate_num_in_region}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_plate_num_in_region)], axis=1)\n return df_ret\n\n\ndef add_community_num_in_plate(df_origin):\n df_ret = df_origin.copy()\n dict_community_num = {}\n list_plate = list(df_ret['plate'].unique())\n list_community_num_in_plate = []\n for plate in list_plate:\n community_num = len(df_ret[df_ret['plate'] == plate]['communityName'].unique())\n dict_community_num[plate] = community_num\n for index, row in df_ret.iterrows():\n plate = row['plate']\n community_num = dict_community_num[plate]\n list_community_num_in_plate.append(community_num)\n dict_community_num_in_plate = {'community_num_in_plate': list_community_num_in_plate}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_community_num_in_plate)], axis=1)\n return df_ret\n\n\ndef add_transport_total_num(df_origin):\n df_ret = df_origin.copy()\n list_transport_total_num = []\n for index, row in df_ret.iterrows():\n subway_num = row['subwayStationNum']\n bus_num = row['busStationNum']\n total_num = subway_num + bus_num\n list_transport_total_num.append(total_num)\n dict_transport_total_num = {'transport_total_num': list_transport_total_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_transport_total_num)], axis=1)\n return df_ret\n\n\ndef add_education_total_num(df_origin):\n df_ret = df_origin.copy()\n list_education_total_num = []\n for index, row in df_ret.iterrows():\n interschool_num = row['interSchoolNum']\n school_num = row['schoolNum']\n privateschool_num = row['privateSchoolNum']\n total_num = interschool_num + school_num + privateschool_num\n list_education_total_num.append(total_num)\n dict_transport_total_num = {'education_total_num': list_education_total_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_transport_total_num)], axis=1)\n return df_ret\n\n\ndef add_service_total_num(df_origin):\n df_ret = df_origin.copy()\n list_service_total_num = []\n for index, row in df_ret.iterrows():\n hospital_num = row['hospitalNum']\n drugstore_num = row['drugStoreNum']\n gym_num = row['gymNum']\n bank_num = row['bankNum']\n shop_num = row['shopNum']\n park_num = row['parkNum']\n mall_num = row['mallNum']\n supermarket_num = row['superMarketNum']\n total_num = hospital_num + drugstore_num + gym_num + bank_num + shop_num + park_num + mall_num + supermarket_num\n list_service_total_num.append(total_num)\n dict_service_total_num = {'service_total_num': list_service_total_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_service_total_num)], axis=1)\n return df_ret\n\n\ndef test_feature(df_origin, feature_function):\n df_test = df_origin.copy()\n df_test = feature_function(df_test)\n X = df_test.drop(columns=['tradeMoney'])\n y = df_test['tradeMoney'].tolist()\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\n\n model_lgb = lgb.LGBMRegressor(objective='regression', num_leaves=900,\n learning_rate=0.1, n_estimators=3141, bagging_fraction=0.7,\n feature_fraction=0.6, reg_alpha=0.3, reg_lambda=0.3,\n min_data_in_leaf=18, min_sum_hessian_in_leaf=0.001)\n model_lgb.fit(X_train, y_train)\n y_predict = model_lgb.predict(X_test)\n if len(y_test)==len(y_predict):\n return test_score(y_test, y_predict)\n else:\n print(\"len ytest != len ypredict\")\n return\n\n\ndef test_score(y_real, y_predict):\n m = len(y_real)\n y_average = np.mean(np.array(y_real))\n sum_fz = 0\n sum_fm = 0\n for i in range(m):\n sum_fz += (y_predict[i] - y_real[i]) ** 2\n sum_fm += (y_real[i] - y_average) ** 2\n score = 1 - sum_fz / sum_fm\n return score\n\n\ndef add_lookNum_div_pv(df_origin):\n df_ret=df_origin.copy()\n list_lookNum_div_pv=[]\n for index,row in df_ret.iterrows():\n lookNum=row['lookNum']\n pv=row['pv']\n lookNum_div_pv=float(lookNum)/float(pv)\n list_lookNum_div_pv.append(lookNum_div_pv)\n dict_lookNum_div_pv={'lookNum_div_pv':list_lookNum_div_pv}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_lookNum_div_pv)],axis=1)\n return df_ret\n\ndef add_lookNum_div_uv(df_origin):\n df_ret=df_origin.copy()\n list_lookNum_div_uv=[]\n for index,row in df_ret.iterrows():\n lookNum=row['lookNum']\n uv=row['uv']\n lookNum_div_uv=float(lookNum)/float(uv)\n list_lookNum_div_uv.append(lookNum_div_uv)\n dict_lookNum_div_uv={'lookNum_div_uv':list_lookNum_div_uv}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_lookNum_div_uv)],axis=1)\n return df_ret\n\ndef add_totalWorkers_div_residentPopulation(df_origin):\n df_ret=df_origin.copy()\n list_totalWorkers_div_residentPopulation=[]\n for index,row in df_ret.iterrows():\n totalWorkers=row['totalWorkers']\n residentPopulation=row['residentPopulation']\n totalWorkers_div_residentPopulation=float(totalWorkers)/float(residentPopulation)\n list_totalWorkers_div_residentPopulation.append(totalWorkers_div_residentPopulation)\n dict_totalWorkers_div_residentPopulation={'totalWorkers_div_residentPopulation':list_totalWorkers_div_residentPopulation}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalWorkers_div_residentPopulation)],axis=1)\n return df_ret\n\ndef add_newWorkers_div_totalWorkers(df_origin):\n df_ret=df_origin.copy()\n list_newWorkers_div_totalWorker=[]\n for index,row in df_ret.iterrows():\n newWorkers=row['newWorkers']\n totalWorker=row['totalWorkers']\n newWorkers_div_totalWorker=float(newWorkers)/float(totalWorker)\n list_newWorkers_div_totalWorker.append(newWorkers_div_totalWorker)\n dict_newWorkers_div_totalWorker={'newWorkers_div_totalWorker':list_newWorkers_div_totalWorker}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_newWorkers_div_totalWorker)],axis=1)\n return df_ret\n\ndef add_tradeLandArea_div_tradeLandNum(df_origin):\n df_ret=df_origin.copy()\n list_tradeLandArea_div_tradeLandNum=[]\n for index,row in df_ret.iterrows():\n tradeLandArea=row['tradeLandArea']\n tradeLandNum=row['tradeLandNum']\n if tradeLandNum==0:\n list_tradeLandArea_div_tradeLandNum.append(0)\n continue\n tradeLandArea_div_tradeLandNum=float(tradeLandArea)/float(tradeLandNum)\n list_tradeLandArea_div_tradeLandNum.append(tradeLandArea_div_tradeLandNum)\n dict_tradeLandArea_div_tradeLandNum={'tradeLandArea_div_tradeLandNum':list_tradeLandArea_div_tradeLandNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_tradeLandArea_div_tradeLandNum)],axis=1)\n return df_ret\n\ndef add_supplyLandArea_div_supplyLandNum(df_origin):\n df_ret=df_origin.copy()\n list_supplyLandArea_div_supplyLandNum=[]\n for index,row in df_ret.iterrows():\n supplyLandArea=row['supplyLandArea']\n supplyLandNum=row['supplyLandNum']\n if supplyLandNum==0:\n list_supplyLandArea_div_supplyLandNum.append(0)\n continue\n supplyLandArea_div_supplyLandNum=float(supplyLandArea)/float(supplyLandNum)\n list_supplyLandArea_div_supplyLandNum.append(supplyLandArea_div_supplyLandNum)\n dict_supplyLandArea_div_supplyLandNum={'supplyLandArea_div_supplyLandNum':list_supplyLandArea_div_supplyLandNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_supplyLandArea_div_supplyLandNum)],axis=1)\n return df_ret\n\n#本月成交套数+未成交套数=总套数\n#总套数*新房成交均价\n\ndef add_totalNewNum(df_origin):\n df_ret=df_origin.copy()\n list_totalNewNum=[]\n for index,row in df_ret.iterrows():\n tradeNewNum=row['tradeNewNum']\n remainNewNum=row['remainNewNum']\n totalNewNum=float(tradeNewNum)+float(remainNewNum)\n list_totalNewNum.append(totalNewNum)\n dict_totalNewNum={'totalNewNum':list_totalNewNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalNewNum)],axis=1)\n return df_ret\n\ndef add_totalNewNum_mul_tradeNewMeanPrice(df_origin):\n df_ret=df_origin.copy()\n list_totalNewNum_mul_tradeNewMeanPrice=[]\n for index,row in df_ret.iterrows():\n tradeNewNum=row['tradeNewNum']\n remainNewNum=row['remainNewNum']\n tradeNewMeanPrice=row['tradeNewMeanPrice']\n totalNewNum=float(tradeNewNum)+float(remainNewNum)\n totalNewNum_mul_tradeNewMeanPrice=totalNewNum*float(tradeNewMeanPrice)\n list_totalNewNum_mul_tradeNewMeanPrice.append(totalNewNum_mul_tradeNewMeanPrice)\n dict_totalNewNum_mul_tradeNewMeanPrice={'totalNewNum_mul_tradeNewMeanPrice':list_totalNewNum_mul_tradeNewMeanPrice}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalNewNum_mul_tradeNewMeanPrice)],axis=1)\n return df_ret\n\n#二手房成交总金额/二手房成交套数\n#新房成交总金额/新房成交总套数\n\ndef add_totalTradeMoney_div_tradeSecNum(df_origin):\n df_ret=df_origin.copy()\n list_totalTradeMoney_div_tradeSecNum=[]\n for index,row in df_ret.iterrows():\n totalTradeMoney=row['totalTradeMoney']\n tradeSecNum=row['tradeSecNum']\n if tradeSecNum==0:\n list_totalTradeMoney_div_tradeSecNum.append(0)\n continue\n totalTradeMoney_div_tradeSecNum=float(totalTradeMoney)/float(tradeSecNum)\n list_totalTradeMoney_div_tradeSecNum.append(totalTradeMoney_div_tradeSecNum)\n dict_totalTradeMoney_div_tradeSecNum={'totalTradeMoney_div_tradeSecNum':list_totalTradeMoney_div_tradeSecNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalTradeMoney_div_tradeSecNum)],axis=1)\n return df_ret\n\ndef add_totalNewTradeMoney_div_tradeNewNum(df_origin):\n df_ret=df_origin.copy()\n list_totalNewTradeMoney_div_tradeNewNum=[]\n for index,row in df_ret.iterrows():\n totalNewTradeMoney=row['totalNewTradeMoney']\n tradeNewNum=row['tradeNewNum']\n if tradeNewNum==0:\n list_totalNewTradeMoney_div_tradeNewNum.append(0)\n continue\n totalNewTradeMoney_div_tradeNewNum=float(totalNewTradeMoney)/float(tradeNewNum)\n list_totalNewTradeMoney_div_tradeNewNum.append(totalNewTradeMoney_div_tradeNewNum)\n dict_totalNewTradeMoney_div_tradeNewNum={'totalNewTradeMoney_div_tradeNewNum':list_totalNewTradeMoney_div_tradeNewNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalNewTradeMoney_div_tradeNewNum)],axis=1)\n return df_ret\n\ndef add_none(df_origin):\n df_ret=df_origin\n return df_ret\n\ndef test_fun(df_processed,function):\n print(function.__name__,\" score= \",test_feature(df_processed, function))\n\ndef add_trademoney_div_area(df_processed,window_length=10):\n df_ret=df_processed.copy()\n dict_trademoney_div_area={}\n list_trademoney_div_area=[]\n left=0\n right=window_length\n while left<1050:\n df_tmp=df_ret[(df_ret['area']>=left)&(df_ret['area']<=right)]\n sum_area=df_tmp['area'].sum()\n sum_trademoney=df_tmp['tradeMoney'].sum()\n dict_trademoney_div_area[int(left/window_length)]=sum_trademoney/sum_area\n left+=window_length\n right+=window_length\n list_area=df_ret['area'].tolist()\n for area in list_area:\n list_trademoney_div_area.append(dict_trademoney_div_area[int(area/window_length)])\n df_ret=pd.concat([df_ret,pd.DataFrame({'trademoney_div_area':list_trademoney_div_area})],axis=1)\n return df_ret\n\n\ndef add_community_ave_trademoney_div_area(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['communityName'].unique():\n df_tmp=df_ret[df_ret['communityName'] == i]\n trademoney_ave = df_tmp['tradeMoney'].sum()/df_tmp['area'].sum()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['communityName']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'community_ave_trademoney_div_area': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_plate_ave_trademoney_div_area(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['plate'].unique():\n df_tmp=df_ret[df_ret['plate'] == i]\n trademoney_ave = df_tmp['tradeMoney'].sum()/df_tmp['area'].sum()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['plate']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'plate_ave_trademoney_div_area': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\n\ndf_processed = pd.read_csv(r\"C:\\Users\\master\\Desktop\\future_lab\\rental_predict\\result\\data_processed.csv\")\n\ndf_processed['houseToward'] = df_processed['houseToward'].astype('category')\ndf_processed['rentType'] = df_processed['rentType'].astype('category')\ndf_processed['houseDecoration'] = df_processed['houseDecoration'].astype('category')\ndf_processed['houseFloor'] = df_processed['houseFloor'].astype('category')\ndf_processed['communityName'] = df_processed['communityName'].astype('category')\ndf_processed['region'] = df_processed['region'].astype('category')\ndf_processed['plate'] = df_processed['plate'].astype('category')\n\ndf_processed = df_processed.drop(columns=['tradeYear'])\ndf_processed = df_processed.drop(columns=['ID'])\n\ndf_processed=add_community_ave_trademoney(df_processed)\ndf_processed=add_region_ave_trademoney(df_processed)\ndf_processed=add_plate_ave_trademoney(df_processed)\ndf_processed=add_pv_div_uv(df_processed)\ndf_processed=add_month_ave_trademoney(df_processed)\n\nlist_function=[add_tradeyear_minus_buildyear,\n add_plate_num_in_region,\n add_community_num_in_plate,\n add_transport_total_num,\n add_education_total_num,\n add_service_total_num,\n add_lookNum_div_pv,\n add_lookNum_div_uv,\n add_totalWorkers_div_residentPopulation,\n add_newWorkers_div_totalWorkers,\n add_tradeLandArea_div_tradeLandNum,\n add_supplyLandArea_div_supplyLandNum,\n add_totalNewNum,\n add_totalNewNum_mul_tradeNewMeanPrice,\n add_totalTradeMoney_div_tradeSecNum,\n add_totalNewTradeMoney_div_tradeNewNum]\nfor function_name in list_function:\n test_fun(df_processed,function_name)\n\nlist_doubt_feature=['saleSecHouseNum',\n 'interSchoolNum',\n 'schoolNum',\n 'privateSchoolNum',\n 'hospitalNum',\n 'drugStoreNum',\n 'gymNum',\n 'bankNum',\n 'shopNum',\n 'parkNum',\n 'mallNum',\n 'superMarketNum',\n 'totalTradeMoney',\n 'totalTradeArea',\n 'tradeMeanPrice',\n 'tradeSecNum',\n 'totalNewTradeMoney',\n 'totalNewTradeArea',\n 'tradeNewMeanPrice',\n 'tradeNewNum',\n 'remainNewNum',\n 'supplyNewNum',\n 'supplyLandNum',\n 'tradeLandNum',\n 'tradeLandArea',\n 'landTotalPrice',\n 'landMeanPrice',\n 'residentPopulation',\n 'tradeMonth',\n 'tradeDay',\n 'bedroom',\n 'livingroom',\n 'bathroom']\nfor feature_name in list_doubt_feature:\n print(\"drop \",feature_name)\n test_fun(df_processed.drop(columns=[feature_name]),add_none)\n\ntest_fun(df_processed,add_trademoney_div_area)\ntest_fun(df_processed,add_plate_ave_trademoney_div_area)\n\nfor i in range(5,30):\n print(\"window_length=\",i)\n test_fun(add_trademoney_div_area(df_processed,i),add_none)","sub_path":"code/feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":21508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"208092800","text":"from scipy import constants\nimport math\n\nx = constants.Planck / (8 * constants.pi**2 * (1500/8) * constants.c)\ny = 0.016 / constants.Avogadro\nz = (y**2) / (2*y)\nw = math.sqrt(x / z)\nprint(x)\nprint(y)\nprint(z)\nprint(\"{:.6e}\".format(w))\n","sub_path":"cem992/previous-assignments/findb.py","file_name":"findb.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"437524284","text":"import main\r\nimport Book_Ticket\r\nimport sqlite3\r\nimport re\r\nair_database=sqlite3.connect('airline.db')\r\nair_cursor=air_database.cursor()\r\nclass authen:\r\n def __init__(self,choice):\r\n print(100*\"*\")\r\n print(\"WELCOME TO TESLA'S AIRLINE RESERVATION\")\r\n print(100*\"*\")\r\n #Check valid mobile and email address (2ND CALL)\r\n def pattern_Match():\r\n pattern_email=re.compile(r'[a-zA-Z0-9._+-]+@\\w+\\.\\w+')\r\n pattern_mobile=re.compile(r'^[9876]\\d{9}') \r\n \r\n if(pattern_email.match(self.email)):\r\n if(choice=='C'):\r\n if(pattern_mobile.match(self.mobile)):\r\n return True\r\n else:\r\n return True\r\n else:\r\n return False\r\n\r\n #Retry when error occured (1st EXECUTED) \r\n while(1):\r\n self.email=input(\"Enter your Email: \")\r\n print(100*\"*\")\r\n if(choice=='C'):\r\n self.name=input(\"Enter your Name: \")\r\n print(60*\"*\")\r\n self.mobile=(input(\"Enter your Mobile no: +91\"))\r\n print(100*\"*\")\r\n self.password=input(\"Enter your Password: \")\r\n print(100*\"*\")\r\n if(pattern_Match()):\r\n break\r\n else:\r\n print(\"Enter the correct credentials.....Try Again\")\r\n print(60*\"*\")\r\n continue\r\n\r\n \r\n\r\n #CHECK LOGIN CRETENTIALS\r\n def Login(self):\r\n self.names_s,self.emails,self.phones,self.choices=self.checkUser()\r\n if(self.choices==True):\r\n main.home(self.names_s,self.emails,self.phones)\r\n else:\r\n return\r\n return\r\n\r\n #USER CHECKING WITH THE SQLITE DATABASE\r\n def checkUser(self):\r\n check_query=\"SELECT Email,Name,Phone_no from User_details where Email=='{}';\".format(self.email)\r\n air_cursor.execute(check_query)\r\n get_result=air_cursor.fetchone()\r\n if(get_result==None or get_result[0]!=self.email):\r\n print(\"Invalid Account...Please Create an Account before Login\")\r\n print(100*\"*\")\r\n return False\r\n else:\r\n return get_result[1],get_result[0],get_result[2],True\r\n\r\n \r\n #INVOKE THE DATABASE(CREATION)\r\n def CreateAc(self):\r\n self.create_user()\r\n main.home(self.name,self.email,self.mobile)\r\n return\r\n\r\n\r\n #UPLOAD THE USER DATA TO DATABASE(CREATION)\r\n def create_user(self):\r\n air_cursor.execute('''INSERT INTO User_details(Name,Email,Password,Phone_no)values(?,?,?,?);''',(self.name,self.email,self.password,self.mobile))\r\n air_database.commit()\r\n \r\nget_choice=int(input(\"1.Login\\n2.Create An Account\\n\"))\r\nif(get_choice==1):\r\n s=authen('L')\r\n s.Login()\r\nelse:\r\n s=authen('C')\r\n s.CreateAc()\r\n","sub_path":"authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"532952164","text":"from lxml import html\nfrom urllib import urlopen\nresponse = urlopen('http://www.entropywebscraping.com')\nresponse_body = response.read()\n\ntree = html.fromstring(response_body)\n\nprint(response.headers)\n\nprint(tree.xpath('//meta[@name=\"description\"]/@content'))","sub_path":"networking/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"425601261","text":"# Author: D Yoan L Mekontchou Yomba\n# Date : 1/26/2018\n# Implement fibonacci in a recursive fashion using memoisation\n\n# imports\nimport sys;\n\n# recursive function definition implementing memoization\ndef fibmemoized(argument, memory):\n # check if input argument was 1 and handle special case\n if argument <= 1:\n return 1\n # case fibonacci sequence is stored in memory already\n elif argument in memory:\n return memory[argument]\n # fill the memo with the contents of fibonacci recursive call\n else:\n memory[argument] = fibmemoized(argument-1, memory) + fibmemoized(argument-2,memory)\n return memory[argument]\n\nif __name__ == \"__main__\":\n # define memo\n memoize = {0:1,1:1}\n if(len(sys.argv)) > 1:\n arg = sys.argv[1]\n # process input\n print(fibmemoized(int(arg), memoize))\n","sub_path":"Week3/problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"445136991","text":"import math\nimport random\nimport sys\nfrom configparser import ConfigParser\n\nLEFT = (-1, 0)\nRIGHT = (1, 0)\nUP = (0, 1)\nDOWN = (0, -1)\nMOVE_DIRECTIONS = [LEFT, RIGHT, UP, DOWN]\n\n# values for the heuristic\nINFINITY = sys.maxsize\nLOST_GAME = -INFINITY\nWIN_GAME = INFINITY\nDRAW_GAME = LOST_GAME / 2\n\nMOVE = \"MOVE\"\nBOOM = \"BOOM\"\n\nWHITE = \"white\"\nBLACK = \"black\"\n\nSTART_BLACK_STACKS = {\n (0, 7): 1, (1, 7): 1, (3, 7): 1, (4, 7): 1, (6, 7): 1, (7, 7): 1,\n (0, 6): 1, (1, 6): 1, (3, 6): 1, (4, 6): 1, (6, 6): 1, (7, 6): 1}\nSTART_WHITE_STACKS = {\n (0, 1): 1, (1, 1): 1, (3, 1): 1, (4, 1): 1, (6, 1): 1, (7, 1): 1,\n (0, 0): 1, (1, 0): 1, (3, 0): 1, (4, 0): 1, (6, 0): 1, (7, 0): 1}\n\nWEIGHT = {1: 12 / 12, 2: 11 / 12, 3: 10 / 12, 4: 9 / 12, 5: 8 / 12, 6: 7 / 12, 7: 6 / 12, 8: 5 / 12, 9: 4 / 12,\n 10: 3 / 12, 11: 2 / 12, 12: 1 / 12}\nEMPTY_STACK_NUMBERS = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}\n\nnum_pieces_evs = []\n\nparser = ConfigParser()\nparser.read('./tdleaf0/weights.ini')\n\nw1 = parser.getfloat('weights', 'w1')\nmanhattan_dist_evs = []\nw2 = parser.getfloat('weights', 'w2')\nnum_groups_evs = []\nw3 = parser.getfloat('weights', 'w3')\n\neval_evs = []\n\n\nclass State:\n \"\"\"State class to be associated with 1 The state is stored in the form of 2 dictionaries, one for white stacks\n and one for black stacks. Each dict has keys which are the (x, y) coordinates of a square where there is at least 1\n piece. The values associated with each x, y coordinate key is the integer number of pieces in that square.\n \"\"\"\n\n def __init__(self, white_stacks=None, black_stacks=None, turn=0):\n # e.g. white_stacks = {(3,2): 1, (3,4): 3}\n if white_stacks is None:\n self.white_stacks = dict(START_WHITE_STACKS)\n else:\n self.white_stacks = dict(white_stacks)\n if black_stacks is None:\n self.black_stacks = dict(START_BLACK_STACKS)\n else:\n self.black_stacks = dict(black_stacks)\n self.turn = turn\n\n def __eq__(self, other):\n return bool((self.white_stacks == other.white_stacks) and (self.black_stacks == other.black_stacks))\n\n def total_white(self):\n return sum(self.white_stacks.values())\n\n def total_black(self):\n return sum(self.black_stacks.values())\n\n def total_pieces(self, colour=None):\n if colour is None:\n return self.total_black() + self.total_white()\n if colour == WHITE:\n return self.total_white()\n return self.total_black()\n\n def get_colour(self, colour):\n \"\"\"returns the dictionary of stacks for colour='white' or colour='black' \"\"\"\n if colour == WHITE:\n return self.white_stacks\n if colour == BLACK:\n return self.black_stacks\n # else, invalid colour given so return None\n return None\n\n def get_squares(self, colour):\n \"\"\"returns the keys of the stack dictionary for 'colour'='white' or 'colour'='black'.\n Since the keys of the stack dictionaries are the (x, y) coordinates where there are at least 1 piece,\n the return type is a list of (x, y) tuples where there are 'colour' pieces\"\"\"\n return list(self.get_colour(colour).keys())\n\n def get_nontrivial_boom_actions(self, colour):\n # dont return square that has the same resulting state\n # dont return a boom action that only removes our pieces\n current = self.copy()\n actions = []\n while len(current.get_squares(colour)) > 0:\n stack_to_boom = current.get_squares(colour)[0]\n actions.append((BOOM, stack_to_boom))\n current = chain_boom(current, stack_to_boom)\n return actions\n\n def get_non_trivial_non_suicidal_boom_actions(self, colour):\n # dont return square that has the same resulting state\n # dont return a boom action that only removes our pieces\n\n current = self.copy()\n actions = []\n while len(current.get_squares(colour)) > 0:\n stack_to_boom = current.get_squares(colour)[0]\n if current.total_pieces(opponent(colour)) < self.total_pieces(opponent(colour)):\n actions.append((BOOM, stack_to_boom))\n current = chain_boom(current, stack_to_boom)\n return actions\n\n def get_non_trivial_move_actions(self, colour):\n actions = []\n\n for stack in self.get_colour(colour).items():\n # iterate through each possible number of pieces to move from our stack at the current occupied_square\n for n_pieces in range(1, stack[1] + 1):\n # possible moving directions\n for move_direction in MOVE_DIRECTIONS:\n # number of squares to move n_pieces from current stack, 1 <= n_steps <= n_pieces\n for n_steps in range(1, stack[1] + 1):\n # check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of\n # bounds and not landing on an enemy piece)\n if is_legal_move(self.get_squares(opponent(colour)), stack[0], move_direction, n_steps):\n final_square = calculate_dest_square(stack[0], move_direction, n_steps)\n act = (MOVE, n_pieces, stack[0], final_square)\n actions.append((heuristic(colour, Node(self).apply_action(colour, act).state), act))\n random.shuffle(actions)\n actions.sort(key=lambda x: x[0], reverse=True)\n return [x[1] for x in actions][0:math.ceil(len(actions) / (3 / 2))]\n\n \"\"\"def eval(self, colour=WHITE):\n return 0\n white_stack_numbers = dict(EMPTY_STACK_NUMBERS)\n for stack_pieces in self.white_stacks.values():\n white_stack_numbers[stack_pieces] += 1\n black_stack_numbers = dict(EMPTY_STACK_NUMBERS)\n for stack_pieces in self.black_stacks.values():\n black_stack_numbers[stack_pieces] += 1\n eval = WEIGHT[1] * (white_stack_numbers[1] - black_stack_numbers[1]) \\\n + WEIGHT[2] * (white_stack_numbers[2] - black_stack_numbers[2]) \\\n + WEIGHT[1] * (white_stack_numbers[1] - black_stack_numbers[1])\n etc...\n if colour == WHITE:\n eval_sign = 1\n else:\n eval_sign = -1\n ev = 0\n for i in range(1, 13):\n ev += WEIGHT[i] * ((white_stack_numbers[i] - black_stack_numbers[i]) * eval_sign)\n # return ev + eval_sign * (self.total_white() - self.total_black())\n # return ((self.total_white() * len(self.white_stacks)) - self.total_black() * len(self.black_stacks)) * eval_sign\"\"\"\n\n def evaluation(self, colour=WHITE):\n eval = 0\n\n if (self.total_black() == 0) and (self.total_white() == 0):\n return DRAW_GAME\n\n if colour == WHITE:\n if self.total_black() == 0:\n # win game\n return WIN_GAME\n if self.total_white() == 0:\n # lost game\n return LOST_GAME\n\n if colour == BLACK:\n if self.total_white() == 0:\n # win game\n return WIN_GAME\n if self.total_black() == 0:\n # lost game\n return LOST_GAME\n\n # eval += self.piece_val(colour) - self.piece_val(opponent(colour))\n # eval += abs(math.tanh(self.num_groups(colour))) - abs(math.tanh(manhattan_dist(self, colour)))\n # eval += normalise(NUM_GROUPS, self.num_groups(colour)) - normalise(MANHATTAN, manhattan_dist(self, colour))\n # eval -= abs(math.tanh(manhattan_dist(self, colour)))\n\n eval += w1 * self.weighted_piece_val(colour)\n\n eval -= manhattan_dist(self, colour) * w2\n\n eval += self.num_groups(colour) * w3\n\n return eval\n\n def weighted_piece_val(self, colour):\n return ((0.95 ** self.total_pieces()) * (self.total_pieces(colour) - self.total_pieces(opponent(colour))))\n\n def num_groups(self, colour):\n \"\"\"A group is defined as a set of pieces over one or more squares which would all be removed in\n a boom action from a boom in any of the pieces in that group.\n That is, a BOOM of any stack in a group of stacks will BOOM all other stacks in that group\"\"\"\n # the number of distinct groups is equal to the number of possible boom actions until we have no more stacks left\n return len(self.get_nontrivial_boom_actions(colour))\n\n def copy(self):\n return State(self.white_stacks, self.black_stacks, self.turn)\n\n\nclass Node:\n \"\"\"Node class for storing states and their values\"\"\"\n\n def __init__(self, state=None, value=0, parent=None, move=None, depth=0):\n if state is None:\n self.state = State()\n self.last_colour = BLACK\n else:\n self.state = State(state.white_stacks, state.black_stacks, state.turn)\n self.value = value\n self.parent = parent\n self.move = move\n self.depth = depth\n self.last_colour = None\n\n # these functions are for comparing the scores (or 'value') associated with each node\n def __lt__(self, other):\n return self.value < other.value\n\n def __gt__(self, other):\n return self.value > other.value\n\n def __le__(self, other):\n return self.value <= other.value\n\n def __ge__(self, other):\n return self.value >= other.value\n\n # this is for checking if the node is already in the explored_nodes array (i.e. it's has the same state)\n # For example, when someone checks if node1 == node2, it will return true if they have the same state\n def __eq__(self, other):\n return self.state == other.state\n\n def copy(self):\n copy_node = Node(self.state, self.value, self.parent, self.move, self.depth)\n copy_node.last_colour = self.last_colour\n return copy_node\n\n def apply_action(self, colour, action):\n \"\"\"return a copy of the base_node after action has happened on it\"\"\"\n if action[0] == MOVE:\n return move_action(colour, self, action[1], action[2], action[3])\n if action[0] == BOOM:\n return boom_action(colour, self, action[1])\n # else invalid action\n print(\"INVALID ACTION GIVEN TO .apply_action() in aiutils.py\\n\")\n return None\n\n def get_possible_actions(self, colour):\n \"\"\"Return a list of legal actions for 'colour' from the current node's state E.g. could return something like\n [(BOOM, (0, 2)), (BOOM, (0, 1)), (MOVE, 2, (0, 1), (2, 1)), (MOVE, 1, (7, 5), (7, 6)) ... etc]\n \"\"\"\n # array of actions which we will return after we have filled it with possible (legal) moves\n actions = []\n\n # go through the list of applicable BOOM actions and add them to actions[]\n squares = self.state.get_squares(colour)\n for stack in squares:\n actions.append((BOOM, stack))\n\n if self.state.total_pieces() > 10:\n # go through the list of applicable BOOM actions and add them to actions[]\n actions += self.state.get_non_trivial_move_actions(colour)\n return actions\n else:\n # go through the list of applicable MOVE actions\n # for each item from .items() from a stack dictionary, item[0] is the (x, y) coordinates of of the stack and\n # item[1] is the number of pieces in the stack\n for stack in self.state.get_colour(colour).items():\n # iterate through each possible number of pieces to move from our stack at the current occupied_square\n for n_pieces in range(1, stack[1] + 1):\n # possible moving directions\n for move_direction in MOVE_DIRECTIONS:\n # number of squares to move n_pieces from current stack, 1 <= n_steps <= n_pieces\n for n_steps in range(1, stack[1] + 1):\n # check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of\n # bounds and not landing on an enemy piece)\n if is_legal_move(self.state.get_squares(opponent(colour)), stack[0], move_direction,\n n_steps):\n final_square = calculate_dest_square(stack[0], move_direction, n_steps)\n actions.append((MOVE, n_pieces, stack[0], final_square))\n return actions\n\n \"\"\"def get_possible_actions(self, colour):\n \"\"\"\"\"\"Return a list of legal actions for 'colour' from the current node's state E.g. could return something like\n [(BOOM, (0, 2)), (BOOM, (0, 1)), (MOVE, 2, (0, 1), (2, 1)), (MOVE, 1, (7, 5), (7, 6)) ... etc]\n \"\"\"\"\"\"\n # array of actions which we will return after we have filled it with possible (legal) moves\n actions = []\n # go through the list of applicable BOOM actions and add them to actions[]\n squares = self.state.get_squares(colour)\n for stack in squares:\n actions.append((BOOM, stack))\n # go through the list of applicable MOVE actions\n # for each item from .items() from a stack dictionary, item[0] is the (x, y) coordinates of of the stack and\n # item[1] is the number of pieces in the stack\n for stack in self.state.get_colour(colour).items():\n # iterate through each possible number of pieces to move from our stack at the current occupied_square\n for n_pieces in range(1, stack[1] + 1):\n # possible moving directions\n for move_direction in MOVE_DIRECTIONS:\n # number of squares to move n_pieces from current stack, 1 <= n_steps <= n_pieces\n for n_steps in range(1, stack[1] + 1):\n # check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of\n # bounds and not landing on an enemy piece)\n if is_legal_move(self.state.get_squares(opponent(colour)), stack[0], move_direction, n_steps):\n final_square = calculate_dest_square(stack[0], move_direction, n_steps)\n actions.append((MOVE, n_pieces, stack[0], final_square))\n return actions\"\"\"\n\n def get_children(self, colour):\n children = []\n actions = self.get_possible_actions(colour)\n for action in actions:\n children.append(self.apply_action(colour, action))\n return children\n\n\ndef normalise(type, value):\n if type == \"md\":\n return (value - 0.5) / (7.5 - 0.5)\n if type == \"ng\":\n return (value - 1) / (4 - 1)\n\n\ndef is_legal_move(enemy_stack_locations, moving_stack_location, move_direction, n_steps):\n \"\"\" check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of bounds and not\n landing on an enemy piece) \"\"\"\n dest_square = calculate_dest_square(moving_stack_location, move_direction, n_steps)\n return bool((dest_square[0] in range(0, 8)) and (dest_square[1] in range(0, 8)) and (\n dest_square not in enemy_stack_locations))\n\n\ndef calculate_dest_square(moving_stack_location, move_direction, n_steps):\n return (\n moving_stack_location[0] + n_steps * move_direction[0], moving_stack_location[1] + n_steps * move_direction[1])\n\n\ndef opponent(colour):\n \"\"\"get the opponent colour. If given 'white' return 'black' and vice versa\"\"\"\n if colour == WHITE:\n return BLACK\n if colour == BLACK:\n return WHITE\n return None\n\n\ndef manhattan_dist(state, colour):\n total = 0\n\n if colour == WHITE:\n for white in state.white_stacks.items():\n current_total = 0\n for black in state.black_stacks.items():\n current_total += (abs(white[0][0] - black[0][0]) + abs(white[0][1] - black[0][1]))\n if len(state.black_stacks) < 3:\n total += current_total / 5\n else:\n total += current_total / len(state.black_stacks)\n # if len(state.black_stacks) == 0: return total\n if len(state.white_stacks) < 3:\n return total / 5\n return total / len(state.white_stacks)\n\n if colour == BLACK:\n for black in state.black_stacks.items():\n current_total = 0\n for white in state.white_stacks.items():\n current_total += (abs(white[0][0] - black[0][0]) + abs(white[0][1] - black[0][1]))\n if len(state.white_stacks) < 3:\n total += current_total / 5\n else:\n total += current_total / len(state.white_stacks)\n # if len(state.black_stacks) == 0: return total\n if len(state.black_stacks) < 3:\n return total / 5\n return total / len(state.black_stacks)\n\n\ndef move_action(colour, base_node, n_pieces, stack, dest_square):\n \"\"\" apply a move action to the given base node by moving n_pieces from stack n_steps in move_direction\n returns new_node resulting from the move \"\"\"\n # make a new node that is a copy of the base_node. Set last_player to current colour making the move\n new_node = base_node.copy()\n # adjust new_node fields according to how our move will change them:\n # parent node of the new_node is the base_node\n new_node.parent = base_node\n # new_node depth is parent depth + 1\n new_node.depth = base_node.depth + 1\n new_node.state.turn = base_node.state.turn + 1\n # store the move which got us to new_node\n new_node.move = (MOVE, n_pieces, stack, dest_square)\n new_node.last_colour = colour\n\n # execute move on new_node state\n # move the pieces from the stack to a new stack\n\n new_node.state.get_colour(colour)[stack] -= n_pieces\n if new_node.state.get_colour(colour)[stack] == 0:\n new_node.state.get_colour(colour).pop(stack)\n if dest_square in new_node.state.get_colour(colour):\n # there is already a stack in the square we are moving to, just add number of pieces\n new_node.state.get_colour(colour)[dest_square] += n_pieces\n else:\n # we have to make a new key value pair because we made a new stack\n new_node.state.get_colour(colour)[dest_square] = n_pieces\n\n # update node value\n # new_node.value = heuristic(colour, new_node.state)\n new_node.value = new_node.state.evaluation(colour)\n\n return new_node\n\n\ndef boom_action(colour, base_node, stack_to_boom):\n # make a new node that is a copy of the base_node\n new_node = base_node.copy()\n\n # adjust new_node fields according to how the boom change them:\n # parent node of the new_node is the base_node\n new_node.parent = base_node\n # new_node depth is parent depth + 1\n new_node.depth = base_node.depth + 1\n new_node.state.turn = base_node.state.turn + 1\n # store the move which got us to new_node\n new_node.move = (BOOM, stack_to_boom)\n new_node.last_colour = colour\n\n # recursive boom at the new_node.state starting at 'stack', this updates the state\n new_node.state = chain_boom(new_node.state, stack_to_boom)\n\n # update value and return\n # new_node.value = heuristic(colour, new_node.state)\n new_node.value = new_node.state.evaluation(colour)\n\n return new_node\n\n\ndef heuristic(colour, state):\n if (state.total_black() == 0) and (state.total_white() == 0):\n return DRAW_GAME\n\n if colour == WHITE:\n if state.total_black() == 0:\n # win game\n return WIN_GAME\n if state.total_white() == 0:\n # lost game\n return LOST_GAME\n # else, the heuristic is the number of our pieces on the board - enemy pieces on the board + manhattan\n # distance, **higer** is better\n # return state.eval(colour)\n return state.total_white() - state.total_black() # - abs(math.tanh(manhattan_dist(\n # state,colour))) # + math.tanh(state.num_groups(WHITE)) #- abs( math.tanh(manhattan_dist(state)) ) # - manhattan_dist(state)\n\n if colour == BLACK:\n if state.total_white() == 0:\n # win game\n return WIN_GAME\n if state.total_black() == 0:\n # lost game\n return LOST_GAME\n # else, the heuristic is the number of our pieces on the board - enemy pieces on the board + manhattan\n # distance, **higer** is better\n # return state.eval(colour)\n return state.total_black() - state.total_white() # - abs(math.tanh(\n # manhattan_dist(state, colour))) # + math.tanh(state.num_groups(BLACK)) #- abs( math.tanh(manhattan_dist(state)) )\n\n # else, incorrect colour given return None\n return None\n\n\ndef is_game_over(state):\n return bool(state.total_black() == 0 or state.total_white() == 0)\n\n\ndef chain_boom(state, stack_to_boom, stacks_to_remove=None):\n # add the stack_to_boom to the stacks_to_remove\n if stacks_to_remove is None:\n stacks_to_remove = set()\n stacks_to_remove.add(stack_to_boom)\n\n # go through all the adjacent stacks to stack_to_boom\n # add the stack to the stacks to be removed\n # make a boom radius from stack_to_boom\n radius_x = [stack_to_boom[0], stack_to_boom[0], stack_to_boom[0] - 1, stack_to_boom[0] - 1,\n stack_to_boom[0] - 1, stack_to_boom[0] + 1,\n stack_to_boom[0] + 1, stack_to_boom[0] + 1]\n # possible corresponding y coordinates e.g. (2,2): [1, 3, 2, 1, 3, 2, 1, 3]\n radius_y = [stack_to_boom[1] - 1, stack_to_boom[1] + 1, stack_to_boom[1], stack_to_boom[1] - 1,\n stack_to_boom[1] + 1, stack_to_boom[1],\n stack_to_boom[1] - 1, stack_to_boom[1] + 1]\n radius = list(zip(radius_x, radius_y))\n\n # get a list of all the squares where the boom hit\n all_stacks = list(state.white_stacks.keys()) + list(state.black_stacks.keys())\n stacks_hit = list(set(all_stacks).intersection(radius))\n\n # add all the stacks_stacks_hit to the stacks_to_remove set, if they havent been added before, boom them\n for st in stacks_hit:\n if st not in stacks_to_remove:\n stacks_to_remove.add(st)\n chain_boom(state, st, stacks_to_remove)\n\n # remove stacks_to_remove from state and return state\n for st in stacks_to_remove:\n if st in state.white_stacks:\n state.white_stacks.pop(st)\n if st in state.black_stacks:\n state.black_stacks.pop(st)\n return state\n\n\ndef get_greedy_action(colour, base_node, budget):\n \"\"\"returns the action associated with the best score achieved after that action is enacted on our current_node.state\n Note: because python uses a min-heap for their priority queue implementation, better scores are lower, the lower the score the better its value\"\"\"\n\n # store actions in a dict {} where the key is the score achieved by that action, break ties randomly\n # get the possible actions from our current position\n\n # make a copy of the initial node we were given\n # base_node = Node(current_node.state)\n\n # check if we can make a book move\n global in_book\n if in_book and base_node.state.turn in book_moves[colour]:\n # check if it is a legal move\n move = book_moves[colour][base_node.state.turn]\n # check if 1) the squre we are moving from is in our stack dictionay, 2) check if the move is not landing in an enemy stack square\n if move[2] in base_node.state.get_colour(colour) and move[3] not in base_node.state.get_colour(\n opponent(colour)):\n return book_moves[colour][base_node.state.turn]\n else:\n in_book = False\n\n best_actions = [] # initialise the best_actions with a dummy value so our loop doesnt kick up a fuss when we try to access the [0] index for the first time\n best_score = LOST_GAME\n actions = base_node.get_possible_actions(colour)\n for action in actions:\n current_node = base_node.apply_action(colour, action)\n current_node.value -= manhattan_dist(current_node.state, colour)\n if current_node.value > best_score:\n best_actions = [action] # reset the list to have 1 action as the new best\n best_score = current_node.value\n elif current_node.value == best_score:\n best_actions.append(action)\n\n # find the best action in those actions and return it. Break draws randomly\n return random.choice(best_actions)\n\n\ndef get_minimax_action(colour, base_node, budget):\n best_actions = [] # initialise the best_actions with a dummy value so our loop doesnt kick up a fuss when we try to access the [0] index for the first time\n best_score = LOST_GAME\n actions = base_node.get_possible_actions(colour)\n for action in actions:\n current_node = base_node.apply_action(colour, action)\n minimax_evlu = minimax(current_node, budget, False, opponent(colour))[colour]\n if minimax_evlu > best_score:\n best_actions = [action] # reset the list to have 1 action as the new best\n best_score = minimax_evlu\n elif minimax_evlu == best_score:\n best_actions.append(action)\n\n # find the best action in those actions and return it. Break draws randomly\n return random.choice(best_actions)\n\n\n# returns {WHITE: white heuristic, BLACK: black heuristic}\n# node = 'current node being worked on'\n# depth = the amount of depth we have left to explore\n# colour = the current players turn\n\"\"\"\ndef minimax(node, depth, maximising_player, colour):\n if depth == 0 or is_game_over(node.state):\n # print({WHITE: heuristic(WHITE, node.state), BLACK: heuristic(BLACK, node.state)})\n return {WHITE: heuristic(WHITE, node.state), BLACK: heuristic(BLACK, node.state)}\n if maximising_player:\n best_value = {colour: LOST_GAME, opponent(colour): WIN_GAME}\n actions = node.get_possible_actions(colour)\n for action in actions:\n current_node = node.apply_action(colour, action)\n tmp = minimax(current_node, depth - 1, False, opponent(colour))\n if tmp[colour] > best_value[colour]:\n best_value[colour] = tmp[colour]\n best_value[opponent(colour)] = tmp[opponent(colour)]\n return best_value\n else:\n best_value = {colour: WIN_GAME, opponent(colour): LOST_GAME}\n actions = node.get_possible_actions(colour)\n for action in actions:\n current_node = node.apply_action(colour, action)\n tmp = minimax(current_node, depth - 1, True, opponent(colour))\n if tmp[colour] < best_value[colour]:\n best_value[colour] = tmp[colour]\n best_value[opponent(colour)] = tmp[opponent(colour)]\n return best_value\n\"\"\"\n\"\"\"def get_alphabeta_action(colour, node, budget):\n current_node = node.copy()\n first_moves = current_node.get_children(colour)\n best_move = None\n best_value = -INFINITY\n for i in range(len(first_moves)):\n child = first_moves[i]\n value = minimax(child, budget, -INFINITY, INFINITY, False)\n if (value > best_value):\n best_move = child.move\n best_value = value\n return best_move\"\"\"\n\n\ndef get_alphabeta_action(colour, node, budget):\n current_node = node.copy()\n first_moves = current_node.get_children(colour)\n\n moves = {}\n for i in range(len(first_moves)):\n child = first_moves[i]\n value = minimax(child, budget, -INFINITY, INFINITY, False)\n if value in moves:\n moves[value].append(child.move)\n else:\n moves[value] = [child.move]\n\n best_move = random.choice(moves[max(moves)])\n return best_move\n\n\ndef minimax(node, depth, alpha, beta, maximising_player):\n if depth == 0:\n return node.value\n current_node = node.copy()\n\n if maximising_player:\n max_eval = -INFINITY\n children = current_node.get_children(opponent(current_node.last_colour))\n children.sort(key=lambda x: x.value, reverse=True)\n for i in range(len(children)):\n ev = minimax(children[i], depth - 1, alpha, beta, False)\n max_eval = max(max_eval, ev)\n alpha = max(alpha, max_eval)\n if beta <= alpha:\n return beta\n return alpha\n else:\n min_eval = INFINITY\n children = current_node.get_children(opponent(current_node.last_colour))\n children.sort(key=lambda x: x.value, reverse=False)\n for i in range(len(children)):\n ev = minimax(children[i], depth - 1, alpha, beta, True)\n min_eval = min(min_eval, ev)\n beta = min(beta, min_eval)\n if beta <= alpha:\n return alpha\n return beta\n\n\nwhite_book = {\n 0: (MOVE, 1, (4, 1), (3, 1)),\n 2: (MOVE, 2, (3, 1), (3, 3)),\n 4: (MOVE, 1, (3, 3), (3, 5)),\n # 6: (MOVE, 1, (3, 1), (3, 5))\n}\n\nblack_book = {\n 1: (MOVE, 1, (3, 6), (4, 6)),\n 3: (MOVE, 2, (4, 6), (4, 4)),\n 5: (MOVE, 1, (4, 4), (4, 2)),\n # 7: (MOVE, 1, (4, 6), (4, 2))\n}\nbook_moves = {WHITE: white_book, BLACK: black_book}\nin_book = True\n","sub_path":"testing/tdleaf0/aiutils.py","file_name":"aiutils.py","file_ext":"py","file_size_in_byte":29103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"620697760","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\nsetup = os.path.abspath(sys.argv[0])\nparent = os.path.dirname(setup)\npkg = os.path.basename(parent)\n\nif pkg.startswith(\"py-cooperhewitt\"):\n pkg = pkg.replace(\"py-\", \"\")\n pkg = pkg.replace(\"-\", \".\")\n\n egg_info = \"%s.egg-info\" % pkg\n egg_info = os.path.join(parent, egg_info)\n\n if os.path.exists(egg_info):\n shutil.rmtree(egg_info)\n\nfrom setuptools import setup, find_packages\n\npackages = find_packages()\ndesc = open(\"README.md\").read()\nversion = open(\"VERSION\").read()\n\nsetup(\n name='cooperhewitt-swatchbook',\n namespace_packages=['cooperhewitt'],\n version=version,\n description='Cooper Hewitt\\'s Python tools for wrangling colours',\n long_description=desc,\n author='Cooper Hewitt Smithsonian Design Museum',\n url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook',\n packages=packages,\n scripts=[],\n download_url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook/releases/tag/' + version,\n license='BSD'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"251923813","text":"# Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer\n# from [0, N) which is NOT in B.\n#\n# Optimize it such that it minimizes the call to system’s Math.random().\n#\n# Note:\n#\n# 1 <= N <= 1000000000\n# 0 <= B.length < min(100000, N)\n# [0, N) does NOT include N. See interval notation.\n# Example 1:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[1,[]],[],[],[]]\n# Output: [null,0,0,0]\n# Example 2:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[2,[]],[],[],[]]\n# Output: [null,1,1,1]\n# Example 3:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[3,[1]],[],[],[]]\n# Output: [null,0,0,2]\n# Example 4:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[4,[2]],[],[],[]]\n# Output: [null,1,3,1]\n# Explanation of Input Syntax:\n#\n# The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments,\n# N and the blacklist B. pick has no arguments. Arguments are always wrapped with a list, even if there aren't any.\n#\nimport collections\nfrom random import randint\n\n\nclass Solution(object):\n\n def __init__(self, N, blacklist):\n \"\"\"\n :type N: int\n :type blacklist: List[int]\n \"\"\"\n m = N - 1\n self._dMap = collections.defaultdict(int)\n self._M = N - len(blacklist)\n\n # bugfixed\n for b in blacklist:\n self._dMap[b] = -1\n\n # try to do re-mapping, assume we have N=10, blacklist [3, 5, 8, 9], we want to re-mapping 3 -> 7, 5->6,\n # so we would [1,2,3,4,5] as a base\n for b in blacklist:\n # we try to generate uniformly from [1, self._M]\n if b < self._M:\n\n # we keep finding element not in blacklist, for ex, 3 we found 7,\n # then we got self._dMap[3] = 7\n # same we got self._dMap[5] = 6\n while m in self._dMap:\n m -= 1\n # re-mapping\n self._dMap[b] = m\n m -= 1\n\n\n\n\n def pick(self):\n \"\"\"\n :rtype: int\n \"\"\"\n # we uniformly generate rand in [1, self._M]\n t = randint(1, self._M)\n # if it is in black list, we find its re-map, let's say we generate 3\n # then we found its remap is 6, return 6 instead of 3\n if t in self._dMap:\n return self._dMap[t]\n # if not in black list, return it directly\n return t\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(N, blacklist)\n# param_1 = obj.pick()\n","sub_path":"learnpythonthehardway/random-pick-with-blacklist-710.py","file_name":"random-pick-with-blacklist-710.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"277957899","text":"\"\"\"\n\n将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。\n\n\n\"\"\"\nfrom notebook.algorithm.链表.utils import ListNode\nfrom notebook.algorithm.链表.utils import init_ln\nfrom notebook.algorithm.链表.utils import print_ln\n\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n if not l1:\n return l2\n if not l2:\n return l1\n\n if l1.val > l2.val:\n head, ln = l2, l1\n else:\n head, ln = l1, l2\n result = head\n while ln and head:\n if head.val < ln.val:\n head = head.next\n else:\n # head的下一个节点置为另一个链条的节点,导致head本来的下一个节点失效\n head.next = ln\n ln = ln.next\n head = head.next\n head.next = ln\n return result\n\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n dump = ListNode()\n tmp = dump\n while l1 and l2:\n if l1.val < l2.val:\n dump.next = l1\n l1 = l1.next\n else:\n dump.next = l2\n l2 = l2.next\n dump = dump.next\n if l1:\n dump.next = l1\n else:\n dump.next = l2\n return tmp.next\n\n\nhead1 = init_ln([1, 3, 5, 7, 9])\nhead2 = init_ln([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\nprint_ln(Solution().mergeTwoLists(head1, head2))\n\n\"\"\"\n\n作者:LeetCode-Solution\n链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\"\"\"\n\n\n# 迭代\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n prehead = ListNode(-1)\n\n prev = prehead\n while l1 and l2:\n if l1.val <= l2.val:\n prev.next = l1\n l1 = l1.next\n else:\n prev.next = l2\n l2 = l2.next\n prev = prev.next\n\n # 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可\n prev.next = l1 if l1 is not None else l2\n\n return prehead.next\n\n\n\"\"\"\n递归的思路: 有点意思。很直观\n\"\"\"\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n if not l1:\n return l2\n if not l2:\n return l1\n if l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n # 直接返回了\n return l1\n else:\n # 直接返回了\n l2.next = self.mergeTwoLists(l2.next, l1)\n return l2\n\n\n\nhead1 = init_ln([1, 3, 5, 7, 9])\nhead2 = init_ln([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\nprint_ln(Solution().mergeTwoLists(head1, head2))\n","sub_path":"algorithm/链表/21. 合并两个有序链表.py","file_name":"21. 合并两个有序链表.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"341605637","text":"from channels.routing import route, include\n\nfrom trams import consumers as trams_consumers\n\n\ntrams_channels = [\n route('websocket.connect', trams_consumers.ws_add),\n route('websocket.disconnect', trams_consumers.ws_disconnect),\n]\n\n\nchannel_routing = [\n include(trams_channels, path=r'^/trams/$'),\n]\n","sub_path":"waw_data/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"356350432","text":"# coding: utf-8\n\"\"\"\nThis modules holds methods for generating predictions from a model.\n\"\"\"\nimport os\nimport sys\nimport logging\nfrom typing import List, Optional, Tuple\nimport numpy as np\n\nimport torch\nfrom torchtext.data import Dataset, Field\n\nfrom joeynmt.helpers import bpe_postprocess, load_config, \\\n get_latest_checkpoint, load_checkpoint, store_attention_plots\nfrom joeynmt.metrics import bleu, chrf, token_accuracy, sequence_accuracy, calc_ent_f1_and_ent_mcc \nfrom joeynmt.model import build_model, Model\nfrom joeynmt.batch import Batch, Batch_with_KB\nfrom joeynmt.data import load_data, make_data_iter, make_data_iter_kb, MonoDataset\nfrom joeynmt.constants import UNK_TOKEN, PAD_TOKEN, EOS_TOKEN\nfrom joeynmt.vocabulary import Vocabulary\n\n\n# pylint: disable=too-many-arguments,too-many-locals,no-member\ndef validate_on_data(model: Model, \n data: Dataset,\n batch_size: int,\n use_cuda: bool, \n max_output_length: int,\n level: str, \n eval_metric: Optional[str],\n loss_function: torch.nn.Module = None,\n beam_size: int = 0, \n beam_alpha: int = -1,\n batch_type: str = \"sentence\",\n kb_task = None,\n valid_kb: Dataset = None,\n valid_kb_lkp: list = [], \n valid_kb_lens:list=[],\n valid_kb_truvals: Dataset = None,\n valid_data_canon: Dataset = None,\n report_on_canonicals: bool = False,\n ) \\\n -> (float, float, float, List[str], List[List[str]], List[str],\n List[str], List[List[str]], List[np.array]):\n \"\"\"\n Generate translations for the given data.\n If `loss_function` is not None and references are given,\n also compute the loss.\n\n :param model: model module\n :param data: dataset for validation\n :param batch_size: validation batch size\n :param use_cuda: if True, use CUDA\n :param max_output_length: maximum length for generated hypotheses\n :param level: segmentation level, one of \"char\", \"bpe\", \"word\"\n :param eval_metric: evaluation metric, e.g. \"bleu\"\n :param loss_function: loss function that computes a scalar loss\n for given inputs and targets\n :param beam_size: beam size for validation.\n If 0 then greedy decoding (default).\n :param beam_alpha: beam search alpha for length penalty,\n disabled if set to -1 (default).\n :param batch_type: validation batch type (sentence or token)\n :param kb_task: is not None if kb_task should be executed\n :param valid_kb: MonoDataset holding the loaded valid kb data\n :param valid_kb_lkp: List with valid example index to corresponding kb indices\n :param valid_kb_len: List with amount of triples per kb \n :param valid_data_canon: TranslationDataset of valid data but with canonized target data (for loss reporting)\n\n\n :return:\n - current_valid_score: current validation score [eval_metric],\n - valid_loss: validation loss,\n - valid_ppl:, validation perplexity,\n - valid_sources: validation sources,\n - valid_sources_raw: raw validation sources (before post-processing),\n - valid_references: validation references,\n - valid_hypotheses: validation_hypotheses,\n - decoded_valid: raw validation hypotheses (before post-processing),\n - valid_attention_scores: attention scores for validation hypotheses\n - valid_ent_f1: TODO FIXME\n \"\"\"\n\n print(f\"\\n{'-'*10} ENTER VALIDATION {'-'*10}\\n\")\n\n print(f\"\\n{'-'*10} VALIDATION DEBUG {'-'*10}\\n\")\n\n print(\"---data---\")\n print(dir(data[0]))\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and \"kb\" in attr or \"src\" in attr or \"trg\" in attr] for example in data[:3] ])\n print(batch_size)\n print(use_cuda)\n print(max_output_length)\n print(level)\n print(eval_metric)\n print(loss_function)\n print(beam_size)\n print(beam_alpha)\n print(batch_type)\n print(kb_task)\n print(\"---valid_kb---\")\n print(dir(valid_kb[0]))\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and \"kb\" in attr or \"src\" in attr or \"trg\" in attr] for example in valid_kb[:3] ])\n print(len(valid_kb_lkp), valid_kb_lkp[-5:])\n print(len(valid_kb_lens), valid_kb_lens[-5:])\n print(\"---valid_kb_truvals---\")\n print(len(valid_kb_truvals), valid_kb_lens[-5:])\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and \"kb\" in attr or \"src\" in attr or \"trg\" in attr or \"trv\" in attr]for example in valid_kb_truvals[:3]])\n print(\"---valid_data_canon---\")\n print(len(valid_data_canon), valid_data_canon[-5:])\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and\"kb\" in attr or \"src\" in attr or \"trg\" in attr or \"trv\" or \"can\" in attr]for example in valid_data_canon[:3] ])\n print(report_on_canonicals)\n\n print(f\"\\n{'-'*10} END VALIDATION DEBUG {'-'*10}\\n\")\n\n if not kb_task:\n valid_iter = make_data_iter(\n dataset=data, batch_size=batch_size, batch_type=batch_type,\n shuffle=False, train=False)\n else:\n # knowledgebase version of make data iter and also provide canonized target data\n # data: for bleu/ent f1 \n # canon_data: for loss \n valid_iter = make_data_iter_kb(\n data, valid_kb, valid_kb_lkp, valid_kb_lens, valid_kb_truvals,\n batch_size=batch_size,\n batch_type=batch_type,\n shuffle=False, train=False,\n canonize=model.canonize,\n canon_data=valid_data_canon)\n\n valid_sources_raw = data.src\n pad_index = model.src_vocab.stoi[PAD_TOKEN]\n\n # disable dropout\n model.eval()\n # don't track gradients during validation\n with torch.no_grad():\n all_outputs = []\n valid_attention_scores = []\n valid_kb_att_scores = []\n total_loss = 0\n total_ntokens = 0\n total_nseqs = 0\n for valid_batch in iter(valid_iter):\n # run as during training to get validation loss (e.g. xent)\n\n batch = Batch(valid_batch, pad_index, use_cuda=use_cuda) \\\n if not kb_task else \\\n Batch_with_KB(valid_batch, pad_index, use_cuda=use_cuda)\n\n assert hasattr(batch, \"kbsrc\") == bool(kb_task)\n\n # sort batch now by src length and keep track of order\n if not kb_task:\n sort_reverse_index = batch.sort_by_src_lengths()\n else:\n sort_reverse_index = list(range(batch.src.shape[0]))\n\n # run as during training with teacher forcing\n if loss_function is not None and batch.trg is not None:\n\n ntokens = batch.ntokens\n if hasattr(batch, \"trgcanon\") and batch.trgcanon is not None:\n ntokens = batch.ntokenscanon # normalize loss with num canonical tokens for perplexity\n # do a loss calculation without grad updates just to report valid loss\n # we can only do this when batch.trg exists, so not during actual translation/deployment\n batch_loss = model.get_loss_for_batch(\n batch, loss_function=loss_function)\n # keep track of metrics for reporting\n total_loss += batch_loss\n total_ntokens += ntokens # gold target tokens\n total_nseqs += batch.nseqs\n\n # run as during inference to produce translations\n output, attention_scores, kb_att_scores = model.run_batch(\n batch=batch, beam_size=beam_size, beam_alpha=beam_alpha,\n max_output_length=max_output_length)\n\n # sort outputs back to original order\n all_outputs.extend(output[sort_reverse_index])\n valid_attention_scores.extend(\n attention_scores[sort_reverse_index]\n if attention_scores is not None else [])\n valid_kb_att_scores.extend(\n kb_att_scores[sort_reverse_index]\n if kb_att_scores is not None else [])\n\n assert len(all_outputs) == len(data)\n\n if loss_function is not None and total_ntokens > 0:\n # total validation loss\n valid_loss = total_loss\n # exponent of token-level negative log likelihood\n # can be seen as 2^(cross_entropy of model on valid set); normalized by num tokens; \n # see https://en.wikipedia.org/wiki/Perplexity#Perplexity_per_word\n valid_ppl = torch.exp(valid_loss / total_ntokens)\n else:\n valid_loss = -1\n valid_ppl = -1\n\n # decode back to symbols\n decoding_vocab = model.trg_vocab if not kb_task else model.trv_vocab\n\n decoded_valid = decoding_vocab.arrays_to_sentences(arrays=all_outputs,\n cut_at_eos=True)\n\n print(f\"decoding_vocab.itos: {decoding_vocab.itos}\")\n print(decoded_valid)\n\n\n # evaluate with metric on full dataset\n join_char = \" \" if level in [\"word\", \"bpe\"] else \"\"\n valid_sources = [join_char.join(s) for s in data.src]\n # TODO replace valid_references with uncanonicalized dev.car data ... requires writing new Dataset in data.py\n valid_references = [join_char.join(t) for t in data.trg]\n valid_hypotheses = [join_char.join(t) for t in decoded_valid]\n\n # post-process\n if level == \"bpe\":\n valid_sources = [bpe_postprocess(s) for s in valid_sources]\n valid_references = [bpe_postprocess(v) for v in valid_references]\n valid_hypotheses = [bpe_postprocess(v) for v in valid_hypotheses]\n\n # if references are given, evaluate against them\n if valid_references:\n assert len(valid_hypotheses) == len(valid_references)\n\n print(list(zip(valid_sources, valid_references, valid_hypotheses)))\n\n current_valid_score = 0\n if eval_metric.lower() == 'bleu':\n # this version does not use any tokenization\n current_valid_score = bleu(valid_hypotheses, valid_references)\n elif eval_metric.lower() == 'chrf':\n current_valid_score = chrf(valid_hypotheses, valid_references)\n elif eval_metric.lower() == 'token_accuracy':\n current_valid_score = token_accuracy(\n valid_hypotheses, valid_references, level=level)\n elif eval_metric.lower() == 'sequence_accuracy':\n current_valid_score = sequence_accuracy(\n valid_hypotheses, valid_references)\n\n if kb_task:\n valid_ent_f1, valid_ent_mcc = calc_ent_f1_and_ent_mcc(valid_hypotheses, valid_references,\n vocab=model.trv_vocab,\n c_fun=model.canonize,\n report_on_canonicals=report_on_canonicals\n )\n \n else:\n valid_ent_f1, valid_ent_mcc = -1, -1\n else:\n current_valid_score = -1\n\n print(f\"\\n{'-'*10} EXIT VALIDATION {'-'*10}\\n\")\n return current_valid_score, valid_loss, valid_ppl, valid_sources, \\\n valid_sources_raw, valid_references, valid_hypotheses, \\\n decoded_valid, valid_attention_scores, valid_kb_att_scores, \\\n valid_ent_f1, valid_ent_mcc\n\n# pylint: disable-msg=logging-too-many-args\ndef test(cfg_file,\n ckpt: str,\n output_path: str = None,\n save_attention: bool = False,\n logger: logging.Logger = None) -> None:\n \"\"\"\n Main test function. Handles loading a model from checkpoint, generating\n translations and storing them and attention plots.\n\n :param cfg_file: path to configuration file\n :param ckpt: path to checkpoint to load\n :param output_path: path to output\n :param save_attention: whether to save the computed attention weights\n :param logger: log output to this logger (creates new logger if not set)\n \"\"\"\n\n if logger is None:\n logger = logging.getLogger(__name__)\n FORMAT = '%(asctime)-15s - %(message)s'\n logging.basicConfig(format=FORMAT)\n logger.setLevel(level=logging.DEBUG)\n\n cfg = load_config(cfg_file)\n\n if \"test\" not in cfg[\"data\"].keys():\n raise ValueError(\"Test data must be specified in config.\")\n\n # when checkpoint is not specified, take latest (best) from model dir\n if ckpt is None:\n model_dir = cfg[\"training\"][\"model_dir\"]\n ckpt = get_latest_checkpoint(model_dir)\n if ckpt is None:\n raise FileNotFoundError(\"No checkpoint found in directory {}.\"\n .format(model_dir))\n try:\n step = ckpt.split(model_dir+\"/\")[1].split(\".ckpt\")[0]\n except IndexError:\n step = \"best\"\n\n batch_size = cfg[\"training\"].get(\n \"eval_batch_size\", cfg[\"training\"][\"batch_size\"])\n batch_type = cfg[\"training\"].get(\n \"eval_batch_type\", cfg[\"training\"].get(\"batch_type\", \"sentence\"))\n use_cuda = cfg[\"training\"].get(\"use_cuda\", False)\n level = cfg[\"data\"][\"level\"]\n eval_metric = cfg[\"training\"][\"eval_metric\"]\n max_output_length = cfg[\"training\"].get(\"max_output_length\", None)\n\n # load the data\n _, dev_data, test_data,\\\n src_vocab, trg_vocab,\\\n _, dev_kb, test_kb,\\\n _, dev_kb_lookup, test_kb_lookup, \\\n _, dev_kb_lengths, test_kb_lengths,\\\n _, dev_kb_truvals, test_kb_truvals, \\\n trv_vocab, canon_fun,\\\n dev_data_canon, test_data_canon \\\n = load_data(\n data_cfg=cfg[\"data\"]\n )\n\n report_entf1_on_canonicals = cfg[\"training\"].get(\"report_entf1_on_canonicals\", False)\n\n kb_task = (test_kb!=None)\n\n data_to_predict = {\"dev\": dev_data, \"test\": test_data}\n\n # load model state from disk\n model_checkpoint = load_checkpoint(ckpt, use_cuda=use_cuda)\n\n # build model and load parameters into it\n model = build_model(cfg[\"model\"], src_vocab=src_vocab, trg_vocab=trg_vocab, trv_vocab=trv_vocab, canonizer=canon_fun)\n model.load_state_dict(model_checkpoint[\"model_state\"])\n\n # FIXME for the moment, for testing, try overriding model.canonize with canon_fun from test functions loaded data\n # should hopefully not be an issue with gridsearch results...\n\n if use_cuda:\n model.cuda() # move to GPU\n\n # whether to use beam search for decoding, 0: greedy decoding\n if \"testing\" in cfg.keys():\n beam_size = cfg[\"testing\"].get(\"beam_size\", 0)\n beam_alpha = cfg[\"testing\"].get(\"alpha\", -1)\n else:\n beam_size = 0\n beam_alpha = -1\n\n for data_set_name, data_set in data_to_predict.items():\n \n if data_set_name == \"dev\":\n kb_info = [dev_kb, dev_kb_lookup, dev_kb_lengths, dev_kb_truvals, dev_data_canon]\n elif data_set_name == \"test\":\n kb_info = [test_kb, test_kb_lookup, test_kb_lengths, test_kb_truvals, test_data_canon]\n else:\n raise ValueError((data_set_name,data_set))\n \n #pylint: disable=unused-variable\n score, loss, ppl, sources, sources_raw, references, hypotheses, \\\n hypotheses_raw, attention_scores, kb_att_scores, ent_f1, ent_mcc = validate_on_data(\n model,\n data=data_set,\n batch_size=batch_size,\n batch_type=batch_type,\n level=level,\n max_output_length=max_output_length,\n eval_metric=eval_metric,\n use_cuda=use_cuda,\n loss_function=None,\n beam_size=beam_size,\n beam_alpha=beam_alpha,\n kb_task = kb_task,\n valid_kb=kb_info[0],\n valid_kb_lkp=kb_info[1], \n valid_kb_lens=kb_info[2],\n valid_kb_truvals=kb_info[3],\n valid_data_canon=kb_info[4],\n report_on_canonicals=report_entf1_on_canonicals\n )\n \"\"\"\n batch_size=self.eval_batch_size,\n data=valid_data,\n eval_metric=self.eval_metric,\n level=self.level, \n model=self.model,\n use_cuda=self.use_cuda,\n max_output_length=self.max_output_length,\n loss_function=self.loss,\n beam_size=0, \n batch_type=self.eval_batch_type,\n kb_task=kb_task,\n valid_kb=valid_kb,\n valid_kb_lkp=valid_kb_lkp,\n valid_kb_lens=valid_kb_lens,\n valid_kb_truvals=valid_kb_truvals\n \"\"\"\n #pylint: enable=unused-variable\n\n if \"trg\" in data_set.fields:\n decoding_description = \"Greedy decoding\" if beam_size == 0 else \\\n \"Beam search decoding with beam size = {} and alpha = {}\".\\\n format(beam_size, beam_alpha)\n\n logger.info(\"%4s %s: %6.2f f1: %6.2f mcc: %6.2f [%s]\",\n data_set_name, eval_metric, score, ent_f1, ent_mcc, decoding_description)\n else:\n logger.info(\"No references given for %s -> no evaluation.\",\n data_set_name)\n\n if save_attention:\n if attention_scores:\n attention_name = \"{}.{}.att\".format(data_set_name, step)\n attention_path = os.path.join(model_dir, attention_name)\n\n logger.info(\"Saving attention plots. This might take a while..\")\n store_attention_plots(attentions=attention_scores,\n targets=hypotheses_raw,\n sources=data_set.src,\n indices=range(len(hypotheses)),\n output_prefix=attention_path)\n logger.info(\"Attention plots saved to: %s\", attention_path)\n if kb_att_scores:\n kb_att_name = \"{}.{}.kbatt\".format(data_set_name, step)\n kb_att_path = os.path.join(model_dir, kb_att_name)\n store_attention_plots(\n attentions=kb_att_scores,\n targets=hypotheses_raw,\n sources=list(data_set.kbsrc),#TODO\n indices=range(len(hypotheses)),\n output_prefix=kb_att_path,\n kb_info = (dev_kb_lookup, dev_kb_lengths, list(data_set.kbtrg)))\n logger.info(\"KB Attention plots saved to: %s\", attention_path)\n \n else:\n logger.warning(\"Attention scores could not be saved. \"\n \"Note that attention scores are not available \"\n \"when using beam search. \"\n \"Set beam_size to 0 for greedy decoding.\")\n\n if output_path is not None:\n output_path_set = \"{}.{}\".format(output_path, data_set_name)\n with open(output_path_set, mode=\"w\", encoding=\"utf-8\") as out_file:\n for hyp in hypotheses:\n out_file.write(hyp + \"\\n\")\n logger.info(\"Translations saved to: %s\", output_path_set)\n\n\ndef translate(cfg_file, ckpt: str, output_path: str = None) -> None:\n # TODO FIXME XXX this function needs to be adapted to the KB case\n \"\"\"\n Interactive translation function.\n Loads model from checkpoint and translates either the stdin input or\n asks for input to translate interactively.\n The input has to be pre-processed according to the data that the model\n was trained on, i.e. tokenized or split into subwords.\n Translations are printed to stdout.\n\n :param cfg_file: path to configuration file\n :param ckpt: path to checkpoint to load\n \"\"\"\n\n def _load_line_as_data(line):\n \"\"\" Create a dataset from one line via a temporary file. \"\"\"\n # write src input to temporary file\n tmp_name = \"tmp\"\n tmp_suffix = \".src\"\n tmp_filename = tmp_name+tmp_suffix\n with open(tmp_filename, \"w\") as tmp_file:\n tmp_file.write(\"{}\\n\".format(line))\n\n test_data = MonoDataset(path=tmp_name, ext=tmp_suffix,\n field=src_field)\n\n # remove temporary file\n if os.path.exists(tmp_filename):\n os.remove(tmp_filename)\n\n return test_data\n\n def _translate_data(test_data):\n \"\"\" Translates given dataset, using parameters from outer scope. \"\"\"\n # pylint: disable=unused-variable\n score, loss, ppl, sources, sources_raw, references, hypotheses, \\\n hypotheses_raw, attention_scores = validate_on_data(\n model, data=test_data, batch_size=batch_size,\n batch_type=batch_type, level=level,\n max_output_length=max_output_length, eval_metric=\"\",\n use_cuda=use_cuda, loss_function=None, beam_size=beam_size,\n beam_alpha=beam_alpha,\n )\n return hypotheses\n\n cfg = load_config(cfg_file)\n\n # when checkpoint is not specified, take oldest from model dir\n if ckpt is None:\n model_dir = cfg[\"training\"][\"model_dir\"]\n ckpt = get_latest_checkpoint(model_dir)\n\n batch_size = cfg[\"training\"].get(\n \"eval_batch_size\", cfg[\"training\"].get(\"batch_size\", 1))\n batch_type = cfg[\"training\"].get(\n \"eval_batch_type\", cfg[\"training\"].get(\"batch_type\", \"sentence\"))\n use_cuda = cfg[\"training\"].get(\"use_cuda\", False)\n level = cfg[\"data\"][\"level\"]\n max_output_length = cfg[\"training\"].get(\"max_output_length\", None)\n\n # read vocabs\n src_vocab_file = cfg[\"data\"].get(\n \"src_vocab\", cfg[\"training\"][\"model_dir\"] + \"/src_vocab.txt\")\n trg_vocab_file = cfg[\"data\"].get(\n \"trg_vocab\", cfg[\"training\"][\"model_dir\"] + \"/trg_vocab.txt\")\n src_vocab = Vocabulary(file=src_vocab_file)\n trg_vocab = Vocabulary(file=trg_vocab_file)\n\n data_cfg = cfg[\"data\"]\n level = data_cfg[\"level\"]\n lowercase = data_cfg[\"lowercase\"]\n\n tok_fun = lambda s: list(s) if level == \"char\" else s.split()\n\n src_field = Field(init_token=None, eos_token=EOS_TOKEN,\n pad_token=PAD_TOKEN, tokenize=tok_fun,\n batch_first=True, lower=lowercase,\n unk_token=UNK_TOKEN,\n include_lengths=True)\n src_field.vocab = src_vocab\n\n # load model state from disk\n model_checkpoint = load_checkpoint(ckpt, use_cuda=use_cuda)\n\n # build model and load parameters into it\n model = build_model(cfg[\"model\"], src_vocab=src_vocab, trg_vocab=trg_vocab)\n model.load_state_dict(model_checkpoint[\"model_state\"])\n\n if use_cuda:\n model.cuda()\n\n # whether to use beam search for decoding, 0: greedy decoding\n if \"testing\" in cfg.keys():\n beam_size = cfg[\"testing\"].get(\"beam_size\", 0)\n beam_alpha = cfg[\"testing\"].get(\"alpha\", -1)\n else:\n beam_size = 0\n beam_alpha = -1\n\n if not sys.stdin.isatty():\n # file given\n test_data = MonoDataset(path=sys.stdin, ext=\"\", field=src_field)\n hypotheses = _translate_data(test_data)\n\n if output_path is not None:\n output_path_set = \"{}\".format(output_path)\n with open(output_path_set, mode=\"w\", encoding=\"utf-8\") as out_file:\n for hyp in hypotheses:\n out_file.write(hyp + \"\\n\")\n print(\"Translations saved to: {}\".format(output_path_set))\n else:\n for hyp in hypotheses:\n print(hyp)\n\n else:\n # enter interactive mode\n batch_size = 1\n while True:\n try:\n src_input = input(\"\\nPlease enter a source sentence \"\n \"(pre-processed): \\n\")\n if not src_input.strip():\n break\n\n # every line has to be made into dataset\n test_data = _load_line_as_data(line=src_input)\n\n hypotheses = _translate_data(test_data)\n print(\"JoeyNMT: {}\".format(hypotheses[0]))\n\n except (KeyboardInterrupt, EOFError):\n print(\"\\nBye.\")\n break\n","sub_path":"joeynmt/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":24328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"496509006","text":"##################################################################\n# Date : 2016-11-15\t\t\t\t\t\t\t\t\t\t\t\n# Author : Krittaphat Pugdeethosapol (krittaphat.pug@gmail.com)\n# Version : 1.0\t\t\t\t\t\t\n##################################################################\n\nimport numpy as np\nimport math\nimport time\nimport random\nimport pickle\nimport ConfigParser\n\nclass RBM:\n\tdef __init__(self, configFile, typeRBM):\n\t\tnp.seterr(all='ignore')\n\t\t# Reading Config file\n\t\tConfig = ConfigParser.ConfigParser()\n\t\tConfig.read(configFile)\n\t\tself.numHidden = int(Config.get(typeRBM, 'numHidden'))\n\t\tself.numVisible = int(Config.get(typeRBM, 'numVisible'))\n\t\tself.startLearningRate = float(Config.get(typeRBM, 'learningRate'))\n\t\tself.maxEpochs = int(Config.get(typeRBM, 'maxEpochs'))\n\t\tself.batchSize = int(Config.get(typeRBM, 'batchSize'))\n\t\tself.weightsObject = Config.get(typeRBM, 'weightsObject')\n\t\tself.hBiasObject = Config.get(typeRBM, 'hBiasObject')\n\t\tself.vBiasObject = Config.get(typeRBM, 'vBiasObject')\n\t\tself.screenObject = Config.get(typeRBM, 'screenObject')\n\t\t\n\t\tself.numpyRng = np.random.RandomState(random.randrange(0, 100))\n\n\t\t# Initial with zero mean and 0.01 std\n\t\ttry:\n\t\t\tself.weights = pickle.load(open(self.weightsObject, 'rb' ))\n\t\texcept:\n\t\t\tself.weights = np.asarray(self.numpyRng.normal(0, 0.01, size = (self.numVisible, self.numHidden)), dtype = np.float32)\n\n\t\t# Inital hidden Bias\n\t\ttry:\n\t\t\tself.hBias = pickle.load(open(self.hBiasObject, 'rb' ))\n\t\texcept:\n\t\t\tself.hBias = np.zeros(self.numHidden, dtype = np.float32)\n\n\t\t# Inital visible Bias\n\t\ttry:\n\t\t\tself.vBias = pickle.load(open(self.vBiasObject, 'rb' ))\n\t\texcept:\n\t\t\tself.vBias = np.zeros(self.numVisible, dtype = np.float32)\n\n\t\t# Initial Screen\n\t\ttry:\n\t\t\tself.screen = pickle.load(open(self.screenObject, 'rb' ))\n\t\texcept:\n\t\t\tself.screen = [1] * self.numVisible\n\n\t# Sigmoid\n\tdef sigmoid (self, x):\n\t\treturn 1.0 / (1 + np.exp(-x))\n\n\t# Calculate and return Positive hidden states and probabilities\n\tdef positiveProb (self, visible):\n\t\tposHiddenActivations = np.dot(visible, self.weights) + self.hBias\n\t\tposHiddenProbs = self.sigmoid(posHiddenActivations)\n\t\tposHiddenStates = posHiddenProbs > np.random.rand(visible.shape[0], self.numHidden)\n\t\treturn [posHiddenStates, posHiddenProbs]\n\n\t# Calculate and return Negative hidden states and probs\n\tdef negativeProb (self, hidden, k = 1):\n\t\tfor i in range (k):\n\t\t\tvisActivations = np.dot(hidden, self.weights.T) + self.vBias\n\t\t\tvisProbs = self.sigmoid(visActivations)\n\t\t\tvisProbs = visProbs * self.screen\n\t\t\thidden, hiddenProbs = self.positiveProb(visProbs)\n\t\treturn [visProbs, hiddenProbs]\n\n\t# Get hidden state\n\tdef getHidden (self, visible):\n\t\thiddenActivations = np.dot(visible, self.weights) + self.hBias\n\t\thiddenProbs = self.sigmoid(hiddenActivations)\n\t\thiddenStates = hiddenProbs > np.random.rand(visible.shape[0], self.numHidden)\n\t\treturn hiddenStates\n\n\t# Get visivle state\n\tdef getVisible (self, hidden):\n\t\tvisibleActivations = np.dot(hidden, self.weights.T) + self.vBias\n\t\tvisibleProbs = self.sigmoid(visibleActivations)\n\t\tvisibleProbs = visibleProbs * self.screen\n\t\treturn visibleProbs\n\n\t# Train RMB model\n\tdef train (self, data):\n\t\t# Screen some visible that always 0\n\t\tself.screen = [1] * self.numVisible\n\t\tfor column in range(data.shape[1]):\n\t\t\ttmpBias = sum(row[column] for row in data)\n\t\t\tif (tmpBias < 10):\n\t\t\t\tself.screen[column] = 0\n\t\tdata = data * self.screen\n\n\t\t# Clear the weight of some visibile that never appear and Add vBias\n\t\tself.weights = np.asarray(self.numpyRng.normal(0, 0.01, size=(self.numVisible, self.numHidden)), dtype=np.float32)\n\t\tself.weights = (self.weights.T * self.screen).T\n\t\tself.hBias = np.zeros(self.numHidden, dtype = np.float32)\n\t\tself.vBias = np.zeros(self.numVisible, dtype = np.float32)\n\n\t\tstart = time.time()\n\t\t# Start at CD1\n\t\tstep = 1\n\t\tlearningRate = self.startLearningRate\n\t\t# Loop for how many iterations\n\t\tfor epoch in range (self.maxEpochs): \n\t\t\tif (epoch != 0 and epoch%20 == 0):\n\t\t\t\tstep += 2\n\n\t\t\tstartTime = time.time()\n\n\t\t\t# Divide in to batch\n\t\t\ttotalBatch = math.ceil(data.shape[0]/self.batchSize)\n\t\t\tif data.shape[0]%self.batchSize != 0:\n\t\t\t\ttotalBatch += 1\n\n\t\t\t# Loop for each batch\n\t\t\tfor batchIndex in range (int(totalBatch)):\n\t\t\t\t# Get the data for each batch\n\t\t\t\ttmpData = data[batchIndex*self.batchSize: (batchIndex+1)*self.batchSize]\n\t\t\t\tnumExamples = tmpData.shape[0]\n\n\t\t\t\t# Caculate positive probs and Expectation for Sigma(ViHj) data\n\t\t\t\tposHiddenStates, posHiddenProbs = self.positiveProb(tmpData)\n\t\t\t\tposAssociations = np.dot(tmpData.T, posHiddenProbs)\n\t\t\t\tposHiddenBias = np.dot(np.ones(tmpData.shape[0]),posHiddenProbs)\n\t\t\t\tposVisibleBias = np.dot(tmpData.T, np.ones(tmpData.shape[0]).T)\n\n\t\t\t\t# Calculate negative probs and Expecatation for Sigma(ViHj) recon with k = step of gibs\n\t\t\t\tnegVisibleProbs, negHiddenProbs = self.negativeProb(posHiddenStates, k = step)\n\t\t\t\tnegAssociations = np.dot(negVisibleProbs.T, negHiddenProbs)\n\t\t\t\tnegHiddenBias = np.dot(np.ones(tmpData.shape[0]),negHiddenProbs)\n\t\t\t\tnegVisibleBias = np.dot(negVisibleProbs.T, np.ones(tmpData.shape[0]).T)\n\n\t\t\t\t# Update weight and Bias\n\t\t\t\tself.weights += learningRate*((posAssociations-negAssociations)/numExamples)\n\t\t\t\tself.hBias += learningRate*((posHiddenBias-negHiddenBias)/numExamples)\n\t\t\t\tself.vBias += learningRate*(((posVisibleBias-negVisibleBias)*self.screen)/numExamples)\n\n\t\t\t# Check error for each epoch\n\t\t\ttmpHidden = self.getHidden(data)\n\t\t\ttmpVisible = self.getVisible(tmpHidden)\n\t\t\ttmpVisible = tmpVisible * data\n\t\t\trmseError = math.sqrt(np.sum((data-tmpVisible)**2)/np.sum(data == 1))\n\t\t\ttotalTime = time.time()-startTime\n\n\t\t\tprint ('{0:7}Epoch : {1:5} Time : {2:15} Train RMSE : {3:10}'.format('INFO', epoch, totalTime, rmseError))\n\n\t\t# Save weights\n\t\tprint ('{0:7}TotalTime : {1}'.format('INFO', time.time()-start))\n\t\tpickle.dump(self.weights, open(self.weightsObject,'wb'))\n\t\tpickle.dump(self.hBias, open(self.hBiasObject,'wb'))\n\t\tpickle.dump(self.vBias, open(self.vBiasObject,'wb'))\n\t\tpickle.dump(self.screen, open(self.screenObject,'wb'))\t\n\nif __name__ == '__main__':\n\t# userRbm = RBM ('../data/Config.ini', 'UserRBM')\n\t# filePointer = open('../data/DocumentInfo.dat')\n\t# iterLines = iter(filePointer)\n #\n\t# # Read Data\n\t# print('Loading')\n\t# dataID = []\n\t# data = []\n\t# for lineNum, line in enumerate(iterLines):\n\t# \ttmp = [0] * userRbm.numVisible\n\t# \tID = line.split('::')\n\t# \tline = line.split('::')[1:]\n\t# \tfor doc in line:\n\t# \t\ttry:\n\t# \t\t\ttmp[int(doc)] = int(1)\n\t# \t\texcept:\n\t# \t\t\ttmpFalse = None\n\t# \tdata.append(tmp)\n\t# \tdataID.append(ID[0])\n\t# data = np.array(data)\n #\n\t# # data = np.array([[1,1,1,0,0,0],[1,0,1,0,0,0],[1,1,1,0,0,0],[0,0,1,1,1,0], [0,0,1,1,0,0],[0,0,1,1,1,0]])\n\t# # dataID = np.array([0,1,2,3,4,5])\n #\n\t# # Divide testing and training data\n\t# print('Training')\n\t# trainPart = 0.8\n\t# trainSize = int(trainPart * len(data))\n\t# train = np.array(data[:trainSize])\n\t# test = np.array(data[trainSize:])\n\t# userRbm.train(train, test)\n #\n\t# # Calculate all output\n\t# print('Recalling')\n\t# tmpHidden = userRbm.getHidden(data)\n\t# tmpVisible = userRbm.getVisible(tmpHidden)\n\t# # np.set_printoptions(threshold=np.nan)\n\t# # print(tmpHidden)\n #\n\t# print('Calculating')\n\t# f = open('../data/tmpOutputTableau.txt','w')\n\t# f2 = open('../data/tmpOutput.txt','w')\n\t# outputArray = {'key':'value'}\n\t# for i in range(tmpVisible.shape[0]):\n\t# \tmaxTop = 10\n\t# \tcountTop = 0\n\t# \ttmpValue = ''\n\t# \ttmpList = sorted(range(len(tmpVisible[i])), key=lambda k: tmpVisible[i][k], reverse=True)\n\t# \tfor j in range(tmpVisible.shape[1]):\n\t# \t\tif data[i][tmpList[j]] == 0:\n\t# \t\t\tif countTop > -1:\n\t# \t\t\t\ttmpValue += str(tmpList[j])\n\t# \t\t\t\tf.write('{0},{1},2\\n'.format(dataID[i],tmpList[j]))\n\t# \t\t\t\tif (countTop < maxTop-1):\n\t# \t\t\t\t\ttmpValue += '::'\n\t# \t\t\tcountTop = countTop + 1\n\t# \t\t\tif countTop == maxTop:\n\t# \t\t\t\tbreak\n\t# \toutputArray[dataID[i]] = tmpValue\n\t# \tf2.write('{0} {1}\\n'.format(dataID[i],tmpValue))\n\tthreshold = 0\n\tuserRBM = RBM('../data/Config.ini', 'UserRBMKCiteU')\n\n\tcountEX = 0\n\t# Read Data\n\tprint('Read Data')\n\tfilePointer = open('../data/UserInfo.dat')\n\titerLines = iter(filePointer)\n\trateEx = []\n\tidEx = []\n\tdataID = []\n\tdata = []\n\tdataTest = []\n\tfor lineNum, line in enumerate(iterLines):\n\t\ttmp = [0] * userRBM.numVisible\n\t\tID = line.split('::')[0]\n\t\tline = line.split('::')[1:]\n\t\texID = np.random.randint(len(line))\n\t\tfor offset, ele in enumerate(line):\n\t\t\tidTmp = ele\n\t\t\tif int(idTmp) < 16980:\n\t\t\t\ttmp[int(idTmp)] = int(1)\n\t\t\t\tif offset == exID:\n\t\t\t\t\tif int(0) >= threshold:\n\t\t\t\t\t\tprint('Ex {0} {1}'.format(lineNum, offset))\n\t\t\t\t\t\trateEx.append(0)\n\t\t\t\t\t\tidEx.append(int(idTmp))\n\t\t\t\t\t\ttmp[int(idTmp)] = int(0)\n\t\t\t\t\t\tif lineNum >= 4000:\n\t\t\t\t\t\t\tcountEX += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\texID += 1\n\t\tif lineNum < 4000:\n\t\t\tdata.append(tmp)\n\t\telse:\n\t\t\tdataTest.append(tmp)\n\t\tdataID.append(ID)\n\tdata = np.array(data)\n\tdataTest = np.array(dataTest)\n\tprint (data.shape)\n\tprint (dataTest.shape)\n\tprint (countEX)\n\n\t# Train\n\tprint('Training')\n\ta = time.time()\n\tuserRBM.train(data)\n\tprint('Time = {0}'.format(time.time() - a))\n\n\t# Calculate all output\n\tprint('Recall')\n\ttmpHidden = userRBM.getHidden(dataTest)\n\ttmpVisible = userRBM.getVisible(tmpHidden)\n\ttmpVisible = np.array(tmpVisible)\n\n\tcountCheck = 0\n\tfor eachUser in range(tmpVisible.shape[0]):\n\t\ttmpVisibleStates = tmpVisible > np.random.rand(tmpVisible.shape[0], tmpVisible.shape[1])\n\t\tif tmpVisible[eachUser][idEx[eachUser]] > 0:\n\t\t\tcountCheck += 1\n\n\tprint('Accuracy = {0}%'.format((countCheck / float(dataTest.shape[0])) * 100))\n\ttmpVisible *= dataTest\n\trmseError = math.sqrt(np.sum((dataTest - tmpVisible) ** 2) / np.sum(dataTest == 1))\n\tprint ('Testing RMSE : {0}'.format(rmseError))\n\n\t# pickle.dump(outputArray, open('../data/tmpOutput.object','wb'))\n\tprint('Done')\n\n\n\n\n\n\n","sub_path":"sourceCode/RBM.py","file_name":"RBM.py","file_ext":"py","file_size_in_byte":9706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"183058156","text":"import requests\nfrom apartment.models import Apartment\nfrom house.models import House\nfrom realestate.models import RealEstate\nfrom building.models import Building\nfrom apartmentbuilding.models import ApartmentBuilding\n\ndef getSimilarRealEstate(request):\n\n print(request.GET)\n realestate = RealEstate.objects.get(id=request.GET['real_estate_id'])\n\n building = Building.objects.get(id=request.GET['building_id'])\n\n if (realestate.lng == 0.0 or realestate.lat == 0.0):\n url = 'https://maps.googleapis.com/maps/api/geocode/json'\n url_address = '?address={} {}, {}, {}'.format(\n realestate.addressStreet,\n realestate.addressNumber,\n realestate.addressCommune,\n realestate.addressRegion)\n url_key = '&key=AIzaSyDgwKrK7tfcd9kCtS9RKSBsM5wYkTuuc7E'\n response = requests.get(url+''+url_address+''+url_key)\n response_json = response.json()\n if len(response_json['results']) > 0:\n response_results = response_json['results'][0]['geometry']['location']\n realestate.lat = response_results['lat']\n realestate.lng = response_results['lng']\n realestate.save()\n\n if 'apartment_id' in request.GET:\n if request.GET['apartment_id'] != '':\n apartment_building = ApartmentBuilding.objects.get(id=request.GET['apartment_building_id'])\n apartment = Apartment.objects.get(id=request.GET['apartment_id'])\n if (apartment.bedrooms != None and\n apartment.bathrooms != None and\n apartment.usefulSquareMeters != None and\n apartment.terraceSquareMeters != None):\n\n apartments = Apartment.objects.filter(\n bedrooms=realestate.apartment.bedrooms,\n bathrooms=realestate.apartment.bathrooms,\n usefulSquareMeters__isnull=False,\n terraceSquareMeters__isnull=False,\n marketPrice__isnull=False).exclude(marketPrice=0)\n\n ds = []\n ni = 0\n for i, apt in enumerate(apartments):\n d1 = float(pow(apartment.usefulSquareMeters - apt.usefulSquareMeters,2))\n d2 = float(pow(apartment.terraceSquareMeters - apt.terraceSquareMeters,2))\n d3 = float(pow(apt.latlng[0] - realestate.latlng[0],2)+pow(apt.latlng[1] - realestate.latlng[1],2))\n ds.append([0,0])\n ds[i][0] = apt.pk\n ds[i][1] = d1+d2+d3\n\n ds = sorted(ds, key=lambda x: x[1])\n ins = [x[0] for x in ds]\n\n references = apartments.filter(pk__in=ins[0:20])\n return references\n else:\n print('nada')\n return []\n elif 'house_id' in request.GET:\n if request.GET['house_id'] != '':\n house = House.objects.get(id=request.GET['house_id'])\n house.bathrooms=3\n house.bedrooms=4\n house.builtSquareMeters=89\n house.terrainSquareMeters=90\n house.save\n if (house.bedrooms != None and\n house.bathrooms != None and\n house.builtSquareMeters != None and\n house.terrainSquareMeters != None):\n\n houses = House.objects.filter(\n bedrooms=house.bedrooms,\n bathrooms=house.bathrooms,\n builtSquareMeters__isnull=False,\n terrainSquareMeters__isnull=False,\n marketPrice__isnull=False)\n\n ds = []\n ni = 0\n print(houses)\n for i, hs in enumerate(houses):\n #o_price_per_terrain_surface = realestate.house.marketPrice/realestate.house.terrainSquareMeters\n #o_price_per_total_surface = realestate.house.marketPrice/realestate.totalSquareMeters\n #i_price_per_terrain_surface = house.marketPrice/house.terrainSquareMeters\n #i_price_per_total_surface = house.marketPrice/house.realestate_ptr.totalSquareMeters\n #f1 = float(pow(o_price_per_terrain_surface-i_price_per_terrain_surface,2))\n #f2 = float(pow(o_price_per_total_surface-i_price_per_total_surface,2))\n\n d1 = float(pow(house.terrainSquareMeters - hs.terrainSquareMeters,2))\n d2 = float(pow(house.builtSquareMeters - hs.builtSquareMeters,2))\n d3 = 1000000000.0*float(pow(hs.building.real_estate.latlng[0] - realestate.latlng[0],2)\n +pow(hs.building.real_estate.latlng[1] - realestate.latlng[1],2))\n\n ds.append([0,0])\n ds[i][0] = hs.pk\n ds[i][1] = d1+d2+d3\n ds = sorted(ds, key=lambda x: x[1])\n ins = [x[0] for x in ds]\n\n references = houses.filter(pk__in=ins[0:20])\n return references\n else:\n print('nothing')\n return []\n else:\n return []","sub_path":"web/appraisal/related.py","file_name":"related.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"252273976","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom TestEnvironmentPackage.FetchEnvironment import getLoggedInPage\n\n\nclass Xpath_Util:\n \"\"\"Class to generate the xpaths\"\"\"\n\n def __init__(self):\n self.elements = None\n self.guessable_elements = ['input', 'button']\n self.known_attribute_list = ['id', 'name', 'placeholder', 'value', 'title', 'type', 'class']\n\n def generate_xpath(self, soup):\n \"generate the xpath\"\n result_flag = False\n try:\n for guessable_element in self.guessable_elements:\n self.elements = soup.find_all(guessable_element)\n for element in self.elements:\n if (not element.has_attr(\"type\")) or (element.has_attr(\"type\") and element['type'] != \"hidden\"):\n for attr in self.known_attribute_list:\n if element.has_attr(attr):\n locator = self.guess_xpath(guessable_element, attr, element)\n if len(driver.find_elements_by_xpath(locator)) == 1:\n result_flag = True\n print(locator.encode('utf-8'))\n break\n elif guessable_element == 'button' and element.getText():\n button_text = element.getText()\n if element.getText() == button_text.strip():\n locator = xpath_obj.guess_xpath_button(guessable_element, \"text()\",\n element.getText())\n else:\n locator = xpath_obj.guess_xpath_using_contains(guessable_element, \"text()\",\n button_text.strip())\n if len(driver.find_elements_by_xpath(locator)) == 1:\n result_flag = True\n print(locator.encode('utf-8'))\n break\n except Exception as e:\n print(\"Exception when trying to generate xpath for:%s\" % guessable_element)\n print(\"Python says:%s\" % str(e))\n\n return result_flag\n\n def guess_xpath(self, tag, attr, element):\n \"Guess the xpath based on the tag,attr,element[attr]\"\n # Class attribute returned as a unicodeded list, so removing 'u from the list and joining back\n if type(element[attr]) is list:\n element[attr] = [i.encode('utf-8') for i in element[attr]]\n element[attr] = ' '.join(element[attr])\n self.xpath = \"//%s[@%s='%s']\" % (tag, attr, element[attr])\n\n return self.xpath\n\n def guess_xpath_button(self, tag, attr, element):\n \"Guess the xpath for button tag\"\n self.button_xpath = \"//%s[%s='%s']\" % (tag, attr, element)\n\n return self.button_xpath\n\n def guess_xpath_using_contains(self, tag, attr, element):\n \"Guess the xpath using contains function\"\n self.button_contains_xpath = \"//%s[contains(%s,'%s')]\" % (tag, attr, element)\n\n return self.button_contains_xpath\n\n#-------START OF SCRIPT--------\nif __name__ == \"__main__\":\n print(\"Start of %s\" % __file__)\n\n # Initialize the xpath object\n xpath_obj = Xpath_Util()\n\n driver = webdriver.Chrome()\n\n driver.get('http://automationpractice.com/index.php')\n getLoggedInPage(driver)\n driver.find_element_by_xpath('//*[@id=\"center_column\"]/div/div[1]/ul/li[4]/a/span').click()\n #print(driver.current_url)\n\n url = driver.current_url\n page = driver.execute_script(\"return document.body.innerHTML\").encode('utf-8')\n soup = BeautifulSoup(page, 'html.parser')\n\n if xpath_obj.generate_xpath(soup) is False:\n print(\"No XPaths generated for the URL:%s\"%url)\n\n driver.quit()","sub_path":"TestEnvironmentPackage/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"585780234","text":"#-*- coding: utf-8 -*-\nimport database as db\n\n###########################################\n#LOGIC FOR MATCHES\n###########################################\n\n\nTYPE_BOTH_RESULTS = 'both_results'\nTYPE_WINNER_ONE_RESULT = 'winner_one_result'\nTYPE_WINNER_NO_RESULT = 'winner_no_result'\nTYPE_DRAW = 'draw'\n\nTYPE_DESCRIPTION = {\n TYPE_BOTH_RESULTS: 'Resultado exacto',\n TYPE_WINNER_ONE_RESULT: 'Ganador, un resultado',\n TYPE_WINNER_NO_RESULT: 'Ganador, ningún resultado',\n TYPE_DRAW: 'Empate, ningún resultado',\n}\n\ndef getAllTypes():\n return (\n TYPE_BOTH_RESULTS,\n TYPE_WINNER_ONE_RESULT,\n TYPE_WINNER_NO_RESULT,\n TYPE_DRAW,\n )\n\n\ndef save_all(idChampDate,obj, cur):\n if 'matchs' in obj:\n for itemMatch in obj[\"matchs\"]:\n itemMatch[\"id_championship_date\"] = idChampDate\n save(itemMatch, cur)\n\ndef save(obj, cur):\n if obj[\"id\"] == '':\n insert(obj,cur)\n else:\n update(obj,cur)\n\ndef disable_all(idDate, cur):\n cur.execute(\"\"\"\n update championship_match set\n is_disabled = true\n where id_championship_date = %s\n \"\"\", ( idDate, ) )\n\ndef update(obj, cur):\n if obj['goals_team1'] == '': obj['goals_team1'] = None\n if obj['goals_team2'] == '': obj['goals_team2'] = None\n\n cur.execute(\"\"\"\n update championship_match set\n goals_team1 = %(goals_team1)s,\n goals_team2 = %(goals_team2)s,\n is_disabled = false\n where id = %(id)s\n \"\"\", obj)\n\ndef insert(obj, cur):\n if obj['goals_team1'] == '': obj['goals_team1'] = None\n if obj['goals_team2'] == '': obj['goals_team2'] = None\n\n cur.execute(\"\"\"\n insert into championship_match(\n id_championship_date,\n id_team1,\n id_team2,\n goals_team1,\n goals_team2,\n date_start ,\n is_disabled\n )\n values(\n %(id_championship_date)s,\n %(id_team1)s,\n %(id_team2)s,\n %(goals_team1)s,\n %(goals_team2)s,\n %(date_start)s,\n false )\n RETURNING id\n \"\"\", obj)\n\n obj['id'] = cur.fetchone()[0]\n\n###########################################\n#LOGIC FOR POINTS\n###########################################\n\n#objMatch should contains: id, goals_team1, goals_team2\ndef save_points(objMatch, objTypePoints, cur):\n cur.execute('''\n select id, score_team1, score_team2\n from gambler_score\n where\n id_championship_match = %(id)s\n ''', objMatch )\n\n for row in db._cursor_fetchall_to_dict(cur):\n if row['score_team1'] == None: continue\n if row['score_team2'] == None: continue\n save_points_by_user(objTypePoints,objMatch, row, cur)\n\ndef save_points_by_user(objTypePoints,objMatch, objGamblerScore, cur):\n s1 = objMatch['goals_team1'] #real score for team 1\n s2 = objMatch['goals_team2'] #real score for team 2\n us1 = objGamblerScore['score_team1'] #user score for team 1\n us2 = objGamblerScore['score_team2'] #user score for team 2\n\n totalPoints = 0\n idType = None \n\n t = TYPE_BOTH_RESULTS\n if (t in objTypePoints) and totalPoints==0:\n if s1 == us1 and s2 == us2:\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n #end-if\n\n t = TYPE_WINNER_ONE_RESULT\n if _exists_winner(s1,s2) and (t in objTypePoints) and totalPoints==0:\n if (s1 == us1 or s2 == us2) and _who_wins(s1,s2) == _who_wins(us1,us2):\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n #end-if\n\n t = TYPE_WINNER_NO_RESULT\n if _exists_winner(s1,s2) and (t in objTypePoints) and totalPoints==0:\n if _who_wins(s1,s2) == _who_wins(us1,us2):\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n #end-if\n\n t = TYPE_DRAW\n if not _exists_winner(s1,s2) and (t in objTypePoints) and totalPoints==0:\n if us1 == us2:\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n\n cur.execute('''\n update gambler_score set\n points = %s,\n id_championship_date_points = %s\n where id = %s\n ''', (totalPoints, idType, objGamblerScore['id']) )\n\ndef _exists_winner(score1, score2):\n return score1 != score2\n\ndef _who_wins(score1,score2):\n who = 0\n if score1>score2: who=1\n if score2>score1: who=2\n return who\n","sub_path":"src/resources/model/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"351997109","text":"\"\"\"Test note API endpoints.\"\"\"\nfrom datetime import datetime\n\nfrom aiohttp import ClientSession\nimport pytest\nimport pytz\n\nfrom aiopinboard import API\nfrom aiopinboard.note import Note\n\nfrom tests.common import TEST_API_TOKEN, load_fixture\n\n\n@pytest.mark.asyncio\nasync def test_get_notes(aresponses):\n \"\"\"Test getting notes.\"\"\"\n aresponses.add(\n \"api.pinboard.in\",\n \"/v1/notes/list\",\n \"get\",\n aresponses.Response(text=load_fixture(\"notes_get_response.xml\"), status=200),\n )\n\n async with ClientSession() as session:\n api = API(TEST_API_TOKEN, session=session)\n\n notes = await api.note.async_get_notes()\n assert len(notes) == 1\n assert notes[0] == Note(\n \"xxxxxxxxxxxxxxxxxxxx\",\n \"Test\",\n \"xxxxxxxxxxxxxxxxxxxx\",\n pytz.utc.localize(datetime(2020, 9, 6, 5, 59, 47)),\n pytz.utc.localize(datetime(2020, 9, 6, 5, 59, 47)),\n 14,\n )\n","sub_path":"tests/test_note_api.py","file_name":"test_note_api.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"410092726","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\nCreated on 2018/12/6\n@author: shimakaze-git\n'''\nimport os\nfrom datetime import datetime\n\nfrom sqlalchemy import Column, DateTime, String, text\nfrom sqlalchemy.dialects.mysql import INTEGER\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom sqlalchemy.sql.functions import current_timestamp\n\nfrom rdb import Base, engine, session\n\nSQLITE3_NAME = \"./db.sqlite3\"\n\n\nclass Task(Base):\n __tablename__ = 'tasks'\n\n id = Column(\n INTEGER(unsigned=True),\n primary_key=True,\n autoincrement=True\n )\n name = Column(String(256))\n text = Column(String(256))\n created_at = Column(\n DateTime,\n default=datetime.now(),\n nullable=False,\n server_default=current_timestamp()\n )\n updated_at = Column(\n DateTime,\n default=datetime.now(),\n nullable=False,\n onupdate=datetime.now()\n )\n\n def __init__(self, name=None, text=None):\n self.name = name\n self.text = text\n\n @property\n def as_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'text': self.text\n }\n\n @classmethod\n def read_list(cls):\n try:\n models = []\n with session.begin():\n query = session.query(cls)\n models = query.all()\n return models\n except SQLAlchemyError as e:\n print(e)\n\n @classmethod\n def read(cls, id):\n try:\n with session.begin():\n task = session.query(\n cls\n ).filter(\n cls.id == id\n ).first()\n return task\n except SQLAlchemyError as e:\n print(e)\n\n def create(self):\n try:\n with session.begin():\n session.add(self)\n except SQLAlchemyError as e:\n print(e)\n\n def update(self, id):\n try:\n task = self.read(id)\n if task:\n with session.begin():\n task.name = self.name\n task.text = self.text\n except SQLAlchemyError as e:\n print(e)\n\n def delete(self, id):\n try:\n task = self.read(id)\n if task:\n with session.begin():\n session.delete(task)\n except SQLAlchemyError as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n path = SQLITE3_NAME\n if not os.path.isfile(path):\n # テーブル作成\n Base.metadata.create_all(engine)\n","sub_path":"step1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"51385593","text":"import sys\nfrom bs4 import BeautifulSoup\nfrom .models import Customer, Account, Statement\nfrom typing import List\n\n\n\nclass HtmlParserBs4:\n \"\"\"A class used to parse html to objects.\"\"\"\n\n def __init__(self) -> None:\n pass\n\n def parse_customers_html_to_objects(self, customers_html: str, username: str) -> List[Customer]:\n \"\"\"Iterate over the customers' html, and create and return Customer objects.\"\"\"\n customers = list()\n soup = BeautifulSoup(customers_html, 'html.parser')\n custs = soup.find_all('ul', attrs={'class':'collection with-header'})\n for cust in custs:\n attributes = cust.find_all('li')\n name = ''\n address = ''\n emails = ''\n phones = ''\n i = 0\n for attribute in attributes:\n if i == 0:\n name = attribute.text\n elif i == 1:\n phones = attribute.text\n elif i == 2:\n emails = attribute.text\n elif i == 3:\n address = attribute.text\n i += 1\n customers.append(Customer(name, username, address, emails, phones))\n return customers\n\n def parse_accounts_html_to_objects(self, accounts_html: str) -> List[Account]:\n \"\"\"Iterate over the accounts' html, and create and return Account objects.\"\"\"\n accounts = list()\n soup = BeautifulSoup(accounts_html, 'html.parser')\n acts = soup.find_all('li', attrs={'class':'collection-item avatar'})\n for act in acts:\n name = act.find('span', attrs={'class':'title'}).text\n number_and_balance = act.find('p')\n number = number_and_balance.next_element.strip()\n balance = number_and_balance.find('span').text\n account_id = act.find('a')['href']\n account_id = account_id[account_id.index('/')+1:]\n accounts.append(Account(name, number, balance, account_id))\n return accounts\n\n def parse_statements_html_to_objects(self, statements_html: str) -> List[Statement]:\n \"\"\"Iterate over the statements' html, and create and return Statement objects.\"\"\"\n statements = list()\n soup = BeautifulSoup(statements_html, 'html.parser')\n thead = soup.find('thead')\n headers = thead.find_all('th')\n i = 0\n headerPositions = {}\n for header in headers:\n headerPositions[i] = header.text.lower()\n i += 1\n tbody = soup.find('tbody')\n stmts = tbody.find_all('tr')\n for stmt in stmts:\n attributes = stmt.find_all('td')\n date = ''\n amount = ''\n balance = ''\n concept = ''\n i = 0\n for attribute in attributes:\n # if the attribute is in the header,\n # user the header for reference\n if i in headerPositions:\n if headerPositions[i] == 'statement':\n concept = attribute.text\n elif headerPositions[i] == 'date':\n date = attribute.text\n elif headerPositions[i] == 'amount':\n amount = attribute.text\n elif headerPositions[i] == 'balance':\n balance = attribute.text\n # otherwise fall back to a set position\n else:\n if i == 0:\n concept = attribute.text\n elif i == 1:\n date = attribute.text\n elif i == 2:\n amount = attribute.text\n elif i == 3:\n balance = attribute.text\n i += 1\n statements.append(Statement(date, amount, balance, concept))\n return statements\n","sub_path":"server/u_test/html_parser_bs4.py","file_name":"html_parser_bs4.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"357084329","text":"# -*- coding: utf-8 -*-\n# @Start_Time : 2018/6/25 10:42\n# @End_time: 2018/6/25 11:52\n# @Author : Andy\n# @Site : \n# @File : 67_add_binary_180625.py\n\n\"\"\"\nGiven two binary strings, return their sum (also a binary string).\n\nThe input strings are both non-empty and contains only characters 1 or 0.\n\nExample 1:\n\nInput: a = \"11\", b = \"1\"\nOutput: \"100\"\nExample 2:\n\nInput: a = \"1010\", b = \"1011\"\nOutput: \"10101\"\n\nInput:\n\"100\"\n\"110010\"\nOutput:\n\"1010000\"\nExpected:\n\"110110\"\n\"\"\"\n\n\nclass Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n if not len(a):\n return b\n if not len(b):\n return a\n\n def add_core(a, b):\n # for char in b:\n # if char != '1' or char != '0':\n # valid_input = False\n # return 0\n valid_input = True\n c = [0 for _ in range(len(a) + 1)]\n index_c = len(a)\n for i in range(len(b) - 1, -1, -1):\n ii = i + len(a) - len(b)\n if a[ii] != '1' and a[ii] != '0' or b[i] != '1' and b[i] != '0':\n valid_input = False\n return 0\n temp = int(a[ii]) + int(b[i]) + c[index_c]\n if temp > 1:\n c[index_c] = temp - 2\n c[index_c - 1] = 1\n else:\n c[index_c] = temp\n index_c -= 1\n for j in range(len(a) - len(b) - 1, -1, -1):\n # jj = j + len(b)\n if a[j] != '1' and a[j] != '0':\n valid_input = False\n return 0\n temp = int(a[j]) + c[index_c]\n if temp > 1:\n c[index_c] = temp - 2\n c[index_c - 1] = 1\n else:\n c[index_c] = temp\n index_c -= 1\n\n return valid_input, c\n\n # make sure that a is the longer string\n if len(a) < len(b):\n valid_input, c = add_core(b, a)\n else:\n valid_input, c = add_core(a, b)\n\n if not valid_input:\n return\n # return c\n return str(int(\"\".join(map(str, c))))\n\nprint(Solution().addBinary(\"1010\", \"1011\"))\nprint(Solution().addBinary(\"100\", \"110010\"))\n\n\n","sub_path":"LeetCode/1806/67_add_binary_180625.py","file_name":"67_add_binary_180625.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"141005726","text":"import contextlib\nimport os\nimport subprocess\n\nimport pytest\n\nfrom git.get_changed_subprojects import get_changed_files, \\\n get_changed_subprojects\n\nHERE = os.path.realpath(os.path.dirname(__file__))\nTEST_REPO = os.path.join(HERE, 'resources', 'test-repo')\nGIT_DIR_UNINITIALIZED = os.path.join(TEST_REPO, 'git')\nGIT_DIR = os.path.join(TEST_REPO, '.git')\n\n\n@contextlib.contextmanager\ndef in_test_repo():\n curr = os.getcwd()\n # print('DEBUG: changing to {}'.format(TEST_REPO))\n os.chdir(TEST_REPO)\n try:\n yield\n finally:\n # print('DEBUG: changing back to {}'.format(curr))\n os.chdir(curr)\n\n\ndef reset_repo():\n with in_test_repo():\n # print('DEBUG: resetting repo')\n subprocess.call('git reset --hard HEAD', shell=True)\n\n\ndef checkout_master():\n reset_repo()\n with in_test_repo():\n # print('DEBUG: checking out master')\n subprocess.call('git checkout master'.format(TEST_REPO), shell=True)\n\n\ndef checkout_new_branch():\n reset_repo()\n with in_test_repo():\n # print('DEBUG: checking out new-branch')\n subprocess.call('git checkout new-branch'.format(TEST_REPO), shell=True)\n\n\n@contextlib.contextmanager\ndef activated_test_repo():\n print('DEBUG: activating test repo')\n os.rename(GIT_DIR_UNINITIALIZED, GIT_DIR)\n try:\n checkout_master()\n yield\n finally:\n reset_repo()\n # print('DEBUG: deactivating test repo')\n os.rename(GIT_DIR, GIT_DIR_UNINITIALIZED)\n\n\n@pytest.mark.parametrize('cwd,base_commit,commit,project_dir,expected', [\n (TEST_REPO, 'master', 'HEAD', '.', {'a-change', 'aaaa-new'}),\n (TEST_REPO, 'master', 'HEAD', 'a-change', {'b-change', 'bbbb-new'}),\n (os.path.join(TEST_REPO, 'a-change'), 'master', 'HEAD', '..', {'a-change', 'aaaa-new'}),\n (os.path.join(TEST_REPO, 'a-change'), 'master', 'HEAD', '.', {'b-change', 'bbbb-new'}),\n (os.path.join(TEST_REPO, 'aa-no-change'), 'master', 'HEAD', '../a-change', {'b-change', 'bbbb-new'}),\n])\ndef test_main(cwd, base_commit, commit, project_dir, expected):\n with activated_test_repo():\n checkout_new_branch()\n os.chdir(cwd)\n\n # print('DEBUG: calling main')\n changed_files = get_changed_files(base_commit, commit)\n changed_subprojects = get_changed_subprojects(changed_files, project_dir)\n assert changed_subprojects == expected\n\n\n","sub_path":"packages/get-changed-subprojects/tests/functional/test_get_changed_subprojects.py","file_name":"test_get_changed_subprojects.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"190805691","text":"import os\n\nfrom kluctl.tests.test_base import DeploymentTestBase\nfrom kluctl.utils.yaml_utils import yaml_load_file\n\ncur_dir = os.path.dirname(__file__)\n\nclass TestTemplating(DeploymentTestBase):\n def get_jinja2_vars(self):\n return {\n 'a': 'a1',\n 'b': 'b1',\n 'include_var': 'd1',\n }\n\n def test_deployment_yml(self):\n with self.build_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as (d, c):\n self.assertEqual(len(d.includes), 2)\n self.assertListEqual(d.conf['tags'], ['a1', 'a2'])\n\n def test_include_var(self):\n with self.build_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as (d, c):\n self.assertEqual(d.includes[0].dir, os.path.join(cur_dir, 'test_deployment', 'd1'))\n\n def test_not_rendered_kustomize_resource(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/not-rendered.yml'))\n self.assertEqual(y['a'], '{{ a }}')\n\n def test_rendered_kustomize_resource(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/rendered.yml'))\n self.assertEqual(y['a'], 'a1')\n\n def test_load_template(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/rendered.yml'))\n self.assertEqual(y['b'], 'test a1')\n self.assertEqual(y['c'], 'test a1')\n\n def test_rendered_kustomization_yml(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/kustomization.yml'))\n self.assertListEqual(y['resources'], ['b1'])\n\n def test_import_no_context(self):\n with self.render_deployment('templating/test_import', self.get_jinja2_vars(), {}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'k1/rendered.yml'))\n self.assertEqual(y['a'], 'a1')\n\n def test_get_var(self):\n with self.render_deployment('templating/test_utils', self.get_jinja2_vars(), {}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'k1/get_var.yml'))\n self.assertEqual(y['test1'], 'default')\n self.assertEqual(y['test2'], 'default')\n self.assertEqual(y['test3'], 'a')\n\n def test_vars(self):\n with self.render_deployment('templating/test_vars', self.get_jinja2_vars(), {}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'k1/test.yml'))\n self.assertEqual(y['test1'], 'v1')\n self.assertEqual(y['test2'], 'f1')\n self.assertEqual(y['test3'], 'v1')\n self.assertEqual(y['test4'], 'b')\n","sub_path":"kluctl/tests/templating/test_templating.py","file_name":"test_templating.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"323541580","text":"from PySide2.QtCore import Signal, QTimer\nfrom PySide2.QtWidgets import (\n QWidget,\n QHBoxLayout,\n QToolButton,\n QLabel,\n QLineEdit,\n QSpacerItem,\n QSizePolicy,\n QFrame,\n)\n\nfrom chartify.settings import Settings\nfrom chartify.utils.utils import FilterTuple\n\n\nclass ViewTools(QFrame):\n \"\"\"\n A class to represent an application toolbar.\n\n \"\"\"\n\n structureChanged = Signal()\n textFiltered = Signal(tuple)\n expandRequested = Signal()\n collapseRequested = Signal()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setObjectName(\"viewTools\")\n view_tools_layout = QHBoxLayout(self)\n view_tools_layout.setSpacing(6)\n view_tools_layout.setContentsMargins(0, 0, 0, 0)\n\n btn_widget = QWidget(self)\n btn_layout = QHBoxLayout(btn_widget)\n btn_layout.setSpacing(0)\n btn_layout.setContentsMargins(0, 0, 0, 0)\n\n # ~~~~ Set up view buttons ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n self.tree_view_btn = QToolButton(self)\n self.tree_view_btn.setObjectName(\"treeButton\")\n self.tree_view_btn.setCheckable(True)\n self.tree_view_btn.setChecked(Settings.TREE_VIEW)\n\n self.collapse_all_btn = QToolButton(self)\n self.collapse_all_btn.setObjectName(\"collapseButton\")\n self.collapse_all_btn.setEnabled(Settings.TREE_VIEW)\n\n self.expand_all_btn = QToolButton(self)\n self.expand_all_btn.setObjectName(\"expandButton\")\n self.expand_all_btn.setEnabled(Settings.TREE_VIEW)\n\n self.filter_icon = QLabel(self)\n self.filter_icon.setObjectName(\"filterIcon\")\n\n btn_layout.addWidget(self.expand_all_btn)\n btn_layout.addWidget(self.collapse_all_btn)\n btn_layout.addWidget(self.tree_view_btn)\n\n # ~~~~ Line edit ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n self.variable_line_edit = QLineEdit(self)\n self.variable_line_edit.setPlaceholderText(\"variable...\")\n self.variable_line_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n self.variable_line_edit.setFixedWidth(100)\n\n self.key_line_edit = QLineEdit(self)\n self.key_line_edit.setPlaceholderText(\"key...\")\n self.key_line_edit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.key_line_edit.setFixedWidth(100)\n\n self.units_line_edit = QLineEdit(self)\n self.units_line_edit.setPlaceholderText(\"units...\")\n self.units_line_edit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.units_line_edit.setFixedWidth(50)\n\n spacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum)\n\n view_tools_layout.addWidget(self.filter_icon)\n view_tools_layout.addWidget(self.variable_line_edit)\n view_tools_layout.addWidget(self.key_line_edit)\n view_tools_layout.addWidget(self.units_line_edit)\n view_tools_layout.addItem(spacer)\n view_tools_layout.addWidget(btn_widget)\n\n # ~~~~ Timer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n # Timer to delay firing of the 'text_edited' event\n self.timer = QTimer()\n self.timer.setSingleShot(True)\n self.timer.timeout.connect(self.request_filter)\n\n # ~~~~ Filter actions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n self.variable_line_edit.textEdited.connect(self.on_text_edited)\n self.key_line_edit.textEdited.connect(self.on_text_edited)\n self.units_line_edit.textEdited.connect(self.on_text_edited)\n self.expand_all_btn.clicked.connect(self.expandRequested.emit)\n self.collapse_all_btn.clicked.connect(self.collapseRequested.emit)\n self.tree_view_btn.toggled.connect(self.tree_btn_toggled)\n\n def tree_requested(self):\n \"\"\" Check if tree structure is requested. \"\"\"\n return self.tree_view_btn.isChecked()\n\n def get_filter_tuple(self):\n \"\"\" Get current filter string. \"\"\"\n return FilterTuple(\n key=self.key_line_edit.text(),\n variable=self.variable_line_edit.text(),\n units=self.units_line_edit.text(),\n )\n\n def tree_btn_toggled(self, checked):\n \"\"\" Update view when view type is changed. \"\"\"\n self.tree_view_btn.setProperty(\"checked\", checked)\n\n # collapse and expand all buttons are not relevant for plain view\n self.collapse_all_btn.setEnabled(checked)\n self.expand_all_btn.setEnabled(checked)\n # store current state in settings\n Settings.TREE_VIEW = checked\n self.structureChanged.emit()\n\n def on_text_edited(self):\n \"\"\" Delay firing a text edited event. \"\"\"\n self.timer.start(200)\n\n def request_filter(self):\n \"\"\" Apply a filter when the filter text is edited. \"\"\"\n self.textFiltered.emit(self.get_filter_tuple())\n","sub_path":"chartify/ui/treeview_tools.py","file_name":"treeview_tools.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"23126709","text":"\n\ndef main():\n module = AnsibleModule(argument_spec=dict(name=dict(type='str', required=True), state=dict(type='str', choices=['killed', 'once', 'reloaded', 'restarted', 'started', 'stopped']), enabled=dict(type='bool'), downed=dict(type='bool'), dist=dict(type='str', default='daemontools'), service_dir=dict(type='str', default='/service'), service_src=dict(type='str', default='/etc/service')), supports_check_mode=True)\n module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C')\n state = module.params['state']\n enabled = module.params['enabled']\n downed = module.params['downed']\n svc = Svc(module)\n changed = False\n orig_state = svc.report()\n if ((enabled is not None) and (enabled != svc.enabled)):\n changed = True\n if (not module.check_mode):\n try:\n if enabled:\n svc.enable()\n else:\n svc.disable()\n except (OSError, IOError) as e:\n module.fail_json(msg=('Could change service link: %s' % to_native(e)))\n if ((state is not None) and (state != svc.state)):\n changed = True\n if (not module.check_mode):\n getattr(svc, state[:(- 2)])()\n if ((downed is not None) and (downed != svc.downed)):\n changed = True\n if (not module.check_mode):\n d_file = ('%s/down' % svc.svc_full)\n try:\n if downed:\n open(d_file, 'a').close()\n else:\n os.unlink(d_file)\n except (OSError, IOError) as e:\n module.fail_json(msg=('Could change downed file: %s ' % to_native(e)))\n module.exit_json(changed=changed, svc=svc.report())\n","sub_path":"Data Set/bug-fixing-1/ff37e5364c7921a9db3415e328924f51ce5fa9ba-
-bug.py","file_name":"ff37e5364c7921a9db3415e328924f51ce5fa9ba-
-bug.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"56107865","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : huxiansheng (you@example.org)\n\nimport pickle\nimport re\nimport time\nfrom Public.Logger import Logger\n\n\nclass WhidowsInfo():\n '''\n 电脑环境信息\n '''\n logger = Logger('WhidowsInfo').getlog()\n def root_coordinate(self,root):\n '''\n 窗口坐标\n 获取电脑的分辨率,并判断中间位置\n :param root: 主窗口控件\n :return:返回屏幕中间坐标\n '''\n ws = root.winfo_screenmmwidth()\n hs = root.winfo_screenheight()\n x = (ws/2)+400\n y = (hs/2)-250\n self.logger.info('当前屏幕分辨率为%sx%s,中间坐标为%s,%s'%(ws,hs,x,y))\n return x,y\n\n\n def get_window_time(self):\n '''\n 获取本地时间\n :return:\n '''\n now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 格式化当前时间\n return now\n\n\nclass Pickle():\n '''\n 二进制文件读取\n '''\n logger = Logger('Pickle').getlog()\n def load(self,file_path):\n '''\n 读取二进制文件\n :return:\n '''\n try:\n f = open(file_path, 'rb')\n file_datas = pickle.load(f) # 读出文件的数据个数\n f.close()\n except Exception as e:\n self.logger.error('读取二进制文件【%s】失败,无法自动填写账号密码,错误信息:%s'%(file_path,e))\n file_datas =False\n return file_datas\n\n\n def dump(self,obj,path):\n '''\n 写入文件\n :param obj: 写入文件的对象\n :param path: 路劲\n :return:\n '''\n try:\n f = open(path, 'wb') # 以写模式打开二进制文件\n pickle.dump(obj,f)\n f.close()\n return True\n except Exception as e:\n self.logger.error('写入二进制文件【%s】失败,错误异常:%s' % (path, e))\n return False\n\n\nclass Str_manager():\n logger = Logger('Str_manager').getlog()\n # 检验字符串是否包含汉字\n def check_contain_chinese(self,check_str):\n '''\n 判断传入字符串是否包含中文\n :param word: 待判断字符串\n :return: None:不包含中文 False:输入的不是字符串\n '''\n zh_pattern = re.compile(u'[\\u4e00-\\u9fa5]+')\n try:\n match = zh_pattern.search(check_str)\n return match\n except:\n return False\n","sub_path":"Public/Common.py","file_name":"Common.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"210143601","text":"import json\nimport random\nimport sys\nfrom datetime import datetime\nfrom django.core import serializers\nfrom django.core.management import setup_environ\nfrom os.path import dirname, abspath, basename\n\nsys.path.insert(0, dirname(dirname(abspath(__file__))))\nimport settings\n\nsetup_environ(settings)\n\nimport free103.artists.models as am\nimport free103.works.models as wm\nimport free103.events.models as em\nimport wgxc.schedule.models as sm\n\n\n# set up the serializer\njsonify = serializers.get_serializer('json')().serialize\n\n# get the ID map\ntry:\n imj = open('id_map.json')\n id_map = json.load(imj)\n imj.close()\nexcept IOError:\n id_map = {}\n\n# open the bulk file for appending\nbulk = open('bulk.json', 'a')\n\ndef get_main(obj_id, model):\n obj = model.objects.get(id=obj_id)\n if model == wm.Work:\n return obj.title\n if model == am.Artist:\n return obj.display_name\n if model == em.Event:\n return obj.name\n if model == sm.Show:\n return obj.title\n if model == em.Location:\n return obj.name\n\n# base32 according to http://www.crockford.com/wrmg/base32.html\nalphabet = '0123456789abcdefghjkmnpqrstvwxyz';\n\ndef generate_id():\n id = []\n for x in range(6):\n id.append(random.choice(alphabet))\n return ''.join(id);\n\ndef get_existing_id(datatype, old_id):\n if datatype not in id_map:\n sys.stdout.write('[%s datatype not in map] ' % datatype)\n return\n new_id = id_map[datatype].get(unicode(old_id))\n if new_id:\n return new_id\n sys.stdout.write('[%s %s not in map] ' % (datatype, old_id))\n\nclass FancyDict(dict):\n 'dict with extra spice'\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n # copy keys so we can add and delete\n keys = self.keys()[:]\n for key in keys:\n if self.get(key):\n if key.startswith('related_'):\n new_key = key.split('_')[1]\n self.rename(key, new_key)\n else: # convert to camelCase\n new_key = ''.join(x.capitalize() for x in key.split('_'))\n new_key = new_key[0].lower() + new_key[1:]\n self.rename(key, new_key)\n else:\n del self[key]\n\n def rename(self, key, new_key):\n val = self.get(key)\n if val:\n del self[key]\n self[new_key] = val\n\n def link(self, key, datatype, model):\n if key in self:\n rels = []\n for old_id in self[key]:\n new_id = get_existing_id(datatype, old_id)\n if new_id:\n rels.append({'id': new_id, 'main': get_main(old_id, model)})\n self[key] = rels\n\nMIMETYPE_MAP = {}\nFILETYPE_MAP = {}\nfor mimetype in wm.MimeType.objects.all():\n MIMETYPE_MAP[mimetype.id] = mimetype.name\n for media_type in ('image', 'audio', 'video'):\n if mimetype.name.startswith(media_type):\n FILETYPE_MAP[mimetype.name] = media_type\n if mimetype.name == 'application/pdf':\n FILETYPE_MAP[mimetype.name] = 'text'\n\ndef artistLink(doc, field):\n if field in doc:\n #print doc[field]\n artists = am.Artist.objects.filter(id__in=doc[field])\n del doc[field]\n for a in artists:\n if a.types.filter(id=1):\n dt = 'artist'\n elif a.types.filter(id=2):\n dt = 'collaborator'\n else: # TODO: handle wgxc artist types\n continue\n new_id = get_existing_id(dt, a.id)\n brief = {'id': new_id, 'main': a.display_name}\n rel = dt + 's'\n if rel in doc:\n doc[rel].append(brief)\n else:\n doc[rel] = [brief]\n\nSITES = [None, 'transmissionarts', 'wgxc']\n\ndef bulk_load(query_set, datatype, munge):\n if datatype not in id_map:\n id_map[datatype] = {}\n\n # TODO jsonify each record manually to avoid these shenanigans\n records = json.loads(jsonify(query_set))\n\n count = 0\n for record in records:\n sys.stdout.write('%s ' % record['pk'])\n doc = FancyDict(record['fields'])\n\n # get ID for new system\n if doc.get('newId'):\n new_id = doc['newId']\n del doc['newId']\n elif id_map[datatype].get(unicode(record['pk'])):\n new_id = id_map[datatype].get(unicode(record['pk']))\n else:\n sys.stdout.write('generating new ID ')\n new_id = generate_id()\n # stick the new_id in the map in case it isn't there already\n id_map[datatype][record['pk']] = new_id\n doc['oldId'] = record['pk']\n doc['id'] = new_id\n doc['type'] = datatype\n doc['timestamp'] = datetime.now().isoformat()\n artistLink(doc, 'artists')\n if datatype in ['artist', 'collaborator']:\n artistLink(doc, 'seeAlso')\n doc.link('works', 'work', wm.Work)\n doc.link('locations', 'location', em.Location)\n doc.link('shows', 'show', sm.Show)\n\n if 'sites' in doc:\n doc['sites'] = [SITES[x] for x in doc['sites']]\n\n # munge doc\n munge(doc)\n\n # after munge since location deletes them\n doc.link('events', 'event', em.Event)\n\n # archive files\n if 'files' in doc:\n for file_id in doc['files']:\n af = wm.ArchiveFile.objects.get(id=file_id)\n dt = FILETYPE_MAP.get(af.mimetype.name)\n if not dt:\n continue\n new_id = get_existing_id(dt, file_id)\n if new_id:\n main = af.title or basename(unicode(af.url)) or basename(unicode(af.upload))\n brief = {'id': new_id, 'main': main}\n if dt in doc:\n doc[dt].append(brief)\n else:\n doc[dt] = [brief]\n del doc['files']\n\n # stick it in the file\n bulk.write('{\"index\": {\"_index\": \"free103\", \"_type\": \"%s\", \"_id\": \"%s\"}}\\n' % \n (doc['type'], doc['id']))\n json.dump(doc, bulk)\n bulk.write('\\n')\n\n count += 1\n sys.stdout.write('\\nTotal: %s\\n' % count)\n\n # write out updated id_map\n id_map_fh = open('id_map.json', 'w')\n json.dump(id_map, id_map_fh)\n id_map_fh.close()\n","sub_path":"free103/utils/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"514808625","text":"from datetime import datetime\n\nfrom flask import jsonify, render_template\n\nfrom main import app\nfrom mongo_test_history import update_data_db\nfrom storage import Storage\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/api/v1.0/test', methods=['GET'])\ndef test():\n storage = Storage()\n client = storage.get_client()\n collection = client.lanscan.topology\n\n update_data_db(collection, '10.1.1.1', '00:00:00:00:00', 'test', datetime.now)\n\n client.close()\n\n return \"OK\"\n\n\n@app.route('/api/v1.0/all', methods=['GET'])\ndef get_all():\n storage = Storage()\n client = storage.get_client()\n collection = client.lanscan.topology\n\n try:\n data = list(collection.aggregate([{\n '$project': {\n '_id': 0,\n 'ip': 1,\n 'dns': {\n '$arrayElemAt': ['$dns.dns', -1]\n },\n 'mac': {\n '$arrayElemAt': ['$mac.mac', -1]\n }\n }\n }]))\n except:\n data = \"Error\"\n\n client.close()\n\n return jsonify(data)\n","sub_path":"app/v1_0.py","file_name":"v1_0.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"561698215","text":"import requests\nimport json\nimport pymysql\nimport datetime\nimport csv\n\nclass dongqiudi_vidio():\n\n#初始化数据库\n def __init__(self):\n dbparams = {\n 'host': '39.100.245.203',\n 'port': 3306,\n 'user': \"root\",\n 'password': \"asus123836.\",\n 'database': \"scrapy\",\n 'charset': 'utf8mb4'\n }\n self.conn = pymysql.connect(**dbparams)\n self.cursur = self.conn.cursor()\n\n def vidio(self,url):\n self.url = url\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'\n }\n\n response = requests.get(headers=headers, url=self.url)\n response.encoding = 'utf-8'\n return response.text\n\n def get_data(self,url):\n html = dongqiudi_vidio.vidio(self,url=url)\n next_url = json.loads(html).get('next')\n print(next_url)\n datas = json.loads(html).get('articles')\n for data in datas:\n item = {}\n item['id'] = data.get('id')\n item['title'] = data.get('title')\n item['thumb'] = data.get('thumb')\n item['mp4'] = data.get('video_info')['video_src']\n item['pub_time'] = data.get('published_at')\n item['avatar'] = 'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqXEgVS72kWucKk8XibicQlspRySDMWicCBfibgEbYQHpHbicVOjp7vlXIib0AxPicJ65gstwThJkEibgRTTQ/132'\n item['nickname'] = 'توپ بىلگە'\n id = str(item['id'])\n if dongqiudi_vidio.virdect(self,id=id):\n print(item)\n # dongqiudi_vidio.save_vidio(self,item=item)\n # dongqiudi_vidio.save_url(self, id=id)\n\n dongqiudi_vidio.get_data(self,url=next_url)\n\n# 保存id\n def save_url(self,id):\n list = []\n with open('dongqiudi.csv', 'a', encoding='utf-8', newline='') as fp:\n list.append(id)\n writer = csv.writer(fp)\n writer.writerow(list)\n\n# 判断id\n def virdect(self,id):\n with open('dongqiudi.csv', mode='r', encoding='cp936') as fp:\n data = fp.read()\n if id in data:\n return False\n else:\n return True\n\n\n def save_vidio(self,item):\n SQL = \"\"\"\n INSERT INTO dongqiudi_vidio (id, title, thumb, mp4, pub_time, avatar, nickname)\n values (%s,%s,%s,%s,%s,%s,%s)\n \"\"\"\n\n self.cursur.execute(SQL, (item['id'], item['title'], item['thumb'], item['mp4'],item['pub_time'], item['avatar'],item['nickname']))\n self.conn.commit()\n print('Insert success for nur_index')\n\n\nif __name__ == '__main__':\n url = 'https://api.dongqiudi.com/v3/archive/app/tabs/getlists?id=100043&platform=android&version=220'\n dic = dongqiudi_vidio().get_data(url=url)\n\n\n\n","sub_path":"spider/nur_news/dongqiudi_vidio.py","file_name":"dongqiudi_vidio.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"322679723","text":"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nbooks = []\n# for i in range(3):\n\nurl = 'http://books.toscrape.com/index.html'\nhost = \"http://books.toscrape.com\"\nr = requests.get(url)\nsoup = BeautifulSoup(r.content, \"html.parser\")\ncontent = soup.find_all(\"article\", class_=\"product_pod\")\n\nfor product_pod in content:\n books.append({\n\n \"titres\": product_pod.find(\"h3\").text,\n \"prix\": product_pod.find(\"p\", class_=\"price_color\").text,\n \"links\": host + product_pod.find(\"a\").get(\"href\"),\n \"images\": host + product_pod.find(\"img\", class_=\"thumbnail\").get(\"src\"),\n\n })\n\nprint(books)\n\ndf = pd.DataFrame(books)\ndf.to_csv(\"books_1.csv\")\ndf.to_excel(\"books.xlsx\")\nprint(\"saved to file\")\n","sub_path":"P2_02_codesource/books_2.py","file_name":"books_2.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"245364460","text":"\"\"\"\n@arthor:金龙\n@school:hrbust\n@depart:computer\n@file: b_私有方法.py\n@time: 2017/10/4 10:43\n@describe:\n\"\"\"\n\n\nclass Cat:\n # __两个下划线表示私有方法\n def __send_msg(self):\n print('正在发送短信')\n\n def send_msg(self, new_money):\n if new_money > 10:\n self.__send_msg()\n else:\n print('余额不足')\n\n\ncat = Cat()\ncat.send_msg(100)\n","sub_path":"day02/b_私有方法.py","file_name":"b_私有方法.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"603167527","text":"import matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import trapz\nfrom matplotlib.colors import LogNorm\nfrom tristan_funcs import load_particle_edotv_withtcs\nimport os\n\n\n\nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.rcParams['font.family'] = 'STIXGeneral'\nplt.rcParams.update({'font.size': 14})\n\n#inputs\n\n#mypath = \"edotv_prtls/bguide.3_untriggered_hightimeres_latetime/tcs_cut/\"\nmypath = \"edotv_prtls/bguide.3_triggered_hightimeres_nothresh/tcs_cut/\"\n\n\n\n#open all .txt files in directory pointed to by filepath\nfilelist = os.listdir(mypath)\n#print(filelist)\n\n\n#for testing purposes\n#filelist = [\"edotv_prtls/bguide.3_untriggered_hightimeres_latetime/1.txt\"]\n\nwpar_list = []\nfinalgam_list = []\n\nfor filename in filelist:\n fullname = mypath + filename\n #testing\n #print(fullname)\n \n filesize = os.stat(fullname).st_size\n if filesize == 0:\n pass\n else:\n \n\n d = load_particle_edotv_withtcs(fullname)\n tcs = d['tcs']\n \n tlow=0 #change this if you want to narrow window that calculation is done in\n tup = -1\n\n #finalgam = d['gamma'][-1]\n #indexing will only work as long as we save prt info from the first timestep on, which we do, but just something to be careful about not to change\n t_arr = np.array(d['time'])[tlow:tup]\n u_arr = np.array(d['u'])[tlow:tup]\n v_arr = np.array(d['v'])[tlow:tup]\n w_arr = np.array(d['w'])[tlow:tup]\n bx_arr = np.array(d['bx'])[tlow:tup]\n by_arr = np.array(d['by'])[tlow:tup]\n bz_arr = np.array(d['bz'])[tlow:tup]\n ex_arr = -np.array(d['ex'])[tlow:tup]\n ey_arr = -np.array(d['ey'])[tlow:tup]\n ez_arr = -np.array(d['ez'])[tlow:tup]\n gamma_arr = np.array(d['gamma'])[tlow:tup]\n finalgam = d['finalgam']\n #print('tcs in output units is : ',tcs)\n\n\n bmag = np.sqrt(bx_arr**2 + by_arr**2 + bz_arr**2)\n\n unitbx = bx_arr / bmag\n unitby = by_arr / bmag\n unitbz = bz_arr / bmag\n \n #unit vector in b direction is (unitbx, unitby, unitbz) \n\n #dividing momenta by gamma to turn them into velocities\n u_arr /= gamma_arr\n v_arr /= gamma_arr\n w_arr /= gamma_arr\n\n\n edotv_tot = u_arr*ex_arr + v_arr*ey_arr + w_arr*ez_arr\n \n \n\n upar = u_arr*unitbx + v_arr*unitby + w_arr*unitbz \n epar = ex_arr*unitbx + ey_arr*unitby + ez_arr*unitbz \n epar_upar = upar*epar \n eperp_uperp = edotv_tot - epar_upar\n edotv_par_cumulative = [] \n edotv_perp_cumulative = [] \n edotv_tot_cumulative = [] \n for i in range(np.size(eperp_uperp)): \n tmp_par = trapz(epar_upar[0:i]) \n tmp_perp = trapz(eperp_uperp[0:i]) \n tmp_tot = trapz(edotv_tot[0:i]) \n edotv_par_cumulative.append(tmp_par) \n edotv_tot_cumulative.append(tmp_tot) \n edotv_perp_cumulative.append(tmp_perp)\n\n \n #testing\n #plt.plot(t_arr, edotv_par_cumulative,color=\"Blue\")\n #plt.plot(t_arr, edotv_perp_cumulative,color=\"Red\")\n #plt.plot(t_arr, edotv_tot_cumulative,color=\"Black\")\n #plt.savefig('testing_reading.png')\n \n \n wpar_frac = edotv_par_cumulative[-1]/edotv_tot_cumulative[-1]\n #print('wpar_frac : ', wpar_frac)\n #print('finalgam : ', finalgam)\n wpar_list.append(wpar_frac)\n finalgam_list.append(finalgam)\n\n\n\nmaxgam = max(finalgam_list)\nmingam = min(finalgam_list)\n\nbinnum = 40\nwpar_bins = np.linspace(-2,1,binnum)\ngambins = np.linspace(min(finalgam_list),max(finalgam_list)+1,binnum)\n\n\n \n#plt.scatter(wpar_list,finalgam_list)\n#plt.xlim(0,1.1)\n#plt.savefig('testing_scatter.png')\n\n#problem is that there are some artificially low values of wpar (down to -60 ish), so when we cut up the bins this skews the entire distribution\n\n\n\n\n#not putting bins in by hand\n#H,xedges,yedges=np.histogram2d(wpar_list,finalgam_list,bins=40)\n \n#H,xedges,yedges = np.histogram2d(wpar_list,finalgam_list,bins=[wpar_bins,gambins])\n#H,xedges,yedges = np.histogram2d(wpar_list,finalgam_list,bins=40,range=[[0,1],[mingam,maxgam]]) \n#plt.yscale('log')\n\n#print(H)\n#extent_list = [int(wpar_bins[0]),int(wpar_bins[-1]),int(gambins[0]),int(gambins[-1])]\n#extent_list = [xedges[0],xedges[-1],yedges[0],yedges[-1]]\n#print('bins : ', extent_list)\n\nplt.hist2d(wpar_list,finalgam_list,bins=40,range=[[0,1],[mingam,maxgam]],norm=LogNorm(),cmin=2,cmax=2001,alpha=1)\n\n#log scale on gamma\n#plt.hist2d(wpar_list, np.log10(finalgam_list),bins=40,range=[[0,1],[np.log10(mingam),np.log10(maxgam)]],norm=LogNorm())\n\nplt.colorbar(label='$N_{e}$')\n#plt.imshow(H,origin='lower',extent=extent_list,aspect=\"auto\")#,extent=extent_list,aspect=\"auto\")\n#plt.yscale('log')\nplt.xlim(0,1)\nplt.xlabel('$W_{||}/W_{tot}$')\nplt.ylabel('$\\gamma_{final}$')\n#plt.ylabel('$\\log{\\gamma_{final}}$')\n\nplt.savefig('wpar_trig_loghist.png')\n\nplt.close()\n","sub_path":"tcs_epar_hist.py","file_name":"tcs_epar_hist.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"601040733","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 5 19:31:21 2020\n\n@author: Christoffer\n\"\"\"\n\nimport os\nimport json\n\ndef remove(listobj):\n cnt = 0\n objectList = []\n for elements in listobj:\n if elements == \" {\\n\":\n objectList.append(cnt)\n if elements == \" },\\n\" or elements == \" }\\n\":\n objectList.append(cnt)\n cnt = cnt + 1\n return(objectList)\n\ndef replace(listobj):\n #listobj = [element.replace('=', ':') for element in listobj]\n listobj = [element.strip() for element in listobj]\n\n return(listobj)\n\ndef dictify(listobj):\n newDict = {}\n lastKey = ''\n concValue = ''\n closingBracket = True\n cnt = 0\n cnt2 = 0\n tmpArray = []\n tmpDict = {}\n separator = 0\n# for elements in listobj:\n# #print(elements)\n# if elements.find('=') > 0 and closingBracket == True:\n# #print(\"1\")\n# separator = elements.find('=')\n# key = elements[0:separator]\n# value = elements[separator+1:len(elements)]\n# newDict[key] = value\n# lastKey = key\n# concValue = ''\n# cnt = 0\n# elif elements.find('{') >= 0 and cnt2 > 0:\n# #print('2')\n# closingBracket = False\n# cnt = cnt + 1\n# concValue = concValue + elements + '\\n'\n# elif elements.find('}') >= 0:\n# #print('3')\n# cnt = cnt -1\n# if cnt == 0:\n# closingBracket = True\n# concValue = concValue + elements + '\\n'\n# #print(concValue)\n# #print(lastKey)\n# newDict[lastKey] = concValue\n# else:\n# #print(\"4\")\n# concValue = concValue + elements + '\\n'\n# #print(concValue)\n# cnt2 = cnt2 + 1\n \n\n for x in range(len(listobj)):\n if x > 0:\n #Checks if the value is another table\n if listobj[x] == '{':\n print('trigg')\n print(x)\n tmpArray = []\n tmpDict = {}\n closingBracket = False\n \n for y in range(x +1, len(listobj)):\n if listobj[y] == '}' or listobj[y] == '},':\n print('break: ' + str(y))\n print(listobj[y])\n break\n else:\n #print('append: ' + str(y))\n #print(listobj[y])\n tmpArray.append(listobj[y])\n print(tmpArray)\n #newDict[lastKey] = dictify(tmpArray)\n closingBracket = True\n continue\n #Checks if the line is a \"normal\" key/value pair, no nested tables\n elif listobj[x].find('=') > 0 and not (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0):\n separator = listobj[x].find('=')\n key = listobj[x][0:separator]\n value = listobj[x][separator+1:len(listobj[x])]\n newDict[key] = value\n lastKey = key\n concValue = ''\n cnt = 0\n #Checks if the line is a nested table\n elif listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0:\n #{ size = 64, filename = \"__base__/graphics/icons/mip/coal.png\", scale = 0.25, mipmap_count = 4 },\n #['{ size = 64', ' filename = \"__base__/graphics/icons/mip/coal-1.png\"', ' scale = 0.25', ' mipmap_count = 4 }', '']\n #print('test3')\n #newDict = {}\n tmpArray = []\n tmpArray = listobj[x].split(',')\n tmpArray = [element.replace('{', '') for element in listobj]\n tmpArray = [element.replace('}', '') for element in listobj]\n #newDict[lastKey] = dictify(tmpArray)\n \n #print(tmpArray)\n separator = listobj[x].find('=')\n key = listobj[x][0:separator]\n value = listobj[x][separator+1:len(listobj[x])]\n\n elif listobj[x].find('=') > 0 and not (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0):\n print('trigg???')\n separator = listobj[x].find('=')\n key = listobj[x][0:separator]\n value = listobj[x][separator+1:len(listobj[x])]\n newDict[key] = value\n lastKey = key\n concValue = ''\n cnt = 0\n elif (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0):\n print('test')\n return(newDict) \n\n\ndef removeExtend(listobj):\n if listobj[0] == 'data:extend(\\n':\n listLen = len(listobj)\n listobj.pop(listLen-1)\n listobj.pop(listLen-2)\n listobj.pop(0)\n listobj.pop(0)\n \n return(listobj)\n \ndef writeDictToLuaFile(listobj):\n file_name = r\"C:\\Users\\Christoffer\\Documents\\test2.lua\"\n file = open(file_name, 'w') \n \n file.write('data:extend(\\n')\n file.write('{\\n')\n \n listLen = len(listobj)\n \n for x in range(listLen):\n file.write(' {\\n')\n for key, value in listobj[x].items():\n #print(value)\n file.write(' ' + key + '=' + value + '\\n')\n if x >= (listLen-1):\n file.write(' }\\n')\n else:\n file.write(' },\\n')\n file.write('}\\n')\n file.write(')')\n\n \n\npath = r\"C:\\Users\\Christoffer\\Documents\"\npath = path + r\"\\demo-turret.lua\"\n\nfile = open(path, 'r')\nfileLines = file.readlines()\nfile.close()\n\nfileLen = len(fileLines)\n\nnewFile = removeExtend(fileLines)\nlistOfIndexes = remove(newFile)\nnewFile = replace(newFile)\nelements = len(listOfIndexes) / 2\n\nitemList = []\nfor i in range(int(elements)):\n itemList.append(dictify(newFile[listOfIndexes[(i*2)]:listOfIndexes[(i*2)+1]+1]))\n\n\nnewlist = newFile[listOfIndexes[0]:listOfIndexes[1]+1]\n#newDict = dictify(newlist)\n#writeDictToLuaFile(itemList)\n\n\n\n\n#file_name = r\"C:\\Users\\Christoffer\\Documents\\test2.lua\"\n#file = open(file_name, 'w') \n#\n#for line in fileLines:\n# file.write(line)\n#\n#\n#file.close()\n\n\n\n\n \n \n","sub_path":"t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"305528072","text":"import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.MIMEImage import MIMEImage\nfrom email.mime.text import MIMEText\n\nmsg = MIMEMultipart()\n\nsenha = \"gama2018\"\nmsg['From'] = \"projetodemonitoramento@gmail.com\"\nmsg['To'] = \"magalhaesrafael07@gmail.com\"\nmsg['Subject'] = \"Sistema de Monitoramento\"\n\nmsg.attach(MIMEImage(file('/home/pi/Monitoramento/imagem0.jpg'.read())))\n\nserver = smtplib.SMTP('smtp.gmail.com: 587')\nserver.starttls()\nserver.login(msg['From'], senha)\nserver.sendmail(msg['From'], msg['To'], msg.as_string())\nserver.quit()\n\nprint (\"Email enviado com sucesso para %s:\" %(msg['To']))\n","sub_path":"Monitoramento/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"295481913","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef load_tune(filename, tune_length):\n \"\"\"\n Load in information about notes and their\n onset times from a text file\n Parameters\n ----------\n filename: string\n Path to file with the tune\n tune_length: float\n Length, in seconds, of the tune\n \n Returns\n -------\n ps: ndarray(N)\n A list of N note numbers\n times: ndarray(N)\n Duration of each note, in increments\n of sixteenth notes\n \"\"\"\n tune = np.loadtxt(filename)\n ps = tune[:, 0]\n times = np.zeros(tune.shape[0])\n times[1::] = np.cumsum(tune[0:-1, 1])\n times = times*tune_length/np.sum(tune[:, 1])\n return ps, times\n\ndef karplus_strong_note(sr, note, duration, decay):\n \"\"\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n decay: float \n Decay amount (between 0 and 1)\n\n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n N = int(duration*sr)\n y = np.zeros(N)\n f = 440*2**(note/12) #stolen from assignment 1, the eq is 440*2**(note/12)\n T = int(sr/f)#this should calculate the period in samples per f seconds\n # we want to initialize the first T samples as random noise and populate 0 through T with random values\n y[0:T] = np.random.rand(T) #generates T random noise samples\n #next we populate the y array\n for i in range(T, N):\n y[i] = decay*((y[i-T]+y[i-T+1])/2)\n return y\n\ndef fm_synth_note(sr, note, duration, ratio = 2, I = 2, \n envelope = lambda N, sr: np.ones(N),\n amplitude = lambda N, sr: np.ones(N)):\n \"\"\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n ratio: float\n Ratio of modulation frequency to carrier frequency\n I: float\n Modulation index (ratio of peak frequency deviation to\n modulation frequency)\n envelope: function (N, sr) -> ndarray(N)\n A function for generating an ADSR profile\n amplitude: function (N, sr) -> ndarray(N)\n A function for generating a time-varying amplitude\n\n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n N = int(duration*sr)\n y = np.zeros(N)\n t = np.arange(N)/sr\n fc = 440*2**(note/12)\n fm = fc*ratio\n env= I*envelope(N, sr) #numpy array that is the full time variant\n amp = amplitude(N, sr)\n #y(t) = A(t)cos(2*pi*fc*t+I(t)sin(2*pi*fm*t))\n y = amp*np.cos(2*np.pi*fc*t + env*np.sin(2*np.pi*fm*t))\n return y\n\ndef exp_env(N, sr, lam = 3):\n \"\"\"\n Make an exponential envelope\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n lam: float\n Exponential decay rate: e^{-lam*t}\n\n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n return np.exp(-lam*np.arange(N)/sr)\n\ndef drum_like_env(N, sr):\n \"\"\"\n Make a drum-like envelope, according to Chowning's paper\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n\n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n t = np.arange(N)/sr\n y = np.zeros(N)\n y = ((t+.025)**2)*np.exp(-12*(t+.025)*3)\n return y\n\ndef wood_drum_env(N, sr):\n \"\"\"\n Make the wood-drum envelope from Chowning's paper\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n\n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n y = np.zeros(N)\n y[0:int(sr*0.025)] = np.linspace(1, 0, int(sr*0.025))\n return y\n\ndef dirty_bass_env(N, sr):\n \"\"\"\n Make the \"dirty bass\" envelope from Attack Magazine\n https://www.attackmagazine.com/technique/tutorials/dirty-fm-bass/\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n \n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n y = np.zeros(N)\n y[0:int(.25*sr)] = np.exp(-29*np.arange(int(N/2))/sr)\n y[int(.25*sr):int(.5*sr)] = 1-np.exp(-29*np.arange(int(N/2))/sr)\n return y\n\ndef fm_plucked_string_note(sr, note, duration, lam = 3):\n \"\"\"\n Make a plucked string of a particular length\n using FM synthesis\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n lam: float\n The decay rate of the note\n \n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n envelope = lambda N, sr: exp_env(N, sr, lam)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1, I = 8, envelope = envelope,\n amplitude = envelope)\n\n\ndef brass_env(N, sr):\n \"\"\"\n Make the brass ADSR envelope from Chowning's paper\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n \n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n #N = dur*sr\n #dur = N/sr\n attack = np.linspace(0, 1, int(sr*.1))\n decay = np.linspace(1, .7, int(sr*.1))\n release = np.linspace(.5, 0, int(sr*.1))\n sustain = np.array([])\n L = N - len(attack) - len(decay) - len(release)\n if L > 0:\n sustain = np.linspace(.7, .5, L)\n y = np.concatenate((attack, decay, sustain , release))\n # Duration check\n if len(y) > N:\n y = y[0:N]\n return y\n \"\"\"\n y = np.zeros(N)\n dur = N/sr\n if dur <= 0.3:\n atk = np.linspace(0, 1, int(sr*0.05))\n dec = np.linspace(1, 0.75, (int(sr*0.2)-int(sr*0.05)))\n sus = np.linspace(0.75, 0.75, (int(sr*0.95) - int(sr*0.05)))\n rel = np.linspace(0.75, 0, (int(sr*1) - int(sr*0.95)))\n y = np.concatenate((atk, dec, sus, rel))\n \n else:\n atk = np.linspace(0, 1, int(sr*0.1))\n dec = np.linspace(1, 0.75, int(sr*0.1))\n sus = np.linspace(0.75, 0.7, (int(sr*0.9)-int(sr*0.2)))\n rel = np.linspace(0.7, 0, int(sr*0.1))\n y = np.concatenate((atk, dec, sus, rel))\n return y\n \"\"\"\n\n\ndef fm_bell_note(sr, note, duration):\n \"\"\"\n Make a bell note of a particular length\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n \n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n envelope = lambda N, sr: exp_env(N, sr, 0.8)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1.4, I = 2, envelope = envelope,\n amplitude = envelope)\n\ndef fm_brass_note(sr, note, duration):\n \"\"\"\n Make a brass note of a particular length\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n \n Return\n ------\n ndarray(N): Audio samples for this note\n \"\"\"\n \n envelope = lambda N, sr: brass_env(N, sr)\n return fm_synth_note(int(sr), note, duration, \\\n ratio = 1, I = 10, envelope = envelope,\n amplitude = envelope)\n\ndef fm_drum_sound(sr, note, duration, fixed_note = -14):\n \"\"\"\n Make what Chowning calls a \"drum-like sound\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number (which is ignored)\n duration: float\n Seconds of audio\n fixed_note: int\n Note number of the fixed note for this drum\n \n Returns\n ------\n ndarray(N): Audio samples for this drum hit\n \"\"\"\n envelope = lambda N, sr: drum_like_env(N, sr)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1.4, I = 2, envelope = envelope,\n amplitude = envelope)\n\ndef fm_wood_drum_sound(sr, note, duration, fixed_note = -14):\n \"\"\"\n Make what Chowning calls a \"wood drum sound\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number (which is ignored)\n duration: float\n Seconds of audio\n fixed_note: int\n Note number of the fixed note for this drum\n \n Returns\n -------\n ndarray(N): Audio samples for this drum hit\n \"\"\"\n envelope = lambda N, sr: wood_drum_env(N, sr)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1.4, I = 10, envelope = envelope,\n amplitude = envelope)\n\ndef fm_dirty_bass_note(sr, note, duration):\n \"\"\"\n Make a \"dirty bass\" note, based on \n https://www.attackmagazine.com/technique/tutorials/dirty-fm-bass/\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number (which is ignored)\n duration: float\n Seconds of audio\n \n Returns\n -------\n ndarray(N): Audio samples for this drum hit\n \"\"\"\n \n envelope = lambda N, sr: dirty_bass_env(N, sr)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1, I = 18, envelope = envelope,\n amplitude = envelope) \n\ndef make_tune(filename, sixteenth_len, sr, note_fn):\n \"\"\"\n Parameters\n ----------\n filename: string\n Path to file containing the tune. Consists of\n rows of , where\n the note number 0 is a 440hz concert A, and the\n note duration is in factors of 16th notes\n sixteenth_len: float\n Length of a sixteenth note, in seconds\n sr: int\n Sample rate\n note_fn: function (sr, note, duration) -> ndarray(M)\n A function that generates audio samples for a particular\n note at a given sample rate and duration\n \n \n Returns\n -------\n -------\n ndarray(N): Audio containing the tune\n \"\"\"\n tune = np.loadtxt(filename)\n notes = tune[:, 0]\n durations = tune[:, 1]\n durations_sec = durations*sixteenth_len\n ret = []\n n = len(notes) #number of notes\n for i in range(n):\n x = note_fn(sr, notes[i], durations_sec[i])\n if np.isnan(notes[i]): #if the note is not a number, append 0 into y such that it has no value i.e is silent\n x = np.zeros(int(durations_sec[i]*sr))\n ret = np.concatenate((ret, x))\n else:\n ret = np.concatenate((ret, x))\n return ret ","sub_path":"HW3_Vocoders-main/HW3_Vocoders-main/instruments.py","file_name":"instruments.py","file_ext":"py","file_size_in_byte":10331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"547783881","text":"#导入模块\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#标签样本大小\nsample_size = 50\n#中心位置\nsample_location = 2\n\n#训练次数\ntraining_num=100\n#学习率\nlearning_rate=0.001\n\n#权值\nw=np.array([-1,1])\n#偏置\nb=0\n\n#生成数据样本\nnp.random.seed(0)\nx=np.r_[np.random.randn(sample_size,2)-[sample_location,sample_location],np.random.randn(sample_size,2)+[sample_location,sample_location]]\n\n#生成标签\ny=[-1]*sample_size+[1]*sample_size\n\n#画样本散点图\nfor i in range(len(x)):\n if y[i]==1:\n plt.plot(x[i][0],x[i][1],'rx')\n else:\n plt.plot(x[i][0],x[i][1],'bo')\nplt.title('sample distribution')\nlim_x=plt.xlim(-5,5)\nlim_y=plt.ylim(-4.5,4.5)\n\nx_lab=plt.xlabel('x',size=15)\ny_lab=plt.ylabel('y',size=15)\n\n\nfor i in range(len(x)):\n if y[i]==1:\n plt.plot(x[i][0],x[i][1],'rx')\n else:\n plt.plot(x[i][0],x[i][1],'bo')\n#开始训练\nfor step in range(training_num+1):\n grad_x=np.array([0,0])\n grad_b=0\n \n #每训练10次更新一次分界线\n if step%10==0:\n ref_x=[-10,10]\n ref_y=[0,0]\n for i in range(len(ref_x)):\n ref_y[i]=-(w[0]*ref_x[i]+b)/w[1]\n pp=plt.plot(ref_x,ref_y)\n\n #遍历训练样本集寻找错分样本、\n for j in range(len(x)):\n if np.sign(np.dot(w,x[j])+b)<0 and y[j]!=np.sign(np.dot(w,x[j])+b):\n grad_x=grad_x-x[j]\n grad_b=grad_b+y[j]\n \n #利用梯度下降法更新参数\n w=w+learning_rate*grad_x\n b=b+learning_rate*grad_b\n \nplt.title('training')\n\nlim_x=plt.xlim(-5,5)\nlim_y=plt.ylim(-4.5,4.5)\n\nx_lab=plt.xlabel('x',size=15)\ny_lab=plt.ylabel('y',size=15)","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"618792357","text":"import json\nimport sys\nimport re\nimport urllib\n\nfrom bs4 import BeautifulSoup\nimport string\n\ndef add(a, b):\n return a + b\n\ndef mycomp(a, b):\n x = str(a[7].text)\n y = str(b[7].text)\n #print x;\n #print y;\n s1 = string.replace(x, \",\", \"\")\n s2 = string.replace(y, \",\", \"\")\n return int(s2) - int(s1)\n\n\ndef contractAsJson(filename):\n jsonQuoteData = \"[]\"\n #return jsonQuoteData\n fh = open(filename)\n soup = BeautifulSoup(fh)\n\n #price = soup.find_all(\"yfs_l84\")\n cur_price = soup.find(class_=\"time_rtq_ticker\")\n currPrice = float(cur_price.find(id=re.compile(\"yfs\")).text)\n\n #urls = soup.find_all(\"a\", {\"href\": re.compile(\"/q/op?\")});\n #urls = soup.find_all(\"a\");\n urls = soup.find_all(\"a\", href = re.compile(\"\\/q\\/o[s,p]\\?s=[A-Za-z]+&m\"));\n dateUrls = []\n\n #print urls\n for link in urls:\n\t #print link.get(\"href\")\n\t link[\"href\"] = \"http://finance.yahoo.com\" + link[\"href\"]\n\t new_link = string.replace(link[\"href\"], '&', '&')\n\t #print new_link\n\t dateUrls.append(new_link)\n#print dateUrls\n\n################find options################################\n tables = soup.find_all(class_=\"yfnc_datamodoutline1\")\n\n table1 = tables[0].find_all(\"tr\")\n table2 = tables[1].find_all(\"tr\")\n mytable = []\n\n for row_index in range(2, len(table1)):\n row = table1[row_index]\n info_list = row.find_all(\"td\")\n #for i in range(0, len(info_list)):\n #print info_list[i].text\n mytable.append(info_list)\n\n for row_index in range(2, len(table2)):\n row = table2[row_index]\n info_list = row.find_all(\"td\")\n #for i in range(0, len(info_list)):\n #print info_list[i].text\n mytable.append(info_list)\n\n #print mytable\n mytable.sort(mycomp)\n option_list = []\n #print \"table row lenth\", len(mytable)\n for row_index in range(0, len(mytable)):\n option = dict()\n option[\"Strike\"] = str(mytable[row_index][0].text)\n symbol = str(mytable[row_index][1].text)\n start = symbol.find(\"1\")\n option[\"Symbol\"] = symbol[:start]\n rest = symbol[start:]\n option[\"Date\"] = re.split('[A-Z]', rest)[0]\n option[\"Type\"] = rest[len(option[\"Date\"])]\n option[\"Last\"] = str(mytable[row_index][2].text)\n option[\"Change\"] = str(mytable[row_index][3].text)\n# if(mytable[row_index][4].text != None):\n# option[\"Bid\"] = str(mytable[row_index][4].text)\n# else:\n# option[\"Bid\"] = \"N/A\" \n option[\"Bid\"] = str(mytable[row_index][4].text)\n option[\"Ask\"] = str(mytable[row_index][5].text)\n option[\"Vol\"] = str(mytable[row_index][6].text)\n option[\"Open\"] = str(mytable[row_index][7].text)\n option_list.append(option)\n\n #print option_list\n \n summary = dict()\n summary[\"currPrice\"] = currPrice\n summary[\"dateUrls\"] = dateUrls\n summary[\"optionQuotes\"] = option_list\n #jsonQuoteData = json.dumps(sorted(summary.iterkeys()))\n #jsonQuoteData = json.dumps(summary)\n jsonQuoteData = json.dumps(summary, sort_keys = True, indent = 4, separators=(',', ': '))\n\n return jsonQuoteData\n\n\n\n\n","sub_path":"project/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"206070898","text":"from firebase import firebase\nimport tensorflow.compat.v1 as tf\nimport pandas as pd\nimport numpy as np\nimport csv\n\ntf.disable_v2_behavior()\n\n\nfirebase = firebase.FirebaseApplication(\"https://mhacks-13-project.firebaseio.com/\")\n\nresult = firebase.get('/users', None)\n\n\n# Set up, populate matrix.\n# Rows = users (learners).\n# Columns = users (teachers).\n\nnum_users = len(result)\nuid_list = []\n\nfor uid, _ in result.items():\n\tuid_list.append(uid)\n\nwith open('uid.csv', 'w') as uid_file:\n\twr = csv.writer(uid_file, quoting=csv.QUOTE_ALL)\n\twr.writerow(uid_list)\n\nvalue_matrix = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.6, 0.8, 1.0], \\\n\t\t\t\t[0.0, 0.0, 0.6, 0.8], [0.0, 0.0, 0.0, 0.6]]\n\nl_t_matrix = pd.DataFrame(0.0, index=np.arange(num_users), columns=np.arange(num_users))\nmax_val = 0.0\n# non_zero = 0\n\nfor i in range(len(uid_list)):\n\tfor j in range(len(uid_list)):\n\t\tlearner_info = result[uid_list[i]]\n\t\tteacher_info = result[uid_list[j]]\n\n\t\tif \"Interests\" in learner_info and \"Skills\" in teacher_info:\n\t\t\tval_lt = 0.0\n\t\t\tfor interest in learner_info[\"Interests\"]:\n\t\t\t\tif interest in teacher_info[\"Skills\"]:\n\t\t\t\t\tval_lt += value_matrix[learner_info[\"Interests\"][interest]]\\\n\t\t\t\t\t\t\t\t\t\t [teacher_info[\"Skills\"][interest]]\n\t\t\tl_t_matrix.at[i, j] = val_lt\n\n\t\t\tif val_lt > max_val:\n\t\t\t\tmax_val = val_lt\n\t\t\t# if val_lt > 0.0:\n\t\t\t# \tnon_zero += 1\n\nif max_val != 0.0:\n\tl_t_matrix = l_t_matrix / max_val # normalize\n\n#print(l_t_matrix)\n#print(max_val)\n#print(non_zero)\n\n\n# Build model.\n\nnum_input = num_users\nnum_hidden_1 = 10\nnum_hidden_2 = 5\n\nX = tf.placeholder(tf.float64, [None, num_input])\n\nweights = {\n 'encoder_h1': tf.Variable(tf.random_normal([num_input, num_hidden_1], dtype=tf.float64)),\n 'encoder_h2': tf.Variable(tf.random_normal([num_hidden_1, num_hidden_2], dtype=tf.float64)),\n 'decoder_h1': tf.Variable(tf.random_normal([num_hidden_2, num_hidden_1], dtype=tf.float64)),\n 'decoder_h2': tf.Variable(tf.random_normal([num_hidden_1, num_input], dtype=tf.float64)),\n}\n\nbiases = {\n 'encoder_b1': tf.Variable(tf.random_normal([num_hidden_1], dtype=tf.float64)),\n 'encoder_b2': tf.Variable(tf.random_normal([num_hidden_2], dtype=tf.float64)),\n 'decoder_b1': tf.Variable(tf.random_normal([num_hidden_1], dtype=tf.float64)),\n 'decoder_b2': tf.Variable(tf.random_normal([num_input], dtype=tf.float64)),\n}\n\n\ndef encoder(x):\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1']))\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2']))\n return layer_2\n\ndef decoder(x):\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']), biases['decoder_b1']))\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']), biases['decoder_b2']))\n return layer_2\n\nencoder_op = encoder(X)\ndecoder_op = decoder(encoder_op)\n\ny_pred = decoder_op\ny_true = X\n\nloss = tf.losses.mean_squared_error(y_true, y_pred)\noptimizer = tf.train.RMSPropOptimizer(0.03).minimize(loss)\neval_x = tf.placeholder(tf.int32, )\neval_y = tf.placeholder(tf.int32, )\npre, pre_op = tf.metrics.precision(labels=eval_x, predictions=eval_y)\n\ninit = tf.global_variables_initializer()\nlocal_init = tf.local_variables_initializer()\npred_data = pd.DataFrame()\n\n\n# Train model.\n\nwith tf.Session() as session:\n\tepochs = 100\n\tbatch_size = 25\n\n\tsession.run(init)\n\tsession.run(local_init)\n\n\tnum_batches = int(l_t_matrix.shape[0] / batch_size)\n\tl_t_matrix = np.array_split(l_t_matrix, num_batches)\n\n\tfor i in range(epochs):\n\t\tavg_cost = 0\n\t\tfor batch in l_t_matrix:\n\t\t\t_, l = session.run([optimizer, loss], feed_dict={X: batch})\n\t\t\tavg_cost += l\n\t\tavg_cost /= num_batches\n\n\t\tprint(\"epoch: {} Loss: {}\".format(i + 1, avg_cost))\n\n\tl_t_matrix = np.concatenate(l_t_matrix, axis=0)\n\n\tpreds = session.run(decoder_op, feed_dict={X: l_t_matrix})\n\n\tpreds = pd.DataFrame(preds)\n\tpreds.to_csv('lt_matrix.csv', index=False, header=False)\n\n\tsimple_save(session, 'model', inputs={\"a\":a}, outputs={\"b\":b})","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"544213866","text":"import scrapy\nimport os\nimport re\nfrom tutorial.items import IqiyiItem\n\n# eg: scrapy crawl iqiyi_film -a url=http://www.iqiyi.com/v_19rrm3ae54.html\nclass IqiyiFilmSpider(scrapy.Spider):\n\n name = \"iqiyi_film\"\n # allowed_domains = [\"iqiyi.com\"]\n file_path = ''\n category = None\n # eg: http://www.iqiyi.com/v_19rrm3ae54.html\n def __init__(self, url=None, *args, **kwargs):\n super(IqiyiFilmSpider, self).__init__(*args, **kwargs)\n self.start_urls = [url]\n\n def parse(self, response):\n item = IqiyiItem()\n # item['url'] = response.url\n # item['tvid'] = response.xpath(\"//div/@data-player-tvid\").extract()[-1]\n # item['vid'] = response.xpath(\"//div/@data-player-videoid\").extract()[-1]\n item['tv_name'] = response.xpath(\"//div/@data-qitancomment-title\").extract()[-1]\n item['album_id'] = response.xpath(\"//div/@data-player-albumid\").extract()[-1]\n\n film = item['tv_name']\n if self.category:\n self.file_path = os.path.join(os.getcwd(), 'data', self.category, film)\n else:\n self.file_path = os.path.join(os.getcwd(), 'data', film)\n\n if not os.path.exists(self.file_path):\n os.makedirs(self.file_path)\n \n file_name = os.path.join(self.file_path, 'source.html')\n with open(file_name, 'wb') as f:\n f.write(response.body)\n\n # get detail json\n # url = 'http://cache.video.qiyi.com/jp/vi/' + item['tvid'] + '/' + item['vid'] + '/'\n url = \"http://mixer.video.iqiyi.com/jp/mixin/videos/\" + item['album_id']\n item['url'] = url\n yield scrapy.Request(url, self.parse_detail)\n\n def parse_detail(self, response):\n file_name = os.path.join(self.file_path, 'data.json')\n with open(file_name, 'wb') as f:\n f.write(re.sub('^[^{]*|[^}]*$','',response.body))","sub_path":"tutorial/tutorial/spiders/iqiyi_film.py","file_name":"iqiyi_film.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"261244376","text":"\"\"\"\nConditions and Loops\n\nProblem\nGiven: Two positive integers a and b (a Environment:\n \"\"\"\n Parses environment variables and sets their defaults if they do not exist.\n \"\"\"\n return Environment(\n media_url=get_endpoint(\"MEDIA\"),\n datastore_reader_url=get_endpoint(\"DATASTORE_READER\"),\n datastore_writer_url=get_endpoint(\"DATASTORE_WRITER\"),\n vote_url=get_endpoint(\"VOTE\"),\n )\n\n\ndef get_endpoint(service: str) -> str:\n parts = {}\n for suffix in (\"PROTOCOL\", \"HOST\", \"PORT\", \"PATH\"):\n variable = \"_\".join((service, suffix))\n value = os.environ.get(variable)\n if value is None:\n default = DEFAULTS.get(variable)\n if default is None:\n raise ValueError(f\"Environment variable {variable} does not exist.\")\n parts[suffix] = default\n else:\n parts[suffix] = value\n return f\"{parts['PROTOCOL']}://{parts['HOST']}:{parts['PORT']}{parts['PATH']}\"\n","sub_path":"openslides_backend/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"107258625","text":"# Part of Release Buddy: checksum Commands\n\nimport hashlib\nfrom buddylib import *\n\n#\n# Copyright (c) 2013 Torgny Nyblom \n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n\ndef buddy_checksum(options, project, version):\n ChangeDir(options, options.Tarballs)\n archives = getArchive(options, project, version)\n for archive in archives:\n with open(os.path.join(options.Tarballs, archive + \".sha256\"), 'w') as f:\n digest = createChecksum(options, archive)\n f.write( digest )\n f.write( \"\\n\" )\n\ndef buddy_checksums(options, projects, version):\n ChangeDir(options, options.Tarballs)\n with open(os.path.join(options.Tarballs, \"sha256sums.txt\"), 'w') as f:\n for project in projects:\n archives = getArchive(options, project, version)\n for archive in archives:\n digest = createChecksum(options, archive)\n f.write( digest )\n f.write( \"\\n\" )\n\n\ndef createChecksum(options, archive):\n info(\"Creating checksum for %s\"%archive)\n crypt = hashlib.sha256()\n\n debug(\"Calculating...\")\n with open( os.path.join(options.Tarballs, archive) ) as f:\n while True:\n block = f.read(256)\n if block == '':\n break\n crypt.update(block)\n digest = crypt.hexdigest()\n info(\"checksum: %s\"%digest)\n return \"%s %s\"%(digest, archive)\n","sub_path":"buddychecksum.py","file_name":"buddychecksum.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"298711110","text":"import argparse\r\nimport os\r\nimport sys\r\nimport logging\r\nimport gzip\r\nimport shutil\r\nfrom functions_reconstructing_macrocomplex import *\r\nfrom Bio.PDB import *\r\n\r\nparser = argparse.ArgumentParser(description = \"\"\"This program models macrocomplex structures of biomolecules formed by proteins. The macrocomplex is build from pairwaise interactions.\"\"\")\r\n\r\nparser.add_argument('-i','--input-directory',\r\n required=True,\r\n dest=\"input_path\",\r\n action=\"store\",\r\n help=\"Directory containig the input structure files.\")\r\n\r\nparser.add_argument('-s', '--stoichiometry',\r\n default=None,\r\n dest=\"stoichiometry\",\r\n action=\"store\",\r\n help=\"Path containing the stoichiometry of the complex.\")\r\n\r\nparser.add_argument('-o','--output-directory',\r\n dest=\"output_path\",\r\n action=\"store\",\r\n type=str,\r\n default=\"output\",\r\n help=\"Directory where the output will be saved.\")\r\n\r\nparser.add_argument('-f','--force',\r\n default=False,\r\n dest=\"force\",\r\n action=\"store\",\r\n help=\"Checks the output-directory doesn't exist before the application is executed.\")\r\n\r\nparser.add_argument('-v','--verbose',\r\n default=False,\r\n dest=\"verbose\",\r\n action=\"store_true\",\r\n help=\"Returns the progression log of the program execution printed in standard error.\")\r\n\r\nparser.add_argument('-ofn', '--output_filename',\r\n dest = \"output_filename\",\r\n action = \"store\",\r\n default = \"final_macrocomplex\",\r\n help = \"Optional. Defines the name of the output file where the final model should be stored.\")\r\n\r\narguments = parser.parse_args()\r\n\r\n\r\nif __name__==\"__main__\":\r\n\r\n absolute_path = os.getcwd()\r\n\r\n try:\r\n os.mkdir(arguments.output_path)\r\n subdirs = ['structures', 'analysis']\r\n for folder in subdirs:\r\n os.mkdir(os.path.join(arguments.output_path, folder))\r\n except FileExistsError:\r\n if arguments.force == False:\r\n print (f\"The {arguments.output_path} already exists.\\n\")\r\n sys.exit(-1)\r\n elif arguments.force == True:\r\n shutil.rmtree(arguments.output_path)\r\n os.mkdir(arguments.output_path)\r\n subdirs = ['structures', 'analysis']\r\n for folder in subdirs:\r\n folder = \"/\" + folder\r\n os.mkdir(os.path.join(arguments.output_path, folder))\r\n\r\n # Create the logging file\r\n logging_storage = arguments.output_path + \"/analysis/macrocomplex_builder.log\"\r\n logging.basicConfig(filename = logging_storage, format = '%(levelname)s:%(message)s', level = logging.DEBUG, filemode = \"w\")\t#move to output folder\r\n logging.debug('...STARTING...')\r\n\r\n if arguments.verbose:\r\n logging.getLogger().addHandler(logging.StreamHandler())\r\n\r\n # Get the list of pdb files in input directory provided\r\n try:\r\n list_files = only_pdb_files(arguments.input_path)\r\n except NotADirectoryError:\r\n logging.info(\"Input path provided could not be found as a directory. Aborting program. Please try again.\")\r\n sys.exit(-1)\r\n\r\n # Get the structures of the PDB files\r\n pdb_structure, molecule_type = read_pdb_files(list_files)\r\n\r\n os.chdir(absolute_path) # get back to main working directory\r\n\r\n # Get the stoichiometry from the file if provided by the user\r\n if arguments.stoichiometry:\r\n logging.info(\"\\nStoichiometry file %s was found. This will be used to build the complex.\\n\" %(arguments.stoichiometry))\r\n try:\r\n stoichiometry_file = {}\r\n with open(arguments.stoichiometry, \"r\") as file:\r\n for line in file:\r\n stoich_info = line.strip().split(\":\")\r\n stoichiometry_file[stoich_info[0]] = int(stoich_info[1])\r\n print(stoichiometry_file)\r\n except FileNotFoundError:\r\n logging.info(\"\\nWe could not find the stoichiometry file provided. Aborting program. Please try again.\")\r\n exit()\r\n else:\r\n logging.info(\"\\nStoichiometry was not provided. The program will use 1 for each chain as default value.\\n\")\r\n stoichiometry_file = {}\r\n for file in pdb_structure:\r\n stoichiometry_file[file] = 1\r\n\r\n # Analyse protein-protein interactions to build complex\r\n if molecule_type == \"PROT\":\r\n logging.info(\"The files provided contain Protein-Protein Interactions.\\n\")\r\n\r\n # get the first file as reference and put it to the end of the list\r\n id_list = list(pdb_structure.keys())\r\n print(id_list)\r\n reference_id = id_list.pop(0)\r\n id_list.append(reference_id)\r\n current_stoichiometry = {reference_id:1}\r\n\r\n # Superimpose C-alphas of those of chains with alignment higher than 0.95\r\n reference_structure = pdb_structure[reference_id] # get the structure of the reference\r\n num_chains = 2 # initial number of chains of the complex\r\n\r\n while (num_chains <= sum(list(stoichiometry_file.values()))): # while the complex has less or same chains as the stoichiometry provided\r\n sample_id = id_list.pop(0) # get interaction to compare with reference and superimpose\r\n if sample_id not in stoichiometry_file:\r\n sample_id = \"\"\r\n continue\r\n if not sample_id in current_stoichiometry: # initialise the count for the structure that is currently being analysed\r\n current_stoichiometry[sample_id] = 0\r\n\r\n sample_structure = pdb_structure[sample_id]\r\n\r\n try:\r\n superimposition, RMSD = superimpose_chains(reference_structure, sample_structure) # superimpose. We get the superimposition with their best RMSD\r\n except:\r\n current_stoichiometry[sample_id] += 1\r\n num_chains += 1\r\n\r\n # If no superimposition\r\n if bool(superimposition) == False:\r\n id_list.append(sample_id) # if the sample could not be superimposed, add it to the end of the list to analysed it again later\r\n continue\r\n\r\n # If there are superimpositions made\r\n for tuple_chains, super_object in superimposition:\r\n logging.info(\"Chain %s of the reference structure and chain %s of the sample structure have been superimposed with a RMSD of %.3f.\\n\" %(tuple_chains[0], tuple_chains[1], RMSD))\r\n chain_to_add = [chain for chain in sample_structure.get_chains() if chain.id != tuple_chains[1]][0]\r\n super_object.apply(chain_to_add.get_atoms()) # apply rotation matrix to moving structure\r\n reference_structure = look_for_clashes (reference_structure, chain_to_add)\r\n\r\n num_chains += 1\r\n\r\n # If the structure is not the same as the stoichoimetry provided, add it to the end of the list to analyse and try to superimpose again later\r\n if current_stoichiometry[sample_id] != stoichiometry_file[sample_id]:\r\n id_list.append(sample_id)\r\n\r\n\r\n store_output (reference_structure[0], arguments.output_path, arguments.output_filename)\r\n logging.info(\"The macrocomplex built has %d chains.\" %(reference_structure[0].__len__()))\r\n","sub_path":"build/scripts-3.8/main_reconstructing_macrocomplex.py","file_name":"main_reconstructing_macrocomplex.py","file_ext":"py","file_size_in_byte":7588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"570450653","text":"# Programmers _ Lv.2 오픈채팅방 2019 KAKAO BLIND RECRUITMENT\n\n\ndef solution(record, id=[], answer=[]):\n for r in record:\n id.append(r.split()[1]) \n dic_id = {x : '' for x in id} # 바뀌는 닉네임을 계속 업데이트하며 아이디와 최종 닉네임을 딕셔너리에 저장\n\n for r in record:\n if len(r.split()) > 2: # Leave일 때 닉네임은 바뀌지 않으므로 제외\n dic_id.update({r.split()[1]:r.split()[2]})\n\n for r in record:\n if r.split()[0] == 'Enter': # Change일 때는 채팅방에 아무런 변화가 없으므로 출력하지 않음\n answer.append(f'{dic_id[r.split()[1]]}님이 들어왔습니다.')\n elif r.split()[0] == 'Leave':\n answer.append(f'{dic_id[r.split()[1]]}님이 나갔습니다.')\n\n return answer","sub_path":"오픈채팅방.py","file_name":"오픈채팅방.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"176701025","text":"import os\nimport utilities as util\nimport globalvar\n\n\"\"\"\nCPU related configurations\n\"\"\"\n\nclass CPU_conf:\n def __init__(self):\n self.str_CPU_code_name = self.__get_CPU_code_name()\n self.str_instruction_supported = self.get_CPU_instructions_supported()\n self.cpu_total_num = self.__get_cpu_total_num()\n self.b_hyperthread_enabled = self.__hyperthread_is_enabled()\n self.b_pstate_disabled = self.__intel_pstate_is_disabled()\n self.b_turbo_disabled = self.__turbo_is_disabled()\n self.b_c6state_disabled = self.__c6state_disabled()\n self.b_c3state_disabled = self.__c3state_disabled()\n self.b_direct_cache_access_enabled = self.__dca_is_enabled()\n self.scaling_governor = self.__get_scaling_governor()\n self.cpu_core_total_num = self.__get_core_total_num()\n self.cores = []\n self.init_all_cpus_conf()\n\n \"\"\"\n CPU related utility functions\n \"\"\"\n\n def __print_lscpu_cmd(self):\n return util.str_cmd_output('lscpu')\n\n def __print_lscpu_e_cmd(self):\n return util.str_cmd_output('lscpu -e')\n\n def __get_lscpu_specific_conf(self, spec):\n return util.str_get_specific_value_after_colon('lscpu', spec)\n\n def get_lscpu_e_specific_conf(self, cpu_id, column):\n output = self.__print_lscpu_e_cmd();\n l = output.split('\\n')\n l_title = l[0].split()\n ll = l[cpu_id + 1].split()\n column_idx = l_title.index(column)\n return ll[column_idx]\n\n def __get_cpu_total_num(self):\n output = self.__print_lscpu_cmd()\n num = self.__get_lscpu_specific_conf('CPU(s)')\n return int(num)\n\n def get_cpu_numa_node_by_cpu_id(self, cpu_id):\n return int(self.get_lscpu_e_specific_conf(cpu_id, 'NODE'))\n\n def get_cpu_core_by_cpu_id(self, cpu_id):\n return int(self.get_lscpu_e_specific_conf(cpu_id, 'CORE'))\n\n def init_all_cpus_conf(self):\n for i in range(self.cpu_total_num ):\n core = self.get_cpu_core_by_cpu_id(i)\n node = self.get_cpu_numa_node_by_cpu_id(i)\n single_cpu = Single_CPU_core_conf(cpu_id = i,\n core_num = core,\n numa_node = node)\n self.cores.append(single_cpu)\n\n def __get_CPU_code_name(self):\n output = self.__print_lscpu_cmd()\n name = self.__get_lscpu_specific_conf('Model name')\n return name\n\n def __hyperthread_is_enabled(self):\n output = self.__print_lscpu_cmd()\n tpc = self.__get_lscpu_specific_conf('Thread(s) per core')\n if int(tpc) == 1:\n return False\n else:\n return True\n\n def __turbo_is_disabled(self):\n output = util.get_cat_command_output('/sys/devices/system/cpu/intel_pstate/no_turbo')\n if output == None:\n return False\n if output == '0':\n return False\n else:\n return True\n\n def __dca_is_enabled(self):\n output = util.str_cmd_output('dmesg | grep dca')\n if output.find('disabled') == -1:\n return True\n else:\n return False\n\n def __get_core_total_num(self):\n if self.b_hyperthread_enabled == True:\n return (self.cpu_total_num / 2)\n else:\n return self.cpu_total_num\n\n def get_CPU_instructions_supported(self):\n pass\n\n def __intel_pstate_is_disabled(self):\n output = util.get_cat_command_output('/boot/config-$(uname -r) | grep -i pstate')\n if output is None:\n return True\n else:\n return False\n\n def __c6state_disabled(self):\n output = util.int_cmd_output('cat /sys/module/intel_idle/parameters/max_cstate')\n if output >= 6:\n return False\n else:\n return True\n\n def __c3state_disabled(self):\n output = util.int_cmd_output('cat /sys/module/intel_idle/parameters/max_cstate')\n if output >= 3:\n return False\n else:\n return True\n\n def __get_scaling_governor(self):\n ret = []\n output = util.get_cat_command_output('/sys/devices/system/cpu/cpu*/cpufreq/scaling_governor')\n if output == None:\n return None\n l = output.split('\\n')\n ret.append(l[0])\n for ll in l:\n if ll not in ret:\n ret.append(ll)\n return ret\n\n def get_single_CPU_conf_by_id(self, id):\n return self.cores[id]\n\nclass Single_CPU_core_conf:\n def __init__(self, cpu_id, core_num, numa_node):\n self.cpu_id = cpu_id\n self.core_num = core_num\n self.numa_node = numa_node\n\n\"\"\"\nMemory related configurations\n\"\"\"\n\nclass Memory_conf:\n def __init__(self):\n self.memroy_total_size = self.__get_memory_total_size()\n self.memory_DIMM_num = self.__get_memory_DIMM_num()\n if self.memory_DIMM_num == 0:\n #Not running in a normal physical host env\n globalvar.NORMAL_PHY_HOST_MEM = False\n return\n self.memory_channels_num = self.__get_memory_channels_num()\n self.memory_DIMM_per_channel = self.memory_DIMM_num / self.memory_channels_num\n self.dmidecode_output = self.__get_dmidecode_output()\n self.dimms = []\n self.__init_memory_DIMMs()\n\n \"\"\"\n Memory related utility functions\n \"\"\"\n def __get_memory_total_size(self):\n cmd = 'cat /proc/meminfo'\n total = util.str_get_specific_value_after_colon(cmd, 'MemTotal')\n return total\n\n def __get_memory_DIMM_num(self):\n cmd = 'dmidecode -t memory | grep Locator | grep DIMM |wc -l'\n return util.int_cmd_output(cmd)\n\n def __get_memory_channels_num(self):\n cmd = 'dmidecode -t memory | grep Locator | grep DIMM | grep 1 |wc -l'\n return util.int_cmd_output(cmd)\n\n def __get_dmidecode_output(self):\n cmd = 'dmidecode -t memory'\n output = util.str_cmd_output(cmd)\n l = output.split('\\n')\n return l\n\n def __init_memory_DIMMs(self):\n for i in range(self.memory_DIMM_num):\n locator = self.__get_mem_dimm_locator(i)\n size = self.__get_mem_dimm_size(i)\n speed = self.__get_mem_dimm_speed(i)\n conf_speed = self.__get_mem_conf_speed(i)\n node = self.__get_mem_bank_locator(i)\n dimm = Memory_DIMM(locator = locator, size = size,\n speed = speed, conf_speed = conf_speed,\n node = node)\n self.dimms.append(dimm)\n\n def __get_mem_dimm_spec_conf(self, conf, index):\n cnt = 0\n for l in self.dmidecode_output:\n if l.find(conf) != -1:\n if cnt == index:\n return l.split(\":\")[1].strip()\n cnt = cnt + 1\n return None\n\n def __get_mem_dimm_locator(self, index):\n return self.__get_mem_dimm_spec_conf(\"Locator: DIMM\", index)\n\n def __get_mem_dimm_size(self, index):\n return self.__get_mem_dimm_spec_conf(\"Size\", index)\n\n def __get_mem_dimm_speed(self, index):\n cnt = 0\n for l in self.dmidecode_output:\n if l.find(\"Speed\") != -1 and l.find(\"Configured\") == -1:\n if cnt == index:\n speed = l.split(\":\")[1].strip()\n if speed != \"Unknown\":\n return int(speed.split(\" \")[0].strip())\n else:\n return speed\n cnt = cnt + 1\n return None\n\n def __get_mem_conf_speed(self, index):\n speed = self.__get_mem_dimm_spec_conf(\"Configured Clock Speed\", index)\n if speed == None:\n return \"Unknown\"\n if speed != \"Unknown\":\n return int(speed.split(\" \")[0].strip())\n else:\n return speed\n\n def __get_mem_bank_locator(self, index):\n return self.__get_mem_dimm_spec_conf(\"Bank Locator\", index)\n\nclass Memory_DIMM:\n def __init__(self, locator, size, speed, conf_speed, node):\n self.locator = locator\n self.memory_size = size\n self.memory_speed = speed\n self.memory_config_speed = conf_speed\n self.bank_node = node\n\n\n\"\"\"\nNIC related configurations\n\"\"\"\n\nclass Single_NIC_conf:\n def __init__(self, lspci_vv_output, code_name, rx_q_num, tx_q_num,\n numa_node, LnkCap, LnkSta, pci_addr,\n cap_mpl, ctl_mpl, mrq, target_link_speed,\n ker_drv):\n\n self.lspci_vv_output = lspci_vv_output\n self.nic_code_name = code_name\n self.rx_queue_num = rx_q_num\n self.tx_queue_num = tx_q_num\n self.NUMA_node = numa_node\n self.LnkCap = LnkCap\n self.LnkSta = LnkSta\n self.pcie_width = 0\n self.pcie_devcap_maxpayloadsize = cap_mpl\n self.pcie_devctl_maxpayloadsize = ctl_mpl\n self.pcie_maxreadreq = mrq\n self.pcie_targetlinkspeed = target_link_speed\n self.pci_address = pci_addr\n self.ker_drv_in_use = ker_drv\n\n\n\"\"\"\nclass Single_NIC_conf_82599(Single_NIC_conf):\n def __init__(self):\n super.__init__(self)\n\"\"\"\n\nclass NICs_conf:\n lspci_nic_cmd = 'lspci | grep Ether'\n\n def __init__(self):\n self.str_nic_pci_conf= self.print_nic_pci_conf()\n self.nic_total_num = self.get_nic_total_num()\n self.nics_conf = []\n self.init_all_nics_conf()\n\n \"\"\"\n NIC related utility functions\n \"\"\"\n def NIC_rx_queue_num(self):\n pass\n\n def NIC_tx_queue_num(self):\n pass\n\n def print_nic_pci_conf(self):\n output = os.popen(self.lspci_nic_cmd, 'r')\n return output.read()\n\n def get_nic_lspci_vv_output(self, pci_addr):\n command = 'lspci -s ' + pci_addr + ' -vv'\n return os.popen(command, 'r').read()\n\n def get_nic_total_num(self):\n command = self.lspci_nic_cmd + '|wc -l'\n output = os.popen(command, 'r')\n return int(output.read())\n\n def get_nic_pci_address(self, list_num):\n output = self.str_nic_pci_conf.splitlines()[list_num]\n return output[0 : 7]\n\n def get_nic_code_name(self, list_num):\n output = self.str_nic_pci_conf.splitlines()[list_num].split(':')[2]\n return output\n\n def get_nic_LnkCap(self, lspci_vv_output):\n loc = lspci_vv_output.rfind('LnkCap')\n str_tmp = lspci_vv_output[loc :]\n loc = str_tmp.find('Speed')\n return str_tmp[loc + 6 : loc + 11]\n\n def get_nic_LnkSta(self, lspci_vv_output):\n loc = lspci_vv_output.find('LnkSta')\n str_tmp = lspci_vv_output[loc :]\n loc = str_tmp.find('Speed')\n return str_tmp[loc + 6 : loc + 11]\n\n def get_nic_numa_node(self, lspci_vv_output):\n loc = lspci_vv_output.find('NUMA node')\n if loc == -1:\n return 0\n else:\n return int(lspci_vv_output[loc + 11 : loc + 12])\n\n def get_nic_devcap_maxpayload(self, lspci_vv_output):\n loc = lspci_vv_output.find('DevCap')\n if loc == -1:\n return None\n maxpayload = lspci_vv_output[loc + 19: loc + 23]\n return int(maxpayload)\n\n def get_nic_devctl_maxpayload(self, lspci_vv_output):\n loc = lspci_vv_output.find('DevCtl')\n if loc == -1:\n return None\n loc1 = lspci_vv_output[loc :].find('MaxPayload')\n if loc1 == -1:\n return None\n maxpayload = lspci_vv_output[loc + loc1 + 11: loc + loc1 + 15]\n return int(maxpayload)\n\n def get_nic_max_read_req(self, lspci_vv_output):\n loc = lspci_vv_output.find('MaxReadReq')\n if loc == -1:\n return None\n loc1 = lspci_vv_output[loc :].find('bytes')\n if loc1 == -1:\n return None\n maxreadreq = lspci_vv_output[loc + 10 : loc + loc1]\n return int(maxreadreq)\n\n def get_nic_target_link_speed(self, lspci_vv_output):\n loc = lspci_vv_output.find('Target Link Speed')\n if loc == -1:\n return None\n loc1 = lspci_vv_output[loc :].find('GT')\n tls = lspci_vv_output[loc + 19 : loc + loc1]\n return tls + 'GT/s'\n\n def get_nic_ker_drv_in_use(self, lspci_vv_output):\n loc = lspci_vv_output.find('Kernel driver in use')\n str_tmp = lspci_vv_output[loc :]\n return str_tmp[22 : 37]\n\n def init_single_nic_conf(self, list_num):\n pci_addr = self.get_nic_pci_address(list_num)\n lspci_vv_output = self.get_nic_lspci_vv_output(pci_addr)\n code_name = self.get_nic_code_name(list_num)\n numa_node = self.get_nic_numa_node(lspci_vv_output)\n LnkCap = self.get_nic_LnkCap(lspci_vv_output)\n LnkSta = self.get_nic_LnkSta(lspci_vv_output)\n devcap_maxpayload = self.get_nic_devcap_maxpayload(lspci_vv_output)\n devctl_maxpayload = self.get_nic_devctl_maxpayload(lspci_vv_output)\n max_read_req = self.get_nic_max_read_req(lspci_vv_output)\n tls = self.get_nic_target_link_speed(lspci_vv_output)\n ker_drv = self.get_nic_ker_drv_in_use(lspci_vv_output)\n\n sig_nic = Single_NIC_conf(lspci_vv_output = lspci_vv_output,\n code_name = code_name, rx_q_num = 0,\n tx_q_num = 0, numa_node = numa_node,\n LnkCap = LnkCap, LnkSta = LnkSta,\n cap_mpl = devcap_maxpayload, ctl_mpl = devctl_maxpayload,\n mrq = max_read_req, target_link_speed = tls,\n pci_addr = pci_addr, ker_drv = ker_drv)\n\n self.nics_conf.append(sig_nic)\n\n def init_all_nics_conf(self):\n for i in range(self.nic_total_num):\n self.init_single_nic_conf(i)\n","sub_path":"testcases/utility/hardware.py","file_name":"hardware.py","file_ext":"py","file_size_in_byte":13688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"228812235","text":"import random\n# helper functions from notes\n\ndef make2dList(rows, cols, value = (0,0)):\n a=[]\n for row in range(rows): a += [[value]*cols]\n return a\n\ndef maxItemLength(a):\n maxLen = 0\n rows = len(a)\n cols = len(a[0])\n for row in range(rows):\n for col in range(cols):\n maxLen = max(maxLen, len(str(a[row][col])))\n return maxLen\n\ndef print2dList(a):\n if (a == []):\n print([])\n return\n rows = len(a)\n cols = len(a[0])\n fieldWidth = maxItemLength(a)\n print(\"[ \", end=\"\")\n for row in range(rows):\n if (row > 0): print(\"\\n \", end=\"\")\n print(\"[ \", end=\"\")\n for col in range(cols):\n if (col > 0): print(\", \", end=\"\")\n formatSpec = \"%\" + str(fieldWidth) + \"s\"\n print(formatSpec % str(a[row][col]), end=\"\")\n print(\" ]\", end=\"\")\n print(\"]\")\n\nclass GameMap(object):\n def __init__(self, width=10, height=10, complexity=2):\n self.wallGrid = []\n self.width = width\n self.height = height\n self.EMPTY = (0,0)#(0,0)\n self.WALL = (1,1) #(1,1)\n self.SAFE = 2\n self.complexity = complexity\n \n def generateMaze(self):\n height = self.height\n width = self.width\n self.wallGrid = make2dList(height, width)\n for row in range(height):\n self.wallGrid[row][0] = self.WALL #left border\n self.wallGrid[row][self.width-1] = self.WALL #right border\n for col in range(self.width):\n self.wallGrid[0][col] = self.WALL #top border\n self.wallGrid[self.height-1][col] = self.WALL #bot border\n print2dList(self.wallGrid)\n self.wallGrid[1][self.width-4] = self.SAFE\n self.wallGrid[1][self.width-3] = self.SAFE #door in upper right\n self.wallGrid[1][self.width-2] = self.SAFE #spawn here or randomly\n self.wallGrid[2][self.width-2] = self.SAFE\n self.wallGrid[self.height-2][1] = self.SAFE #key in bottom right\n self.wallGrid[self.height-2][2] = self.SAFE\n self.wallGrid[self.height-3][1] = self.SAFE\n self.randomizeChamber(0,0,self.width, self.height)\n print2dList(self.wallGrid)\n for row in range(self.height):\n for col in range(self.width):\n val = self.wallGrid[row][col]\n if val == self.EMPTY or val == self.SAFE: \n self.wallGrid[row][col] = (0,0)\n elif val == self.WALL:\n self.wallGrid[row][col] = (1,1)\n self.wallGrid[1][self.width-1] = (1,5) #door\n #START CELL = (1,width-2)\n self.wallGrid[2][self.width-1] = (1,3) #doorinstr\n self.wallGrid[self.height-1][1] = (1,4) #key\n #END CELL = (height-2, 1)\n self.wallGrid[self.height-1][2] = (1,8) #keyinstr\n #print2dList(self.wallGrid)\n for row in range(len(self.wallGrid)):\n for col in range(len(self.wallGrid[0])):\n if self.wallGrid[row][col][1] == 5:\n self.doorPosX, self.doorPosY = col, row\n elif self.wallGrid[row][col][1] == 4:\n self.keyPosX, self.keyPosY = col, row\n \n def randomizeChamber(self, row, col, width, height, depth = 0):\n #print(\"chamber top-left: %d,%d\" %(row, col))\n #print(\"chamber bot-right: %d,%d\"%(row + height-1, col+width-1))\n if width <= 4 or height <= 4 or depth==self.complexity: #split this up and place the walls separately for small spaces\n return None\n randRow = random.randint(row+2, row + height-3)\n randCol = random.randint(col+2, col + width-3)\n #print(\"randRow %d\" %randRow)\n #print(\"randCol %d\" %randCol)\n randCompleteWall = random.randint(1,4)\n wall1hole = random.randint(row+1, randRow-1)\n wall2hole = random.randint(col+1, randCol-1)\n wall3hole = random.randint(randRow+1, row + height-2)\n wall4hole = random.randint(randCol+1, col + width-2) \n for x in range(row+1, row + height-1):\n if self.wallGrid[x][randCol] == self.EMPTY:\n self.wallGrid[x][randCol] = self.WALL \n for y in range(col+1, col + width-1):\n if self.wallGrid[randRow][y] == self.EMPTY:\n self.wallGrid[randRow][y] = self.WALL\n if randCompleteWall != 1:\n #print(\"wall1 hole %d \" %wall1hole)\n self.wallGrid[wall1hole][randCol] = self.SAFE\n self.wallGrid[wall1hole][randCol-1] = self.SAFE\n self.wallGrid[wall1hole][randCol+1] = self.SAFE\n if randCompleteWall != 2:\n #print(\"wall2 hole %d \" %wall2hole)\n self.wallGrid[randRow][wall2hole] = self.SAFE\n self.wallGrid[randRow+1][wall2hole] = self.SAFE\n self.wallGrid[randRow-1][wall2hole] = self.SAFE\n if randCompleteWall != 3:\n #print(\"wall3 hole %d \" %wall3hole)\n self.wallGrid[wall3hole][randCol] = self.SAFE\n self.wallGrid[wall3hole][randCol+1] = self.SAFE\n self.wallGrid[wall3hole][randCol-1] = self.SAFE\n if randCompleteWall != 4:\n #print(\"wall4 hole %d \" %wall4hole)\n self.wallGrid[randRow][wall4hole] = self.SAFE\n self.wallGrid[randRow+1][wall4hole] = self.SAFE\n self.wallGrid[randRow-1][wall4hole] = self.SAFE\n \n #self.randomizeChamber(row, col, width, height)\n self.randomizeChamber(0, 0, randCol, randRow, depth+1)#topleft\n self.randomizeChamber(0, randCol, self.width-randCol, randRow+1, depth+1)#top right\n self.randomizeChamber(randRow, 0, randCol+1, self.height-randRow, depth+1)#botleft\n self.randomizeChamber(randRow, randCol, self.width-randCol, self.height-randRow, depth+1)#botright\n print(\"randomized\")\n \n def testMaze(self):\n self.startCell = (endX, endY) = (self.keyPosX,self.keyPosY-1)\n self.endCell = (startX, startY) = (self.doorPosX-1, self.doorPosY)\n return None#isLegalMaze((startX, startY),(endX, endY))\n \n \"\"\"def isLegalMaze(self,solution = []):\n if the problem is solved then:\n return the solution\nelse:\n for each legal move:\n do the move\n try to recursively solve the problem\n if the problem is solved:\n return the solution # woohoo!\n undo the move\n fail # we tried all legal moves, none worked\"\"\"\n\nfor i in range(1):\n map = GameMap()\n map.generateMaze()\n print2dList(map.wallGrid)\n print(map.testMaze())","sub_path":"foo.py","file_name":"foo.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"98066978","text":"\"\"\"\nimport socket\nfrom numpy import *\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((\"localhost\", 2333))\ns.listen(1)\n\n\ndef detect(str_in):\n\tprint(str_in.decode())\n\n\nprint('Now working...')\n\nwhile True:\n\tconn, address = s.accept()\n\tdata = conn.recv(1024)\n\tconn.close()\n\tdetect(data)\n\"\"\"\n\n\nfrom test import *\nfrom client import *\nimport time\n\n\ndef run_server():\n\tn = int(input('Please input the number of nodes (n > 1): '))\n\tif n < 2:\n\t\traise ValueError('The number of nodes should be greater than 1')\n\tg = Graph(n)\n\tclients = [Client(i) for i in range(n)]\n\twhile True:\n\t\tg.display()\n\t\tstart = time.time()\n\t\tfor i in range(1, n):\n\t\t\tcost, order = dijkstra(0, i, g)\n\t\t\tprint('Node: {}, Cost: {}, Order: {}'.format(i, cost, order))\n\t\t\t# sending message\n\t\t\tclients[0].send(order, clients)\n\t\tend = time.time()\n\t\tprint('Total time: {}s'.format(end - start))\n\t\t# For convenience, use system pause to represent every 10s passed\n\t\tos.system('pause')\n\t\t# Generate a new graph\n\t\tg.generate()\n\n\nif __name__ == '__main__':\n\trun_server()\n","sub_path":"DataStructure/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"362463632","text":"import pandas as pd\nimport numpy as np\nimport datetime \nimport pandas_datareader as web\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nstart = datetime.datetime(2012 , 1 , 1)\nend = datetime.date.today()\n\ngoogle = web.DataReader (\"GOOGL\" , \"yahoo\" , start , end)\n#+------------------------------------------------------------------+\n#| | \n#| 分析google股票自2012年起 只要87日均線>284日均線就買進 |\n#| |\n#| 反之跌破賣出,並計算總獲利截至2019/03/29 |\n#| |\n#+------------------------------------------------------------------+\ngoogle[\"tomorrow\"] = google[\"Close\"].shift(-1)\ngoogle[\"diff\"] = google[\"tomorrow\"] - google[\"Close\"]\ngoogle[\"return\"] = google[\"diff\"] / google [\"Close\"] \ngoogle[\"direction\"] = [1 if google.loc[ei,\"diff\"] > 0 else -1 for ei in google.index]\ngoogle[\"ma87\"] = google[\"Close\"].rolling(87).mean() #87日均線\ngoogle[\"ma284\"] = google[\"Close\"].rolling(284).mean() #284日均線\ngoogle[\"share\"] = [1 if google.loc[ei,\"ma87\"] > google.loc[ei,\"ma284\"] else 0 for ei in google.index] #當ma87>ma284進場\ngoogle[\"profit\"] = [google.loc[ei,\"tomorrow\"] - google.loc[ei , \"Close\"] if google.loc[ei ,\"share\"] ==1 else 0 for ei in google.index]\ngoogle[\"wealth\"]= google[\"profit\"].cumsum()\n\n#+------------------------------------------------------------------+\n#| |\n#| 用 matplotlib模組畫出 價格和兩條均線關係圖 | \n#| |\n#| 2015/7月時候黃金交叉買進 |\n#| |\n#+------------------------------------------------------------------+\n\n\nplt.title(\"GOOGL\",size=30)\nplt.xlabel(\"Time\",size=20)\nplt.ylabel(\"USD\", size= 20)\nplt.plot(google.loc[:,\"Close\"], alpha = 0.5)\nplt.plot(google[\"ma87\"] ,label = \"ma87\", color = \"red\")\nplt.plot(google[\"ma284\"] , color= \"green\")\nplt.legend()\nplt.show()\n\n\nmu = google[\"return\"].mean() #平均值\nsigma = google [\"return\"].std(ddof=1) #標準差\n\n#den = pd.DataFrame()\n# den[\"x\"] = np.arange(-0.1 , 0.1 ,0.01)\n# den[\"pdf\"] = norm.pdf(den[\"x\"] , mu ,sigma)\n# # plt.ylim(0,100)\n# plt.plot(den[\"x\"],den[\"pdf\"])\n# plt.fill_between(x=np.arange(-0.1,-0.01,0.0001),\n# y2=0,\n# y1=norm.pdf(np.arange(-0.1,-0.01,0.0001), mu ,sigma),\n# color=\"pink\",\n# alpha= 0.5,\n# )\n# plt.show()\ndensity_google_cdf = norm.cdf(-0.05 , mu ,sigma)\n\ndensity_google_ppf = norm.ppf(0.05 , mu ,sigma)\n\nmu220=220*mu \nsigma220=220**0.5*sigma\nprobability_drop_20 = norm.cdf(-0.2,mu220,sigma220)\n\nprint(\"一日下跌5%的機率為:\" , density_google_cdf)\nprint(\"每日有5%下跌幅度為:\", density_google_ppf )\nprint(\"一年220約交易日下跌20%機率\",probability_drop_20)","sub_path":"google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"468532699","text":"from ..utils import DataikuException\nfrom ..utils import DataikuUTF8CSVReader\nfrom ..utils import DataikuStreamedHttpUTF8CSVReader\nimport json\nimport time\nfrom .metrics import ComputedMetrics\nfrom .utils import DSSDatasetSelectionBuilder, DSSFilterBuilder\n\nclass PredictionSplitParamsHandler(object):\n \"\"\"Object to modify the train/test splitting params.\"\"\"\n\n def __init__(self, mltask_settings):\n \"\"\"Do not call directly, use :meth:`DSSMLTaskSettings.get_split_params`\"\"\"\n self.mltask_settings = mltask_settings\n\n def set_split_random(self, train_ratio = 0.8, selection = None, dataset_name=None):\n \"\"\"\n Sets the train/test split to random splitting of an extract of a single dataset\n\n :param float train_ratio: Ratio of rows to use for train set. Must be between 0 and 1\n :param object selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the dataset. May be None (won't be changed)\n :param str dataset_name: Name of dataset to split. If None, the main dataset used to create the visual analysis will be used.\n \"\"\"\n sp = self.mltask_settings[\"splitParams\"]\n sp[\"ttPolicy\"] = \"SPLIT_SINGLE_DATASET\"\n if selection is not None:\n if isinstance(selection, DSSDatasetSelectionBuilder):\n sp[\"ssdSelection\"] = selection.build()\n else:\n sp[\"ssdSelection\"] = selection\n\n sp[\"ssdTrainingRatio\"] = train_ratio\n sp[\"kfold\"] = False\n\n if dataset_name is not None:\n sp[\"ssdDatasetSmartName\"] = dataset_name\n\n def set_split_kfold(self, n_folds = 5, selection = None, dataset_name=None):\n \"\"\"\n Sets the train/test split to k-fold splitting of an extract of a single dataset\n\n :param int n_folds: number of folds. Must be greater than 0\n :param object selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the dataset. May be None (won't be changed)\n :param str dataset_name: Name of dataset to split. If None, the main dataset used to create the visual analysis will be used.\n \"\"\"\n sp = self.mltask_settings[\"splitParams\"]\n sp[\"ttPolicy\"] = \"SPLIT_SINGLE_DATASET\"\n if selection is not None:\n if isinstance(selection, DSSDatasetSelectionBuilder):\n sp[\"ssdSelection\"] = selection.build()\n else:\n sp[\"ssdSelection\"] = selection\n\n sp[\"kfold\"] = True\n sp[\"nFolds\"] = n_folds\n\n if dataset_name is not None:\n sp[\"ssdDatasetSmartName\"] = dataset_name\n\n def set_split_explicit(self, train_selection, test_selection, dataset_name=None, test_dataset_name=None, train_filter=None, test_filter=None):\n \"\"\"\n Sets the train/test split to explicit extract of one or two dataset(s)\n\n :param object train_selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the train dataset. May be None (won't be changed)\n :param object test_selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the test dataset. May be None (won't be changed)\n :param str dataset_name: Name of dataset to use for the extracts. If None, the main dataset used to create the ML Task will be used.\n :param str test_dataset_name: Name of a second dataset to use for the test data extract. If None, both extracts are done from dataset_name\n :param object train_filter: A :class:`~dataikuapi.dss.utils.DSSFilterBuilder` to build the settings of the filter of the train dataset. May be None (won't be changed)\n :param object test_filter: A :class:`~dataikuapi.dss.utils.DSSFilterBuilder` to build the settings of the filter of the test dataset. May be None (won't be changed)\n \"\"\"\n sp = self.mltask_settings[\"splitParams\"]\n if dataset_name is None:\n raise Exception(\"For explicit splitting a dataset_name is mandatory\")\n if test_dataset_name is None or test_dataset_name == dataset_name:\n sp[\"ttPolicy\"] = \"EXPLICIT_FILTERING_SINGLE_DATASET\"\n train_split ={}\n test_split = {}\n sp['efsdDatasetSmartName'] = dataset_name\n sp['efsdTrain'] = train_split\n sp['efsdTest'] = test_split\n else: \n sp[\"ttPolicy\"] = \"EXPLICIT_FILTERING_TWO_DATASETS\"\n train_split ={'datasetSmartName' : dataset_name}\n test_split = {'datasetSmartName' : test_dataset_name}\n sp['eftdTrain'] = train_split\n sp['eftdTest'] = test_split\n\n if train_selection is not None:\n if isinstance(train_selection, DSSDatasetSelectionBuilder):\n train_split[\"selection\"] = train_selection.build()\n else:\n train_split[\"selection\"] = train_selection\n if test_selection is not None:\n if isinstance(test_selection, DSSDatasetSelectionBuilder):\n test_split[\"selection\"] = test_selection.build()\n else:\n test_split[\"selection\"] = test_selection\n\n if train_filter is not None:\n if isinstance(train_filter, DSSFilterBuilder):\n train_split[\"filter\"] = train_filter.build()\n else:\n train_split[\"filter\"] = train_filter\n if test_filter is not None:\n if isinstance(test_filter, DSSFilterBuilder):\n test_split[\"filter\"] = test_filter.build()\n else:\n test_split[\"filter\"] = test_filter\n\n\nclass DSSMLTaskSettings(object):\n \"\"\"\n Object to read and modify the settings of a ML task.\n\n Do not create this object directly, use :meth:`DSSMLTask.get_settings()` instead\n \"\"\"\n def __init__(self, client, project_key, analysis_id, mltask_id, mltask_settings):\n self.client = client\n self.project_key = project_key\n self.analysis_id = analysis_id\n self.mltask_id = mltask_id\n self.mltask_settings = mltask_settings\n\n def get_raw(self):\n \"\"\"\n Gets the raw settings of this ML Task. This returns a reference to the raw settings, not a copy,\n so changes made to the returned object will be reflected when saving.\n\n :rtype: dict\n \"\"\"\n return self.mltask_settings\n\n def get_split_params(self):\n \"\"\"\n Gets an object to modify train/test splitting params.\n\n :rtype: :class:`PredictionSplitParamsHandler`\n \"\"\"\n return PredictionSplitParamsHandler(self.mltask_settings)\n\n\n def get_feature_preprocessing(self, feature_name):\n \"\"\"\n Gets the feature preprocessing params for a particular feature. This returns a reference to the\n feature's settings, not a copy, so changes made to the returned object will be reflected when saving\n\n :return: A dict of the preprocessing settings for a feature\n :rtype: dict \n \"\"\"\n return self.mltask_settings[\"preprocessing\"][\"per_feature\"][feature_name]\n\n def foreach_feature(self, fn, only_of_type = None):\n \"\"\"\n Applies a function to all features (except target)\n\n :param function fn: Function that takes 2 parameters: feature_name and feature_params and returns modified feature_params\n :param str only_of_type: if not None, only applies to feature of the given type. Can be one of ``CATEGORY``, ``NUMERIC``, ``TEXT`` or ``VECTOR``\n \"\"\"\n import copy\n new_per_feature = {}\n for (k, v) in self.mltask_settings[\"preprocessing\"][\"per_feature\"].items():\n if v[\"role\"] == \"TARGET\" or (only_of_type is not None and v[\"type\"] != only_of_type):\n new_per_feature[k] = v\n else:\n new_per_feature[k] = fn(k, copy.deepcopy(v))\n self.mltask_settings[\"preprocessing\"][\"per_feature\"] = new_per_feature\n\n def reject_feature(self, feature_name):\n \"\"\"\n Marks a feature as rejected and not used for training\n :param str feature_name: Name of the feature to reject\n \"\"\"\n self.get_feature_preprocessing(feature_name)[\"role\"] = \"REJECT\"\n\n def use_feature(self, feature_name):\n \"\"\"\n Marks a feature as input for training\n :param str feature_name: Name of the feature to reject\n \"\"\"\n self.get_feature_preprocessing(feature_name)[\"role\"] = \"INPUT\"\n\n def use_sample_weighting(self, feature_name):\n \"\"\"\n Uses a feature as sample weight\n :param str feature_name: Name of the feature to use\n \"\"\"\n self.remove_sample_weighting()\n if not feature_name in self.mltask_settings[\"preprocessing\"][\"per_feature\"]:\n raise ValueError(\"Feature %s doesn't exist in this ML task, can't use as weight\" % feature_name)\n self.mltask_settings['weight']['weightMethod'] = 'SAMPLE_WEIGHT'\n self.mltask_settings['weight']['sampleWeightVariable'] = feature_name\n self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] = 'WEIGHT'\n\n\n def remove_sample_weighting(self):\n \"\"\"\n Remove sample weighting. If a feature was used as weight, it's set back to being an input feature\n \"\"\"\n self.mltask_settings['weight']['weightMethod'] = 'NO_WEIGHTING'\n for feature_name in self.mltask_settings['preprocessing']['per_feature']:\n if self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] == 'WEIGHT':\n self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] = 'INPUT'\n\n def get_algorithm_settings(self, algorithm_name):\n \"\"\"\n Gets the training settings for a particular algorithm. This returns a reference to the\n algorithm's settings, not a copy, so changes made to the returned object will be reflected when saving.\n\n This method returns a dictionary of the settings for this algorithm.\n All algorithm dicts have at least an \"enabled\" key in the dictionary.\n The 'enabled' key indicates whether this algorithm will be trained\n\n Other settings are algorithm-dependent and are the various hyperparameters of the \n algorithm. The precise keys for each algorithm are not all documented. You can print\n the returned dictionary to learn more about the settings of each particular algorithm\n\n Please refer to the documentation for details on available algorithms.\n\n :param str algorithm_name: Name (in capitals) of the algorithm.\n :return: A dict of the settings for an algorithm\n :rtype: dict \n \"\"\"\n if algorithm_name in self.__class__.algorithm_remap:\n algorithm_name = self.__class__.algorithm_remap[algorithm_name]\n\n return self.mltask_settings[\"modeling\"][algorithm_name.lower()]\n\n def set_algorithm_enabled(self, algorithm_name, enabled):\n \"\"\"\n Enables or disables an algorithm based on its name.\n\n Please refer to the documentation for details on available algorithms.\n\n :param str algorithm_name: Name (in capitals) of the algorithm.\n \"\"\"\n self.get_algorithm_settings(algorithm_name)[\"enabled\"] = enabled\n\n def set_metric(self, metric=None, custom_metric=None, custom_metric_greater_is_better=True, custom_metric_use_probas=False):\n \"\"\"\n Sets the score metric to optimize for a prediction ML Task\n\n :param str metric: metric to use. Leave empty to use a custom metric. You need to set the ``custom_metric`` value in that case\n :param str custom_metric: code of the custom metric\n :param bool custom_metric_greater_is_better: whether the custom metric is a score or a loss\n :param bool custom_metric_use_probas: whether to use the classes' probas or the predicted value (for classification)\n \"\"\"\n if custom_metric is None and metric is None:\n raise ValueError(\"Either metric or custom_metric must be defined\")\n self.mltask_settings[\"modeling\"][\"metrics\"][\"evaluationMetric\"] = metric if custom_metric is None else 'CUSTOM'\n self.mltask_settings[\"modeling\"][\"metrics\"][\"customEvaluationMetricCode\"] = custom_metric\n self.mltask_settings[\"modeling\"][\"metrics\"][\"customEvaluationMetricGIB\"] = custom_metric_greater_is_better\n self.mltask_settings[\"modeling\"][\"metrics\"][\"customEvaluationMetricNeedsProba\"] = custom_metric_use_probas\n\n def save(self):\n \"\"\"Saves back these settings to the ML Task\"\"\"\n\n self.client._perform_empty(\n \"POST\", \"/projects/%s/models/lab/%s/%s/settings\" % (self.project_key, self.analysis_id, self.mltask_id),\n body = self.mltask_settings)\n\nclass DSSPredictionMLTaskSettings(DSSMLTaskSettings):\n __doc__ = []\n algorithm_remap = {\n \"SVC_CLASSIFICATION\" : \"svc_classifier\",\n \"SGD_CLASSIFICATION\" : \"sgd_classifier\",\n \"SPARKLING_DEEP_LEARNING\" : \"deep_learning_sparkling\",\n \"SPARKLING_GBM\" : \"gbm_sparkling\",\n \"SPARKLING_RF\" : \"rf_sparkling\",\n \"SPARKLING_GLM\" : \"glm_sparkling\",\n \"SPARKLING_NB\" : \"nb_sparkling\",\n \"XGBOOST_CLASSIFICATION\" : \"xgboost\",\n \"XGBOOST_REGRESSION\" : \"xgboost\",\n \"MLLIB_LOGISTIC_REGRESSION\" : \"mllib_logit\",\n \"MLLIB_LINEAR_REGRESSION\" : \"mllib_linreg\",\n \"MLLIB_RANDOM_FOREST\" : \"mllib_rf\"\n }\n\nclass DSSClusteringMLTaskSettings(DSSMLTaskSettings):\n __doc__ = []\n algorithm_remap = {\n \"DBSCAN\" : \"db_scan_clustering\",\n }\n\n\n\nclass DSSTrainedModelDetails(object):\n def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):\n self.details = details\n self.snippet = snippet\n self.saved_model = saved_model\n self.saved_model_version = saved_model_version\n self.mltask = mltask\n self.mltask_model_id = mltask_model_id\n\n def get_raw(self):\n \"\"\"\n Gets the raw dictionary of trained model details\n \"\"\"\n return self.details\n\n def get_raw_snippet(self):\n \"\"\"\n Gets the raw dictionary of trained model snippet. \n The snippet is a lighter version than the details.\n \"\"\"\n return self.snippet\n\n def get_train_info(self):\n \"\"\"\n Returns various information about the train process (size of the train set, quick description, timing information)\n\n :rtype: dict\n \"\"\"\n return self.details[\"trainInfo\"]\n\n def get_user_meta(self):\n \"\"\"\n Gets the user-accessible metadata (name, description, cluster labels, classification threshold)\n Returns the original object, not a copy. Changes to the returned object are persisted to DSS by calling\n :meth:`save_user_meta`\n\n \"\"\"\n return self.details[\"userMeta\"]\n\n def save_user_meta(self):\n um = self.details[\"userMeta\"]\n\n if self.mltask is not None:\n self.mltask.client._perform_empty(\n \"PUT\", \"/projects/%s/models/lab/%s/%s/models/%s/user-meta\" % (self.mltask.project_key,\n self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id), body = um)\n else:\n self.saved_model.client._perform_empty(\n \"PUT\", \"/projects/%s/savedmodels/%s/versions/%s/user-meta\" % (self.saved_model.project_key,\n self.saved_model.sm_id, self.saved_model_version), body = um)\n\nclass DSSTreeNode(object):\n def __init__(self, tree, i):\n self.tree = tree\n self.i = i\n\n def get_left_child(self):\n \"\"\"Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the left side of the tree node (or None)\"\"\"\n left = self.tree.tree['leftChild'][self.i]\n if left < 0:\n return None\n else:\n return DSSTreeNode(self.tree, left)\n\n def get_right_child(self):\n \"\"\"Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the right side of the tree node (or None)\"\"\"\n left = self.tree.tree['rightChild'][self.i]\n if left < 0:\n return None\n else:\n return DSSTreeNode(self.tree, left)\n\n def get_split_info(self):\n \"\"\"Gets the information on the split, as a dict\"\"\"\n info = {}\n features = self.tree.tree.get(\"feature\", None)\n probas = self.tree.tree.get(\"probas\", None)\n leftCategories = self.tree.tree.get(\"leftCategories\", None)\n impurities = self.tree.tree.get(\"impurity\", None)\n predicts = self.tree.tree.get(\"predict\", None)\n thresholds = self.tree.tree.get(\"threshold\", None)\n nSamples = self.tree.tree.get(\"nSamples\", None)\n info['feature'] = self.tree.feature_names[features[self.i]] if features is not None else None\n info['probas'] = probas[self.i] if probas is not None else None\n info['leftCategories'] = leftCategories[self.i] if leftCategories is not None else None\n info['impurity'] = impurities[self.i] if impurities is not None else None\n info['predict'] = predicts[self.i] if predicts is not None else None\n info['nSamples'] = nSamples[self.i] if nSamples is not None else None\n info['threshold'] = thresholds[self.i] if thresholds is not None else None\n return info\n \nclass DSSTree(object):\n def __init__(self, tree, feature_names):\n self.tree = tree\n self.feature_names = feature_names\n\n def get_raw(self):\n \"\"\"Gets the raw tree data structure\"\"\"\n return self.tree\n\n def get_root(self):\n \"\"\"Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the root of the tree\"\"\"\n return DSSTreeNode(self, 0)\n\nclass DSSTreeSet(object):\n def __init__(self, trees):\n self.trees = trees\n\n def get_raw(self):\n \"\"\"Gets the raw trees data structure\"\"\"\n return self.trees\n\n def get_feature_names(self):\n \"\"\"Gets the list of feature names (after dummification) \"\"\"\n return self.trees[\"featureNames\"]\n\n def get_trees(self):\n \"\"\"Gets the list of trees as :class:`dataikuapi.dss.ml.DSSTree` \"\"\"\n return [DSSTree(t, self.trees[\"featureNames\"]) for t in self.trees[\"trees\"]]\n\nclass DSSCoefficientPaths(object):\n def __init__(self, paths):\n self.paths = paths\n\n def get_raw(self):\n \"\"\"Gets the raw paths data structure\"\"\"\n return self.paths\n\n def get_feature_names(self):\n \"\"\"Get the feature names (after dummification)\"\"\"\n return self.paths['features']\n\n def get_coefficient_path(self, feature, class_index=0):\n \"\"\"Get the path of the feature\"\"\"\n i = self.paths['features'].index(feature)\n if i >= 0 and i < len(self.paths['path'][0][class_index]):\n n = len(self.paths['path'])\n return [self.paths['path'][j][class_index][i] for j in range(0, n)]\n else:\n return None\n\nclass DSSScatterPlots(object):\n def __init__(self, scatters):\n self.scatters = scatters\n\n def get_raw(self):\n \"\"\"Gets the raw scatters data structure\"\"\"\n return self.scatters\n\n def get_feature_names(self):\n \"\"\"Get the feature names (after dummification)\"\"\"\n feature_names = []\n for k in self.scatters['features']:\n feature_names.append(k)\n return feature_names\n\n def get_scatter_plot(self, feature_x, feature_y):\n \"\"\"Get the scatter plot between feature_x and feature_y\"\"\"\n ret = {'cluster':self.scatters['cluster'], 'x':self.scatters['features'].get(feature_x, None), 'y':self.scatters['features'].get(feature_x, None)}\n return ret\n\nclass DSSTrainedPredictionModelDetails(DSSTrainedModelDetails):\n \"\"\"\n Object to read details of a trained prediction model\n\n Do not create this object directly, use :meth:`DSSMLTask.get_trained_model_details()` instead\n \"\"\"\n\n def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):\n DSSTrainedModelDetails.__init__(self, details, snippet, saved_model, saved_model_version, mltask, mltask_model_id)\n\n def get_roc_curve_data(self):\n roc = self.details.get(\"perf\", {}).get(\"rocVizData\",{})\n if roc is None:\n raise ValueError(\"This model does not have ROC visualization data\")\n\n return roc\n\n def get_performance_metrics(self):\n \"\"\"\n Returns all performance metrics for this model.\n\n For binary classification model, this includes both \"threshold-independent\" metrics like AUC and\n \"threshold-dependent\" metrics like precision. Threshold-dependent metrics are returned at the\n threshold value that was found to be optimal during training.\n\n To get access to the per-threshold values, use the following:\n\n .. code-block:: python\n\n # Returns a list of tested threshold values\n details.get_performance()[\"perCutData\"][\"cut\"]\n # Returns a list of F1 scores at the tested threshold values\n details.get_performance()[\"perCutData\"][\"f1\"]\n # Both lists have the same length\n\n If K-Fold cross-test was used, most metrics will have a \"std\" variant, which is the standard deviation\n accross the K cross-tested folds. For example, \"auc\" will be accompanied with \"aucstd\"\n\n :returns: a dict of performance metrics values\n :rtype: dict\n \"\"\"\n import copy\n clean_snippet = copy.deepcopy(self.snippet)\n for x in [\"gridsearchData\", \"trainDate\", \"topImportance\", \"backendType\", \"userMeta\", \"sessionDate\", \"trainInfo\", \"fullModelId\", \"gridLength\", \"algorithm\", \"sessionId\"]:\n if x in clean_snippet:\n del clean_snippet[x]\n return clean_snippet\n\n\n def get_preprocessing_settings(self):\n \"\"\"\n Gets the preprocessing settings that were used to train this model\n\n :rtype: dict\n \"\"\"\n return self.details[\"preprocessing\"]\n\n def get_modeling_settings(self):\n \"\"\"\n Gets the modeling (algorithms) settings that were used to train this model.\n\n Note: the structure of this dict is not the same as the modeling params on the ML Task\n (which may contain several algorithm)\n\n :rtype: dict\n \"\"\"\n return self.details[\"modeling\"]\n\n def get_actual_modeling_params(self):\n \"\"\"\n Gets the actual / resolved parameters that were used to train this model, post\n hyperparameter optimization.\n\n :return: A dictionary, which contains at least a \"resolved\" key, which is a dict containing the post-optimization parameters\n :rtype: dict\n \"\"\"\n return self.details[\"actualParams\"]\n\n def get_trees(self):\n \"\"\"\n Gets the trees in the model (for tree-based models) \n\n :return: a DSSTreeSet object to interact with the trees\n :rtype: :class:`dataikuapi.dss.ml.DSSTreeSet`\n \"\"\"\n data = self.mltask.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/trees\" % (self.mltask.project_key, self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id))\n if data is None:\n raise ValueError(\"This model has no tree data\")\n return DSSTreeSet(data)\n\n def get_coefficient_paths(self):\n \"\"\"\n Gets the coefficient paths for Lasso models\n\n :return: a DSSCoefficientPaths object to interact with the coefficient paths\n :rtype: :class:`dataikuapi.dss.ml.DSSCoefficientPaths`\n \"\"\"\n data = self.mltask.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/coef-paths\" % (self.mltask.project_key, self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id))\n if data is None:\n raise ValueError(\"This model has no coefficient paths\")\n return DSSCoefficientPaths(data)\n\n\nclass DSSClustersFacts(object):\n def __init__(self, clusters_facts):\n self.clusters_facts = clusters_facts\n\n def get_raw(self):\n \"\"\"Gets the raws facts data structure\"\"\"\n return self.clusters_facts\n\n def get_cluster_size(self, cluster_index):\n \"\"\"Gets the size of a cluster identified by its index\"\"\"\n return self.clusters_facts[\"clusters\"][cluster_index][\"size\"]\n\n def get_facts_for_cluster(self, cluster_index):\n \"\"\"\n Gets all facts for a cluster identified by its index. Returns a list of dicts\n\n :rtype: list\n \"\"\"\n return self.clusters_facts[\"clusters\"][cluster_index][\"facts\"]\n\n def get_facts_for_cluster_and_feature(self, cluster_index, feature_name):\n \"\"\"\n Gets all facts for a cluster identified by its index, limited to a feature name. Returns a list of dicts\n\n :rtype: list\n \"\"\"\n return [x for x in self.get_facts_for_cluster(cluster_index) if x[\"feature_label\"] == feature_name]\n\n\nclass DSSTrainedClusteringModelDetails(DSSTrainedModelDetails):\n \"\"\"\n Object to read details of a trained clustering model\n\n Do not create this object directly, use :meth:`DSSMLTask.get_trained_model_details()` instead\n \"\"\"\n\n def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):\n DSSTrainedModelDetails.__init__(self, details, snippet, saved_model, saved_model_version, mltask, mltask_model_id)\n\n\n def get_raw(self):\n \"\"\"\n Gets the raw dictionary of trained model details\n \"\"\"\n return self.details\n\n def get_train_info(self):\n \"\"\"\n Returns various information about the train process (size of the train set, quick description, timing information)\n\n :rtype: dict\n \"\"\"\n return self.details[\"trainInfo\"]\n\n def get_facts(self):\n \"\"\"\n Gets the 'cluster facts' data, i.e. the structure behind the screen \"for cluster X, average of Y is Z times higher than average\n\n :rtype: :class:`DSSClustersFacts`\n \"\"\"\n return DSSClustersFacts(self.details[\"facts\"])\n\n def get_performance_metrics(self):\n \"\"\"\n Returns all performance metrics for this clustering model.\n :returns: a dict of performance metrics values\n :rtype: dict\n \"\"\"\n import copy\n clean_snippet = copy.deepcopy(self.snippet)\n for x in [\"fullModelId\", \"algorithm\", \"trainInfo\", \"userMeta\", \"backendType\", \"sessionId\", \"sessionDate\", \"facts\"]:\n if x in clean_snippet:\n del clean_snippet[x]\n return clean_snippet\n\n def get_preprocessing_settings(self):\n \"\"\"\n Gets the preprocessing settings that were used to train this model\n\n :rtype: dict\n \"\"\"\n return self.details[\"preprocessing\"]\n\n def get_modeling_settings(self):\n \"\"\"\n Gets the modeling (algorithms) settings that were used to train this model.\n\n Note: the structure of this dict is not the same as the modeling params on the ML Task\n (which may contain several algorithm)\n\n :rtype: dict\n \"\"\"\n return self.details[\"modeling\"]\n\n def get_actual_modeling_params(self):\n \"\"\"\n Gets the actual / resolved parameters that were used to train this model.\n :return: A dictionary, which contains at least a \"resolved\" key\n :rtype: dict\n \"\"\"\n return self.details[\"actualParams\"]\n\n def get_scatter_plots(self):\n \"\"\"\n Gets the cluster scatter plot data \n\n :return: a DSSScatterPlots object to interact with the scatter plots\n :rtype: :class:`dataikuapi.dss.ml.DSSScatterPlots`\n \"\"\"\n scatters = self.mltask.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/scatter-plots\" % (self.mltask.project_key, self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id))\n return DSSScatterPlots(scatters)\n\n\nclass DSSMLTask(object):\n \"\"\"A handle to interact with a MLTask for prediction or clustering in a DSS visual analysis\"\"\"\n def __init__(self, client, project_key, analysis_id, mltask_id):\n self.client = client\n self.project_key = project_key\n self.analysis_id = analysis_id\n self.mltask_id = mltask_id\n\n def delete(self):\n \"\"\"\n Delete the present ML task\n \"\"\"\n return self.client._perform_json(\n \"DELETE\", \"/projects/%s/models/lab/%s/%s/\" % (self.project_key, self.analysis_id, self.mltask_id))\n \n\n def wait_guess_complete(self):\n \"\"\"\n Waits for guess to be complete. This should be called immediately after the creation of a new ML Task\n (if the ML Task was created with wait_guess_complete=False),\n before calling ``get_settings`` or ``train``\n \"\"\"\n while True:\n status = self.get_status()\n if status.get(\"guessing\", \"???\") == False:\n break\n time.sleep(0.2)\n\n\n def get_status(self):\n \"\"\"\n Gets the status of this ML Task\n\n :return: a dict\n \"\"\"\n return self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/status\" % (self.project_key, self.analysis_id, self.mltask_id))\n \n\n def get_settings(self):\n \"\"\"\n Gets the settings of this ML Tasks\n\n :return: a DSSMLTaskSettings object to interact with the settings\n :rtype: :class:`dataikuapi.dss.ml.DSSMLTaskSettings`\n \"\"\"\n settings = self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/settings\" % (self.project_key, self.analysis_id, self.mltask_id))\n\n if settings[\"taskType\"] == \"PREDICTION\":\n return DSSPredictionMLTaskSettings(self.client, self.project_key, self.analysis_id, self.mltask_id, settings)\n else:\n return DSSClusteringMLTaskSettings(self.client, self.project_key, self.analysis_id, self.mltask_id, settings)\n\n def train(self, session_name=None, session_description=None):\n \"\"\"\n Trains models for this ML Task\n \n :param str session_name: name for the session\n :param str session_description: description for the session\n\n This method waits for train to complete. If you want to train asynchronously, use :meth:`start_train` and :meth:`wait_train_complete`\n\n This method returns the list of trained model identifiers. It returns models that have been trained for this train\n session, not all trained models for this ML task. To get all identifiers for all models trained across all training sessions,\n use :meth:`get_trained_models_ids`\n\n These identifiers can be used for :meth:`get_trained_model_snippet`, :meth:`get_trained_model_details` and :meth:`deploy_to_flow`\n\n :return: A list of model identifiers\n :rtype: list of strings\n \"\"\"\n train_ret = self.start_train(session_name, session_description)\n self.wait_train_complete()\n return self.get_trained_models_ids(session_id = train_ret[\"sessionId\"])\n\n def ensemble(self, model_ids=[], method=None):\n \"\"\"\n Create an ensemble model of a set of models\n \n :param list model_ids: A list of model identifiers\n :param str method: the ensembling method. One of: AVERAGE, PROBA_AVERAGE, MEDIAN, VOTE, LINEAR_MODEL, LOGISTIC_MODEL\n\n This method waits for the ensemble train to complete. If you want to train asynchronously, use :meth:`start_ensembling` and :meth:`wait_train_complete`\n\n This method returns the identifier of the trained ensemble.\n To get all identifiers for all models trained across all training sessions,\n use :meth:`get_trained_models_ids`\n\n This identifier can be used for :meth:`get_trained_model_snippet`, :meth:`get_trained_model_details` and :meth:`deploy_to_flow`\n\n :return: A model identifier\n :rtype: string\n \"\"\"\n train_ret = self.start_ensembling(model_ids, method)\n self.wait_train_complete()\n return train_ret\n\n\n def start_train(self, session_name=None, session_description=None):\n \"\"\"\n Starts asynchronously a new train session for this ML Task.\n\n :param str session_name: name for the session\n :param str session_description: description for the session\n\n This returns immediately, before train is complete. To wait for train to complete, use ``wait_train_complete()``\n \"\"\"\n session_info = {\n \"sessionName\" : session_name,\n \"sessionDescription\" : session_description\n }\n\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/train\" % (self.project_key, self.analysis_id, self.mltask_id), body=session_info)\n\n\n def start_ensembling(self, model_ids=[], method=None):\n \"\"\"\n Creates asynchronously a new ensemble models of a set of models.\n\n :param list model_ids: A list of model identifiers\n :param str method: the ensembling method (AVERAGE, PROBA_AVERAGE, MEDIAN, VOTE, LINEAR_MODEL, LOGISTIC_MODEL)\n\n This returns immediately, before train is complete. To wait for train to complete, use :meth:`wait_train_complete`\n\n :return: the model identifier of the ensemble\n :rtype: string\n \"\"\"\n ensembling_request = {\n \"method\" : method,\n \"modelsIds\" : model_ids\n }\n\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/ensemble\" % (self.project_key, self.analysis_id, self.mltask_id), body=ensembling_request)['id']\n\n\n def wait_train_complete(self):\n \"\"\"\n Waits for train to be complete (if started with :meth:`start_train`)\n \"\"\"\n while True:\n status = self.get_status()\n if status.get(\"training\", \"???\") == False:\n break\n time.sleep(2)\n\n\n def get_trained_models_ids(self, session_id=None, algorithm=None):\n \"\"\"\n Gets the list of trained model identifiers for this ML task.\n\n These identifiers can be used for :meth:`get_trained_model_snippet` and :meth:`deploy_to_flow`\n\n :return: A list of model identifiers\n :rtype: list of strings\n \"\"\"\n full_model_ids = self.get_status()[\"fullModelIds\"]\n if session_id is not None:\n full_model_ids = [fmi for fmi in full_model_ids if fmi.get('fullModelId', {}).get('sessionId', '') == session_id]\n model_ids = [x[\"id\"] for x in full_model_ids]\n if algorithm is not None:\n # algorithm is in the snippets\n model_ids = [fmi for fmi, s in self.get_trained_model_snippet(ids=model_ids).iteritems() if s.get(\"algorithm\", \"\") == algorithm]\n return model_ids\n\n\n def get_trained_model_snippet(self, id=None, ids=None):\n \"\"\"\n Gets a quick summary of a trained model, as a dict. For complete information and a structured object, use :meth:`get_trained_model_detail`\n\n :param str id: a model id\n :param list ids: a list of model ids\n\n :rtype: dict\n \"\"\"\n if id is not None:\n obj = {\n \"modelsIds\" : [id]\n }\n elif ids is not None:\n obj = {\n \"modelsIds\" : ids\n }\n else:\n obj = {}\n\n ret = self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models-snippets\" % (self.project_key, self.analysis_id, self.mltask_id),\n body = obj)\n if id is not None:\n return ret[id]\n else:\n return ret\n\n def get_trained_model_details(self, id):\n \"\"\"\n Gets details for a trained model\n \n :param str id: Identifier of the trained model, as returned by :meth:`get_trained_models_ids`\n\n :return: A :class:`DSSTrainedPredictionModelDetails` or :class:`DSSTrainedClusteringModelDetails` representing the details of this trained model id\n :rtype: :class:`DSSTrainedPredictionModelDetails` or :class:`DSSTrainedClusteringModelDetails`\n \"\"\"\n ret = self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/details\" % (self.project_key, self.analysis_id, self.mltask_id,id))\n snippet = self.get_trained_model_snippet(id)\n\n if \"facts\" in ret:\n return DSSTrainedClusteringModelDetails(ret, snippet, mltask=self, mltask_model_id=id)\n else:\n return DSSTrainedPredictionModelDetails(ret, snippet, mltask=self, mltask_model_id=id)\n\n def deploy_to_flow(self, model_id, model_name, train_dataset, test_dataset=None, redo_optimization=True):\n \"\"\"\n Deploys a trained model from this ML Task to a saved model + train recipe in the Flow.\n\n :param str model_id: Model identifier, as returned by :meth:`get_trained_models_ids`\n :param str model_name: Name of the saved model to deploy in the Flow\n :param str train_dataset: Name of the dataset to use as train set. May either be a short name or a PROJECT.name long name (when using a shared dataset)\n :param str test_dataset: Name of the dataset to use as test set. If null, split will be applied to the train set. May either be a short name or a PROJECT.name long name (when using a shared dataset). Only for PREDICTION tasks\n :param bool redo_optimization: Should the hyperparameters optimization phase be done ? Defaults to True. Only for PREDICTION tasks\n :return: A dict containing: \"savedModelId\" and \"trainRecipeName\" - Both can be used to obtain further handles\n :rtype: dict\n \"\"\"\n obj = {\n \"trainDatasetRef\" : train_dataset,\n \"testDatasetRef\" : test_dataset,\n \"modelName\" : model_name,\n \"redoOptimization\": redo_optimization\n }\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/models/%s/actions/deployToFlow\" % (self.project_key, self.analysis_id, self.mltask_id, model_id),\n body = obj)\n\n\n def redeploy_to_flow(self, model_id, recipe_name=None, saved_model_id=None, activate=True):\n \"\"\"\n Redeploys a trained model from this ML Task to a saved model + train recipe in the Flow. Either \n recipe_name of saved_model_id need to be specified\n\n :param str model_id: Model identifier, as returned by :meth:`get_trained_models_ids`\n :param str recipe_name: Name of the training recipe to update\n :param str saved_model_id: Name of the saved model to update\n :param bool activate: Should the deployed model version become the active version \n :return: A dict containing: \"impactsDownstream\" - whether the active version changed and downstream recipes are impacted \n :rtype: dict\n \"\"\"\n obj = {\n \"recipeName\" : recipe_name,\n \"savedModelId\" : saved_model_id,\n \"activate\" : activate\n }\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/models/%s/actions/redeployToFlow\" % (self.project_key, self.analysis_id, self.mltask_id, model_id),\n body = obj)\n\n","sub_path":"dataikuapi/dss/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":39424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"270122650","text":"'''\r\nCreated on Jan 30, 2015\r\n\r\n@author: Jeremy\r\n'''\r\n\r\nimport pygame\r\nimport sys\r\nfrom random import randint, choice\r\n\r\n\r\nfrom Player import Player\r\nfrom Food import Food\r\n\r\nclass Game(object):\r\n def __init__(self, screen):\r\n clock = pygame.time.Clock()\r\n self.foodGroup = pygame.sprite.Group()\r\n self.initFood()\r\n self.player = Player()\r\n \r\n\r\n while True:\r\n dt = clock.tick(60)\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit(0)\r\n if event.type == pygame.KEYDOWN:\r\n if self.player.keydown(event):\r\n continue\r\n elif event.type == pygame.KEYUP:\r\n if self.player.keyup(event):\r\n continue\r\n\r\n self.player.update(dt / 1000.0)\r\n self.foodGroup.update(dt / 1000.0)\r\n screen.fill((200, 200, 200))\r\n self.foodGroup.draw(screen)\r\n self.player.draw(screen)\r\n pygame.display.flip()\r\n \r\n def initFood(self):\r\n for x in range(0, 100):\r\n xDir = choice((-1, 1))\r\n yDir = choice((-1, 1))\r\n self.foodGroup.add(Food(randint(4, 16), randint(40, 600), randint(40, 400), randint(60, 100)*xDir, randint(60, 100)*yDir, 640, 480, randint(1, 255), randint(1, 255), randint(1, 255), self.foodGroup))\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n pygame.init()\r\n pygame.display.set_caption(\"Cube Man\")\r\n screen = pygame.display.set_mode((640,480))\r\n Game(screen)\r\n \r\n\r\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"274956743","text":"from flask_restful import Resource, abort, reqparse\nfrom flask import request, jsonify\nfrom services.statistics import app\nfrom services.statistics.repository.statistics_repository import StatisticsRepository\nimport jsonpickle\nfrom services.statistics.security.security import *\n\nrepo = StatisticsRepository()\nparser = reqparse.RequestParser()\nparser.add_argument(\"type\", type=str)\n\n\nclass StatisticsResource(Resource):\n def get(self):\n if 'token' in request.cookies:\n result = check_if_current_user_is_privileged()\n if result:\n args = parser.parse_args(strict=True)\n if 'type' not in args:\n response = app.make_response(\"Тип возвращаемой статистики не задан\")\n response.status_code = 400\n return response\n stat = repo.get_by_type(args['type'])\n payload = jsonpickle.encode(stat)\n response = app.make_response()\n response.data = payload\n return response\n else:\n response = app.make_response(\"Недостаточные привилегии для данного запроса\")\n response.status_code = 403\n return response\n response = app.make_response(\"Не предоставлен токен при совершении запроса\")\n response.status_code = 403\n return response\n\n def post(self):\n if 'token' in request.cookies:\n result = check_value(current_config.TRUSTED_SERVICE)\n if result:\n payload = jsonpickle.decode(flask.request.data)\n repo.create(payload[\"type\"], payload[\"data\"])\n response = app.make_response(\"OK\")\n response.status_code = 200\n return response\n else:\n response = app.make_response(\"Предоставленный токен не является валидным\")\n response.status_code = 403\n return response\n response = app.make_response(\"Не предоставлен токен при совершении запроса\")\n response.status_code = 403\n return response\n\n","sub_path":"services/statistics/rest_api/statistics_resource.py","file_name":"statistics_resource.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"298791060","text":"import os\nimport sys\nimport unittest\nimport doctest\nimport django\n\nBASE_PATH = os.path.dirname(__file__)\n\ndef main(db_engine='sqlite3'):\n \"\"\"\n Standalone django model test with a 'memory-only-django-installation'.\n You can play with a django model without a complete django app installation.\n http://www.djangosnippets.org/snippets/1044/\n \"\"\"\n os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"django.conf.global_settings\"\n from django.conf import global_settings\n\n global_settings.INSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'jsonfield',\n )\n global_settings.DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.%s' % db_engine,\n 'NAME': 'django-jsonfield',\n }\n } \n\n global_settings.STATIC_URL = \"/static/\"\n global_settings.MEDIA_ROOT = os.path.join(BASE_PATH, 'static')\n global_settings.STATIC_ROOT = global_settings.MEDIA_ROOT\n \n global_settings.SECRET_KEY = '334ebe58-a77d-4321-9d01-a7d2cb8d3eea'\n from django.test.utils import get_runner\n test_runner = get_runner(global_settings)\n\n test_runner = test_runner()\n \n if getattr(django, 'setup', None):\n django.setup()\n \n failures = test_runner.run_tests(['jsonfield'])\n \n sys.exit(failures)\n\ndef test_postgres():\n main('postgresql_psycopg2')\n\nif __name__ == '__main__':\n main()\n","sub_path":"packages/django-jsonfield/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"66662136","text":"import sys\nimport tensorflow as tf\nimport pandas as pd\nfrom sklearn.model_selection import KFold\n\n\ndef tf_model():\n model = tf.keras.models.Sequential()\n model.add(tf.keras.layers.Dense(\n 50, input_shape=(2304,), activation='relu'))\n model.add(tf.keras.layers.Dense(128, activation='sigmoid'))\n model.add(tf.keras.layers.Dense(10, activation='softmax'))\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n return model\n\n\ntrain = pd.read_csv(\n '../data/train/x_train_gr_smpl_normalized.csv').values / 255.0\ntrain_labels = pd.read_csv('../data/train/y_train_smpl.csv').values.ravel()\n\nif sys.argv[1] == '-kfold': # 10 fold validation\n print('USING 10 FOLD CROSSVALIDATION')\n for train_index, test_index in KFold(10).split(train):\n x_train, x_test = train[train_index], train[test_index]\n y_train, y_test = train_labels[train_index], train_labels[test_index]\n\n model = tf_model()\n model.fit(x_train, y_train, epochs=5)\n\n test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)\n print('Test loss:', test_loss)\n print('Test accuracy:', test_accuracy)\nelif sys.argv[1] == '-testset': # Using test set\n print('USING TEST SETS')\n test = pd.read_csv(\n '../data/test/x_test_gr_smpl_normalized.csv').values / 255.0\n test_labels = pd.read_csv('../data/test/y_test_smpl.csv').values.ravel()\n model = tf.keras.models.Sequential()\n model.add(tf.keras.layers.Dense(\n 2304, input_shape=(2304,), activation='relu'))\n model.add(tf.keras.layers.Dense(128, activation='sigmoid'))\n model.add(tf.keras.layers.Dense(10, activation='softmax'))\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n print(model.summary())\n model.fit(train, train_labels, epochs=5)\n test_loss, test_accuracy = model.evaluate(test, test_labels, verbose=2)\n print('Test loss:', test_loss)\n print('Test accuracy:', test_accuracy)\nelse:\n print('Invalid arguments.')\n print('Launch script with \"-kfold\" or \"-testset\"')\n","sub_path":"scripts/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"530554279","text":"import nltk\n\n# chunking tecnica base per entity detection, la quale segmenta e etchetta\n# multi toke in una frase\n\n# data una sentence con i rispettivi POS tag\n# si è costruita una grammatica molto semplice per ricavare i NP\n# che sono i Noun Phrase\ndef nounPhraseChunking(sentence):\n\n #print(sentences)\n\n # divide ogni frase in word_token\n\n tokenized_sentences = nltk.word_tokenize(sentence)\n tagged_sentences =nltk.pos_tag( tokenized_sentences)\n print(tagged_sentences)\n\n # define a simple grammar, di come è fatto NP\n # NP è formato da
opzionale o un pronome possessivo\n # più aggettivi quanti se ne vuole edopo un nome oppure un pronome --> indica I ,he\n # la seconda indica uno o più nomi propri di persona\n\n grammar = \"\"\" NP: {?*|}\n {+}\n VP: {?*}\"\"\"\n\n # creiamo un chunck parse seguendo questa grammatica\n cp = nltk.RegexpParser(grammar)\n\n # per funzionare la frase deve essere una sola!!\n result = cp.parse(tagged_sentences)\n # per l'albero sintattico trovato ispezioniamo tutti i sottoalberi\n # e stampiano solo quelli con NP\n for subtree in result.subtrees():\n if subtree.label() == \"NP\": print(subtree)\n\n # stampa l'albero\n print(result)\n # stampa l'albero graficamnete\n result.draw()\n\n\n# divide ogni frase in word_token\nnounPhraseChunking(\"he is buy a big little elephant \")\n","sub_path":"grammarRegularExpressionChunking.py","file_name":"grammarRegularExpressionChunking.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"303226876","text":"\"\"\"\n8008 CPU\n\"\"\"\n\n\nfrom collections import deque\nfrom .byte import byte\nfrom .instructions import INSTRUCTIONS\nfrom .memory import Memory\n\n\nclass CPU:\n \"\"\"\n 8008 CPU\n \"\"\"\n\n # Register M\n\n @property\n def rm(self):\n \"\"\"\n Register M\n\n This is a virtual register pointing directly to memory.\n \"\"\"\n\n return self.memory[int((self.rh<<8) + self.rl)]\n\n @rm.setter\n def rm(self, value):\n \"\"\"\n Set the Register M\n \"\"\"\n\n self.memory[int((self.rh<<8) + self.rl)] = value\n\n # Program position pointer\n\n @property\n def pos(self):\n \"\"\"\n Program memory pointer\n :return:\n \"\"\"\n\n return self._pos\n\n @pos.setter\n def pos(self, value):\n \"\"\"\n Set the position to the designated value\n :param value:\n :return:\n \"\"\"\n\n self._pos = value % (1<<14)\n\n # Initialisation\n\n def __init__(self):\n \"\"\"\n Initialise the CPU\n \"\"\"\n\n # Loading the instructions\n self.instructions = {}\n for opcode in INSTRUCTIONS:\n self.instructions[opcode] = INSTRUCTIONS[opcode](self)\n\n # Run Method\n\n def start(self):\n \"\"\"\n Start the CPU\n :return:\n \"\"\"\n\n # Initialise registers\n self.ra = byte(0)\n self.rb = byte(0)\n self.rc = byte(0)\n self.rd = byte(0)\n self.re = byte(0)\n self.rh = byte(0)\n self.rl = byte(0)\n\n # Initialise flags\n self.fc = byte(0)\n self.fs = byte(0)\n self.fz = byte(0)\n self.fp = byte(0)\n\n # Create the memory\n self.memory = Memory()\n\n # Set the program memory pointer address\n self.pos = 0\n\n # Initialise the stack\n\n self.stack = deque(maxlen=7)\n\n # Set the CPU as not halted\n self.halted = False\n\n def run(self, program):\n \"\"\"\n Run a program\n :param data:\n :return:\n \"\"\"\n\n # Reset the CPU\n self.start()\n\n # Load the program in memory\n for i in range(0, len(program)):\n self.memory[i] = program[i]\n\n # Main loop\n while not self.halted:\n # PCI state\n opcode = self.memory[self.pos]\n self.pos += 1\n instruction = self.instructions[opcode]\n\n # PCR state\n data = []\n for i in range(1, instruction.length):\n data.append(self.memory[self.pos])\n self.pos += 1\n\n # PCC/PCW state\n instruction.run(opcode, *data)","sub_path":"src/eighty/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"372394215","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\n\nfrom rest_framework import routers\n\nfrom apps.api.views import ItemViewSet, TagViewSet, CategoryViewSet, RecipientViewSet, \\\n OccasionViewSet, StoreViewSet, LikeViewSet, find_gift, tester, backup\n\nadmin.autodiscover()\n\nrouter = routers.DefaultRouter()\nrouter.register(r'items', ItemViewSet)\nrouter.register(r'tags', TagViewSet)\nrouter.register(r'categories', CategoryViewSet)\nrouter.register(r'recipients', RecipientViewSet)\nrouter.register(r'occasions', OccasionViewSet)\nrouter.register(r'stores', StoreViewSet)\nrouter.register(r'likes', LikeViewSet)\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'presentpicker.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^api/1.0/', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n\n url(r'^api/find_gift/$', find_gift),\n url(r'^yedekle/$', backup),\n\n url(r'^runtests/$', tester),\n\n # custom\n url(r'^accounts/', include('apps.profiles.urls')),\n\n # static\n url(r'^$', TemplateView.as_view(template_name=\"index.html\"), name=\"index\"),\n)\n","sub_path":"giftfinder/giftfinder/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"361546141","text":"import sqlite3\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\ndb = sqlite3.connect(\"STC_DB.db\")\ncursor = db.cursor()\n\ntry:\n \n cursor.execute(\"CREATE TABLE USER(password varchar(15))\")\n print(\"user table create sucessfull!\")\n db.commit()\n\nexcept:\n print(\"User Table already added!\")\n\n\n\ntry:\n cursor.execute(\"\"\"CREATE TABLE teacher(first_name varchar(20),\n full_name varchar(50),\n NIC_NO varchar(12),\n Date_Of_Birth varchar(20),\n Addmision_date varchar(20),\n Address varchar(50),\n Contacts int(26),\n email varchar(40))\"\"\")\n print(\"teachers table create sucessfull!\")\n \n db.commit()\nexcept:\n print(\"teacher table already added!\")\n\n\n\ntry: \n cursor.execute(\"\"\"CREATE TABLE STUDENTS( full_name varchar(50),\n NIC_NO varchar(12),\n Date_of_birth varchar(20),\n Addmission_no int(6),\n Addmited_date varchar(20),\n Address varchar(40),\n Contacts int(30),\n p_name varchar(50))\"\"\")\n print(\"students table create sucessfull!!\")\n db.commit()\n\nexcept:\n print(\"student table already added!\")\ndb.close()\n\nclass Ui_Form(object):\n def savet(self):\n db = sqlite3.connect(\"STC_DB.db\")\n cursor = db.cursor()\n a = self.lineEdit.text()\n b = self.lineEdit_13.text()\n c = self.lineEdit_16.text()\n d = self.dateEdit_5.text()\n e = self.dateEdit_6.text()\n f = self.lineEdit_17.text()\n g = self.lineEdit_18.text()\n h = self.lineEdit_19.text()\n try:\n sql = (\"\"\"INSERT INTO teacher(first_name,\n full_name,\n NIC_NO,\n Date_Of_Birth,\n Addmision_date,\n Address,\n Contacts,\n email)values(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")\"\"\"%(a,b,c,d,e,f,g,h))\n results = cursor.execute(\"select*from teacher\")\n \n data = results.fetchall()\n \n for row in data:\n d1 = row[0]\n d2 = row[2]\n if d1==a or d2==c:\n print(\"This name or NIC_No already added!try another member..\")\n elif d1!=a or d2!=c:\n cursor.execute(sql)\n print(\"data saved sucessfully!\")\n db.commit()\n except:\n print(\"Something went wrong!!\")\n db.close()\n\n def savest(self):\n db = sqlite3.connect(\"STC_DB.db\")\n cursor = db.cursor()\n \n i = self.fname.text()\n j = self.lineEdit_3.text()\n k = self.dateEdit_2.text()\n l = self.lineEdit_4.text()\n m = self.dateEdit.text()\n n = self.lineEdit_6.text()\n o = self.lineEdit_7.text()\n p = self.lineEdit_8.text()\n\n print(i,j,k,l,m,n,o,p)\n \n try:\n sql = (\"\"\"INSERT INTO STUDENTS(full_name,\n NIC_NO,\n Date_of_birth,\n Addmission_no,\n Addmited_date,\n Address,\n Contacts,\n p_name)values(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\") \"\"\"%(i,j,k,l,m,n,o,p))\n \n results = cursor.execute(\"select*from STUDENTS\")\n \n data = results.fetchall()\n \n for row in data:\n d1 = row[4]\n \n if d1==l:\n print(\"This name or NIC_No already added!try another member..\")\n else:\n cursor.execute(sql)\n print(\"data saved sucessfully!\")\n db.commit()\n except:\n print(\"Something went wrong!!\")\n db.close()\n \n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8(\"Form\"))\n Form.resize(1044, 671)\n self.verticalLayout = QtGui.QVBoxLayout(Form)\n self.verticalLayout.setObjectName(_fromUtf8(\"verticalLayout\"))\n self.gridLayout = QtGui.QGridLayout()\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.gridLayout.setContentsMargins(-1, 0, -1, -1)\n self.gridLayout.setObjectName(_fromUtf8(\"gridLayout\"))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setMinimumSize(QtCore.QSize(0, 50))\n self.label_3.setMaximumSize(QtCore.QSize(16777215, 50))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Old English Text MT\"))\n font.setPointSize(36)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.gridLayout.addWidget(self.label_3, 0, 2, 1, 1)\n self.label = QtGui.QLabel(Form)\n self.label.setMinimumSize(QtCore.QSize(120, 120))\n self.label.setMaximumSize(QtCore.QSize(120, 120))\n self.label.setLayoutDirection(QtCore.Qt.RightToLeft)\n self.label.setStyleSheet(_fromUtf8(\"image: url(:/newPrefix/stc.png);\"))\n self.label.setText(_fromUtf8(\"\"))\n self.label.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.gridLayout.addWidget(self.label, 0, 0, 1, 1)\n spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)\n self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)\n self.label_42 = QtGui.QLabel(Form)\n font = QtGui.QFont()\n font.setPointSize(14)\n self.label_42.setFont(font)\n self.label_42.setText(_fromUtf8(\"\"))\n self.label_42.setObjectName(_fromUtf8(\"label_42\"))\n self.gridLayout.addWidget(self.label_42, 0, 3, 1, 1)\n self.verticalLayout.addLayout(self.gridLayout)\n self.tabWidget = QtGui.QTabWidget(Form)\n self.tabWidget.setObjectName(_fromUtf8(\"tabWidget\"))\n self.tab = QtGui.QWidget()\n self.tab.setObjectName(_fromUtf8(\"tab\"))\n self.gridLayout_3 = QtGui.QGridLayout(self.tab)\n self.gridLayout_3.setObjectName(_fromUtf8(\"gridLayout_3\"))\n self.tabWidget_3 = QtGui.QTabWidget(self.tab)\n self.tabWidget_3.setObjectName(_fromUtf8(\"tabWidget_3\"))\n self.tab_5 = QtGui.QWidget()\n self.tab_5.setObjectName(_fromUtf8(\"tab_5\"))\n self.gridLayout_8 = QtGui.QGridLayout(self.tab_5)\n self.gridLayout_8.setObjectName(_fromUtf8(\"gridLayout_8\"))\n self.lineEdit_17 = QtGui.QLineEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_17.setFont(font)\n self.lineEdit_17.setObjectName(_fromUtf8(\"lineEdit_17\"))\n self.gridLayout_8.addWidget(self.lineEdit_17, 5, 3, 1, 1)\n self.lineEdit = QtGui.QLineEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit.setFont(font)\n self.lineEdit.setObjectName(_fromUtf8(\"lineEdit\"))\n self.gridLayout_8.addWidget(self.lineEdit, 0, 3, 1, 1)\n self.label_2 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.gridLayout_8.addWidget(self.label_2, 0, 0, 1, 1)\n self.label_19 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_19.setFont(font)\n self.label_19.setObjectName(_fromUtf8(\"label_19\"))\n self.gridLayout_8.addWidget(self.label_19, 1, 0, 1, 1)\n self.dateEdit_5 = QtGui.QDateEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_5.setFont(font)\n self.dateEdit_5.setObjectName(_fromUtf8(\"dateEdit_5\"))\n self.gridLayout_8.addWidget(self.dateEdit_5, 3, 3, 1, 1)\n self.lineEdit_13 = QtGui.QLineEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_13.setFont(font)\n self.lineEdit_13.setObjectName(_fromUtf8(\"lineEdit_13\"))\n self.gridLayout_8.addWidget(self.lineEdit_13, 1, 3, 1, 1)\n self.label_25 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_25.setFont(font)\n self.label_25.setObjectName(_fromUtf8(\"label_25\"))\n self.gridLayout_8.addWidget(self.label_25, 5, 0, 1, 1)\n self.lineEdit_18 = QtGui.QLineEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_18.setFont(font)\n self.lineEdit_18.setObjectName(_fromUtf8(\"lineEdit_18\"))\n self.gridLayout_8.addWidget(self.lineEdit_18, 6, 3, 1, 1)\n self.line_19 = QtGui.QFrame(self.tab_5)\n self.line_19.setFrameShape(QtGui.QFrame.VLine)\n self.line_19.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_19.setObjectName(_fromUtf8(\"line_19\"))\n self.gridLayout_8.addWidget(self.line_19, 2, 1, 1, 1)\n self.lineEdit_16 = QtGui.QLineEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_16.setFont(font)\n self.lineEdit_16.setObjectName(_fromUtf8(\"lineEdit_16\"))\n self.gridLayout_8.addWidget(self.lineEdit_16, 2, 3, 1, 1)\n self.label_26 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_26.setFont(font)\n self.label_26.setObjectName(_fromUtf8(\"label_26\"))\n self.gridLayout_8.addWidget(self.label_26, 6, 0, 1, 1)\n self.label_23 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_23.setFont(font)\n self.label_23.setObjectName(_fromUtf8(\"label_23\"))\n self.gridLayout_8.addWidget(self.label_23, 3, 0, 1, 1)\n self.label_22 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_22.setFont(font)\n self.label_22.setObjectName(_fromUtf8(\"label_22\"))\n self.gridLayout_8.addWidget(self.label_22, 2, 0, 1, 1)\n self.line = QtGui.QFrame(self.tab_5)\n self.line.setFrameShape(QtGui.QFrame.VLine)\n self.line.setFrameShadow(QtGui.QFrame.Sunken)\n self.line.setObjectName(_fromUtf8(\"line\"))\n self.gridLayout_8.addWidget(self.line, 0, 1, 1, 1)\n self.line_20 = QtGui.QFrame(self.tab_5)\n self.line_20.setFrameShape(QtGui.QFrame.VLine)\n self.line_20.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_20.setObjectName(_fromUtf8(\"line_20\"))\n self.gridLayout_8.addWidget(self.line_20, 3, 1, 1, 1)\n self.dateEdit_6 = QtGui.QDateEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_6.setFont(font)\n self.dateEdit_6.setObjectName(_fromUtf8(\"dateEdit_6\"))\n self.gridLayout_8.addWidget(self.dateEdit_6, 4, 3, 1, 1)\n self.line_11 = QtGui.QFrame(self.tab_5)\n self.line_11.setFrameShape(QtGui.QFrame.VLine)\n self.line_11.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_11.setObjectName(_fromUtf8(\"line_11\"))\n self.gridLayout_8.addWidget(self.line_11, 1, 1, 1, 1)\n self.line_21 = QtGui.QFrame(self.tab_5)\n self.line_21.setFrameShape(QtGui.QFrame.VLine)\n self.line_21.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_21.setObjectName(_fromUtf8(\"line_21\"))\n self.gridLayout_8.addWidget(self.line_21, 4, 1, 1, 1)\n self.label_24 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_24.setFont(font)\n self.label_24.setObjectName(_fromUtf8(\"label_24\"))\n self.gridLayout_8.addWidget(self.label_24, 4, 0, 1, 1)\n self.line_23 = QtGui.QFrame(self.tab_5)\n self.line_23.setFrameShape(QtGui.QFrame.VLine)\n self.line_23.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_23.setObjectName(_fromUtf8(\"line_23\"))\n self.gridLayout_8.addWidget(self.line_23, 6, 1, 1, 1)\n self.line_22 = QtGui.QFrame(self.tab_5)\n self.line_22.setFrameShape(QtGui.QFrame.VLine)\n self.line_22.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_22.setObjectName(_fromUtf8(\"line_22\"))\n self.gridLayout_8.addWidget(self.line_22, 5, 1, 1, 1)\n self.horizontalLayout_4 = QtGui.QHBoxLayout()\n self.horizontalLayout_4.setObjectName(_fromUtf8(\"horizontalLayout_4\"))\n self.pushButton_11 = QtGui.QPushButton(self.tab_5)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/delete.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_11.setIcon(icon)\n self.pushButton_11.setObjectName(_fromUtf8(\"pushButton_11\"))\n self.horizontalLayout_4.addWidget(self.pushButton_11)\n spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_4.addItem(spacerItem1)\n self.pushButton_5 = QtGui.QPushButton(self.tab_5)\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/save.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_5.setIcon(icon1)\n self.pushButton_5.setObjectName(_fromUtf8(\"pushButton_5\"))\n self.horizontalLayout_4.addWidget(self.pushButton_5)\n self.gridLayout_8.addLayout(self.horizontalLayout_4, 8, 3, 1, 1)\n self.label_27 = QtGui.QLabel(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_27.setFont(font)\n self.label_27.setObjectName(_fromUtf8(\"label_27\"))\n self.gridLayout_8.addWidget(self.label_27, 7, 0, 1, 1)\n self.line_24 = QtGui.QFrame(self.tab_5)\n self.line_24.setFrameShape(QtGui.QFrame.VLine)\n self.line_24.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_24.setObjectName(_fromUtf8(\"line_24\"))\n self.gridLayout_8.addWidget(self.line_24, 7, 1, 1, 1)\n self.lineEdit_19 = QtGui.QLineEdit(self.tab_5)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_19.setFont(font)\n self.lineEdit_19.setObjectName(_fromUtf8(\"lineEdit_19\"))\n self.gridLayout_8.addWidget(self.lineEdit_19, 7, 3, 1, 1)\n self.tabWidget_3.addTab(self.tab_5, _fromUtf8(\"\"))\n self.tab_6 = QtGui.QWidget()\n self.tab_6.setObjectName(_fromUtf8(\"tab_6\"))\n self.gridLayout_9 = QtGui.QGridLayout(self.tab_6)\n self.gridLayout_9.setObjectName(_fromUtf8(\"gridLayout_9\"))\n self.teacher = QtGui.QTableWidget(self.tab_6)\n self.teacher.setObjectName(_fromUtf8(\"teacher\"))\n self.teacher.setColumnCount(7)\n self.teacher.setRowCount(0)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(0, item)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(1, item)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(2, item)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(3, item)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(4, item)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(5, item)\n item = QtGui.QTableWidgetItem()\n self.teacher.setHorizontalHeaderItem(6, item)\n self.gridLayout_9.addWidget(self.teacher, 1, 0, 1, 1)\n self.horizontalLayout_5 = QtGui.QHBoxLayout()\n self.horizontalLayout_5.setContentsMargins(-1, 0, -1, -1)\n self.horizontalLayout_5.setObjectName(_fromUtf8(\"horizontalLayout_5\"))\n self.label_28 = QtGui.QLabel(self.tab_6)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_28.setFont(font)\n self.label_28.setObjectName(_fromUtf8(\"label_28\"))\n self.horizontalLayout_5.addWidget(self.label_28)\n self.lineEdit_20 = QtGui.QLineEdit(self.tab_6)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_20.setFont(font)\n self.lineEdit_20.setObjectName(_fromUtf8(\"lineEdit_20\"))\n self.horizontalLayout_5.addWidget(self.lineEdit_20)\n self.pushButton_6 = QtGui.QPushButton(self.tab_6)\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/search.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_6.setIcon(icon2)\n self.pushButton_6.setObjectName(_fromUtf8(\"pushButton_6\"))\n self.horizontalLayout_5.addWidget(self.pushButton_6)\n spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_5.addItem(spacerItem2)\n self.gridLayout_9.addLayout(self.horizontalLayout_5, 0, 0, 1, 1)\n self.tabWidget_3.addTab(self.tab_6, _fromUtf8(\"\"))\n self.tab_7 = QtGui.QWidget()\n self.tab_7.setObjectName(_fromUtf8(\"tab_7\"))\n self.gridLayout_4 = QtGui.QGridLayout(self.tab_7)\n self.gridLayout_4.setObjectName(_fromUtf8(\"gridLayout_4\"))\n self.lineEdit_22 = QtGui.QLineEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_22.setFont(font)\n self.lineEdit_22.setObjectName(_fromUtf8(\"lineEdit_22\"))\n self.gridLayout_4.addWidget(self.lineEdit_22, 1, 2, 1, 1)\n self.lineEdit_24 = QtGui.QLineEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_24.setFont(font)\n self.lineEdit_24.setObjectName(_fromUtf8(\"lineEdit_24\"))\n self.gridLayout_4.addWidget(self.lineEdit_24, 5, 2, 1, 1)\n self.label_31 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_31.setFont(font)\n self.label_31.setObjectName(_fromUtf8(\"label_31\"))\n self.gridLayout_4.addWidget(self.label_31, 2, 0, 1, 1)\n self.line_30 = QtGui.QFrame(self.tab_7)\n self.line_30.setFrameShape(QtGui.QFrame.VLine)\n self.line_30.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_30.setObjectName(_fromUtf8(\"line_30\"))\n self.gridLayout_4.addWidget(self.line_30, 5, 1, 1, 1)\n self.line_28 = QtGui.QFrame(self.tab_7)\n self.line_28.setFrameShape(QtGui.QFrame.VLine)\n self.line_28.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_28.setObjectName(_fromUtf8(\"line_28\"))\n self.gridLayout_4.addWidget(self.line_28, 3, 1, 1, 1)\n self.label_33 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_33.setFont(font)\n self.label_33.setObjectName(_fromUtf8(\"label_33\"))\n self.gridLayout_4.addWidget(self.label_33, 4, 0, 1, 1)\n self.dateEdit_7 = QtGui.QDateEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_7.setFont(font)\n self.dateEdit_7.setObjectName(_fromUtf8(\"dateEdit_7\"))\n self.gridLayout_4.addWidget(self.dateEdit_7, 3, 2, 1, 1)\n self.label_30 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_30.setFont(font)\n self.label_30.setObjectName(_fromUtf8(\"label_30\"))\n self.gridLayout_4.addWidget(self.label_30, 1, 0, 1, 1)\n self.lineEdit_21 = QtGui.QLineEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_21.setFont(font)\n self.lineEdit_21.setObjectName(_fromUtf8(\"lineEdit_21\"))\n self.gridLayout_4.addWidget(self.lineEdit_21, 0, 2, 1, 1)\n self.label_35 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_35.setFont(font)\n self.label_35.setObjectName(_fromUtf8(\"label_35\"))\n self.gridLayout_4.addWidget(self.label_35, 6, 0, 1, 1)\n self.line_29 = QtGui.QFrame(self.tab_7)\n self.line_29.setFrameShape(QtGui.QFrame.VLine)\n self.line_29.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_29.setObjectName(_fromUtf8(\"line_29\"))\n self.gridLayout_4.addWidget(self.line_29, 4, 1, 1, 1)\n self.lineEdit_25 = QtGui.QLineEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_25.setFont(font)\n self.lineEdit_25.setObjectName(_fromUtf8(\"lineEdit_25\"))\n self.gridLayout_4.addWidget(self.lineEdit_25, 6, 2, 1, 1)\n self.dateEdit_8 = QtGui.QDateEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_8.setFont(font)\n self.dateEdit_8.setObjectName(_fromUtf8(\"dateEdit_8\"))\n self.gridLayout_4.addWidget(self.dateEdit_8, 4, 2, 1, 1)\n self.label_29 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_29.setFont(font)\n self.label_29.setObjectName(_fromUtf8(\"label_29\"))\n self.gridLayout_4.addWidget(self.label_29, 0, 0, 1, 1)\n self.line_26 = QtGui.QFrame(self.tab_7)\n self.line_26.setFrameShape(QtGui.QFrame.VLine)\n self.line_26.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_26.setObjectName(_fromUtf8(\"line_26\"))\n self.gridLayout_4.addWidget(self.line_26, 1, 1, 1, 1)\n self.line_27 = QtGui.QFrame(self.tab_7)\n self.line_27.setFrameShape(QtGui.QFrame.VLine)\n self.line_27.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_27.setObjectName(_fromUtf8(\"line_27\"))\n self.gridLayout_4.addWidget(self.line_27, 2, 1, 1, 1)\n self.lineEdit_26 = QtGui.QLineEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_26.setFont(font)\n self.lineEdit_26.setObjectName(_fromUtf8(\"lineEdit_26\"))\n self.gridLayout_4.addWidget(self.lineEdit_26, 7, 2, 1, 1)\n self.line_32 = QtGui.QFrame(self.tab_7)\n self.line_32.setFrameShape(QtGui.QFrame.VLine)\n self.line_32.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_32.setObjectName(_fromUtf8(\"line_32\"))\n self.gridLayout_4.addWidget(self.line_32, 7, 1, 1, 1)\n self.line_31 = QtGui.QFrame(self.tab_7)\n self.line_31.setFrameShape(QtGui.QFrame.VLine)\n self.line_31.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_31.setObjectName(_fromUtf8(\"line_31\"))\n self.gridLayout_4.addWidget(self.line_31, 6, 1, 1, 1)\n self.lineEdit_23 = QtGui.QLineEdit(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_23.setFont(font)\n self.lineEdit_23.setObjectName(_fromUtf8(\"lineEdit_23\"))\n self.gridLayout_4.addWidget(self.lineEdit_23, 2, 2, 1, 1)\n self.label_34 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_34.setFont(font)\n self.label_34.setObjectName(_fromUtf8(\"label_34\"))\n self.gridLayout_4.addWidget(self.label_34, 5, 0, 1, 1)\n self.label_36 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_36.setFont(font)\n self.label_36.setObjectName(_fromUtf8(\"label_36\"))\n self.gridLayout_4.addWidget(self.label_36, 7, 0, 1, 1)\n self.label_32 = QtGui.QLabel(self.tab_7)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_32.setFont(font)\n self.label_32.setObjectName(_fromUtf8(\"label_32\"))\n self.gridLayout_4.addWidget(self.label_32, 3, 0, 1, 1)\n self.line_25 = QtGui.QFrame(self.tab_7)\n self.line_25.setFrameShape(QtGui.QFrame.VLine)\n self.line_25.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_25.setObjectName(_fromUtf8(\"line_25\"))\n self.gridLayout_4.addWidget(self.line_25, 0, 1, 1, 1)\n self.horizontalLayout_6 = QtGui.QHBoxLayout()\n self.horizontalLayout_6.setObjectName(_fromUtf8(\"horizontalLayout_6\"))\n self.pushButton_8 = QtGui.QPushButton(self.tab_7)\n self.pushButton_8.setIcon(icon)\n self.pushButton_8.setObjectName(_fromUtf8(\"pushButton_8\"))\n self.horizontalLayout_6.addWidget(self.pushButton_8)\n spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_6.addItem(spacerItem3)\n self.pushButton_7 = QtGui.QPushButton(self.tab_7)\n icon3 = QtGui.QIcon()\n icon3.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/update.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_7.setIcon(icon3)\n self.pushButton_7.setObjectName(_fromUtf8(\"pushButton_7\"))\n self.horizontalLayout_6.addWidget(self.pushButton_7)\n self.gridLayout_4.addLayout(self.horizontalLayout_6, 8, 2, 1, 1)\n self.tabWidget_3.addTab(self.tab_7, _fromUtf8(\"\"))\n self.gridLayout_3.addWidget(self.tabWidget_3, 0, 0, 1, 1)\n icon4 = QtGui.QIcon()\n icon4.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/Teachers.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.tabWidget.addTab(self.tab, icon4, _fromUtf8(\"\"))\n self.tab_2 = QtGui.QWidget()\n self.tab_2.setObjectName(_fromUtf8(\"tab_2\"))\n self.gridLayout_2 = QtGui.QGridLayout(self.tab_2)\n self.gridLayout_2.setObjectName(_fromUtf8(\"gridLayout_2\"))\n self.tabWidget_2 = QtGui.QTabWidget(self.tab_2)\n self.tabWidget_2.setObjectName(_fromUtf8(\"tabWidget_2\"))\n self.tab_3 = QtGui.QWidget()\n self.tab_3.setObjectName(_fromUtf8(\"tab_3\"))\n self.gridLayout_5 = QtGui.QGridLayout(self.tab_3)\n self.gridLayout_5.setObjectName(_fromUtf8(\"gridLayout_5\"))\n self.label_6 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_6.setFont(font)\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.gridLayout_5.addWidget(self.label_6, 2, 0, 1, 1)\n self.label_9 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_9.setFont(font)\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.gridLayout_5.addWidget(self.label_9, 5, 0, 1, 1)\n self.label_5 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_5.setFont(font)\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.gridLayout_5.addWidget(self.label_5, 1, 0, 1, 1)\n self.fname = QtGui.QLineEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.fname.setFont(font)\n self.fname.setObjectName(_fromUtf8(\"fname\"))\n self.gridLayout_5.addWidget(self.fname, 0, 2, 1, 1)\n self.label_4 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_4.setFont(font)\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.gridLayout_5.addWidget(self.label_4, 0, 0, 1, 1)\n self.dateEdit_2 = QtGui.QDateEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_2.setFont(font)\n self.dateEdit_2.setObjectName(_fromUtf8(\"dateEdit_2\"))\n self.gridLayout_5.addWidget(self.dateEdit_2, 2, 2, 1, 1)\n self.label_7 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.gridLayout_5.addWidget(self.label_7, 3, 0, 1, 1)\n self.label_8 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_8.setFont(font)\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.gridLayout_5.addWidget(self.label_8, 4, 0, 1, 1)\n self.lineEdit_4 = QtGui.QLineEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_4.setFont(font)\n self.lineEdit_4.setObjectName(_fromUtf8(\"lineEdit_4\"))\n self.gridLayout_5.addWidget(self.lineEdit_4, 3, 2, 1, 1)\n self.dateEdit = QtGui.QDateEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit.setFont(font)\n self.dateEdit.setObjectName(_fromUtf8(\"dateEdit\"))\n self.gridLayout_5.addWidget(self.dateEdit, 4, 2, 1, 1)\n self.lineEdit_6 = QtGui.QLineEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_6.setFont(font)\n self.lineEdit_6.setObjectName(_fromUtf8(\"lineEdit_6\"))\n self.gridLayout_5.addWidget(self.lineEdit_6, 5, 2, 1, 1)\n self.lineEdit_3 = QtGui.QLineEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_3.setFont(font)\n self.lineEdit_3.setObjectName(_fromUtf8(\"lineEdit_3\"))\n self.gridLayout_5.addWidget(self.lineEdit_3, 1, 2, 1, 1)\n self.lineEdit_7 = QtGui.QLineEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_7.setFont(font)\n self.lineEdit_7.setObjectName(_fromUtf8(\"lineEdit_7\"))\n self.gridLayout_5.addWidget(self.lineEdit_7, 6, 2, 1, 1)\n self.line_2 = QtGui.QFrame(self.tab_3)\n self.line_2.setFrameShape(QtGui.QFrame.VLine)\n self.line_2.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_2.setObjectName(_fromUtf8(\"line_2\"))\n self.gridLayout_5.addWidget(self.line_2, 0, 1, 1, 1)\n self.label_11 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.gridLayout_5.addWidget(self.label_11, 7, 0, 1, 1)\n self.line_3 = QtGui.QFrame(self.tab_3)\n self.line_3.setFrameShape(QtGui.QFrame.VLine)\n self.line_3.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_3.setObjectName(_fromUtf8(\"line_3\"))\n self.gridLayout_5.addWidget(self.line_3, 1, 1, 1, 1)\n self.lineEdit_8 = QtGui.QLineEdit(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_8.setFont(font)\n self.lineEdit_8.setObjectName(_fromUtf8(\"lineEdit_8\"))\n self.gridLayout_5.addWidget(self.lineEdit_8, 7, 2, 1, 1)\n self.label_10 = QtGui.QLabel(self.tab_3)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_10.setFont(font)\n self.label_10.setObjectName(_fromUtf8(\"label_10\"))\n self.gridLayout_5.addWidget(self.label_10, 6, 0, 1, 1)\n self.line_5 = QtGui.QFrame(self.tab_3)\n self.line_5.setFrameShape(QtGui.QFrame.VLine)\n self.line_5.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_5.setObjectName(_fromUtf8(\"line_5\"))\n self.gridLayout_5.addWidget(self.line_5, 3, 1, 1, 1)\n self.line_9 = QtGui.QFrame(self.tab_3)\n self.line_9.setFrameShape(QtGui.QFrame.VLine)\n self.line_9.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_9.setObjectName(_fromUtf8(\"line_9\"))\n self.gridLayout_5.addWidget(self.line_9, 7, 1, 1, 1)\n self.line_6 = QtGui.QFrame(self.tab_3)\n self.line_6.setFrameShape(QtGui.QFrame.VLine)\n self.line_6.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_6.setObjectName(_fromUtf8(\"line_6\"))\n self.gridLayout_5.addWidget(self.line_6, 4, 1, 1, 1)\n self.line_8 = QtGui.QFrame(self.tab_3)\n self.line_8.setFrameShape(QtGui.QFrame.VLine)\n self.line_8.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_8.setObjectName(_fromUtf8(\"line_8\"))\n self.gridLayout_5.addWidget(self.line_8, 6, 1, 1, 1)\n self.line_4 = QtGui.QFrame(self.tab_3)\n self.line_4.setFrameShape(QtGui.QFrame.VLine)\n self.line_4.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_4.setObjectName(_fromUtf8(\"line_4\"))\n self.gridLayout_5.addWidget(self.line_4, 2, 1, 1, 1)\n self.line_7 = QtGui.QFrame(self.tab_3)\n self.line_7.setFrameShape(QtGui.QFrame.VLine)\n self.line_7.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_7.setObjectName(_fromUtf8(\"line_7\"))\n self.gridLayout_5.addWidget(self.line_7, 5, 1, 1, 1)\n self.horizontalLayout = QtGui.QHBoxLayout()\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.pushButton_12 = QtGui.QPushButton(self.tab_3)\n self.pushButton_12.setIcon(icon)\n self.pushButton_12.setObjectName(_fromUtf8(\"pushButton_12\"))\n self.horizontalLayout.addWidget(self.pushButton_12)\n spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacerItem4)\n self.pushButton = QtGui.QPushButton(self.tab_3)\n self.pushButton.setIcon(icon1)\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.horizontalLayout.addWidget(self.pushButton)\n self.gridLayout_5.addLayout(self.horizontalLayout, 8, 2, 1, 1)\n self.tabWidget_2.addTab(self.tab_3, _fromUtf8(\"\"))\n self.tab_8 = QtGui.QWidget()\n self.tab_8.setObjectName(_fromUtf8(\"tab_8\"))\n self.gridLayout_6 = QtGui.QGridLayout(self.tab_8)\n self.gridLayout_6.setObjectName(_fromUtf8(\"gridLayout_6\"))\n self.student = QtGui.QTableWidget(self.tab_8)\n self.student.setObjectName(_fromUtf8(\"student\"))\n self.student.setColumnCount(9)\n self.student.setRowCount(0)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(0, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(1, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(2, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(3, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(4, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(5, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(6, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(7, item)\n item = QtGui.QTableWidgetItem()\n self.student.setHorizontalHeaderItem(8, item)\n self.gridLayout_6.addWidget(self.student, 1, 0, 1, 1)\n self.horizontalLayout_2 = QtGui.QHBoxLayout()\n self.horizontalLayout_2.setContentsMargins(-1, 0, -1, -1)\n self.horizontalLayout_2.setObjectName(_fromUtf8(\"horizontalLayout_2\"))\n self.label_12 = QtGui.QLabel(self.tab_8)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.horizontalLayout_2.addWidget(self.label_12)\n self.lineEdit_5 = QtGui.QLineEdit(self.tab_8)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_5.setFont(font)\n self.lineEdit_5.setObjectName(_fromUtf8(\"lineEdit_5\"))\n self.horizontalLayout_2.addWidget(self.lineEdit_5)\n self.pushButton_2 = QtGui.QPushButton(self.tab_8)\n self.pushButton_2.setIcon(icon2)\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.horizontalLayout_2.addWidget(self.pushButton_2)\n spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem5)\n self.gridLayout_6.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)\n self.tabWidget_2.addTab(self.tab_8, _fromUtf8(\"\"))\n self.tab_4 = QtGui.QWidget()\n self.tab_4.setObjectName(_fromUtf8(\"tab_4\"))\n self.gridLayout_7 = QtGui.QGridLayout(self.tab_4)\n self.gridLayout_7.setObjectName(_fromUtf8(\"gridLayout_7\"))\n self.lineEdit_12 = QtGui.QLineEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_12.setFont(font)\n self.lineEdit_12.setObjectName(_fromUtf8(\"lineEdit_12\"))\n self.gridLayout_7.addWidget(self.lineEdit_12, 0, 2, 1, 1)\n self.line_18 = QtGui.QFrame(self.tab_4)\n self.line_18.setFrameShape(QtGui.QFrame.VLine)\n self.line_18.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_18.setObjectName(_fromUtf8(\"line_18\"))\n self.gridLayout_7.addWidget(self.line_18, 1, 1, 1, 1)\n self.line_16 = QtGui.QFrame(self.tab_4)\n self.line_16.setFrameShape(QtGui.QFrame.VLine)\n self.line_16.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_16.setObjectName(_fromUtf8(\"line_16\"))\n self.gridLayout_7.addWidget(self.line_16, 2, 1, 1, 1)\n self.line_17 = QtGui.QFrame(self.tab_4)\n self.line_17.setFrameShape(QtGui.QFrame.VLine)\n self.line_17.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_17.setObjectName(_fromUtf8(\"line_17\"))\n self.gridLayout_7.addWidget(self.line_17, 0, 1, 1, 1)\n self.label_14 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_14.setFont(font)\n self.label_14.setObjectName(_fromUtf8(\"label_14\"))\n self.gridLayout_7.addWidget(self.label_14, 1, 0, 1, 1)\n self.dateEdit_4 = QtGui.QDateEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_4.setFont(font)\n self.dateEdit_4.setObjectName(_fromUtf8(\"dateEdit_4\"))\n self.gridLayout_7.addWidget(self.dateEdit_4, 2, 2, 1, 1)\n self.lineEdit_9 = QtGui.QLineEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_9.setFont(font)\n self.lineEdit_9.setObjectName(_fromUtf8(\"lineEdit_9\"))\n self.gridLayout_7.addWidget(self.lineEdit_9, 1, 2, 1, 1)\n self.label_17 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_17.setFont(font)\n self.label_17.setObjectName(_fromUtf8(\"label_17\"))\n self.gridLayout_7.addWidget(self.label_17, 3, 0, 1, 1)\n self.label_21 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_21.setFont(font)\n self.label_21.setObjectName(_fromUtf8(\"label_21\"))\n self.gridLayout_7.addWidget(self.label_21, 0, 0, 1, 1)\n self.label_20 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_20.setFont(font)\n self.label_20.setObjectName(_fromUtf8(\"label_20\"))\n self.gridLayout_7.addWidget(self.label_20, 2, 0, 1, 1)\n self.line_14 = QtGui.QFrame(self.tab_4)\n self.line_14.setFrameShape(QtGui.QFrame.VLine)\n self.line_14.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_14.setObjectName(_fromUtf8(\"line_14\"))\n self.gridLayout_7.addWidget(self.line_14, 3, 1, 1, 1)\n self.lineEdit_14 = QtGui.QLineEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_14.setFont(font)\n self.lineEdit_14.setObjectName(_fromUtf8(\"lineEdit_14\"))\n self.gridLayout_7.addWidget(self.lineEdit_14, 3, 2, 1, 1)\n self.line_10 = QtGui.QFrame(self.tab_4)\n self.line_10.setFrameShape(QtGui.QFrame.VLine)\n self.line_10.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_10.setObjectName(_fromUtf8(\"line_10\"))\n self.gridLayout_7.addWidget(self.line_10, 4, 1, 1, 1)\n self.label_16 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_16.setFont(font)\n self.label_16.setObjectName(_fromUtf8(\"label_16\"))\n self.gridLayout_7.addWidget(self.label_16, 6, 0, 1, 1)\n self.line_13 = QtGui.QFrame(self.tab_4)\n self.line_13.setFrameShape(QtGui.QFrame.VLine)\n self.line_13.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_13.setObjectName(_fromUtf8(\"line_13\"))\n self.gridLayout_7.addWidget(self.line_13, 7, 1, 1, 1)\n self.line_15 = QtGui.QFrame(self.tab_4)\n self.line_15.setFrameShape(QtGui.QFrame.VLine)\n self.line_15.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_15.setObjectName(_fromUtf8(\"line_15\"))\n self.gridLayout_7.addWidget(self.line_15, 5, 1, 1, 1)\n self.line_12 = QtGui.QFrame(self.tab_4)\n self.line_12.setFrameShape(QtGui.QFrame.VLine)\n self.line_12.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_12.setObjectName(_fromUtf8(\"line_12\"))\n self.gridLayout_7.addWidget(self.line_12, 6, 1, 1, 1)\n self.lineEdit_11 = QtGui.QLineEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_11.setFont(font)\n self.lineEdit_11.setObjectName(_fromUtf8(\"lineEdit_11\"))\n self.gridLayout_7.addWidget(self.lineEdit_11, 7, 2, 1, 1)\n self.lineEdit_10 = QtGui.QLineEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_10.setFont(font)\n self.lineEdit_10.setObjectName(_fromUtf8(\"lineEdit_10\"))\n self.gridLayout_7.addWidget(self.lineEdit_10, 5, 2, 1, 1)\n self.label_15 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_15.setFont(font)\n self.label_15.setObjectName(_fromUtf8(\"label_15\"))\n self.gridLayout_7.addWidget(self.label_15, 7, 0, 1, 1)\n self.label_18 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_18.setFont(font)\n self.label_18.setObjectName(_fromUtf8(\"label_18\"))\n self.gridLayout_7.addWidget(self.label_18, 4, 0, 1, 1)\n self.dateEdit_3 = QtGui.QDateEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dateEdit_3.setFont(font)\n self.dateEdit_3.setObjectName(_fromUtf8(\"dateEdit_3\"))\n self.gridLayout_7.addWidget(self.dateEdit_3, 4, 2, 1, 1)\n self.lineEdit_15 = QtGui.QLineEdit(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.lineEdit_15.setFont(font)\n self.lineEdit_15.setObjectName(_fromUtf8(\"lineEdit_15\"))\n self.gridLayout_7.addWidget(self.lineEdit_15, 6, 2, 1, 1)\n self.label_13 = QtGui.QLabel(self.tab_4)\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_13.setFont(font)\n self.label_13.setObjectName(_fromUtf8(\"label_13\"))\n self.gridLayout_7.addWidget(self.label_13, 5, 0, 1, 1)\n self.horizontalLayout_3 = QtGui.QHBoxLayout()\n self.horizontalLayout_3.setObjectName(_fromUtf8(\"horizontalLayout_3\"))\n self.pushButton_4 = QtGui.QPushButton(self.tab_4)\n self.pushButton_4.setIcon(icon)\n self.pushButton_4.setObjectName(_fromUtf8(\"pushButton_4\"))\n self.horizontalLayout_3.addWidget(self.pushButton_4)\n spacerItem6 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem6)\n self.pushButton_3 = QtGui.QPushButton(self.tab_4)\n self.pushButton_3.setIcon(icon3)\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.horizontalLayout_3.addWidget(self.pushButton_3)\n self.gridLayout_7.addLayout(self.horizontalLayout_3, 8, 2, 1, 1)\n self.tabWidget_2.addTab(self.tab_4, _fromUtf8(\"\"))\n self.gridLayout_2.addWidget(self.tabWidget_2, 0, 0, 1, 1)\n icon5 = QtGui.QIcon()\n icon5.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/student-mdl.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.tabWidget.addTab(self.tab_2, icon5, _fromUtf8(\"\"))\n self.tab_9 = QtGui.QWidget()\n self.tab_9.setObjectName(_fromUtf8(\"tab_9\"))\n self.groupBox = QtGui.QGroupBox(self.tab_9)\n self.groupBox.setGeometry(QtCore.QRect(30, 20, 511, 321))\n self.groupBox.setTitle(_fromUtf8(\"\"))\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.line_34 = QtGui.QFrame(self.groupBox)\n self.line_34.setGeometry(QtCore.QRect(190, 30, 311, 21))\n self.line_34.setFrameShape(QtGui.QFrame.HLine)\n self.line_34.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_34.setObjectName(_fromUtf8(\"line_34\"))\n self.formLayoutWidget = QtGui.QWidget(self.groupBox)\n self.formLayoutWidget.setGeometry(QtCore.QRect(40, 80, 351, 181))\n self.formLayoutWidget.setObjectName(_fromUtf8(\"formLayoutWidget\"))\n self.formLayout = QtGui.QFormLayout(self.formLayoutWidget)\n self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)\n self.formLayout.setObjectName(_fromUtf8(\"formLayout\"))\n self.label_38 = QtGui.QLabel(self.formLayoutWidget)\n font = QtGui.QFont()\n font.setPointSize(12)\n self.label_38.setFont(font)\n self.label_38.setObjectName(_fromUtf8(\"label_38\"))\n self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.label_38)\n self.lineEdit_27 = QtGui.QLineEdit(self.formLayoutWidget)\n font = QtGui.QFont()\n font.setPointSize(12)\n self.lineEdit_27.setFont(font)\n self.lineEdit_27.setObjectName(_fromUtf8(\"lineEdit_27\"))\n self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.lineEdit_27)\n spacerItem7 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)\n self.formLayout.setItem(1, QtGui.QFormLayout.FieldRole, spacerItem7)\n self.label_39 = QtGui.QLabel(self.formLayoutWidget)\n font = QtGui.QFont()\n font.setPointSize(12)\n self.label_39.setFont(font)\n self.label_39.setObjectName(_fromUtf8(\"label_39\"))\n self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.label_39)\n self.lineEdit_28 = QtGui.QLineEdit(self.formLayoutWidget)\n font = QtGui.QFont()\n font.setPointSize(12)\n self.lineEdit_28.setFont(font)\n self.lineEdit_28.setObjectName(_fromUtf8(\"lineEdit_28\"))\n self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.lineEdit_28)\n spacerItem8 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)\n self.formLayout.setItem(3, QtGui.QFormLayout.FieldRole, spacerItem8)\n self.label_41 = QtGui.QLabel(self.formLayoutWidget)\n font = QtGui.QFont()\n font.setPointSize(12)\n self.label_41.setFont(font)\n self.label_41.setObjectName(_fromUtf8(\"label_41\"))\n self.formLayout.setWidget(4, QtGui.QFormLayout.LabelRole, self.label_41)\n self.lineEdit_29 = QtGui.QLineEdit(self.formLayoutWidget)\n font = QtGui.QFont()\n font.setPointSize(12)\n self.lineEdit_29.setFont(font)\n self.lineEdit_29.setObjectName(_fromUtf8(\"lineEdit_29\"))\n self.formLayout.setWidget(4, QtGui.QFormLayout.FieldRole, self.lineEdit_29)\n spacerItem9 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)\n self.formLayout.setItem(5, QtGui.QFormLayout.FieldRole, spacerItem9)\n self.pushButton_9 = QtGui.QPushButton(self.formLayoutWidget)\n self.pushButton_9.setIcon(icon3)\n self.pushButton_9.setObjectName(_fromUtf8(\"pushButton_9\"))\n self.formLayout.setWidget(6, QtGui.QFormLayout.FieldRole, self.pushButton_9)\n self.label_37 = QtGui.QLabel(self.groupBox)\n self.label_37.setGeometry(QtCore.QRect(10, 20, 171, 41))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.label_37.setFont(font)\n self.label_37.setObjectName(_fromUtf8(\"label_37\"))\n self.groupBox_2 = QtGui.QGroupBox(self.tab_9)\n self.groupBox_2.setGeometry(QtCore.QRect(550, 20, 491, 321))\n self.groupBox_2.setTitle(_fromUtf8(\"\"))\n self.groupBox_2.setObjectName(_fromUtf8(\"groupBox_2\"))\n self.line_35 = QtGui.QFrame(self.groupBox_2)\n self.line_35.setGeometry(QtCore.QRect(160, 20, 271, 21))\n self.line_35.setFrameShape(QtGui.QFrame.HLine)\n self.line_35.setFrameShadow(QtGui.QFrame.Sunken)\n self.line_35.setObjectName(_fromUtf8(\"line_35\"))\n self.textEdit = QtGui.QTextEdit(self.groupBox_2)\n self.textEdit.setGeometry(QtCore.QRect(40, 60, 411, 191))\n self.textEdit.setObjectName(_fromUtf8(\"textEdit\"))\n self.label_40 = QtGui.QLabel(self.groupBox_2)\n self.label_40.setGeometry(QtCore.QRect(40, 10, 211, 41))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.label_40.setFont(font)\n self.label_40.setObjectName(_fromUtf8(\"label_40\"))\n icon6 = QtGui.QIcon()\n icon6.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/Material Icons_e8b8(0)_32.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.tabWidget.addTab(self.tab_9, icon6, _fromUtf8(\"\"))\n self.verticalLayout.addWidget(self.tabWidget)\n self.horizontalLayout_7 = QtGui.QHBoxLayout()\n self.horizontalLayout_7.setContentsMargins(-1, 0, -1, -1)\n self.horizontalLayout_7.setObjectName(_fromUtf8(\"horizontalLayout_7\"))\n spacerItem10 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_7.addItem(spacerItem10)\n self.pushButton_10 = QtGui.QPushButton(Form)\n self.pushButton_10.setBaseSize(QtCore.QSize(0, 50))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.pushButton_10.setFont(font)\n icon7 = QtGui.QIcon()\n icon7.addPixmap(QtGui.QPixmap(_fromUtf8(\":/newPrefix/exit.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_10.setIcon(icon7)\n self.pushButton_10.setIconSize(QtCore.QSize(20, 20))\n self.pushButton_10.setObjectName(_fromUtf8(\"pushButton_10\"))\n self.horizontalLayout_7.addWidget(self.pushButton_10)\n self.verticalLayout.addLayout(self.horizontalLayout_7)\n\n self.retranslateUi(Form)\n self.tabWidget.setCurrentIndex(1)\n self.tabWidget_3.setCurrentIndex(0)\n self.tabWidget_2.setCurrentIndex(0)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit.clear)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_13.clear)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_16.clear)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_17.clear)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_18.clear)\n QtCore.QObject.connect(self.pushButton_11, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_19.clear)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.fname.clear)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_3.clear)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_4.clear)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_6.clear)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_7.clear)\n QtCore.QObject.connect(self.pushButton_12, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.lineEdit_8.clear)\n QtCore.QObject.connect(self.pushButton_10, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Form.close)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate(\"Form\", \"Form\", None))\n self.label_3.setText(_translate(\"Form\", \"St. Thomas\\' Collage Matale\", None))\n self.label_2.setText(_translate(\"Form\", \"First Name\", None))\n self.label_19.setText(_translate(\"Form\", \"Full Name\", None))\n self.label_25.setText(_translate(\"Form\", \"Address\", None))\n self.label_26.setText(_translate(\"Form\", \"Contacts\", None))\n self.label_23.setText(_translate(\"Form\", \"Date Of Birth\", None))\n self.label_22.setText(_translate(\"Form\", \"NIC No\", None))\n self.label_24.setText(_translate(\"Form\", \"Admited date of School\", None))\n self.pushButton_11.setText(_translate(\"Form\", \"Clear\", None))\n self.pushButton_5.setText(_translate(\"Form\", \"Save\", None))\n self.label_27.setText(_translate(\"Form\", \"E-Mail\", None))\n self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_5), _translate(\"Form\", \"Add New\", None))\n item = self.teacher.horizontalHeaderItem(0)\n item.setText(_translate(\"Form\", \"Full Name\", None))\n item = self.teacher.horizontalHeaderItem(1)\n item.setText(_translate(\"Form\", \"NIC No\", None))\n item = self.teacher.horizontalHeaderItem(2)\n item.setText(_translate(\"Form\", \"Date Of Birth\", None))\n item = self.teacher.horizontalHeaderItem(3)\n item.setText(_translate(\"Form\", \"Admited date\", None))\n item = self.teacher.horizontalHeaderItem(4)\n item.setText(_translate(\"Form\", \"Address\", None))\n item = self.teacher.horizontalHeaderItem(5)\n item.setText(_translate(\"Form\", \"Contacts\", None))\n item = self.teacher.horizontalHeaderItem(6)\n item.setText(_translate(\"Form\", \"E-Mail\", None))\n self.label_28.setText(_translate(\"Form\", \"Enter First Name or NIC No\", None))\n self.pushButton_6.setText(_translate(\"Form\", \"Search\", None))\n self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_6), _translate(\"Form\", \"Search\", None))\n self.label_31.setText(_translate(\"Form\", \"NIC No\", None))\n self.label_33.setText(_translate(\"Form\", \"Admited date of school\", None))\n self.label_30.setText(_translate(\"Form\", \"Full Name\", None))\n self.label_35.setText(_translate(\"Form\", \"Contacts\", None))\n self.label_29.setText(_translate(\"Form\", \"First Name\", None))\n self.label_34.setText(_translate(\"Form\", \"Address\", None))\n self.label_36.setText(_translate(\"Form\", \"E-Mail\", None))\n self.label_32.setText(_translate(\"Form\", \"Date Of Birth\", None))\n self.pushButton_8.setText(_translate(\"Form\", \"Delete\", None))\n self.pushButton_7.setText(_translate(\"Form\", \"Update\", None))\n self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_7), _translate(\"Form\", \"Update/Delete\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate(\"Form\", \"Teachers Details\", None))\n self.label_6.setText(_translate(\"Form\", \"Date Of Birth\", None))\n self.label_9.setText(_translate(\"Form\", \"Address\", None))\n self.label_5.setText(_translate(\"Form\", \"NIC No\", None))\n self.label_4.setText(_translate(\"Form\", \"Full Name\", None))\n self.label_7.setText(_translate(\"Form\", \"Admission No\", None))\n self.label_8.setText(_translate(\"Form\", \"Admited Date\", None))\n self.label_11.setText(_translate(\"Form\", \"Parents Names\", None))\n self.label_10.setText(_translate(\"Form\", \"Contacts\", None))\n self.pushButton_12.setText(_translate(\"Form\", \"Clear\", None))\n self.pushButton.setText(_translate(\"Form\", \"Save\", None))\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_3), _translate(\"Form\", \"Add New\", None))\n item = self.student.horizontalHeaderItem(0)\n item.setText(_translate(\"Form\", \"Full Name\", None))\n item = self.student.horizontalHeaderItem(1)\n item.setText(_translate(\"Form\", \"NIC No\", None))\n item = self.student.horizontalHeaderItem(2)\n item.setText(_translate(\"Form\", \"Date Of Birth\", None))\n item = self.student.horizontalHeaderItem(3)\n item.setText(_translate(\"Form\", \"Admission No\", None))\n item = self.student.horizontalHeaderItem(4)\n item.setText(_translate(\"Form\", \"Admission Date\", None))\n item = self.student.horizontalHeaderItem(5)\n item.setText(_translate(\"Form\", \"Age\", None))\n item = self.student.horizontalHeaderItem(6)\n item.setText(_translate(\"Form\", \"Address\", None))\n item = self.student.horizontalHeaderItem(7)\n item.setText(_translate(\"Form\", \"Contacts\", None))\n item = self.student.horizontalHeaderItem(8)\n item.setText(_translate(\"Form\", \"Parents Names\", None))\n self.label_12.setText(_translate(\"Form\", \"Enter Admission No or NIC No\", None))\n self.pushButton_2.setText(_translate(\"Form\", \"Search\", None))\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_8), _translate(\"Form\", \"Search\", None))\n self.label_14.setText(_translate(\"Form\", \"NIC No\", None))\n self.label_17.setText(_translate(\"Form\", \"Admission No\", None))\n self.label_21.setText(_translate(\"Form\", \"Full Name\", None))\n self.label_20.setText(_translate(\"Form\", \"Date Of Birth\", None))\n self.label_16.setText(_translate(\"Form\", \"Contacts\", None))\n self.label_15.setText(_translate(\"Form\", \"Parents Names\", None))\n self.label_18.setText(_translate(\"Form\", \"Admited Date\", None))\n self.label_13.setText(_translate(\"Form\", \"Address\", None))\n self.pushButton_4.setText(_translate(\"Form\", \"Delete\", None))\n self.pushButton_3.setText(_translate(\"Form\", \"Update\", None))\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), _translate(\"Form\", \"Update/Delete\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate(\"Form\", \"Students Details\", None))\n self.label_38.setText(_translate(\"Form\", \"Current Password\", None))\n self.label_39.setText(_translate(\"Form\", \"New Password\", None))\n self.label_41.setText(_translate(\"Form\", \"Confirm Password\", None))\n self.pushButton_9.setText(_translate(\"Form\", \"Update password\", None))\n self.label_37.setText(_translate(\"Form\", \"Change Password \", None))\n self.textEdit.setHtml(_translate(\"Form\", \"\\n\"\n\"\\n\"\n\"

Developed by Dinushka Piyumal

\\n\"\n\"

St. Thomas\\' Collage Matale

\\n\"\n\"

13 T1

\\n\"\n\"

2018 A/L in Technology Stream

\\n\"\n\"

dinushkapiyumal678@gmail.com

\\n\"\n\"


\", None))\n self.label_40.setText(_translate(\"Form\", \"About Me :) \", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_9), _translate(\"Form\", \"Settings\", None))\n self.pushButton_10.setText(_translate(\"Form\", \"Close\", None))\n\n self.pushButton_5.clicked.connect(self.savet)\n self.pushButton.clicked.connect(self.savest)\n\n\nimport addt_rc\nimport asss_rc\nimport clear_st_rc\nimport clear_t_rc\nimport close_rc\nimport delete_s_rc\nimport delete_t_rc\nimport flag_rc\nimport save_s_rc\nimport save_t_rc\nimport searctst_rc\nimport searc_t_rc\nimport settings_rc\nimport update_password_rc\nimport update_s_rc\nimport update_t_rc\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n Form = QtGui.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n\n","sub_path":"Source files/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":61123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"489957187","text":"import os\r\nimport pandas as pd\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.tokenize import word_tokenize\r\nimport numpy as np\r\nimport datetime\r\nimport pickle\r\nimport sys\r\nimport emoji\r\nimport dataset_sentiment as ds\r\nimport classifier_sentiment as xs\r\n\r\n\r\nconversation_stored_for_session = []\r\nclean_inst_con_dict ={}\r\nexit_sequence = \"no data read...\"\r\nlabel = {0:\"bad\",1:\"good\"}\r\npath1 = os.path.join(os.getcwd(),\"Con_Sessions\",str(datetime.date.today()),str(datetime.datetime.now().strftime(\"%H_%M_%S\"))+\".csv\")\r\npath2 = os.path.join(os.getcwd(),\"Con_Sessions\",str(datetime.date.today()))\r\npath3 = os.path.join(os.getcwd(),\"Con_Sessions\")\r\npath4 = os.path.join(os.getcwd(),r\"tmp\\Raw_Data.csv\")\r\n\r\ndef chat(inst):\r\n\tinstance_conversion = inst\r\n\tconversation_stored_for_session.append(instance_conversion)\r\n\tprint(conversation_stored_for_session)\r\n\tclean_inst_con = clean_data_for_instance(instance_conversion)\r\n\ttrain_data = create_instance_bag(clean_inst_con)\r\n\tdecideTheinstance(train_data,clean_inst_con)\r\n\r\n\r\ndef clean_data_for_instance(instance_conversion):\r\n\tprint(\"Cleaning\")\r\n\tword_tokens = word_tokenize(instance_conversion)\r\n\tprint(word_tokens)\r\n\tstop_words = set(stopwords.words('english'))\r\n\tclean_instance_conversation = []\r\n\tfor w in word_tokens:\r\n\t\tif not w in stop_words:\r\n\t\t\tclean_instance_conversation.append(w)\r\n\r\n\tprint(clean_instance_conversation)\r\n\treturn clean_instance_conversation\r\n\r\ndef create_instance_bag(clean_con):\r\n\t\r\n\tprint(\"Creating the bag\")\r\n\tverctorizer = CountVectorizer(analyzer = \"word\",\r\n\t\t\t\t\t\t\t\ttokenizer = None,\r\n\t\t\t\t\t\t\t\tpreprocessor = None,\r\n\t\t\t\t\t\t\t\tstop_words = None,\r\n\t\t\t\t\t\t\t\tmax_features = 1000)\r\n\r\n\ttrain_data_feat = verctorizer.fit_transform(clean_con)\r\n\ttrain_data_feat = train_data_feat.toarray()\r\n\treturn train_data_feat\r\n\r\ndef decideTheinstance(train_data,clean_data):\r\n\t#file =open(os.path.join(os.getcwd(),r\"Models\\model.pickle\"),'rb')\r\n\ttry:\r\n\t\tRFC_predict = pickle.load(open(os.path.join(os.getcwd(),r\"Models\\model\"+str(len(clean_data))+\".pickle\"),\"rb\"))\r\n\t\tprint(\"Predicting...\")\r\n\t\tresult = RFC_predict.predict(train_data)\r\n\t\toutput = []\r\n\t\tfor w in result:\r\n\t\t\toutput.append(label[w])\r\n\t\tprint(output)\r\n\texcept FileNotFoundError:\r\n\t\tprint(\"I dont know how to help with...\")\r\n\texcept ValueError:\r\n\t\tprint(\"I dont know how to help with...but I'm learning..so I might know next time\")\r\n\telse:\r\n\t\tprint(\"\\tCome again!!!\\n\\n\")\r\n\tfinally:\r\n\t\tpass\r\n\t\r\n\r\ndef settingUpRawData():\r\n\tprint(\"Got till Here!!!\")\r\n\r\n\tdf = pd.DataFrame(conversation_stored_for_session)\r\n\tdf.to_csv(path4,index = None,header = None,sep =\" \",mode = 'a')\r\n\tds.assignTo()\r\n\tds.alignDataForvariousModels()\r\n\tdata,model = xs.alignDataForvariousModels()\r\n\tfor i in range(len(data)):\r\n\t\txs.classify(model[i],data[i])\r\n\r\n\tprint(\"All models trained!!!\")\r\n\r\n\r\nif __name__ == '__main__':\r\n\tif os.path.exists(path3):\r\n\t\tprint(\"Reading\")\r\n\telse:\r\n\t\tos.mkdir(path3)\r\n\tif os.path.exists(path2):\r\n\t\t\tprint(\"Following the line-up...\")\r\n\telse:\r\n\t\tos.mkdir(path2)\r\n\tprint(\"Hey how is your day...\\n\\n\")\r\n\r\n\tinst = input(\">>>\\t\")\r\n\r\n\ttry:\r\n\t\texit_sequence = pd.read_csv(os.path.join(os.getcwd(),r\"tmp\\escape_seq.csv\"))\r\n\t\texit_sequence = list(exit_sequence[\"Sequence\"])\r\n\texcept FileNotFoundError:\r\n\t\tprint(\"DataNotFound: escape_seq.csv\")\r\n\telse:\r\n\t\tpass\r\n\r\n\t\r\n\tprint(type(inst))\r\n\ttry:\r\n\t\twhile inst not in exit_sequence:\r\n\t\t\tchat(inst)\r\n\t\t\tinst = input(\">>>\\t\")\r\n\texcept TypeError:\r\n\t\tprint(\"I am not used to numbers yet, but I'm learning...\")\r\n\telse:\r\n\t\tpass\r\n\tfinally:\r\n\t\tpass\r\n\r\n\tprint(\"Bye\")\r\n\tsettingUpRawData()","sub_path":"sentiment_analyzer/sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"572470190","text":"#!/usr/bin/env python3\nfrom sys import argv\n\"\"\"\ntake a dalton output file like output_files/NB_rotated_static_gamma_STO-3G_hf.out and extract the\ngamma info\n\"\"\"\n\ndef strip_gamma(k):\n return k.replace(\"gamma(\", \"\").replace(\")\", \"\")\n\n\ndef convert(k):\n \"\"\"convert \"Y;Y,Z,Z\" to (1,1,2,2)\n output is a tuple\n \"\"\"\n convert_axes = {\n \"X\": 0,\n \"Y\": 1,\n \"Z\": 2\n }\n k = k.replace(\";\", \",\")\n parts = k.split(',')\n converted = [convert_axes[part] for part in parts]\n return tuple(converted)\n\n\ndef parse_gamma(gamma_line):\n \"\"\"convert line from dalton to\n (\n (int, int, int, int),\n float\n )\n \"\"\"\n _, k, v = gamma_line.split()\n k = convert(strip_gamma(k))\n v = float(v)\n return (k, v)\n\n\ndef extract_gammas_from_file(filename):\n with open(filename) as f:\n lines = f.readlines()\n gammas = []\n for line in lines:\n if \"@ gamma(\" in line:\n gammas.append(parse_gamma(line))\n return gammas\n\nif __name__ == \"__main__\":\n gamma_output = extract_gammas_from_file(argv[1])\n print(gamma_output)\n \n\n","sub_path":"parse_gammas.py","file_name":"parse_gammas.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"115143413","text":"import os, sys\nimport unittest\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nbasedir = os.path.abspath(os.path.dirname(__file__))\nfrom app import app\nfrom db import db\nimport json\nfrom datetime import datetime, timedelta\nfrom freezegun import freeze_time\n\nfrom helper_tests import helper\n\nTEST_DB = 'test.db'\n\nclass BasicTests(unittest.TestCase):\n\n ############################\n #### setup and teardown ####\n ############################\n\n # executed prior to each test\n def setUp(self):\n app.config['TESTING'] = True\n app.config['WTF_CSRF_ENABLED'] = False\n app.config['DEBUG'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db')\n self.app = app.test_client()\n db.init_app(app)\n db.drop_all(app=app)\n db.create_all(app=app)\n\n\n # executed after each test\n def tearDown(self):\n pass\n\n # common methods\n def make_cards_json(self, numCards):\n cards = {}\n count = 0\n for i in range(numCards):\n card = {str(i+1): \"name\"+str(i+1)} # condensed version of the card\n cards.update(card)\n return cards\n\n ###############\n #### tests ####\n ###############\n # /quiz/cardlist\n\n def test_make_quiz_card_list(self):\n cards = self.make_cards_json(5)\n new_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(new_quiz_card_list.status_code, 201)\n\n def test_get_quiz_card_list(self):\n cards = self.make_cards_json(6)\n first_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n second_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 2,\n 'cards': cards\n })\n )\n lists_list = self.app.get('/quiz/cardlist')\n data = json.loads(lists_list.data.decode())\n self.assertEqual(len(data['response']), 2)\n self.assertEqual(data['response'][0]['cards']['1'], 'name1')\n self.assertEqual(data['response'][0]['cards']['2'], 'name2')\n\n def test_duplicate_quiz_id_for_list(self):\n cards = self.make_cards_json(10)\n first_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(first_quiz_card_list.status_code, 201)\n duplicate_quiz_id_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(duplicate_quiz_id_list.status_code, 400)\n\n def test_duplicate_cards_in_one_quiz(self):\n cards = self.make_cards_json(10)\n cards['card1'] = \"name100\"\n cards['card2'] = \"name100\"\n new_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(new_quiz_card_list.status_code, 400)\n\n def test_get_list_by_id(self):\n cards = self.make_cards_json(10)\n new_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(new_quiz_card_list.status_code, 201)\n non_target_list = self.app.get('/quiz/cardlist/' + str(2))\n self.assertEqual(non_target_list.status_code, 400)\n target_list = self.app.get('/quiz/cardlist/' + str(1))\n self.assertEqual(target_list.status_code, 200)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_quizcardlist.py","file_name":"test_quizcardlist.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"276177017","text":"# sky, the ground, and clouds.\nimport tkinter as tk\nfrom random import random, seed, randint\n\n# MAIN PROGRAM\n\n\ndef main():\n # The width and height of the scene window.\n width = 800\n height = 500\n\n # Create the Tk root object.\n root = tk.Tk()\n root.geometry(f\"{width}x{height}\")\n\n # Create a Frame object.\n frame = tk.Frame(root)\n frame.master.title(\"Scene\")\n frame.pack(fill=tk.BOTH, expand=1)\n\n # Create a canvas object that will draw into the frame.\n canvas = tk.Canvas(frame, bg='steelBlue1')\n canvas.pack(fill=tk.BOTH, expand=1)\n\n # Call the draw_scene function.\n draw_scene(canvas, 0, 0, width-1, height-1)\n\n root.mainloop()\n\n# FUNCTION DEFINITION\n\n\ndef draw_scene(canvas, scene_left, scene_top, scene_right, scene_bottom):\n \"\"\"Draw a scene in the canvas. scene_left, scene_top,\n scene_right, and scene_bottom contain the extent in\n pixels of the region where the scene should be drawn.\n Parameters\n scene_left: left side of the region; less than scene_right\n scene_top: top of the region; less than scene_bottom\n scene_right: right side of the region\n scene_bottom: bottom of the region\n Return: nothing\n\n If needed, the width and height of the\n region can be calculated like this:\n scene_width = scene_right - scene_left + 1\n scene_height = scene_bottom - scene_top + 1\n \"\"\"\n\n # Call your functions here, such as draw_sky, draw_ground,\n # draw_snowman, draw_tree, draw_shrub, etc.\n\n # # GROUND\n draw_ground(canvas, scene_right, scene_bottom)\n\n # CLOUDS\n cloud_count = randint(10, 25)\n print(f'Cloud count: {cloud_count}')\n draw_random_clouds(canvas, scene_right, scene_bottom, cloud_count)\n \n # TREE\n tree_center = scene_right * 0.8\n tree_top = scene_bottom - scene_bottom * 0.5\n tree_height = 150\n draw_pine_tree(canvas, tree_center, tree_top, tree_height)\n\n # # RANDOM TREES\n # \"\"\" Draw random pine trees at random locations.\"\"\"\n # draw_random_pine_trees(canvas, tree_count)\n\n\n# Define more functions here, like draw_sky, draw_ground,\n# draw_cloud, draw_tree, draw_kite, draw_snowflake, etc.\ndef draw_ground(canvas, scene_right, scene_bottom):\n ground_left = 0\n ground_top = scene_bottom * 0.7\n ground_right = scene_right\n ground_bottom = scene_bottom\n canvas.create_rectangle(ground_left, ground_top,\n ground_right, ground_bottom,\n outline=\"black\", width=1, fill=\"green\")\n\n\ndef draw_random_clouds(canvas, scene_right, scene_bottom, cloud_count=1, cloud_size=30):\n limit_sky_bottom = int(scene_bottom * 0.7)\n for i in range(cloud_count):\n ii = i + 1\n scene_right_random = randint(0, scene_right)\n scene_bottom_random = randint(0, limit_sky_bottom)\n cloud_size_random = randint(cloud_size, cloud_size * 3)\n \n scene_left_random = scene_right_random - cloud_size_random\n scene_top_random = scene_bottom_random - cloud_size_random\n cloud_random_width = random() + 1\n scene_right_random = scene_right_random * cloud_random_width\n\n canvas.create_oval(scene_left_random, scene_top_random, scene_right_random,\n scene_bottom_random, width=0, fill=\"snow\")\n\n\ndef draw_pine_tree(canvas, peak_x, peak_y, height):\n \"\"\"Draw a single pine tree.\n Parameters\n canvas: The tkinter canvas where this\n function will draw a pine tree.\n peak_x, peak_y: The x and y location in pixels where\n this function will draw the top peak of a pine tree.\n height: The height in pixels of the pine tree that\n this function will draw.\n Return: nothing\n \"\"\"\n trunk_width = height / 10\n trunk_height = height / 8\n trunk_left = peak_x - trunk_width / 2\n trunk_right = peak_x + trunk_width / 2\n trunk_bottom = peak_y + height\n\n skirt_width = height / 2\n skirt_height = height - trunk_height\n skirt_left = peak_x - skirt_width / 2\n skirt_right = peak_x + skirt_width / 2\n skirt_bottom = peak_y + skirt_height\n\n # Draw the trunk of the pine tree.\n canvas.create_rectangle(trunk_left, skirt_bottom,\n trunk_right, trunk_bottom,\n outline=\"gray20\", width=1, fill=\"tan3\")\n\n # Draw the crown (also called skirt) of the pine tree.\n canvas.create_polygon(peak_x, peak_y,\n skirt_right, skirt_bottom,\n skirt_left, skirt_bottom,\n outline=\"gray20\", width=1, fill=\"dark green\")\n\n\n# Call the main function so that\n# this program will start executing.\nif __name__ == '__main__':\n main()\n\n\"\"\" W03 Assignment\nDuring this lesson, you will write code that draws:\n - the sky,\n - the ground,\n - and clouds. \nDuring the next lesson, you will write code that completes the scene. The scene that your program draws may be very different from the example scene above. However, your scene must:\n - be outdoor,\n - the sky must have clouds,\n - and the scene must include repetitive elements such as blades of grass, trees, leaves on a tree, birds, flowers, insects, fish, pickets in a fence, dashed lines on a road, buildings, bales of hay, snowmen, snowflakes, or icicles. Be creative.\n\"\"\"\n","sub_path":"w03-writing-functions/prove-drawingScene/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"156405451","text":"#!/usr/bin/python3\n\"\"\"This is the new engine DBStorage\"\"\"\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom models.base_model import BaseModel, Base\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nimport os\n\n\nclass DBStorage:\n \"\"\"DBStorage class\n \"\"\"\n __engine = None\n __session = None\n\n def __init__(self):\n \"\"\"creates the engine\n \"\"\"\n env_nm = os.environ.get('HBNB_ENV')\n user_nm = os.environ.get('HBNB_MYSQL_USER')\n passwd = os.environ.get('HBNB_MYSQL_PWD')\n host = os.environ.get('HBNB_MYSQL_HOST')\n db_nm = os.environ.get('HBNB_MYSQL_DB')\n\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(user_nm, passwd, host, db_nm),\n pool_pre_ping=True)\n\n Base.metadata.create_all(self.__engine)\n Session = sessionmaker(bind=self.__engine)\n self.__session = Session()\n if env_nm == \"test\":\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n \"\"\"returns a dictionary\n \"\"\"\n classes = ['State', 'City', 'User', 'Place', 'Review', 'Amenity']\n objs = {}\n\n if cls is None:\n for class_nm in classes:\n query = self.__session.query(eval(class_nm)).all()\n for obj in query:\n key = obj.__class__.__name__ + '.' + obj.id\n objs[key] = obj\n else:\n query = self.__session.query(eval(cls)).all()\n for obj in query:\n key = obj.__class__.__name__ + '.' + obj.id\n objs[key] = obj\n return objs\n\n def new(self, obj):\n \"\"\"adds the object to the current database session\n \"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"commits all changes of the current database session\n \"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes from the current database session obj if not None\n \"\"\"\n if obj:\n self.__session.delete(obj)\n self.save()\n\n def reload(self):\n \"\"\"creates all tables in the database\n \"\"\"\n Base.metadata.create_all(self.__engine)\n session_factory = sessionmaker(bind=self.__engine,\n expire_on_commit=False)\n self.__session = scoped_session(session_factory)\n\n def close(self):\n \"\"\"call remove()\"\"\"\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"32910658","text":"import numpy as np\nfrom scipy.interpolate import SmoothBivariateSpline\nimport h5py\n\n# For rendering\nfrom .gaussmodel import convert_to_gaussians, compute_gig\n\n__all__ = [\"Scene\", \"Source\",\n \"Star\",\n \"SimpleGalaxy\", \"Galaxy\", \"ConformalGalaxy\"]\n\n\nclass Scene(object):\n \"\"\"The Scene holds the sources and provides the mapping between a giant 1-d\n array of parameters and the parameters of each source in each band/image\n \"\"\"\n\n def __init__(self, sources=[]):\n self.sources = sources\n self.identify_sources()\n\n def __repr__(self):\n ss = [str(s) for s in self.sources]\n return \"\\n\".join(ss)\n\n def param_indices(self, sid, filtername=None):\n \"\"\"Get the indices of the relevant parameters in the giant Theta\n vector. Assumes that the order of parameters for each source is\n is [flux1, flux2...fluxN, pos1, pos2, shape1, shape2, ..., shapeN]\n\n :param sid:\n Source ID\n\n :param filtername: (optional, default: None)\n The name of the filter for which you want the corresponding flux\n parameter index. If None (default) then indices for all fluxes are\n returned\n\n :returns theta:\n An array with elements [flux, (shape_params)]\n \"\"\"\n npar_per_source = [s.nparam for s in self.sources[:sid]]\n # get all the shape parameters\n source = self.sources[sid]\n start = int(np.sum(npar_per_source))\n # indices of the shape and position parameters\n inds = range(start + source.nband, start + source.nparam)\n # put in the flux for this source in this band\n inds.insert(0, start + source.filter_index(filtername))\n return inds\n\n def set_all_source_params(self, Theta):\n \"\"\"Loop over sources in the scene, setting the parameters in each\n source based on the relevant subset of Theta parameters.\n \"\"\"\n start = 0\n for source in self.sources:\n end = start + source.nparam\n source.set_params(Theta[start:end])\n start += source.nparam\n\n def get_all_source_params(self):\n \"\"\"Get the total scene parameter vector\n \"\"\"\n plist = [s.get_param_vector() for s in self.sources if not s.fixed]\n params = np.concatenate(plist)\n return params\n\n @property\n def parameter_names(self):\n \"\"\"Get names for all the parameters in the scene\n \"\"\"\n return np.concatenate([s.parameter_names for s in self.sources])\n\n def identify_sources(self):\n \"\"\"Give each source in the scene a unique identification number.\n \"\"\"\n for i, source in enumerate(self.sources):\n source.id = i\n\n\nclass Source(object):\n \"\"\"Parameters describing a source in the celestial plane. For each galaxy\n there are 7 parameters, only some of which may be relevant for changing the\n apparent flux:\n * flux: total flux (possibly a vector)\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * q, pa: axis ratio squared and position angle\n * n: sersic index\n * r: half-light radius (arcsec)\n\n Methods are provided to return the amplitudes and covariance matrices of\n the constituent gaussians, as well as derivatives of the amplitudes with\n respect to sersic index and half light radius.\n \"\"\"\n\n id = 0\n fixed = False\n radii = np.zeros(1)\n\n # Parameters\n flux = 0. # flux. This will get rewritten on instantiation to have\n # a length that is the number of bands\n ra = 0.\n dec = 0.\n q = 1. # sqrt of the axis ratio, i.e. (b/a)^0.5\n pa = 0. # postion angle (N of E)\n sersic = 0. # sersic index\n rh = 0. # half light radius\n\n def __init__(self, filters=['dummy'], radii=None):\n \"\"\"\n :param filters:\n A list of strings giving the filternames for which you want fluxes.\n These names should correspond to values of the `filtername`\n attribute of PostageStamps, since they will be used to choose the\n appropriate element of the `flux` vector for generating model pixel\n values.\n\n The length of the supplied `filters` list will determine the length\n of the `flux` vector, accessible via the `nband` attribute.\n \"\"\"\n assert type(filters) == list\n self.filternames = filters\n self.flux = np.zeros(len(self.filternames))\n if radii is not None:\n self.radii = radii\n\n def __repr__(self):\n kk, vv = self.parameter_names, self.get_param_vector()\n parstring = [\"{}={}\".format(k, v)\n for k, v in zip(kk, vv)]\n return '{}\\n\\t({})'.format(self.__class__, \",\\n\\t\".join(parstring))\n\n @property\n def nband(self):\n \"\"\"Number of elements of the flux vector (corresponding to the filters\n in `filternames`)\n \"\"\"\n return len(self.filternames)\n\n @property\n def nparam(self):\n \"\"\"Total number of source parameters, including position, shape, and\n flux(es)\n \"\"\"\n return self.npos + self.nshape + self.nband\n\n @property\n def ngauss(self):\n \"\"\"Total number of gaussians used to describe the source.\n \"\"\"\n return len(self.radii)\n\n @property\n def use_gradients(self):\n \"\"\"Which of the 7 gradients (d/dFlux, d/dRA, d/dDec, d/dq, d/dpa,\n d/dsersic, d/drh) will you actually use?\n \"\"\"\n return slice(0, 1 + self.npos + self.nshape)\n\n @property\n def parameter_names(self):\n names = self.filternames + [\"ra\", \"dec\"] + [\"q\", \"pa\", \"n\", \"r\"][:self.nshape]\n names = [\"{}_{}\".format(n, self.id) for n in names]\n return names\n\n def filter_index(self, filtername):\n \"\"\"Returns the index of the element of the `flux` array that\n corresponds to the supplied `filtername`.\n\n :param filtername:\n String giving the name of the filter for which you want the\n corresponding `flux` vector index.\n\n :returns index:\n An integer index that when used to subscript the `flux` attribute\n gives the source flux in `filtername`\n \"\"\"\n return self.filternames.index(filtername)\n\n @property\n def covariances(self):\n raise(NotImplementedError)\n\n @property\n def amplitudes(self):\n \"\"\"Code here for getting amplitudes from a splined look-up table\n (dependent on self.n and self.r). Placeholder code gives them all\n equal amplitudes.\n \"\"\"\n return np.ones(self.ngauss) / (self.ngauss * 1.0)\n\n @property\n def damplitude_dsersic(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.sersic and self.rh)\n \"\"\"\n # ngauss array of da/dsersic\n return np.zeros(self.ngauss)\n\n @property\n def damplitude_drh(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.sersic and self.rh)\n \"\"\"\n # ngauss array of da/drh\n return np.zeros(self.ngauss)\n\n def render(self, stamp, compute_deriv=True, **compute_keywords):\n \"\"\"Render a source on a PostageStamp.\n\n :param stamp:\n A PostageStamp object\n\n :param compute_deriv: (optional, default: True)\n If True, return the gradients of the image with respect to the\n relevant free parameters for the source.\n \"\"\"\n gig = convert_to_gaussians(self, stamp, compute_deriv=compute_deriv)\n im, grad = compute_gig(gig, stamp.xpix.flat, stamp.ypix.flat,\n compute_deriv=compute_deriv, **compute_keywords)\n\n if compute_deriv:\n return im, grad[self.use_gradients]\n else:\n return im, None\n\n\nclass Star(Source):\n \"\"\"This is a represenation of a point source in terms of Scene (on-sky)\n parameters. Only 3 of the 7 full Source parameters are relevant:\n * flux: total flux\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n \"\"\"\n\n radii = np.zeros(1)\n\n # PointSources only have two position parameters.\n npos = 2\n nshape = 0\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec) from a theta array. Assumes\n that the order of parameters in the theta vector is [flux1,\n flux2...fluxN, ra, dec]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + 2` (if `filtername` is `None`) or 3.\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 3-element (fluxI,\n ra, dec) where fluxI is the source flux through the filter given by\n `filtername`. If `None` then the theta vector is assumed to be of\n length `Source().nband + 2`, where the first `nband` elements\n correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + 2, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra], [self.dec]])\n return params\n\n @property\n def covariances(self):\n \"\"\"This just constructs a set of source gaussian covariance matrices\n based on the radii. For point sources these are all zeros, since a\n point source has no size.\n \"\"\"\n # ngauss x 2 x 2\n # this has no derivatives, since the radii are fixed.\n return np.zeros([1, 2, 2])\n\n\nclass SimpleGalaxy(Source):\n \"\"\"Parameters describing a simple gaussian galaxy in the celestial plane\n (i.e. the Scene parameters.) Only 5 of the possible 7 Source parameters are\n relevant:\n * flux: total flux\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * q, pa: axis ratio squared and position angle\n\n The radial profile is assumed to be a sum of equally weighted gaussians\n with radii given by SimpleGalaxy.radii\n \"\"\"\n\n radii = np.ones(1)\n\n # Galaxies have two position parameters, 2 or 4 shape parameters (pa and q)\n # and nband flux parameters\n npos = 2\n nshape = 2\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec, q, pa) from a theta array.\n Assumes that the order of parameters in the theta vector is [flux1,\n flux2...fluxN, ra, dec, q, pa]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + 4` (if `filtername` is `None`) or 5 (if a filter is\n specified)\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 5-element (fluxI,\n ra, dec, q, pa) where fluxI is the source flux through the filter\n given by `filtername`. If `None` then the theta vector is assumed\n to be of length `Source().nband + 4`, where the first `nband`\n elements correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + 4, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n self.q = theta[nflux + 2]\n self.pa = theta[nflux + 3]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra], [self.dec],\n [self.q], [self.pa]])\n return params\n\n @property\n def covariances(self):\n \"\"\"This just constructs a set of covariance matrices based on the fixed\n radii used in approximating the galaxies.\n \"\"\"\n # ngauss x 2 x 2\n # this has no derivatives, since the radii are fixed.\n return (self.radii**2)[:, None, None] * np.eye(2)\n\n\nclass Galaxy(Source):\n \"\"\"Parameters describing a gaussian galaxy in the celestial plane (i.e. the\n Scene parameters) All 7 Source parameters are relevant:\n * flux: total flux\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * q, pa: axis ratio squared and position angle\n * n: sersic index\n * r: half-light radius (arcsec)\n\n Methods are provided to return the amplitudes and covariance matrices of\n the constituent gaussians, as well as derivatives of the amplitudes with\n respect to sersic index and half light radius.\n\n The amplitudes and the derivatives of the amplitudes with respect to the\n sersic index and half-light radius are based on splines.\n \"\"\"\n\n radii = np.ones(1)\n\n # Galaxies have 2 position parameters,\n # 2 or 4 shape parameters (pa and q),\n # and nband flux parameters\n npos = 2\n nshape = 4\n\n def __init__(self, filters=['dummy'], radii=None, splinedata=None, free_sersic=True):\n self.filternames = filters\n self.flux = np.zeros(len(self.filternames))\n if radii is not None:\n self.radii = radii\n if splinedata is None:\n raise(ValueError, \"Galaxies must have information to make A(r, n) bivariate splines\")\n else:\n self.initialize_splines(splinedata)\n\n if not free_sersic:\n # Fix the sersic parameters n_sersic and r_h\n self.nshape = 2\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec, q, pa, n_sersic, r_h) from a\n theta array. Assumes that the order of parameters in the theta vector\n is [flux1, flux2...fluxN, ra, dec, q, pa, sersic, rh]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + npos + nshape` (if `filtername` is `None`) or `1 +\n npos + nshape` (if a filter is specified)\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 7-element (fluxI,\n ra, dec, q, pa) where fluxI is the source flux through the filter\n given by `filtername`. If `None` then the theta vector is assumed\n to be of length `Source().nband + 6`, where the first `nband`\n elements correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + self.npos + self.nshape, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n self.q = theta[nflux + 2]\n self.pa = theta[nflux + 3]\n if self.nshape > 2:\n self.sersic = theta[nflux + 4]\n self.rh = theta[nflux + 5]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra, self.dec, self.q, self.pa]])\n if self.nshape > 2:\n params = np.concatenate([params, [self.sersic, self.rh]])\n return params\n\n def initialize_splines(self, splinedata, spline_smoothing=None):\n \"\"\"Initialize Bivariate Splines used to interpolate and get derivatives\n for gaussian amplitudes as a function of sersic and rh\n \"\"\"\n with h5py.File(splinedata, \"r\") as data:\n n = data[\"nsersic\"][:]\n r = data[\"rh\"][:]\n A = data[\"amplitudes\"][:]\n self.radii = data[\"radii\"][:]\n\n nm, ng = A.shape\n self.splines = [SmoothBivariateSpline(n, r, A[:, i], s=spline_smoothing) for i in range(ng)]\n self.rh_range = (r.min(), r.max())\n self.sersic_range = (n.min(), n.max())\n\n @property\n def covariances(self):\n \"\"\"This just constructs a set of covariance matrices based on the fixed\n radii used in approximating the galaxies.\n \"\"\"\n # ngauss x 2 x 2\n # this has no derivatives, since the radii are fixed.\n return (self.radii**2)[:, None, None] * np.eye(2)\n\n @property\n def amplitudes(self):\n \"\"\"Code here for getting amplitudes from a splined look-up table\n (dependent on self.n and self.r). Placeholder code gives them all\n equal amplitudes.\n \"\"\"\n return np.squeeze(np.array([spline(self.sersic, self.rh) for spline in self.splines]))\n\n @property\n def damplitude_dsersic(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.n and self.r)\n \"\"\"\n # ngauss array of da/dsersic\n return np.array([spline(self.sersic, self.rh, dx=1) for spline in self.splines])\n\n @property\n def damplitude_drh(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.n and self.r)\n \"\"\"\n # ngauss array of da/drh\n return np.array([spline(self.sersic, self.rh, dy=1) for spline in self.splines])\n\n\nclass ConformalGalaxy(Galaxy):\n\n \"\"\"Parameters describing a source in the celestial plane, with the shape\n parameterized by the conformal shear vector instead of traditional axis\n ratio and position angle. For each galaxy there are 7 parameters:\n * flux: total flux (possibly a vector)\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * ep, ec: the eta vector defined by Bernstein & Jarvis 2002, eq 2.10\n * n: sersic index\n * r: half-light radius (arcsec)\n\n Methods are provided to return the amplitudes and covariance matrices of\n the constituent gaussians, as well as derivatives of the amplitudes with\n respect to sersic index and half light radius.\n \"\"\"\n\n # Parameters\n flux = 0. # flux. This will get rewritten on instantiation to have\n # a length that is the number of bands\n ra = 0.\n dec = 0.\n ep = 0. # eta_+ (Bernstein & Jarvis) = \\eta \\cos(2\\phi)\n ec = 0. # eta_x (Bernstein & Jarvis) = \\eta \\sin(2\\phi)\n sersic = 0. # sersic index\n rh = 0. # half light radius\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec, ep, ec, n_sersic, r_h) from a\n theta array. Assumes that the order of parameters in the theta vector\n is [flux1, flux2...fluxN, ra, dec, ep, ec, sersic, rh]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + npos + nshape` (if `filtername` is `None`) or `1 +\n npos + nshape` (if a filter is specified)\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 7-element (fluxI,\n ra, dec, ep, ec) where fluxI is the source flux through the filter\n given by `filtername`. If `None` then the theta vector is assumed\n to be of length `Source().nband + 6`, where the first `nband`\n elements correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + self.npos + self.nshape, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n self.ep = theta[nflux + 2]\n self.ec = theta[nflux + 3]\n if self.nshape > 2:\n self.sersic = theta[nflux + 4]\n self.rh = theta[nflux + 5]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra, self.dec, self.ep, self.ec]])\n if self.nshape > 2:\n params = np.concatenate([params, [self.sersic, self.rh]])\n return params\n\n def etas_from_qphi(self, q, phi):\n \"\"\"Get eta vector from native shape units\n\n :param q: (b/a)^0.5\n :param phi: position angle (radians)\n \"\"\"\n eta = -np.log(q**2)\n eta_plus = eta * np.cos(phi * 2.)\n eta_cross = eta * np.sin(phi * 2.)\n return eta_plus, eta_cross\n\n @property\n def parameter_names(self):\n names = self.filternames + [\"ra\", \"dec\"] + [\"ep\", \"ec\", \"n\", \"r\"][:self.nshape]\n names = [\"{}_{}\".format(n, self.id) for n in names]\n return names\n\n @property\n def q(self):\n \"\"\"(b/a)^0.5 following conventions above\n \"\"\"\n eta = np.hypot(self.ep, self.ec)\n return np.exp(-eta / 2.)\n\n @property\n def pa(self):\n \"\"\"Position angle\n \"\"\"\n return np.arctan2(self.ec, self.ep) / 2.\n\n @property\n def ds_deta(self):\n \"\"\"The Jacobian for d(q, pa) / d(eta_+, eta_x).\n I.e., multiply gradients with respect to q and pa by this to get\n gradients with respect to eta_+, eta_x.\n \"\"\"\n sqrtq = self.q # ugh\n q = (sqrtq)**2\n phi = self.pa\n sin2phi = np.sin(2 * phi)\n cos2phi = np.cos(2 * phi)\n itlq = 1. / (2. * np.log(q))\n ds_de = np.array([[-q * cos2phi, -q * sin2phi],\n [sin2phi * itlq, -cos2phi * itlq]])\n # account for sqrt in q = sqrt(b/a)\n sq = np.array([[0.5 / sqrtq, 0.],\n [0., 1.]])\n\n return np.dot(ds_de.T, sq)\n\n def render(self, stamp, compute_deriv=True, **compute_keywords):\n \"\"\"Render a source on a PostageStamp.\n\n :param stamp:\n A PostageStamp object\n\n :param withgrad: (optional, default: True)\n If True, return the gradients of the image with respect to the\n relevant free parameters for the source.\n \"\"\"\n gig = convert_to_gaussians(self, stamp, compute_deriv=compute_deriv)\n im, grad = compute_gig(gig, stamp.xpix.flat, stamp.ypix.flat,\n compute_deriv=compute_deriv, **compute_keywords)\n\n if compute_deriv:\n # convert d/dq, d/dphi to d/deta_+, d/deta_x\n # FIXME: This is a brittle way to do this!\n grad[3:5, :] = np.matmul(self.ds_deta, grad[3:5, :])\n return im, grad[self.use_gradients]\n else:\n return im, None\n\n\ndef scale_matrix(q):\n \"\"\"q=(b/a)^0.5\n \"\"\"\n return np.array([[1./q, 0],\n [0, q]])\n\n\ndef rotation_matrix(theta):\n costheta = np.cos(theta)\n sintheta = np.sin(theta)\n return np.array([[costheta, -sintheta],\n [sintheta, costheta]])\n\n\ndef scale_matrix_deriv(q):\n \"\"\"q=(b/a)^0.5\n \"\"\"\n return np.array([[-1./q**2, 0],\n [0, 1]])\n\n\ndef rotation_matrix_deriv(theta):\n costheta = np.cos(theta)\n msintheta = -np.sin(theta)\n return np.array([[msintheta, -costheta],\n [costheta, msintheta]])\n\n\ndef dummy_spline(x, y, dx=0, dy=0):\n if (dx > 0) | (dy > 0):\n return 0.\n else:\n return 1.\n","sub_path":"forcepho/sources.py","file_name":"sources.py","file_ext":"py","file_size_in_byte":24665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"188153483","text":"\"\"\"\nhttps://www.codewars.com/kata/5ff0fc329e7d0f0010004c03/train/python\n\"\"\"\n\n\ndef count_diamonds(diamond_map, num_of_diamonds):\n parcels = []\n size = float('inf')\n for up in range(len(diamond_map)):\n inter_sum = [0] * len(diamond_map[0])\n for bottom in range(up, len(diamond_map)):\n inter_sum = [inter_sum[i] + diamond_map[bottom][i] for i in range(len(inter_sum))]\n for col1, col2 in _sliding_window_1d(inter_sum, num_of_diamonds):\n square_of_the_area = (bottom - up + 1) * (col2 - col1 + 1)\n if square_of_the_area < size:\n size = square_of_the_area\n parcels = [[(up, col1), (bottom, col2)]]\n elif square_of_the_area == size:\n parcels.append([(up, col1), (bottom, col2)])\n return sorted(parcels)\n\n\ndef _sliding_window_1d(some_list: list, target_sum: int):\n current_sum = left = 0\n for right in range(len(some_list)):\n current_sum += some_list[right]\n while current_sum - some_list[left] >= target_sum:\n current_sum -= some_list[left]\n left += 1\n if current_sum == target_sum:\n yield left, right\n","sub_path":"test/codewars/4_kyu_Counting_Diamonds.py","file_name":"4_kyu_Counting_Diamonds.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"459720965","text":"\nimport webapp2\n\nfrom google.appengine.api import app_identity\nfrom google.appengine.api import images\nfrom google.appengine.api import mail\nfrom google.appengine.api import users\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import blobstore_handlers\n\nfrom models import Employee as Emp\nfrom models import Role\nfrom querydefs import JinjaEnv\nfrom querydefs import QueryDefs\n\n\nclass UserProfile(webapp2.RequestHandler):\n \"\"\"Handler for admin views.\"\"\"\n def get(self):\n employee = Emp.query(\n Emp.user_id == users.get_current_user().user_id()\n ).get()\n\n projects = []\n qd = QueryDefs()\n\n if employee.projects:\n for project_id in employee.projects:\n if project_id:\n projects.append(qd.get_project_name(project_id))\n if employee.role:\n role = Role.query(Role.key == employee.role).get()\n else:\n role = None\n\n if employee.photo:\n serving_url = images.get_serving_url(blobstore.create_gs_key(employee.photo))\n else:\n serving_url = None\n\n jinjaenv = JinjaEnv()\n template = jinjaenv.get_jinja_env().get_template(\n 'templates/user/userprofile.html'\n )\n template_values = {\n 'employee': employee,\n 'projects': projects,\n 'role': role,\n 'serving_url': serving_url,\n 'is_admin': users.is_current_user_admin(),\n 'url_link': users.create_logout_url('/')\n }\n self.response.write(template.render(template_values))\n","sub_path":"handlers/userprofile.py","file_name":"userprofile.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510683147","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 29 09:03:49 2020\r\n\r\n@author: rpira\r\n\"\"\"\r\n\r\nfrom OptimizedFunction import compile_model\r\nimport pickle\r\n\r\n## Importing the database for the combination of hyper parameters \r\nfilehandler = open('filename_pi.obj', 'rb') \r\nModelInfo = pickle.load(filehandler)\r\n\r\n## Initial values\r\ncount=0\r\ntot=[]\r\nMapeOpt=100\r\nTreasureholdAccuracy=1\r\nTreasholdCount=1000\r\n### Finding the minimum mape with 2 treashhold with radomized search\r\nfor i in range(0,len(ModelInfo)):\r\n count=count+1\r\n saved_model, mape =compile_model(ModelInfo[i])\r\n print(\"Mape=\", mape)\r\n ### Checking if the difference between the current and previous minimum mape\r\n ### is bigger than the desired on, then restart the counter. So we have 2 treashholdhere\r\n if MapeOpt-mape>TreasureholdAccuracy:\r\n count=0\r\n ## Choose the min mape\r\n if mapeTreasholdCount:\r\n break\r\n","sub_path":"HyperParamOptimization/OptimizingHyperParam.py","file_name":"OptimizingHyperParam.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"159452649","text":"\"\"\"\nCreated on 6/22/2018\n@author: Jingchao Yang\n\nLevel Two credibility test include basic event based cross check\nEvent sources includes:\nTwitter embedded text events extraction\nTwitter linked web page text events extraction\n\nGoal is to analysis if events from a same twitter are correlated (same)\n\"\"\"\nfrom psqlOperations import queryFromDB\n\n\ndef checkEvents(eventList1, eventList2):\n \"\"\"if same event found within tweets and url page under same tid\"\"\"\n matchByEvent = []\n for e1 in eventList1:\n tid = e1[2]\n print(tid)\n for e2 in eventList2:\n if e1[-2:] == e2[-2:]:\n event = e1[1]\n print(event)\n matchByEvent.append((tid, event))\n return matchByEvent\n\n\n'''databsed connection variables'''\ndbConnect = \"dbname='harveyTwitts' user='postgres' host='localhost' password='123456'\"\ntw_event_tb = \"test_events\"\nurl_event_tb = \"test_urlevents\"\n\n'''data select from db'''\ntw_events = queryFromDB.get_allData(dbConnect, tw_event_tb)\nprint(\"events from tweets\", len(tw_events))\nurl_events = queryFromDB.get_allData(dbConnect, url_event_tb)\nprint(\"events from tweets\", len(url_events))\n\nmatchEvent = checkEvents(tw_events, url_events)\nprint(\"matched events\", len(matchEvent))\n","sub_path":"analysis_Credibility/level2.py","file_name":"level2.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"253948287","text":"from flask import Flask, g\nfrom flask_sqlalchemy import SQLAlchemy\n\n\ndb = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_mapping(\n SQLALCHEMY_DATABASE_URI='sqlite:////tmp/alayatodo.db',\n SECRET_KEY='development key',\n USERNAME='admin',\n PASSWORD='default',\n SQLALCHEMY_ECHO=True,\n )\n\n db.init_app(app)\n\n from alayatodo import models\n from alayatodo import views\n\n app.register_blueprint(views.bp)\n\n return app\n\ndef init_db():\n db.drop_all()\n db.create_all()\n","sub_path":"alayatodo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"632008039","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\n\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport tkinter.filedialog\nimport os\nimport csv\n\nOUTPUT = './deformated.txt'\nNPY_OUTPUT = 'robot.npy'\n\nif __name__==\"__main__\":\n print('dataset maker')\n \n root = tkinter.Tk()\n root.withdraw()\n fType = [(\"dataset\",\"txt\")]\n iDir = os.path.abspath(os.path.dirname(__file__))\n file_path = tkinter.filedialog.askopenfile(filetype=fType, initialdir=iDir)\n \n print('File >>', file_path.name)\n \n #------------------------------\n # raw data set object\n #------------------------------\n raw_data = np.genfromtxt(fname=file_path.name,\n dtype=None,\n names=['role','situ',\n 'bx','by','ax','ay','bx','by','cx','cy','d',\n 'wl','t',\n 'shoot','pass','ballget','clear','active','cover','waitpass'],\n encoding='utf-8',delimiter='\\t',comments='#')\n\n # print(raw_data)\n\n\n #------------------------------\n # extraction alpha dataset\n #------------------------------\n alpha_data = []\n beta_data = []\n gamma_data = []\n for dat in raw_data:\n if dat[0] == 'α':\n tmp = [v for v in dat]\n alpha_data.append(tmp[2:])\n if dat[0] == 'β':\n tmp = [v for v in dat]\n beta_data.append(tmp[2:])\n if dat[0] == 'γ':\n tmp = [v for v in dat]\n gamma_data.append(tmp[2:])\n\n alpha_data = np.array(alpha_data)\n beta_data = np.array(beta_data)\n gamma_data = np.array(gamma_data)\n\n\n\n print('Alpha {} >>'.format(len(alpha_data)*18))\n # print(alpha_data)\n\n #\n # change shape for T-SOM\n #\n alpha_data = alpha_data.flatten(order='F')\n beta_data = beta_data.flatten(order='F')\n gamma_data = gamma_data.flatten(order='F')\n # np.savetxt('test.txt', tmp, encoding='utf-8')\n\n #titin puipui\n alpha_data = np.reshape(alpha_data, (-1, 1))\n beta_data = np.reshape(beta_data, (-1, 1))\n gamma_data = np.reshape(gamma_data, (-1, 1))\n # print(alpha_data.shape)\n\n train_data = np.hstack([alpha_data, beta_data])\n train_data = np.hstack([train_data, gamma_data])\n print('Stacked {}'.format(train_data.shape))\n\n PARAM_NUM = 18\n PRODUCT_NUM = 270\n ROLE_NUM = 3\n print(PARAM_NUM, PRODUCT_NUM, ROLE_NUM)\n train_data = np.reshape(train_data,(PARAM_NUM, PRODUCT_NUM, ROLE_NUM))\n\n print(\"TRAIN DATA {} >>\".format(train_data.shape))\n # print(train_data)\n\n train_data = np.transpose(train_data, (1,2,0))\n\n #debug\n print(train_data[:,0,11]-train_data[:,1,11])\n\n print(\"TRANSPOSED {} >>\".format(train_data.shape))\n # print(train_data)\n\n #------------------------------\n # save to npy\n #------------------------------ \n np.save(NPY_OUTPUT, train_data)\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"Questionnaire/dataset/dataset_maker.py","file_name":"dataset_maker.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"285316588","text":"#! /usr/bin/env python3\n#\n#test_neuro.py\n#\n\"\"\"Unit tests for neuro.py\"\"\"\n\n#standard modules:\nimport math\nimport unittest\nfrom copy import deepcopy\nfrom random import randrange, randint, random, choice, uniform\nfrom numbers import Number as _Number\nfrom collections.abc import Sequence as _Sequence\n#included modules:\nfrom neuro import *\n\n#global parameters:\n_NUM = 50 #number of invokes per test\n_SIZE = 20 #size coefficient that is describes how big test items must be\n#notive: the size must be at least 3, ERROR othewise\n\n\n\nclass TestNeuralNetwork(unittest.TestCase):\n \n #helping methods:\n __mulsum = lambda W, O: sum(map(lambda o, w: o*w, O, W))\n __sigmoid = lambda x: 1/(1 + math.e**-x)\n @classmethod\n def __out(cls, W, O):\n return cls.__sigmoid(cls.__mulsum(W[:-1], O) + W[-1])\n \n def test_multioutput_sigmoid_backpropagation(self):\n setup = i, j, k = 6, 4, 3\n sp = 0.25 #learning speen coefficient\n alg = Algorithms.SigmoidBackPropagation #current algorithm\n sigmoid = self.__class__.__sigmoid #activation function\n out = self.__class__.__out #output calculator\n mulsum = self.__class__.__mulsum\n N = Network(*setup, n = sp, algorithm = alg)\n # | o | | | | |\n # | o | | | | |\n # | o | | o | | | } NETWORK\n # | o | | o | | o |->output\n # | o | | o | | o |->output\n # | o | | o | | o |->output\n # _________________\n # I J K\n #\n # There are two sets of weighs: the weighs from layer i to j \n # and from j to k respectively\n \n Lyer = N._links #get links\n Outs = N._Network__algorithm._SigmoidBackPropagation__outputs\n Lclc = deepcopy(Lyer)\n sel = tuple(random() for x in range(i)) #testing selection\n res = [0]*k\n res[randint(0, len(res) - 1)] = 1\n learning_outcome = N.learn(sel, res)\n \n #FORWARD PROPAGATION:\n #step i-outputs:\n self.assertSequenceEqual(Outs[0], sel)\n self.assertEqual(len(Outs[0]), i)\n\n #calculate j - outputs:\n j_outs = []\n for n in Lclc[0]:\n j_outs.append(out(n, sel))\n #check j-outputs:\n self.assertSequenceEqual(Outs[1], j_outs)\n self.assertEqual(len(Outs[1]), j)\n\n #calculate k - outputs:\n k_outs = []\n for n in Lclc[1]:\n k_outs.append(out(n, j_outs))\n #check k-outputs:\n self.assertSequenceEqual(Outs[2], k_outs)\n self.assertEqual(len(Outs[2]), k)\n\n #BACK PROPAGATION:\n #calculate new layer:\n k_delta = tuple(map(lambda o, t: o*(1 - o)*(o - t), k_outs, res))\n #init next psy:\n j_psi = []\n for lnj in range(len(Lclc[-2])):\n j_psi.append(\n sum(k_delta[n]*Lclc[-1][n][lnj] \n for n in range(len(k_delta))))\n #correct all weights\n for ln in range(len(Lclc[-1])):\n dw = sp*k_delta[ln]\n for k in range(len(j_outs)):\n Lclc[-1][ln][k] -= j_outs[k]*dw\n Lclc[-1][ln][-1] -= dw\n\n self.assertTrue(len(Lyer[-1]), len(Lclc[-1]))\n self.assertSequenceEqual(Lyer[-1], Lclc[-1])\n\n #calculate new layer:\n j_delta = tuple(\n j_outs[lnj]*(1 - j_outs[lnj])*j_psi[lnj] \n for lnj in range(len(Lclc[-2])))\n for ln in range(len(Lclc[-2])):\n dw = sp*j_delta[ln]\n for k in range(len(sel)):\n Lclc[-2][ln][k] -= sel[k]*dw\n Lclc[-2][ln][-1] -= dw\n\n self.assertTrue(len(Lyer[-2]), len(Lclc[-2]))\n self.assertSequenceEqual(Lyer[-2], Lclc[-2])\n \n #TEST ACTIVATION FUNCTION:\n aouts = tuple(N.activate(sel))\n #calculate j - outputs:\n j_outs = []\n for n in Lclc[0]:\n j_outs.append(out(n, sel))\n #calculate k - outputs:\n k_outs = []\n for n in Lclc[1]:\n k_outs.append(out(n, j_outs))\n \n #check k-outputs:\n self.assertSequenceEqual(aouts, k_outs)\n self.assertEqual(len(aouts), len(k_outs))\n\n\n def ftest_network_structure(self):\n setup = i, j, k = 5, 2, 1\n # | o | | | | |\n # | o | | o | | |\n # | o | | | | o | } NEURONS\n # | o | | o | | |\n # | o | | | | |\n # ___________________\n # I J K\n #\n # So there are two sets of weighs: the weighs from layer i to j \n # and from k to k respectively\n N = Network(setup)\n self.assertEqual(len(N[:]), 2, \n 'wrong structure: the number of weights is wrong')\n self.assertEqual(len(N[0] + N[1]), j + k,\n 'wrong structure: the number of neurons is wrong')\n self.assertEqual(len(N[0][0]) + len(N[0][1]), 12, \n 'wrong struncture: the number the weighs from I to J '\n 'is wrong')\n self.assertEqual(len(N[1][0]), 3, \n 'wrong struncture: the number the weighs ' \n 'from J to K is wrong')\n\n def ftest_network_evaluation(self):\n W = [random() for x in range(12)]\n setup = 5, 2, 1\n ins = [1, 2, 3, 4, 5]\n N = Network(setup)\n bias = 0.05\n N[0][0][:5], N[0][0][-1] = W[:5], bias\n N[0][1][:5], N[0][1][-1] = W[5:10], bias\n N[1][0][:2], N[1][0][-1] = W[10:], bias\n #expected result:\n o1 = out(W[:5] + [bias], ins)\n o2 = out(W[5:10] + [bias], ins)\n oo = sigmoid(o1*W[10] + o2*W[11] + bias)\n #neural network structure validating:\n self.assertTrue((N[0][0][:-1] == W[:5] and \n N[0][1][:-1] == W[5:10] and \n N[1][0][:-1] == W[10:]), 'the weighs are incorrect')\n #evaluate method validating:\n self.assertEqual(next(N.evaluate(ins)), oo, 'invalid output')\n\n def ftest_network_learning_1(self):\n W = [random() for x in range(12)]\n setup = 5, 2, 1\n ins = [1, 2, 3, 4, 5]\n N = Network(setup)\n bias = 0.05\n N[0][0][-1] = N[0][1][-1] = N[1][0][-1] = bias #biases are zeros\n N[0][0][:5] = W[:5]\n N[0][1][:5] = W[5:10]\n N[1][0][:2] = W[10:]\n #expected result:\n o1 = out(W[:5] + [bias], ins)\n o2 = out(W[5:10] + [bias], ins)\n oo = sigmoid(o1*W[10] + o2*W[11] + bias)\n t = 1\n delta_k = oo*(1 - oo)*(oo - t)\n psai_k = W[10]*delta_k, W[11]*delta_k\n W[10] -= o1*delta_k\n W[11] -= o2*delta_k\n\n #hidden layer weighs correction\n #first neuron:\n delta_o1 = o1*(1 - o1)*psai_k[0]\n for i in range(5):\n W[i]-=ins[i]*delta_o1\n delta_o2 = o2*(1 - o2)*psai_k[1]\n for i in range(5, 10):\n W[i]-=ins[i - 5]*delta_o2\n E = N.learn(ins, (t,))\n #error checking:\n self.assertEqual(E, 0.5*(oo - t)**2)\n #weighs correction from k-1 to k:\n self.assertEqual(N[1][0], \n W[10:] + [-delta_k], \n \"invalid weight correction on the output layer\")\n #validating the hidden layer neurons' weithgs:\n self.assertEqual(\n N[0][0],\n W[:5] + [-delta_o1], \n \"invalid weight correction on the hidden layer\")\n self.assertEqual(N[0][1], \n W[5:10] + [-delta_o2],\n \"invalid weight correction on the hidden layer\")\n \n def ftest_network_learning_2(self):\n setup = (6, 2, 3, 1)\n ins = [1, 99, 1, 11, 3, 123]\n t = 1\n \n N = Network(setup)\n W = []\n for i in range(0, len(setup) - 1):\n W.append([random() for x in range(setup[i]*setup[i + 1])])\n for j in range(setup[i + 1]):\n N[i][j][:setup[i]] = W[i][j*setup[i]:(j + 1)*setup[i]]\n\n #structure validating:\n test_i = randint(1, len(setup) - 1)\n self.assertEqual(len(N[test_i-1]), setup[test_i])\n self.assertEqual(len(N[test_i-1][0]) -1, setup[test_i-1])\n\n #forward iteration 1:\n Oi1 = out(W[0][0:6], ins)\n Oi2 = out(W[0][6:12], ins)\n i_outs = Oi1, Oi2\n \n #forward iteration 2:\n Oj1 = out(W[1][0:2], i_outs)\n Oj2 = out(W[1][2:4], i_outs)\n Oj3 = out(W[1][4:6], i_outs)\n j_outs = Oj1, Oj2, Oj3\n \n #forward iteration 3:\n Ok = out(W[2], j_outs)\n\n #backward iteration 1:\n delta_k = Ok*(1 - Ok)*(Ok - t)\n psai = (W[2][0]*delta_k, W[2][1]*delta_k, W[2][2]*delta_k)\n W[2][0] -= Oj1*delta_k\n W[2][1] -= Oj2*delta_k\n W[2][2] -= Oj3*delta_k\n\n #helping func:\n def calc_delta(O, P):\n return list(map(lambda o, p: o*(1 - o)*p, O, P))\n #backward iteration 2:\n delta_J = calc_delta(j_outs, psai)\n psai = ((\n W[1][0]*delta_J[0] + \n W[1][2]*delta_J[1] + \n W[1][4]*delta_J[2]\n ),\n W[1][1]*delta_J[0] + \n W[1][3]*delta_J[1] + \n W[1][5]*delta_J[2])\n\n W[1][0] -= Oi1*delta_J[0]\n W[1][1] -= Oi2*delta_J[0]\n\n W[1][2] -= Oi1*delta_J[1]\n W[1][3] -= Oi2*delta_J[1]\n \n W[1][4] -= Oi1*delta_J[2]\n W[1][5] -= Oi2*delta_J[2]\n\n #backward iteration 3:\n delta_I = calc_delta(i_outs, psai)\n for i in range(len(delta_I)):\n for j in range(6):\n W[0][i*6 + j] -= ins[j - i*6]*delta_I[i]\n\n E = N.learn(ins, (t,))\n self.assertEqual(E,0.5*(Ok-t)**2)\n #layer k checking:\n self.assertEqual(N[2][0], W[2] + [-delta_k])\n #layer j checking:\n self.assertEqual(N[1][0], W[1][0:2] + [-delta_J[0]])\n self.assertEqual(N[1][1], W[1][2:4] + [-delta_J[1]])\n self.assertEqual(N[1][2], W[1][4:6] + [-delta_J[2]])\n #leyar i checking:\n self.assertEqual(N[0][0], W[0][:6] + [-delta_I[0]])\n self.assertEqual(N[0][1], W[0][6:] + [-delta_I[1]])\n\nclass TestMutableNeuralNetwork(unittest.TestCase):\n \n def test_instance(self):\n layers = (5, 4, 1)\n m = MutableNetwork(*layers, n = 0.05)\n\n self.assertSequenceEqual(m.shape, layers)\n self.assertEqual(m.ninps, layers[0])\n self.assertEqual(m.nouts, layers[-1])\n self.assertEqual(m.speed, 0.05)\n self.assertEqual(repr(m), \n \"MutableNetwork({}, {}, {}, n = 0.05)\".format(*layers))\n self.assertTrue(HiddenLayers(m)) #true when the network has at \n #least one hidden layer, false otherwise\n self.assertTrue(InputLayer(m)) #always true\n self.assertTrue(OutputLayer(m)) #alwayes true\n self.assertFalse( #__len__() is called to consider bool value\n HiddenLayers(MutableNetwork(9, 2))) #len == 0 (no h-layers)\n\n self.assertIsNot(InputLayer(m), m.input_layer)\n self.assertIsNot(HiddenLayers(m), m.hidden_layers)\n self.assertIsNot(OutputLayer(m), m.output_layer)\n\n self.assertRaises(ValueError, MutableNetwork, 3) #too few args\n self.assertRaises(ValueError, MutableNetwork, 3, 0, 1) #empty layer\n self.assertRaises(ValueError, MutableNetwork, 8, -4, 1) #negative\n \n self.assertRaises(TypeError, MutableNetwork, 10, 9, 7, 1.01, 3)\n self.assertRaises(TypeError, MutableNetwork, 1.2, 9) #float size\n with self.assertRaises(TypeError):\n #verify that the speed coefficient cannot be non-numbers\n MutableNetwork(3, 2, n = 'str')\n self.assertRaises(TypeError, HiddenLayers, [0, 1])\n self.assertRaises(TypeError, OutputLayer, 99)\n self.assertRaises(TypeError, InputLayer, 'shrub')\n\n def test_primitives(self):\n self.assertIsInstance(Primitives.initweight(), _Number)\n #init sequence test:\n w_cnt = randrange(1, _SIZE)\n weights = Primitives.initweights(w_cnt)\n self.assertIsInstance(weights, _Sequence)\n for w in weights:\n self.assertIsInstance(w, _Number)\n self.assertEqual(len(weights), w_cnt)\n self.assertEqual(len(Primitives.initneuron(w_cnt)), w_cnt + 1)\n #init layer test:\n n_cnt = randrange(1, _SIZE)\n lyr = Primitives.initlayer(n_cnt, w_cnt)\n self.assertEqual(len(lyr), n_cnt)\n for n in lyr:\n self.assertIsInstance(n, _Sequence)\n self.assertEqual(len(n), w_cnt + 1)\n\n #adjusting layer:\n wshift = randrange(1, _SIZE)\n Primitives.adjustlayer(lyr, w_cnt + wshift)\n for n in lyr:\n self.assertIsInstance(n, _Sequence)\n self.assertEqual(len(n), w_cnt + wshift + 1)\n for w in n:\n self.assertIsInstance(w, _Number)\n\n self.assertRaises(ValueError, Primitives.initneuron, 0)\n self.assertRaises(TypeError, Primitives.initlayer, 2.1, 99)\n self.assertRaises(ValueError, Primitives.initlayer, \n randrange(-_SIZE, 1), 99)\n self.assertRaises(ValueError, Primitives.initlayer, 3, \n randrange(-_SIZE, 1))\n self.assertRaises(ValueError, Primitives.adjustlayer, lyr,\n randrange(-_SIZE, 1))\n\n def test_neuron_view_1(self):\n \"\"\"Tests basic operations of NeuronView\"\"\"\n test_nlinks = randrange(1, _SIZE)\n test_seq = Primitives.initneuron(test_nlinks)\n test_view = NeuronView(test_seq)\n eval_view = eval(repr(test_view))\n\n self.assertEqual(eval_view, test_view)\n self.assertSequenceEqual(eval_view, test_view)\n \n self.assertEqual(eval_view, test_seq)\n self.assertSequenceEqual(eval_view, test_seq[:-1])\n\n self.assertEqual(len(test_view), test_nlinks)\n self.assertEqual(test_view.bias, test_seq[-1])\n self.assertSequenceEqual(test_view.weights, test_seq[:-1])\n self.assertSequenceEqual(test_view.tolist(), test_seq)\n \n #simple mutation:\n test_index = randrange(len(test_view))\n test_value = uniform(-_SIZE, _SIZE)\n test_view[test_index] = test_value\n self.assertEqual(test_view[test_index], test_value)\n self.assertEqual(test_view[test_index], test_seq[test_index])\n\n test_seq[test_index] = uniform(-_SIZE, _SIZE)\n self.assertEqual(test_view[test_index], test_seq[test_index])\n self.assertFalse(test_view.tolist() is test_seq) #if copy\n\n #errors:\n self.assertRaises(IndexError, test_view.__getitem__, \n choice([-1, 1])*len(test_seq))\n self.assertRaises(TypeError, test_view.__getitem__, 2.33)\n self.assertRaises(TypeError, test_view.__setitem__, \n \"cowabunga dude!\")\n with self.assertRaises(TypeError):\n test_view.bias = \"Pokemon\"\n\n def test_neuron_view_2(self):\n \"\"\"Tests set and get methods of NeuronView by using mixed slices\"\"\"\n sz = _SIZE\n for x in range(_NUM):\n nlinks = randrange(1, sz)\n links = Primitives.initneuron(nlinks)\n view = NeuronView(links)\n\n tslice = slice(randrange(0, sz), randrange(0, sz), \n choice([1, -1])*randrange(1, 4))\n self.assertSequenceEqual(links[:-1][tslice], view[tslice])\n slice_len = len(range(*tslice.indices(len(view))))\n new_weights = Primitives.initweights(slice_len)\n view[tslice] = new_weights\n \n self.assertSequenceEqual(links[:-1][tslice], new_weights)\n self.assertSequenceEqual(links[:-1][tslice], view[tslice])\n \n self.assertRaises(ValueError, view.__setitem__, tslice, \n [0]*(nlinks + 1))\n self.assertRaises(ValueError, view.__getitem__, \n slice(None, None, 0))\n self.assertRaises(ValueError, view.__setitem__, \n slice(None, None, 0), [])\n self.assertRaises(TypeError, view.__setitem__, \n slice(None, None), ['spam']*len(view))\n\n indx = randrange(len(view))\n with self.assertRaises(TypeError):\n view[randrange(len(view))] = 'S'\n\n self.assertEqual(view[indx:indx], [])\n \n def test_get_hlayer(self):\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem(minsize = 3)\n L = M.hidden_layers\n test_start = randrange(0, len(L)) #target index\n test_slice = slice(test_start, randrange(test_start, len(L)))\n self.assertTrue(\n all(all(isinstance(n, NeuronView) for n in lyr) \n for lyr in L[test_slice]), \n 'inappropriate type of returning values')\n #check correspondence between M._links[s] and M[s]\n for Mi, Li in zip(M._links[test_slice], L[test_slice]):\n for Mij, Lij in zip(Mi, Li):\n self.assertSequenceEqual(Mij[:-1], Lij) #only weights\n self.assertSequenceEqual(\n Mij[:-1], Lij.weights) #only weights\n self.assertEqual(Mij[-1], Lij.bias) #only bias term\n self.assertSequenceEqual(Mij, Lij.tolist())\n\n #check slices at random layer\n test_layer_index = test_start\n test_layer = tuple(L[test_layer_index])\n test_start = randrange(len(test_layer))\n test_slice = slice(test_start, \n randrange(0, len(test_layer)))\n self.assertTrue(all(\n isinstance(n, NeuronView) for n in test_layer[test_slice]),\n 'inappropriate tupe of returning values')\n for m, n in zip(M._links[test_layer_index][test_slice], \n test_layer[test_slice]):\n self.assertSequenceEqual(m[:-1], n) #only weights\n self.assertSequenceEqual(m[:-1], n.weights) #only weights\n self.assertEqual(m[-1], n.bias) #only bias term\n self.assertSequenceEqual(m, n.tolist())\n \n #weird index combinations:\n self.assertEqual(L[test_layer_index:test_layer_index], tuple())\n self.assertEqual(list(L[test_layer_index, \n test_start:test_start]), [])\n\n self.assertSequenceEqual(tuple(L[test_layer_index, :]), \n tuple(L[test_layer_index]))\n self.assertEqual(list(L[test_layer_index, \n test_slice.start:len(test_layer):-1]), [])\n\n #exceptions:\n self.assertRaises(TypeError, L.__getitem__, (test_slice, 1)\n #the double index notation should not accept slices\n #at the first part\n )\n self.assertRaises(IndexError, L.__getitem__, len(M._links) - 1\n #the hidden layer view allow access by input layer's \n #index\n )\n self.assertRaises(IndexError, L.__getitem__, \n choice([1,-1])*(randrange(0, _SIZE) + len(M._links)),\n #index error is not raised when the given index is\n #out of range\n )\n self.assertRaises(ValueError, L.__getitem__, \n slice(test_slice.start, test_slice.stop, 0)\n ) #slice step cannot be zero\n\n def test_insert_hlayer_1(self):\n \"\"\"\n Verify inserting a new layer using simple sequences\n \"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n L = M.hidden_layers\n test_index = randint(0, len(L)) #target index\n #height of the current layer:\n height = M.shape[test_index] #number of inpurts per neuron\n test_layer = Primitives.initlayer(randrange(1, _SIZE), height)\n L.insert(test_index, test_layer)\n #next layer:\n next_layer = M._links[test_index + 1] #adjusted layer\n inserted_layer = M._links[test_index] #inserted layer\n #if the next layer consistent:\n self.assertTrue(\n all(len(l) - 1 == len(test_layer) for l in next_layer),\n \"lost consistency after insertion\")\n self.assertEqual(inserted_layer, test_layer, \n \"the inserted layer does not match the initial layer\")\n #checking if there is no dependencies between the inserted \n #layer and the source layer:\n self.assertTrue(all(not l is v for l, v in \n zip(test_layer, inserted_layer)), \n \"inserted layer has a dependency on its source\")\n \n fake_layer = Primitives.initlayer(randrange(1, _SIZE), height)\n fake_layer[randrange(len(fake_layer))].append(0) #contains the \n #wrong number of weights\n \n #run with fake values:\n self.assertRaises(ValueError, L.insert, test_index, fake_layer)\n self.assertRaises(TypeError, L.insert, randint(0, len(L)), \n [\"Em-bin-gun-do\", \"Endin-bo-go\"])\n self.assertRaises(ValueError, L.insert, \n test_index, [[0]*height])\n\n def test_insert_hlayer_2(self):\n \"\"\"\n Verify inserting a new layer using mixed sequences \n \"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n L = M.hidden_layers\n test_index = randint(0, len(L)) #target index\n #height of the current layer:\n height = M.shape[test_index]\n test_layer = tuple(choice([tuple, NeuronView, list])(\n Primitives.initweights(height + 1)) for x in range(\n randrange(2, _SIZE)))\n L.insert(test_index, test_layer)\n next_layer = M._links[test_index + 1] #adjusted layer\n self.assertTrue(all(len(l) - 1 == len(test_layer) \n for l in next_layer), \"lost consistency after insertion\")\n \n self.assertRaises(ValueError, L.insert, test_index, \n [NeuronView(Primitives.initweights(height + 2)) \n for x in range(randrange(1, _SIZE))])\n \n def test_delete_hlayer(self):\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem(minsize = 3)\n L = M.hidden_layers\n test_index = randrange(0, len(L)) #target index\n #delete one lyr:\n del L[test_index]\n links_per_neuron = M.shape[test_index]\n next_layer = M._links[test_index]\n self.assertTrue(all(len(n) - 1 == links_per_neuron \n for n in next_layer), \"lost consistency after deleting\")\n #delete all:\n del L[:]\n self.assertTrue(all(len(n) == M.ninps #'n' is NeuronView \n for n in M.output_layer), \"lost consistency in the \"\n \"output layer after deleting all hidden layers\")\n\n def test_setget_hlayer(self):\n \"\"\"Tests assignment, deletion and evaluation implementations of \n HiddenLayers (__setitem__, __delitem__, __getitem__)\"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n #to ensure that the count of inputs does not changes:\n ninps = M.ninps #initial count of inputs\n H = M.hidden_layers\n shape = M.shape\n start = randrange(len(M) - 1)\n inset = [Primitives.initlayer(\n randrange(1, _SIZE), shape[start])]\n inset.append(Primitives.initlayer(randrange(1, _SIZE), \n len(inset[0])))\n H[start:] = inset\n for o in M.output_layer:\n self.assertEqual(len(o), len(inset[1]))\n #deletion test:\n del H[:]\n for o in M.output_layer:\n self.assertEqual(len(o), ninps)\n\n def test_output_layer_1(self):\n \"\"\"Tests basic operations of OutputLayer\"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n O = M.output_layer\n rindex = randrange(len(O)) #random index\n view = O[rindex]\n tnode = M._links[-1][rindex] #target node\n self.assertSequenceEqual(view, tnode[:-1])\n self.assertEqual(view.bias, tnode[-1])\n #mutaion test:\n windex = randrange(len(view))\n wvalue = randrange(-_SIZE, _SIZE)\n view[windex] = wvalue\n\n self.assertEqual(tnode[windex], wvalue)\n #check how consistency is reestablished after mutation:\n links = M.shape[-2]\n if M.nlayr > 2:\n H = M.hidden_layers\n H[-1, links:] = [Primitives.initneuron(M.shape[-3])]\n b = len(tuple(H[-1, :]))\n else:\n I = M.input_layer\n I.insert(len(I))\n \n self.assertEqual(len(view), links + 1)\n self.assertEqual(len(tnode), links + 2)\n self.assertSequenceEqual(tnode, view)\n\n @staticmethod\n def __inititem(minsize = 2):\n return MutableNetwork(*(\n randrange(1, _SIZE) for x in range(randrange(minsize, _SIZE))))\n\n\n###########################################################################\n### Run tests\n###########################################################################\n\ndef _test():\n unittest.main(verbosity = 2)\n\n#run test:\nif __name__ == '__main__':\n _test()\n","sub_path":"multinet/nn/test_neuro.py","file_name":"test_neuro.py","file_ext":"py","file_size_in_byte":25555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"326553491","text":"import logging\nimport os\nfrom typing import List, Optional, Tuple\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nimport scipy.sparse as ss\n\nfrom gleams import config\nfrom gleams.feature import encoder, spectrum\nfrom gleams.ms_io import ms_io\n\n\nlogger = logging.getLogger('gleams')\n\n\ndef _peaks_to_features(dataset: str, filename: str,\n metadata: Optional[pd.DataFrame],\n enc: encoder.SpectrumEncoder)\\\n -> Tuple[str, Optional[pd.DataFrame], Optional[List[ss.csr_matrix]]]:\n \"\"\"\n Convert the spectra with the given identifiers in the given file to a\n feature array.\n\n Parameters\n ----------\n dataset : str\n The peak file's dataset.\n filename : str\n The peak file name.\n metadata : Optional[pd.DataFrame]\n DataFrame containing metadata for the PSMs in the peak file to be\n processed. If None, all spectra in the peak file are converted to\n features.\n enc : encoder.SpectrumEncoder\n The SpectrumEncoder used to convert spectra to features.\n\n Returns\n -------\n Tuple[str, Optional[pd.DataFrame], Optional[List[ss.csr_matrix]]]\n A tuple of length 3 containing: the name of the file that has been\n converted, information about the converted spectra (scan number,\n precursor charge, and precursor m/z), the converted spectra.\n If the given file does not exist the final two elements of the tuple\n are None.\n \"\"\"\n peak_filename = os.path.join(\n os.environ['GLEAMS_HOME'], 'data', 'peak', dataset, filename)\n if not os.path.isfile(peak_filename):\n logger.warning('Missing peak file %s, no features generated',\n peak_filename)\n return filename, None, None\n logger.debug('Process file %s/%s', dataset, filename)\n file_scans, file_mz, file_charge, file_encodings = [], [], [], []\n if metadata is not None:\n metadata = metadata.reset_index(['dataset', 'filename'], drop=True)\n for spec in ms_io.get_spectra(peak_filename):\n if ((metadata is None or np.int64(spec.identifier) in metadata.index)\n and spectrum.preprocess(spec, config.fragment_mz_min,\n config.fragment_mz_max).is_valid):\n file_scans.append(spec.identifier)\n file_mz.append(spec.precursor_mz)\n file_charge.append(spec.precursor_charge)\n file_encodings.append(enc.encode(spec))\n scans = pd.DataFrame({'scan': file_scans, 'charge': file_charge,\n 'mz': file_mz})\n scans['scan'] = scans['scan'].astype(np.int64)\n return filename, scans, file_encodings\n\n\ndef convert_peaks_to_features(metadata_filename: str)\\\n -> None:\n \"\"\"\n Convert all peak files listed in the given metadata file to features.\n\n Encoded spectra will be stored as NumPy binary files for each dataset in\n the metadata. A corresponding index file for each dataset containing the\n peak filenames, spectrum identifiers, and indexes in the NumPy binary file\n will be stored as Parquet files.\n\n If both the NumPy binary file and the Parquet index file already exist, the\n corresponding dataset will _not_ be processed again.\n\n Parameters\n ----------\n metadata_filename : str\n The metadata file name. Should be a Parquet file.\n \"\"\"\n metadata = pd.read_parquet(metadata_filename)\n metadata = metadata.set_index(['dataset', 'filename', 'scan'])\n\n enc = encoder.MultipleEncoder([\n encoder.PrecursorEncoder(\n config.num_bits_precursor_mz, config.precursor_mz_min,\n config.precursor_mz_max, config.num_bits_precursor_mass,\n config.precursor_mass_min, config.precursor_mass_max,\n config.precursor_charge_max),\n encoder.FragmentEncoder(\n config.fragment_mz_min, config.fragment_mz_max, config.bin_size),\n encoder.ReferenceSpectraEncoder(\n config.ref_spectra_filename, config.fragment_mz_min,\n config.fragment_mz_max, config.fragment_mz_tol,\n config.num_ref_spectra)\n ])\n\n logger.info('Convert peak files for metadata file %s', metadata_filename)\n feat_dir = os.path.join(os.environ['GLEAMS_HOME'], 'data', 'feature',\n 'dataset')\n if not os.path.isdir(feat_dir):\n try:\n os.makedirs(os.path.join(feat_dir))\n except OSError:\n pass\n dataset_total = len(metadata.index.unique('dataset'))\n for dataset_i, (dataset, metadata_dataset) in enumerate(\n metadata.groupby('dataset', as_index=False, sort=False), 1):\n # Group all encoded spectra per dataset.\n feat_dir = os.path.join(os.environ['GLEAMS_HOME'], 'data', 'feature')\n filename_encodings = os.path.join(\n feat_dir, 'dataset', f'{dataset}.npz')\n filename_index = os.path.join(\n feat_dir, 'dataset', f'{dataset}.parquet')\n if (not os.path.isfile(filename_encodings) or\n not os.path.isfile(filename_index)):\n logging.info('Process dataset %s [%3d/%3d]', dataset, dataset_i,\n dataset_total)\n metadata_index, encodings = [], []\n for filename, file_scans, file_encodings in\\\n joblib.Parallel(n_jobs=-1, backend='multiprocessing')(\n joblib.delayed(_peaks_to_features)\n (dataset, fn, md_fn, enc)\n for fn, md_fn in metadata_dataset.groupby(\n 'filename', as_index=False, sort=False)):\n if file_scans is not None and len(file_scans) > 0:\n metadata_index.extend([(dataset, filename, scan)\n for scan in file_scans['scan']])\n encodings.extend(file_encodings)\n # Store the encoded spectra in a file per dataset.\n if len(metadata_index) > 0:\n ss.save_npz(filename_encodings, ss.vstack(encodings, 'csr'))\n metadata.loc[metadata_index].reset_index().to_parquet(\n filename_index, index=False)\n\n\ndef combine_features(metadata_filename: str) -> None:\n \"\"\"\n Combine feature files for multiple datasets into a single feature file.\n\n If the combined feature file already exists it will _not_ be recreated.\n\n Parameters\n ----------\n metadata_filename : str\n Features for all datasets included in the metadata will be combined.\n Should be a Parquet file.\n \"\"\"\n feat_dir = os.path.join(os.environ['GLEAMS_HOME'], 'data', 'feature')\n feat_filename = os.path.join(feat_dir, os.path.splitext(\n os.path.basename(metadata_filename))[0].replace('metadata', 'feature'))\n if (os.path.isfile(f'{feat_filename}.npz') and\n os.path.isfile(f'{feat_filename}.parquet')):\n return\n datasets = pd.read_parquet(\n metadata_filename, columns=['dataset'])['dataset'].unique()\n logger.info('Combine features for metadata file %s containing %d datasets',\n metadata_filename, len(datasets))\n encodings, indexes = [], []\n for i, dataset in enumerate(datasets, 1):\n logger.debug('Append dataset %s [%3d/%3d]', dataset, i, len(datasets))\n dataset_encodings_filename = os.path.join(\n feat_dir, 'dataset', f'{dataset}.npz')\n dataset_index_filename = os.path.join(\n feat_dir, 'dataset', f'{dataset}.parquet')\n if (not os.path.isfile(dataset_encodings_filename) or\n not os.path.isfile(dataset_index_filename)):\n logger.warning('Missing features for dataset %s, skipping...',\n dataset)\n else:\n encodings.append(ss.load_npz(dataset_encodings_filename))\n indexes.append(pq.read_table(dataset_index_filename))\n ss.save_npz(f'{feat_filename}.npz', ss.vstack(encodings, 'csr'))\n pq.write_table(pa.concat_tables(indexes), f'{feat_filename}.parquet')\n","sub_path":"gleams/feature/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":8073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"457430424","text":"import numpy as np\nimport matplotlib as plt\nimport os\nimport serial\nimport time\nimport h5py\nimport sys\nimport matplotlib.pyplot as plt\nfrom frgpl.camera import camera\nfrom frgpl.stage import stage\nfrom frgpl.kepco import kepco\nfrom frgpl.daq import daq\nfrom frgpl.laser import laser\nfrom frgpl.tec import omega\nimport datetime\nimport time\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom tqdm import tqdm\nimport threading\nimport pdb\nimport winsound\nfrom frgpl.checkPLmaps import plotPL\n\nsoundpath='C:\\\\Users\\\\Operator\\\\Documents\\\\GitHub\\\\Instruments\\\\FRG Hardware\\\\frgpl\\\\frgpl\\\\tada.wav'\n\nroot = 'C:\\\\Users\\\\Operator\\\\Desktop\\\\frgPL'\t\t#default folder to save data\nif not os.path.exists(root):\n\tos.mkdir(root)\ndatafolder = os.path.join(root, 'Data')\nif not os.path.exists(datafolder):\n\tos.mkdir(datafolder)\ncalibrationfolder = os.path.join(root, 'Calibration')\nif not os.path.exists(calibrationfolder):\n\tos.mkdir(calibrationfolder)\n\n\nclass control:\n\n\tdef __init__(self, kepcoport = 'COM5',laserport = 'COM1', spotmapnumber = None):\n\t\t# hardware properties\n\t\tself.kepcoport = kepcoport\n\t\tself.laserport = laserport\n\t\tself.__laserON = False\n\t\tself.__kepcoON = False\n\t\tself.__cameraON = False\n\n\t\t# measurement settings\n\t\tself.bias = 0\t\t\t#bias applied to sample\n\t\tself.laserpower = 0\t#current supplied to laser ###may replace this with n_suns, if calibration is enabled\n\t\tself.saturationtime = 0.5\t#delay between applying voltage/illumination and beginning measurement\n\t\tself.numIV = 20\t\t#number of IV measurements to average\n\t\tself.numframes = 50\t#number of image frames to average\n\t\tself.__temperature = 25\t#TEC stage temperature setpoint (C) during measurement\n\t\tself.temperatureTolerance = 0.2\t#how close to the setpoint we need to be to take a measurement (C)\n\t\tself.maxSoakTime = 60\t# max soak time, in seconds, to wait for temperature to reach set point. If we reach this point, just go ahead with the measurement\n\t\tself.note = ''\n\t\tself._spotMap = None\t# optical power map of laser spot, used for PL normalization\n\t\tself._sampleOneSun = None # fractional laser power with which to approximate one-sun injection levels\n\t\tself._sampleOneSunJsc = None # target Jsc, matching of which is used for one-sun injection level is approximated\n\t\tself._sampleOneSunSweep = None # fractional laser power vs photocurrent (Isc), fit to provide one-sun estimate\n\t\tself.__previewFigure = None\t#handle for matplotlib figure, used for previewing most recent image results\n\t\tself.__previewAxes = [None, None]\t# handle for matplotib axes, used to hold the image and colorbar\n\t\tself.__backgroundImage = None\n\n\t\t# data saving settings\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\t\tself.outputDirectory = os.path.join(root, 'Data', todaysDate)\t#default save locations is desktop/frgPL/Data/(todaysDate)\n\t\tself.sampleName = None\n\t\tself.__dataBuffer = [] # buffer to hold data files during sequential measurements of single sample. Held until a batch export\n\n\t\t# stage/positioning constants\n\t\tself.__sampleposition = (52000, 56000)\t#position where TEC stage is centered in camera FOV, um\n\t\tself.__detectorposition = (68000, 117000)\t#delta position between detector and sampleposition, um.\n\t\tself.__fov = (77000, 56000)\t#dimensions of FOV, um\n\n\t\tself.connect()\n\t\tself.loadSpotCalibration(spotmapnumber)\n\t@property\n\tdef temperature(self):\n\t\treturn self.__temperature\n\n\t@temperature.setter\n\tdef temperature(self, t):\n\t\tif self.tec.setSetPoint(t):\n\t\t\tself.__temperature = t\n\t\t\n\n\tdef connect(self):\n\t\tself.camera = camera()\t\t# connect to FLIR camera\n\t\tself.kepco = kepco()\t\t# connect to Kepco\n\t\tself.kepco.set(voltage=0) # set voltage to 0, seems to solve current compliance issues\n\t\tself.laser = laser()\t\t# Connect to OSTECH Laser\n\t\tself.daq = daq()\t\t\t# connect to NI-USB6000 DAQ\n\t\tself.stage = stage(sampleposition = self.__sampleposition)\t\t# connect to FRG stage\n\t\tself.tec = omega()\t\t\t# connect to omega PID controller, which is driving the TEC stage.\n\t\t\n\tdef disconnect(self):\n\t\ttry:\n\t\t\tself.camera.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect camera')\n\n\t\ttry:\n\t\t\tself.kepco.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect Kepco')\n\t\ttry:\n\t\t\tself.laser.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect OSTech Laser')\n\t\ttry:\n\t\t\tself.daq.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect DAQ')\n\t\ttry:\n\t\t\tself.stage.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect stage')\n\t\ttry:\n\t\t\tself.tec.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect TEC controller')\n\n\n\t### basic use functions\n\n\tdef setMeas(self, bias = None, laserpower = None, suns = None, saturationtime = None, temperature = None, numIV = None, numframes = None, note = ''):\n\n\t\tif bias is None:\n\t\t\tbias = self.bias\n\t\tif laserpower is None:\n\t\t\tif suns is None:\n\t\t\t\tlaserpower = self.laserpower\n\t\t\telse:\n\t\t\t\tif self._sampleOneSun is None:\n\t\t\t\t\tprint('Error: can\\'t use \"suns =\" without calibration - please run .findOneSun to calibrate one-sun power level for this sample.')\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tlaserpower = suns * self._sampleOneSun\n\t\t\t\t\tif (laserpower > 1) or (laserpower < 0):\n\t\t\t\t\t\tmaxsuns = 1/self._sampleOneSun\n\t\t\t\t\t\tprint('Error: {0} suns is out of range! Based on laser power and current sample, allowed suns range = 0 - {1}.'.format(suns, maxsuns))\n\t\t\t\t\t\tif laserpower > 1:\n\t\t\t\t\t\t\tprint('Setting to max laser power ({0} suns)'.format(maxsuns))\n\t\t\t\t\t\t\tlaserpower = 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint('Setting laser off')\n\t\t\t\t\t\t\tlaserpower = 0\n\t\t\t\t\t\t# return False\n\t\tif saturationtime is None:\n\t\t\tsaturationtime = self.saturationtime\n\t\tif temperature is None:\n\t\t\ttemperature = self.__temperature\n\t\tif numIV is None:\n\t\t\tnumIV = self.numIV\n\t\tif numframes is None:\n\t\t\tnumframes = self.numframes\n\n\n\t\tresult = self.kepco.set(voltage = bias)\n\t\tif result:\n\t\t\tself.bias = bias\n\t\telse:\n\t\t\tprint('Error setting kepco')\n\t\t\t# return False\n\n\t\tresult = self.laser.set(power = laserpower)\n\n\t\tif result:\n\t\t\tself.laserpower = laserpower\n\t\telse:\n\t\t\tprint('Error setting laser')\n\t\t\t# return False\n\n\n\t\tresult = self.tec.setSetPoint(temperature)\n\t\tif result:\n\t\t\tself.__temperature = temperature\n\t\telse:\n\t\t\tprint('Error setting TEC temperature')\n\t\t\t# return False\n\n\n\t\tself.numIV = numIV\n\t\tself.numframes = numframes\n\t\tself.note = note\n\n\tdef takeMeas(self, lastmeasurement = True, preview = True, imputeHotPixels = False):\n\t\t### takes a measurement with settings stored in method (can be set with .setMeas()).\n\t\t#\tmeasurement settings + results are appended to .__dataBuffer\n\t\t#\n\t\t#\tif .__dataBuffer is empty (ie, no measurements have been taken yet), takeMeas() will \n\t\t#\tautomatically take a 0 bias, 0 laser power baseline measurement before the scheduled\n\t\t#\tmeasurement.\n\n\t\tif len(self.__dataBuffer) == 0: # sample is being measured for the first time, take a baseline image\n\t\t\tprint('New sample: taking a 0 bias, 0 illumination baseline image.')\n\t\t\t# store scheduled measurement parameters\n\t\t\tsavedlaserpower = self.laserpower\n\t\t\tsavedbias = self.bias\n\t\t\tsavednote = self.note\n\n\t\t\t# take a 0 bias, 0 laserpower measurement, append to .__dataBuffer\n\t\t\tself.setMeas(bias = 0, laserpower = 0, note = 'automatic baseline image')\n\t\t\tself._waitForTemperature()\n\t\t\tmeasdatetime = datetime.datetime.now()\n\t\t\ttemperature = self.tec.getTemperature()\n\t\t\tim, _, _ = self.camera.capture(frames = self.numframes, imputeHotPixels = imputeHotPixels)\n\t\t\tv, i = self.kepco.read(counts = self.numIV)\n\t\t\tirradiance = self._getOpticalPower()\n\t\t\ttemperature = (temperature + self.tec.getTemperature()) / 2\t#average the temperature from just before and after the measurement. Typically averaging >1 second of time here.\n\t\t\tmeas = {\n\t\t\t\t'sample': \tself.sampleName,\n\t\t\t\t'note':\t\tself.note,\n\t\t\t\t'date': \tmeasdatetime.strftime('%Y-%m-%d'),\n\t\t\t\t'time':\t\tmeasdatetime.strftime('%H:%M:%S'),\n\t\t\t\t'cameraFOV':self.__fov,\n\t\t\t\t'bias':\t\tself.bias,\n\t\t\t\t'laserpower': self.laserpower,\n\t\t\t\t'saturationtime': self.saturationtime,\n\t\t\t\t'numIV':\tself.numIV,\n\t\t\t\t'numframes':self.numframes,\n\t\t\t\t'v_meas':\tv,\n\t\t\t\t'i_meas':\ti,\n\t\t\t\t'image':\tim,\n\t\t\t\t'image_bgcorrected': im-im,\n\t\t\t\t'irradiance_ref': irradiance, \n\t\t\t\t'temperature':\ttemperature,\n\t\t\t\t'temperature_setpoint': self.temperature\n\t\t\t}\n\t\t\tself.__dataBuffer.append(meas)\t\n\t\t\tself.__backgroundImage = im \t#store background image for displaying preview\n\n\t\t\t# restore scheduled measurement parameters + continue \t\n\t\t\tself.setMeas(bias = savedbias, laserpower = savedlaserpower, note = savednote)\n\n\t\tif not self.__laserON and self.laserpower > 0:\n\t\t\tself.laser.on()\n\t\t\tself.__laserON = True\n\t\tif not self.__kepcoON: #and self.bias is not 0:\n\t\t\tself.kepco.on()\t#turn on the kepco source\n\t\t\tself.__kepcoON = True\n\n\t\ttime.sleep(self.saturationtime)\n\n\t\t#take image, take IV meas during image\n\t\tself._waitForTemperature()\n\t\tmeasdatetime = datetime.datetime.now()\n\t\ttemperature = self.tec.getTemperature()\n\t\tim, _, _ = self.camera.capture(frames = self.numframes, imputeHotPixels = imputeHotPixels)\n\t\tv, i = self.kepco.read(counts = self.numIV)\n\t\t#pdb.set_trace()\n\t\tirradiance = self._getOpticalPower()\n\t\ttemperature = (temperature + self.tec.getTemperature()) / 2\t#average the temperature from just before and after the measurement. Typically averaging >1 second of time here.\n\n\t\tif self.__laserON and lastmeasurement:\n\t\t\tself.laser.off()\n\t\t\tself.__laserON = False\n\t\tif self.__kepcoON and lastmeasurement:\n\t\t\tself.kepco.off()\n\t\t\tself.__kepcoON = False\n\n\t\tmeas = {\n\t\t\t'sample': \tself.sampleName,\n\t\t\t'note':\t\tself.note,\n\t\t\t'date': \tmeasdatetime.strftime('%Y-%m-%d'),\n\t\t\t'time':\t\tmeasdatetime.strftime('%H:%M:%S'),\n\t\t\t'cameraFOV':self.__fov,\n\t\t\t'bias':\t\tself.bias,\n\t\t\t'laserpower': self.laserpower,\n\t\t\t'saturationtime': self.saturationtime,\n\t\t\t'numIV':\tself.numIV,\n\t\t\t'numframes':self.numframes,\n\t\t\t'v_meas':\tv,\n\t\t\t'i_meas':\ti,\n\t\t\t'image':\tim,\n\t\t\t'image_bgcorrected': self._backgroundCorrection(im),\n\t\t\t'irradiance_ref': irradiance,\n\t\t\t'temperature': temperature,\n\t\t\t'temperature_setpoint': self.temperature\n\t\t}\n\t\tself.__dataBuffer.append(meas)\n\n\t\tif preview:\n\t\t\tself.displayPreview(self._backgroundCorrection(im), v, i)\n\n\t\treturn im, v, i\n\n\tdef displayPreview(self, img, v, i):\n\t\tdef handle_close(evt, self):\n\t\t\tself.__previewFigure = None\n\t\t\tself.__previewAxes = [None, None]\n\t\t\n\t\tif self.__previewFigure is None:\t#preview window is not created yet, lets make it\n\t\t\tplt.ioff()\n\t\t\tself.__previewFigure, self.__previewAxes[0] = plt.subplots()\n\t\t\tdivider = make_axes_locatable(self.__previewAxes[0])\n\t\t\tself.__previewAxes[1] = divider.append_axes('right', size='5%', pad=0.05)\n\t\t\tself.__previewFigure.canvas.mpl_connect('close_event', lambda x: handle_close(x, self))\t# if preview figure is closed, lets clear the figure/axes handles so the next preview properly recreates the handles\n\t\t\tplt.ion()\n\t\t\tplt.show()\n\n\t\tfor ax in self.__previewAxes:\t#clear the axes\n\t\t\tax.clear()\n\t\timg_handle = self.__previewAxes[0].imshow(img)\n\t\tself.__previewFigure.colorbar(img_handle, cax = self.__previewAxes[1])\n\t\tself.__previewAxes[0].set_title('{0} V, {1} A, {2} Laser'.format(v, i, self.laserpower))\n\t\tself.__previewFigure.canvas.draw()\n\t\tself.__previewFigure.canvas.flush_events()\n\t\ttime.sleep(1e-4)\t\t#pause allows plot to update during series of measurements \n\n\tdef save(self, samplename = None, note = '', outputdirectory = None, reset = True):\n\t\tif len(self.__dataBuffer) == 0:\n\t\t\tprint('Data buffer is empty - no data to save!')\n\t\t\treturn False\n\n\t\t## figure out the sample directory, name, total filepath\n\t\tif samplename is not None:\n\t\t\tself.sampleName = samplename\n\n\t\tif outputdirectory is not None:\n\t\t\tself.outputDirectory = outputdirectory\n\t\tif not os.path.exists(self.outputDirectory):\n\t\t\tos.mkdir(self.outputDirectory)\n\n\t\tfids = os.listdir(self.outputDirectory)\n\t\tsampleNumber = 1\n\t\tfor fid in fids:\n\t\t\tif 'frgPL' in fid:\n\t\t\t\tsampleNumber = sampleNumber + 1\n\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\n\t\tif self.sampleName is not None:\n\t\t\tfname = 'frgPL_{0}_{1:04d}_{2}.h5'.format(todaysDate, sampleNumber, self.sampleName)\n\t\telse:\n\t\t\tfname = 'frgPL_{0}_{1:04d}.h5'.format(todaysDate, sampleNumber)\n\t\t\tself.sampleName = ''\n\n\t\tfpath = os.path.join(self.outputDirectory, fname)\n\n\t\t## build each category in h5 file\n\n\t\t### example dataset saved to _dataBuffer by .takeMeas\n\t\t# meas = {\n\t\t# \t'sample': \tself.sampleName,\n\t\t# \t'date': \tmeasdatetime.strftime('%Y-%m-%d'),\n\t\t# \t'time':\t\tmeasdatetime.strftime('%H:%M:%S'),\n\t\t# \t'cameraFOV':self.__fov,\n\t\t# \t'bias':\t\tself.bias,\n\t\t# \t'laserpower': self.laserpower,\n\t\t# \t'saturationtime': self.saturationtime,\n\t\t# \t'numIV':\tself.numIV,\n\t\t# \t'numframes':self.numframes,\n\t\t# \t'v_meas':\tv,\n\t\t# \t'i_meas':\ti,\n\t\t# \t'image':\tim,\n\t\t# }\n\n\t\tnumData = len(self.__dataBuffer)\n\n\t\tdata = {}\n\t\tfor field in self.__dataBuffer[0].keys():\n\t\t\tdata[field] = []\n\t\t### field to store normalized PL images\n\t\t# if self._spotmap is not None:\n\t\t# \tdata['image_norm'] = []\n\n\t\tfor meas in self.__dataBuffer:\n\t\t\tfor field, measdata in meas.items():\n\t\t\t\tdata[field].append(measdata)\n\t\t\t\t### normalize PL images here\n\t\t\t\t# if field is 'image' and self._spotmap is not None:\n\t\t\t\t# \tdata['image_norm']\n\n\n\t\t## write h5 file\n\n\t\twith h5py.File(fpath, 'w') as f:\n\t\t\t# sample info\n\t\t\tinfo = f.create_group('/info')\n\t\t\tinfo.attrs['description'] = 'Metadata describing sample, datetime, etc.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('name', data = self.sampleName.encode('utf-8'))\n\t\t\ttemp.attrs['description'] = 'Sample name.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('notes', data = np.array(note.encode('utf-8')))\n\t\t\ttemp.attrs['description'] = 'Any notes describing each measurement.'\n\n\t\t\tdate = info.create_dataset('date', data = np.array([x.encode('utf-8') for x in data['date']]))\n\t\t\ttemp.attrs['description'] = 'Measurement date.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('time', data = np.array([x.encode('utf-8') for x in data['time']]))\n\t\t\ttemp.attrs['description'] = 'Measurement time of day.'\n\n\n\t\t\t# measurement settings\n\t\t\tsettings = f.create_group('/settings')\n\t\t\tsettings.attrs['description'] = 'Settings used for measurements.'\n\n\t\t\ttemp = settings.create_dataset('vbias', data = np.array(data['bias']))\n\t\t\ttemp.attrs['description'] = 'Nominal voltage bias set by Kepco during measurement.'\n\n\t\t\ttemp = settings.create_dataset('notes', data = np.array([x.encode('utf-8') for x in data['note']]))\n\t\t\ttemp.attrs['description'] = 'Any notes describing each measurement.'\n\n\t\t\ttemp = settings.create_dataset('laserpower', data = np.array(data['laserpower']))\n\t\t\ttemp.attrs['description'] = 'Fractional laser power during measurement. Calculated as normalized laser current (max current = 55 A). Laser is operated at steady state.'\n\n\t\t\ttemp = settings.create_dataset('sattime', data = np.array(data['saturationtime']))\n\t\t\ttemp.attrs['description'] = 'Saturation time for laser/bias conditioning prior to sample measurement. Delay between applying condition and measuring, in seconds.'\n\n\t\t\ttemp = settings.create_dataset('numIV', data = np.array(data['numIV']))\n\t\t\ttemp.attrs['description'] = 'Number of current/voltage measurements averaged by Kepco when reading IV.'\n\n\t\t\ttemp = settings.create_dataset('numframes', data = np.array(data['numframes']))\n\t\t\ttemp.attrs['description'] = 'Number of camera frames averaged when taking image.'\n\n\t\t\ttemp = settings.create_dataset('tempsp', data = np.array(data['temperature_setpoint']))\n\t\t\ttemp.attrs['description'] = 'TEC stage temperature setpoint for each measurement.'\n\n\n\t\t\tif self.stage.position[0] is None:\n\t\t\t\tstagepos = self.__sampleposition\n\t\t\telse:\n\t\t\t\tstagepos = self.stage.position\n\n\t\t\ttemp = settings.create_dataset('position', data = np.array(stagepos))\n\t\t\ttemp.attrs['description'] = 'Stage position during measurement.'\n\n\t\t\tif self._sampleOneSun is not None:\n\t\t\t\tsuns = [x/self._sampleOneSun for x in data['laserpower']]\n\t\t\t\ttemp = settings.create_dataset('suns', data = np.array(suns))\n\t\t\t\ttemp.attrs['description'] = 'PL injection level in terms of suns. Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t# calibrations\n\t\t\tcalibrations = f.create_group('/calibrations')\n\t\t\tcalibrations.attrs['description'] = 'Instrument calibrations to be used for data analysis.'\n\n\t\t\ttemp = settings.create_dataset('samplepos', data = np.array(self.__sampleposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um)[x,y] where sample is centered in camera field of view'\n\n\t\t\ttemp = settings.create_dataset('detectorpos', data = np.array(self.__detectorposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um) [x,y] where photodetector is centered in camera field of view'\n\n\t\t\ttemp = settings.create_dataset('camerafov', data = np.array(self.__fov))\n\t\t\ttemp.attrs['description'] = 'Camera field of view (um) [x,y]'\n\n\t\t\tif self._spotMap is not None:\n\t\t\t\ttemp = calibrations.create_dataset('spot', data = np.array(self._spotMap))\n\t\t\t\ttemp.attrs['description'] = 'Map [y, x] of incident optical power across camera FOV, can be used to normalize PL images. Laser power set to 0.5 during spot mapping.'\n\n\t\t\t\ttemp = calibrations.create_dataset('spotx', data = np.array(self._spotMapX))\n\t\t\t\ttemp.attrs['description'] = 'X positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\t\t\ttemp = calibrations.create_dataset('spoty', data = np.array(self._spotMap))\n\t\t\t\ttemp.attrs['description'] = 'Y positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\t\tif self._sampleOneSunSweep is not None:\n\t\t\t\ttemp = calibrations.create_dataset('onesunsweep', data = np.array(self._sampleOneSunSweep))\n\t\t\t\ttemp.attrs['description'] = 'Laser current vs photocurrent, measured for this sample. Column 1: fractional laser current. Column 2: total photocurrent (Isc), NOT current density (Jsc). Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t\ttemp = calibrations.create_dataset('onesun', data = np.array(self._sampleOneSun))\n\t\t\t\ttemp.attrs['description'] = 'Fractional laser current used to approximate a one-sun injection level. Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t\ttemp = calibrations.create_dataset('onesunjsc', data = np.array(self._sampleOneSunJsc))\n\t\t\t\ttemp.attrs['description'] = 'Target Jsc (NOT Isc) used to approximate a one-sun injection level. Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t# raw data\n\t\t\trawdata = f.create_group('/data')\n\t\t\trawdata.attrs['description'] = 'Raw measurements taken during imaging'\n\n\t\t\ttemp = rawdata.create_dataset('image', data = np.array(data['image']), chunks = True, compression = 'gzip')\n\t\t\ttemp.attrs['description'] = 'Raw images acquired for each measurement.'\n\n\t\t\ttemp = rawdata.create_dataset('image_bgc', data = np.array(data['image_bgcorrected']), chunks = True, compression = 'gzip')\n\t\t\ttemp.attrs['description'] = 'Background-subtracted images acquired for each measurement.'\n\n\t\t\ttemp = rawdata.create_dataset('v', data = np.array(data['v_meas']))\n\t\t\ttemp.attrs['description'] = 'Voltage measured during measurement'\n\n\t\t\ttemp = rawdata.create_dataset('i', data = np.array(data['i_meas']))\n\t\t\ttemp.attrs['description'] = 'Current (not current density!) measured during measurement'\n\n\t\t\ttemp = rawdata.create_dataset('irr_ref', data = np.array(data['irradiance_ref']))\n\t\t\ttemp.attrs['description'] = 'Measured irradiance @ photodetector during measurement. Note that the photodetector is offset from the sample FOV. Assuming that the laser spot is centered on the sample, this value is lower than the true sample irradiance. This value should be used in conjunction with a .spotMap() calibration map.'\t\t\t\n\n\t\t\ttemp = rawdata.create_dataset('temp', data = np.array(data['temperature']))\n\t\t\ttemp.attrs['description'] = 'Measured TEC stage temperature during measurement. This value is the average of two temperature measurements, just before and after the image/kepco readings/photodetector readings are made. These two values typically span >1 second'\n\n\t\tprint('Data saved to {0}'.format(fpath))\n\t\tif reset:\n\t\t\tself._sampleOneSun = None\n\t\t\tself._sampleOneSunSweep = None\n\t\t\tself._sampleOneSunJsc = None\n\t\t\tself.samplename = None\n\t\t\tself.__backgroundImage = None\n\n\t\t\tprint('Note: sample name and one sun calibration results have been reset to None')\n\t\t\n\t\tself.__dataBuffer = []\n\n\t\treturn fpath\n\n\t### tile imaging\n\tdef tileImages(self, xmin, xmax, numx, ymin, ymax, numy, frames = 100):\n\t\tx0, y0 = self.stage.position\n\t\txp = [int(x) for x in np.linspace(x0+xmin, x0+xmax, numx)]\n\t\typ = [int(y) for y in np.linspace(y0+ymin, y0+ymax, numy)]\n\t\tims = np.zeros((numy, numx, 512, 640))\n\t\tself.stage.moveto(x = xp[0], y = yp[0])\n\t\ttime.sleep(5) #sometimes stage says its done moving too early, expect that on first move which is likely a longer travel time\n\n\t\tflip = True #for snaking\n\t\tfor m, y in tqdm(enumerate(yp), total = numy, desc = 'Y', leave = False):\n\t\t\tif flip:\n\t\t\t\tflip = False\n\t\t\telse:\n\t\t\t\tflip = True\n\t\t\tself.stage.moveto(y = y)\n\t\t\tfor n, x in tqdm(enumerate(xp), total = numx, desc = 'X', leave = False):\n\t\t\t\tif flip:\n\t\t\t\t\tnn = -n-1\n\t\t\t\t\txx = xp[nn]\n\t\t\t\telse:\n\t\t\t\t\tnn = n\n\t\t\t\t\txx = x\n\t\t\t\tself.stage.moveto(x = xx)\n\t\t\t\tims[m,nn], _, _ = self.camera.capture(frames = frames)\n\t\tself.stage.moveto(x = x0, y = y0)\n\t\treturn ims, xp, yp\n\n\t### calibration methods\n\n\tdef findOneSun(self, jsc, area):\n\t\t### finds fraction laser power for which measured jsc = target value from solar simulator JV testing.\n\t\t# jsc: short circuit current density in mA/cm^2 (positive)\n\t\t# area: active area cm^2\n\t\tif jsc < 1:\n\t\t\tprint('Please provide jsc in units of mA/cm^2, and area in units of cm^2')\n\t\t\treturn False\n\n\t\tisc = -jsc * area / 1000 \t#negative total current in amps, since kepco will be measuring total photocurrent as amps\n\n\t\tlaserpowers = np.linspace(0,1, 7)[1:]\t#skip 0, lean on lower end to reduce incident power\n\t\tself.kepco.set(voltage = 0)\n\n\t\tlaserjsc = np.zeros(len(laserpowers))\n\n\t\tself.laser.set(power = laserpowers[0])\t\t#set to first power before turning on laser\n\t\tself.laser.on()\n\t\tself.kepco.on()\n\t\tfor idx, power in enumerate(laserpowers):\n\t\t\tself.laser.set(power = power)\n\t\t\ttime.sleep(self.saturationtime)\n\t\t\t_,laserjsc[idx] = self.kepco.read(counts = 25) \n\t\tself.laser.off()\n\t\tself.kepco.off()\n\n\t\t#pdb.set_trace()\n\n\t\tpfit = np.polyfit(laserjsc, laserpowers, 2)\n\t\tp = np.poly1d(pfit)\t#polynomial fit object where x = measured jsc, y = laser power applied\n\t\t\n\t\tself._sampleOneSun = p(isc)\n\t\tself._sampleOneSunSweep = [laserpowers, laserjsc]\n\t\tself._sampleOneSunJsc = jsc\n\n\t\t#pdb.set_trace()\n\n\t\treturn p(isc), laserpowers, laserjsc\t#return laser power to match target jsc\n\n\tdef calibrateSpot(self, numx = 21, numy = 21, rngx = None, rngy = None, laserpower = 0.5, export = True):\n\t\t### maps an area around the sample FOV, finds the optical power at each point\n\t\tprint(\"calibration starting\")\n\n\t\tif not self.stage._homed:\n\t\t\tprint('Homing stage')\n\t\t\tself.stage.gohome()\n\t\t#default calibration area range = camera FOV\n\t\tif rngx is None:\n\t\t\trngx = self.__fov[0]\n\t\tif rngy is None:\n\t\t\trngy = self.__fov[1]\n\n\t\txpos = np.linspace(self.__detectorposition[0] - (rngx/2), self.__detectorposition[0] + (rngx/2), numx).astype(int)\n\t\typos = np.linspace(self.__detectorposition[1] - (rngy/2), self.__detectorposition[1] + (rngy/2), numy).astype(int)\n\t\t\n\t\tself.laser.set(power = laserpower)\n\t\tself._spotMap = np.zeros((numy, numx))\n\t\tself._spotMapX = xpos\n\t\tself._spotMapY = ypos\n\t\t\n\t\tprint('Moving to start position ({0}, {1})'.format(xpos[0], ypos[0]))\n\t\tif not self.stage.moveto(x = xpos[0], y = ypos[0]):\n\t\t\tprint('Error moving stage to starting position ({0}, {1}) - stage is probably not homed. run method ._stage.gohome()'.format(xpos[0], ypos[0]))\t\t\n\t\t\treturn False\n\n\t\tself.laser.on()\n\t\tflip = 1\n\t\tfor m, x in tqdm(enumerate(xpos), desc = 'X', total = len(xpos), leave = False):\n\t\t\tflip = flip * -1\n\t\t\tself.stage.moveto(x = x)\n\t\t\tfor n in tqdm(range(len(ypos)), desc = 'Y', total = len(ypos), leave = False):\n\t\t\t\tif flip > 0:\t\t#use nn instead of n, accounts for snaking between lines\n\t\t\t\t\tnn = len(ypos) - n - 1\n\t\t\t\telse:\n\t\t\t\t\tnn = n\n\t\t\t\tself.stage.moveto(y = ypos[nn])\n\t\t\t\tself._spotMap[nn,m] = self._getOpticalPower()/100 # suns\n\t\tself.laser.off()\n\n\t\tself.stage.moveto(x = self.__sampleposition[0], y = self.__sampleposition[1])\t#return stage to camera FOV\n\n\t\tif export:\n\t\t\tself.saveSpotCalibration(note = 'Autosaved by calibrateSpot')\n\n\tdef saveSpotCalibration(self, note = ''):\n\t\tfids = os.listdir(calibrationfolder)\n\t\tsampleNumber = 1\n\t\tfor fid in fids:\n\t\t\tif 'frgPL_spotCalibration' in fid:\n\t\t\t\tsampleNumber = sampleNumber + 1\n\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\t\ttodaysTime = datetime.datetime.now().strftime('%H:%M:%S')\n\t\tfname = 'frgPL_spotCalibration_{0}_{1:04d}.h5'.format(todaysDate, sampleNumber)\n\t\tfpath = os.path.join(calibrationfolder, fname)\n\n\t\t## write h5 file\n\n\t\twith h5py.File(fpath, 'w') as f:\n\t\t\t# sample info\n\t\t\tinfo = f.create_group('/info')\n\t\t\tinfo.attrs['description'] = 'Metadata describing sample, datetime, etc.'\n\t\t\t\n\t\t\t# temp = info.create_dataset('name', data = self.sampleName.encode('utf-8'))\n\t\t\t# temp.attrs['description'] = 'Sample name.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('notes', data = note.encode())\n\t\t\ttemp.attrs['description'] = 'Any notes describing each measurement.'\n\n\t\t\ttemp = info.create_dataset('date', data = todaysDate.encode())\n\t\t\ttemp.attrs['description'] = 'Measurement date.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('time', data = todaysTime.encode())\n\t\t\ttemp.attrs['description'] = 'Measurement time of day.'\n\n\n\t\t\t# calibrations\n\t\t\tcalibrations = f.create_group('/calibrations')\n\t\t\tcalibrations.attrs['description'] = 'Instrument calibrations to be used for data analysis.'\n\n\t\t\ttemp = calibrations.create_dataset('samplepos', data = np.array(self.__sampleposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um)[x,y] where sample is centered in camera field of view'\n\n\t\t\ttemp = calibrations.create_dataset('detectorpos', data = np.array(self.__detectorposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um) [x,y] where photodetector is centered in camera field of view'\n\n\t\t\ttemp = calibrations.create_dataset('camerafov', data = np.array(self.__fov))\n\t\t\ttemp.attrs['description'] = 'Camera field of view (um) [x,y]'\n\n\t\t\ttemp = calibrations.create_dataset('spot', data = np.array(self._spotMap))\n\t\t\ttemp.attrs['description'] = 'Map [y, x] of incident optical power across camera FOV, can be used to normalize PL images. Laser power set to 0.5 during spot mapping.'\n\n\t\t\ttemp = calibrations.create_dataset('spotx', data = np.array(self._spotMapX))\n\t\t\ttemp.attrs['description'] = 'X positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\t\ttemp = calibrations.create_dataset('spoty', data = np.array(self._spotMapY))\n\t\t\ttemp.attrs['description'] = 'Y positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\tprint('Data saved to {0}'.format(fpath))\t\n\n\tdef loadSpotCalibration(self, calibrationnumber = None):\n\t\tfids = os.listdir(calibrationfolder)\n\t\tcalnum = []\n\t\tfor fid in fids:\n\t\t\tif 'frgPL_spotCalibration' in fid:\n\t\t\t\tcalnum.append(int(fid.split('_')[3].split('.')[0]))\n\t\t\telse:\n\t\t\t\tcalnum.append(0)\n\n\t\tif len(calnum) == 0:\n\t\t\tprint('Could not find any calibration files! No spotmap loaded')\n\t\t\treturn False\n\n\t\tcalfile = fids[calnum.index(max(calnum))]\t#default to most recent calibration\n\t\t\n\t\tif calibrationnumber is not None:\n\t\t\ttry:\n\t\t\t\tcalfile = fids[calnum.index(calibrationnumber)]\n\t\t\texcept:\n\t\t\t\tprint('Could not find calibration {0}: defaulting to most recent calibration {1}'.format(calibrationnumber, max(calnum)))\n\t\tfpath = os.path.join(calibrationfolder, calfile)\n\t\t## write h5 file\n\n\t\twith h5py.File(fpath, 'r') as f:\n\t\t\tself._spotMap = f['calibrations']['spot'][:]\n\t\t\tself._spotMapX = f['calibrations']['spotx'][:]\n\t\t\tself._spotMapT = f['calibrations']['spoty'][:]\n\n\t\tprint('Loaded calibration {0} from {1}.'.format(calnum[fids.index(calfile)], fpath))\n\t\treturn True\n\n\t### group measurement methods\n\n\tdef takeRseMeas(self, vmpp, voc, vstep = 0.005):\n\t\t# generate list of biases spanning from vmpp to at least voc, with intervals of vstep\n\t\tbiases = [vmpp + (voc-vmpp)/2]\n\t\twhile biases[-1] < voc + 0.07:\t\t#go to 70 mV (about 10% of starting Voc) higher voltage than Voc, better fitting/calibration constant is linear\n\t\t\tbiases.append(biases[-1] + vstep)\n\n\t\twith tqdm(total = len(biases), desc = 'Rse EL', leave = False) as pb:\n\t\t\tfor bias in biases[0:-1]:\t#measure all but last with lastmeasurement = True (doesnt turn kepco off between measurements). Last measurement is normal\n\t\t\t\tself.setMeas(bias = bias, laserpower = 0, note = 'part of Rse measurement series')\n\t\t\t\tself.takeMeas(lastmeasurement = False)\n\t\t\t\tpb.update(1)\n\n\t\t\tself.setMeas(bias = biases[-1], laserpower = 0, note = 'part of Rse measurement series')\n\t\t\tself.takeMeas(lastmeasurement = True)\t\t\n\t\t\tpb.update(1)\n\n\tdef takePLIVMeas(self, vmpp, voc, jsc, area):\n\t\t### Takes images at varied bias and illumination for PLIV fitting of cell parameters\n\t\t### based on https://doi.org/10.1016/j.solmat.2012.10.010\n\n\t\tif self._sampleOneSun is None:\n\t\t\tself.findOneSun(jsc = jsc, area = area)\t\t# calibrate laser power to one-sun injection by matching jsc from solar simulator measurement\n\n\t\t# full factorial imaging across voltage (vmpp - voc) and illumination (0.2 - 1.0 suns). 25 images\n\t\tallbiases = np.append(0,np.linspace(vmpp, voc, 5))\t\t#range of voltages used for image generation (including short-circuit image at each intensity)\n\t\tallsuns = np.linspace(0.2, 1, 5)\t\t\t#range of suns (pl injection) used for image generation\n\n\t\tself.setMeas(bias = 0, suns = 1, temperature = 25, note = 'PLIV - open circuit PL image')\n\t\t# this should work, something else is going wrong occasionally.\n\t\tself.kepco.set(current = 0) # does not work as takeMeas will reset the voltage setting based on setMeas parameters. Better to set voc directly in setMeas.\n\t\t#pdb.set_trace()\n\t\tself.takeMeas()\n\n\t\twith tqdm(total = allbiases.shape[0] * allsuns.shape[0], desc = 'PLIV', leave = False) as pb:\n\t\t\tfor suns in allsuns:\n\t\t\t\tfor bias in allbiases:\n\t\t\t\t\tself.setMeas(bias = bias, suns = suns, temperature = 25, note = 'PLIV')\n\t\t\t\t\tself.takeMeas(lastmeasurement = False)\n\t\t\t\t\tpb.update(1)\n\n\n\t\tself.laser.off()\t#turn off the laser and kepco\n\t\tself.kepco.off()\n\n\t\t#self.save(samplename = 'Test_GG_Al_10_PLIV', note = '', reset = True) # remove this for a regular measurement with takePVRD2Meas\n\n\n\tdef takePVRD2Meas(self, samplename, note, vmpp, voc, jsc, area = 22.1, vstep = 0.005):\n\t\t#reset in case previous measurement was cancelled midway\n\t\tself.__dataBuffer = []\n\t\tself._sampleOneSun = None\n\t\tself._sampleOneSunSweep = None\n\t\tself._sampleOneSunJsc = None\n\t\tself.__backgroundImage = None\n\n\t\tself.takeRseMeas(\n\t\t\tvmpp = vmpp,\n\t\t\tvoc = voc,\n\t\t\tvstep = vstep\n\t\t\t)\n\n\t\tself.takePLIVMeas(\n\t\t\tvmpp = vmpp,\n\t\t\tvoc = voc,\n\t\t\tjsc = jsc,\n\t\t\tarea = area\n\t\t\t)\n\n\t\tself.setMeas(\n\t\t\tbias = -12,\n\t\t\tlaserpower = 0,\n\t\t\tnote = 'Reverse Bias EL'\n\t\t\t)\n\t\tself.takeMeas()\n\n\t\t#figure out the directory to save data to\n\t\tstoredOutputDir = self.outputDirectory\n\t\tself.outputDirectory = os.path.join(root, 'PVRD2 Degradation Study')\n\t\tif not os.path.exists(self.outputDirectory):\n\t\t\tos.mkdir(self.outputDirectory)\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\t\tself.outputDirectory = os.path.join(root, 'PVRD2 Degradation Study', todaysDate)\n\t\tif not os.path.exists(self.outputDirectory):\n\t\t\tos.mkdir(self.outputDirectory)\n\n\t\tfpath=self.save(samplename = samplename, note = note, reset = True)\n\n\t\tself.outputDirectory = storedOutputDir\n\n\t\twinsound.PlaySound(soundpath,winsound.SND_FILENAME)\n\t\tplotPL(fpath) # plot images to check the measurement\n\n\t### helper methods\n\tdef _waitForTemperature(self):\n\t\trefreshDelay = 0.5\t#how long to wait between temperautre checks, in seconds\n\t\treachedTemp = False\n\n\t\tstartTime = time.time()\n\t\twhile (not reachedTemp) and (time.time() - startTime <= self.maxSoakTime):\n\t\t\tcurrentTemp = self.tec.getTemperature()\n\t\t\tif np.abs(currentTemp - self.temperature) <= self.temperatureTolerance:\n\t\t\t\treachedTemp = True\n\t\t\telse:\n\t\t\t\ttime.sleep(refreshDelay)\n\n\t\tif not reachedTemp:\n\t\t\tprint('Did not reach {0} C within {1} seconds: starting measurement anyways.'.format(self.temperature, self.maxSoakTime))\n\n\t\treturn True\n\n\tdef _getOpticalPower(self):\n\t\t### reads signal from photodetector, converts to optical power using calibration vs thorlabs Si power meter (last checked 2019-08-20)\n\t\tcalibrationFit = [-0.1145, 9.1180]; #polyfit of detector reading vs (Si power meter / detector reading), 2019-08-20\n\t\tvoltage, _, _ = self.daq.acquire()\n\t\tpower = voltage * (calibrationFit[0]*voltage + calibrationFit[1])\t#measured optical power, units of mW/cm^2\n\n\t\treturn power\n\n\tdef _backgroundCorrection(self, img):\n\t\timg = img - self.__backgroundImage\n\t\timg[img<0] = 0\n\n\t\treturn img\n\t#def normalizePL(self):\n\t### used laser spot power map to normalize PL counts to incident optical power\n","sub_path":"FRG Hardware/frgpl/frgpl/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":33142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"148549684","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\ResultDashboard\\Dashboard\\DistMetricPVTab.py\n# Compiled at: 2020-03-15 13:04:26\n# Size of source mod 2**32: 15125 bytes\nimport dash_html_components as html\nfrom ResultDashboard.Dashboard.DashContent import *\nfrom ResultDashboard.Dashboard.DashPlot import *\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nimport dash_daq as daq, dash_table\n\nclass DistMetricPVTab:\n\n def __init__(self, app, DataObject):\n self.app = app\n self.DataObject = DataObject\n self.content = html.Div([\n self.FirstLayer(),\n self.SecondLayer(),\n self.ThirdLayer(),\n self.FourthLayer(),\n self.FifthLayer()])\n\n def FirstLayer(self):\n self.Heading_content = 'System Level Risk Metrics'\n self.Detail_content = 'Percentage time average customer would experience violations are defined as risk metrics. Violations are categorized into three types: Voltage violation (any voltage magnitude above 1.1 pu and below 0.9 pu) , line violation (loading aboove 100%) and transformer violation (above 100%). SARDI_voltage, SARDI_line, SARDI_transformer represent System Average Risk Duration Index for voltage, line and transformer violation respectievely. SARDI_aggregated represents System Average Risk Duration Index for all violations. Knowing how PV deployement would alter these risk metrics can better inform PV deployement decisions. Base case means no PV. PV scenarios is defined by two components. For e.g. 10%-100% PV scenario means that 10% of total customers (chosen uniformly randomly) have installed PV with a capcity to meet 100% of their annual energy need when they do not have PV in their system.'\n left_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.ViolationDict), ylabel='Risk Metric (%)').layout()))])], className='col')\n self.Heading_content = 'Percentage Energy Loss'\n self.Detail_content = 'Percentage energy Loss is an indicator of efficiency. Loss in the energy is a loss in economic reveune and also increases loss of life of an equipment (such as conductors and transformers). Along with risk metrics we also need to see how PV deployment affects percentage energy loss. Higher deployement of PV would increase loading in the distribution network thus increasing loss in the system. SE_line, SE_transformer and SE represent system energy loss for line elements (including both conductors and cables), system energy loss for transformers and overall system energy loss. Accuracy of these results depend on accuracy ofparameters of component such as resistance, reactance, capacitance, percentage loss during full load and no load of transformer etc. Furthermore, how accurate load profiles are also has an impact. Field measurements could certainly help validating these results.'\n right_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.Efficiency), ylabel='Energy Loss (%)').layout()))])], className='col')\n return html.Div([left_col, right_col], className='row margin-top-20')\n\n def SecondLayer(self):\n self.Heading_content = 'Percentage Loss of Life of Transformer'\n self.Detail_content = 'Transformer loss of life is a function of hot-spot temperature inside transformer element. Hot spot temperature further depends on loading pattern which certainly would be affected by PV deployment. IEEE C57.92-1981 provides detail description on how to compute loss of life from loading pattern. Here we have assumed life of transformer is determined by deterioration of insulating material because of temperature. The numbers are reliable only if the loadings are normal (meaning not severly high for long period of time). This may not be highly accurate now however provides relative understanding pattern in loss of life because of PV deployement providing more support to PV deployement decision.'\n left_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.Lossoflife), ylabel='Loss of Life - DTs (%)').layout()))])], className='col')\n self.Heading_content = 'Percentage Overgeneration by PV'\n self.Detail_content = 'Higher deployment of PV can cause reverse power flow in the system which can accumulate at the substation level. If there is a limit on reverse power flow because of storage constraints or market constraints or any other constraints deploying PV above certain percentage of overgeneration might be infesabile to utility. This metric further complements the PV deployement decesion by providing more insight on PV overgeneration. For now we have not included storage in the system. Furthermore, more advanced protection scheme might be necessary to allow reverse power flow in the system.'\n right_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.overgeneration), ylabel='PV Overgeneration (%)').layout()))])], className='col')\n return html.Div([left_col, right_col], className='row margin-top-20')\n\n def ThirdLayer(self):\n self.Heading_content = 'Time Series System Level Metrics: Understading daily variation of system level risk metrics'\n self.Detail_content = \"Now let's take a look at above metrics in time-series mode. How would above metrics vary in time at different PV scenarios would help us identify day when they are highly impacted. You can select PV scenarios and observe metric variation in the graph.Note you can multi-select parameters to observe. Values are aggregated for day.\"\n col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(),\n html.Div([\n html.Div([html.H6('Select System Level Metric'),\n dcc.Dropdown(id='Metric', options=[{'label':key, 'value':key} for key in self.DataObject.SystemMetrics],\n value=[\n 'SARDI_aggregated'],\n multi=True,\n style={'color': '#000000'})],\n className='col DropDown'),\n html.Div([html.H6('Select PV Penetration Scenario'),\n dcc.Dropdown(id='PVScenario', options=[{'label':key, 'value':key} for key in self.DataObject.Scenarios],\n value='Base',\n style={'color': '#000000'})],\n className='col H6 DropDown')],\n className='row'),\n html.Div([dcc.Graph(id='TimeSeriesSystemLevelMetric')])])\n return col\n\n def FourthLayer(self):\n TimeStamps = list(self.DataObject.SystemLevelMetricsTimeSeries['Base']['TimeStamp'])\n self.Heading_content = 'Time Series Asset Level Metric: Scatter plot on top of network map'\n self.Detail_content = 'Now that we know what the system level distribution metric look like, it is also important to know which asset are at vulnerable state or which asset is actually causing problem. The Scatter plot on top of network allows utility which components are vulnerable and where they are located and at what time. User can use dropdown menu to select different PV scenarios.'\n col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(),\n html.Div([\n html.Div([html.H6('Select Asset Level Metric'),\n dcc.Dropdown(id='AssetMetric', options=[{'label':key, 'value':key} for key in self.DataObject.AssetLevelMetrics],\n value='NVRI',\n style={'color': '#000000'})],\n className='col DropDown'),\n html.Div([html.H6('Select PV Penetration Scenario'),\n dcc.Dropdown(id='PVScenario2', options=[{'label':key, 'value':key} for key in self.DataObject.Scenarios],\n value='Base',\n style={'color': '#000000'})],\n className='col H6 DropDown')],\n className='row'),\n html.Div([html.H6('Slide for observing temporal change'),\n daq.Slider(id='TimeIndex', min=0, max=(len(TimeStamps)), value=3, step=1, marks={str(val):{'label': TimeStamps[val].strftime('%m-%d')} for val in range(0, len(TimeStamps), 6)}, size=1100)],\n style={'margin-left':'50px', \n 'margin-right':'10px'}),\n html.Div([dcc.Graph(id='AssetLevelMetricHeatMap')], style={'margin-top': '30px'})])\n return col\n\n def FifthLayer(self):\n self.Heading_content = 'Asset Level Metric: Table and Aggregated Map'\n self.Detail_content = ' The aggreagted metric for an asset is listed in table on the right and shown in the form of scatter heatmap on the left. Size and color both help to identify vulnerable component. The components are selected based on the metric you selected to observe in time series asset level metric.'\n col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(),\n html.Div([\n dash_table.DataTable(id='interactiveTable', columns=[], data=[], sort_action='native', column_selectable='single', sort_mode='multi',\n page_action='native',\n page_current=0,\n page_size=10,\n style_header={'backgroundColor':'rgb(30, 30, 30)', 'fontWeight':'bold'},\n style_cell={'backgroundColor':'rgb(30, 30, 30)', \n 'color':'white'})],\n className='col DropDown'),\n html.Div([dcc.Graph(id='AssetLocation')], className='col')],\n className='row')\n return col\n\n def layout(self):\n return self.content\n\n def MarkerDict(self, Data, title):\n SizeArray = [0 + 40 * (value - min(Data)) / (max(Data) - min(Data)) for value in Data]\n return dict(color=Data, showscale=True, colorscale=[\n [\n 0, '#21c7ef'], [0.33, '#76f2ff'], [0.66, '#ff6969'], [1, '#ff1717']],\n cmin=(min(Data)),\n cmax=(max(Data)),\n size=SizeArray,\n colorbar=dict(x=0.85, len=0.7, title=dict(text=title, font={'color':'#737a8d', \n 'family':'Open Sans', 'size':16}),\n titleside='top',\n tickmode='array',\n tickvals=[\n min(Data), max(Data)],\n ticktext=[\n '{:,.2f}'.format(min(Data)), '{:,.2f}'.format(max(Data))],\n ticks='outside',\n thickness=25,\n tickfont={'family':'Open Sans', \n 'color':'#737a8d', 'size':16}))\n\n def Callbacks(self):\n\n @self.app.callback(Output('TimeSeriesSystemLevelMetric', 'figure'), [Input('PVScenario', 'value'), Input('Metric', 'value')])\n def UpdateTimeSeriesPlot(PVscenario, Metric):\n ScenarioData = self.DataObject.SystemLevelMetricsTimeSeries[PVscenario]\n DataDict = {'TimeStamp': ScenarioData['TimeStamp']}\n for metric in Metric:\n DataDict[metric] = ScenarioData[metric]\n\n return TimeSeriesLinePlot(DataDict, ylabel='Metric in %').layout()\n\n @self.app.callback([Output('interactiveTable', 'data'), Output('interactiveTable', 'columns')], [\n Input('AssetMetric', 'value'), Input('PVScenario2', 'value')])\n def update_table(Metric, PVScenario):\n DataFrameSelected = self.DataObject.AssetMetricsAggregated[PVScenario][Metric]\n columns = [{'name':col, 'id':col, 'selectable':True} for col in ['Component', Metric]]\n DataDict = [{'Component': DataFrameSelected['Metrics'].tolist()[index], Metric: DataFrameSelected['Values'].tolist()[index]} for index in range(len(DataFrameSelected))]\n return (DataDict, columns)\n\n @self.app.callback([Output('AssetLevelMetricHeatMap', 'figure'), Output('AssetLocation', 'figure')], [\n Input('AssetMetric', 'value'), Input('PVScenario2', 'value'), Input('TimeIndex', 'value')])\n def UpdateAssetMetricOverNetwork(Metric, PVScenario, TimeIndex):\n DataSelected = self.DataObject.AssetMetricsTimeSeries[PVScenario][Metric].loc[TimeIndex]\n PVcoordinates = self.DataObject.PVcoordinates[PVScenario]\n AggregatedAssetData = self.DataObject.AssetMetricsAggregated[PVScenario][Metric]\n if Metric in ('NVRI', ):\n ComponentCoordinates = self.DataObject.NodeCoordinatesDict\n if Metric in ('TVRI', 'TE', 'TLOF', 'TOG'):\n ComponentCoordinates = self.DataObject.TransformerCoordinatesDict\n if Metric in ('LE', 'LVRI'):\n ComponentCoordinates = self.DataObject.LineCoordintesDict\n if Metric in ('CRI', ):\n ComponentCoordinates = self.DataObject.CustomerCoordinatesDict\n MetricArray = [DataSelected[keys] for keys in ComponentCoordinates.keys()]\n x_coordinate = [values['x'] for keys, values in ComponentCoordinates.items()]\n y_coordinate = [values['y'] for keys, values in ComponentCoordinates.items()]\n return (\n GeoScatterMap((self.DataObject.x_lines), (self.DataObject.y_lines), x_coordinate, y_coordinate, (self.DataObject.initial_x), (self.DataObject.initial_y), marker=(self.MarkerDict(MetricArray, Metric)), height=800, zoom=14).layout(),\n GeoScatterMap((self.DataObject.x_lines), (self.DataObject.y_lines), x_coordinate, y_coordinate, (self.DataObject.initial_x),\n (self.DataObject.initial_y), marker=(self.MarkerDict(AggregatedAssetData['Values'].tolist(), Metric))).layout())","sub_path":"pycfiles/EMeRGE-1.4a0-py3.7/DistMetricPVTab.cpython-37.py","file_name":"DistMetricPVTab.cpython-37.py","file_ext":"py","file_size_in_byte":13571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"528619766","text":"#!/usr/bin/python\n\nfrom Bio import SeqIO\nfrom itertools import count\nimport sys\n\nfake_header = \"NS500502:001:HT3KMBGXY:{n}:{n:05}:{n:05}:{n:04} {r}:N:0:CTGAAGCT+AGGATAGG\"\n\nwith open(sys.argv[1], 'r') as forward:\n with open(sys.argv[2], 'r') as reverse:\n try:\n fw = open(sys.argv[3], 'w')\n rw = open(sys.argv[4], 'w')\n except IndexError:\n fw = rw = sys.stdout\n for fr, rv, ind in zip(SeqIO.parse(forward, 'fastq'), SeqIO.parse(reverse, 'fastq'), count()):\n fr.id = fr.name = fake_header.format(n=ind, r=1)\n rv.id = rv.name = fake_header.format(n=ind, r=2)\n fr.description = rv.description = ''\n SeqIO.write(fr, fw, 'fastq')\n SeqIO.write(rv, rw, 'fastq')\n","sub_path":"python/03_fake_header.py","file_name":"03_fake_header.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"566730652","text":"# coding: utf-8\n\nimport pandas as pd\nimport os.path, argparse\n\n\nif __name__=='__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('assignment_path', type=str, help='Path to the csv file containing classification info.')\n\tparser.add_argument('data_path', type=str, help='Path to the tsv file containing full data classified.')\n\tparser.add_argument('--subdata', type=str, default=None, help='Path to a file containing subdata to be output.')\n\tparser.add_argument('--sep', type=str, default='\\t', help='Separator of the subdata file. tab stop by default (i.e., tsv).')\n\targs = parser.parse_args()\n\n\n\tdf_assign = pd.read_csv(args.assignment_path)\n\n\tdf_data = pd.read_csv(args.data_path, encoding='utf-8', sep='\\t')\n\n\t# df_assign.loc[:,'lemma'] = df_data.lemma\n\tdf_assign.loc[:,'DISC'] = df_data.DISC\n\tdf_assign.loc[:,'IdNum'] = df_data.loc[:,'rank']\n\n\tif args.subdata is None:\n\t\tdatafile_name = os.path.splitext(os.path.basename(args.data_path))[0]\n\telse:\n\t\tdf_subdata = pd.read_csv(args.subdata, encoding='utf-8', sep=args.sep)\n\t\tdf_assign = pd.merge(df_subdata, df_assign, how='left', on='IdNum')\n\t\tdf_assign = df_assign.drop(columns='customer_id').drop_duplicates()\n\t\tdatafile_name = os.path.splitext(os.path.basename(args.subdata))[0]\n\n\tresult_dir = os.path.dirname(args.assignment_path)\n\tclassification_filename = datafile_name+'_posterior-classification.tsv'\n\tdf_assign.to_csv(os.path.join(result_dir, classification_filename), index=False, encoding = 'utf-8', sep='\\t')\n","sub_path":"code/analysis/English/posterior_predict_classification_CELEX_from_IdNum.py","file_name":"posterior_predict_classification_CELEX_from_IdNum.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"635872174","text":"\"\"\"Contains neural network training sets.\n\"\"\"\n\nimport sys\n\ndef sample(data):\n\treturn getattr(sys.modules[__name__], '{}_sample'.format(data))\n\ndef weights(data):\n\treturn getattr(sys.modules[__name__], '{}_WEIGHTS'.format(data.upper()))\n\ndef xor_sample():\t\n\tyield [0, 0], [0]\n\tyield [0, 1], [1]\n\tyield [1, 0], [1]\n\tyield [1, 1], [0]\n\nXOR_WEIGHTS = (2, 2, 1), \"\"\"1 -1\n\t\t-1 1\n\n\t\t1\n\t\t1\n\t\t\"\"\"\n\ndef and_sample():\n\tyield [0, 0], [0]\n\tyield [0, 1], [0]\n\tyield [1, 0], [0]\n\tyield [1, 1], [1]\n\ndef or_sample():\n\tyield [0, 0], [0]\n\tyield [0, 1], [1]\n\tyield [1, 0], [1]\n\tyield [1, 1], [1]\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"123346556","text":"#Nathan Jones\n#GRAND CENTRAL v3 - TGG TEACH EDITION\n#2018\n\nfrom datetime import datetime\n\nimport time\nimport sys\nimport os.path\nimport os\nimport string \nimport random\nimport statistics\nimport itertools\nimport datetime\n\ndef SCROLL():\n\n Scroll=\"\\n\"*70\n print(Scroll)\n\ndef SCROLL2():\n\n Scroll2=\"\\n\"*10\n print(Scroll2)\n\ndef SCROLL3():\n\n Scroll3=\"\\n\"*28\n print(Scroll3) \n\ndef TEST_GRADE_GEN():\n\n print(\"\"\"\n████████╗███████╗███████╗████████╗ \n╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ \n ██║ █████╗ ███████╗ ██║ \n ██║ ██╔══╝ ╚════██║ ██║ \n ██║ ███████╗███████║ ██║ \n ╚═╝ ╚══════╝╚══════╝ ╚═╝ \n \n ██████╗ ██████╗ █████╗ ██████╗ ███████╗ \n██╔════╝ ██╔══██╗██╔══██╗██╔══██╗██╔════╝ \n██║ ███╗██████╔╝███████║██║ ██║█████╗ \n██║ ██║██╔══██╗██╔══██║██║ ██║██╔══╝ \n╚██████╔╝██║ ██║██║ ██║██████╔╝███████╗ \n ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝ \n \n ██████╗ ███████╗███╗ ██╗███████╗██████╗ █████╗ ████████╗ ██████╗ ██████╗ \n██╔════╝ ██╔════╝████╗ ██║██╔════╝██╔══██╗██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗\n██║ ███╗█████╗ ██╔██╗ ██║█████╗ ██████╔╝███████║ ██║ ██║ ██║██████╔╝\n██║ ██║██╔══╝ ██║╚██╗██║██╔══╝ ██╔══██╗██╔══██║ ██║ ██║ ██║██╔══██╗\n╚██████╔╝███████╗██║ ╚████║███████╗██║ ██║██║ ██║ ██║ ╚██████╔╝██║ ██║\n ╚═════╝ ╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝\n\"\"\")\n SCROLL2()\n GRADE_GEN()\n\ndef GRADE_GEN():\n\n RES=[]\n\n print((\"SYSTEM TIME: \")+str(datetime.datetime.now()))\n print(\" \")\n F_NAME=input(\"ENTER FIRST NAME: \")\n L_NAME=input(\"ENTER LAST NAME: \")\n AGE=input(\"ENTER AGE: \")\n FORM=input(\"ENTER FORM: \")\n print(\" \")\n\n x = 0\n print(\" \")\n while (x == 0):\n DATA=input(\"TEST SCORE: \")\n RES.append(int(DATA))\n LOOP=input(\"Do You Have Another? Y/N \")\n if LOOP ==\"n\".upper():\n print(RES)\n x = x+1\n elif LOOP ==\"y\".upper():\n print(RES)\n x = 0\n\n print(\" \")\n statistics.stdev(RES)\n print((\"Standard Deviation: \")+str(statistics.stdev(RES)))\n statistics.mean(RES)\n print((\"Mean of Results: \")+str(statistics.mean(RES)))\n \n\n if statistics.mean(RES) <= 25:\n GRADE=(\"D\")\n \n elif statistics.mean(RES) <= 50:\n GRADE=(\"C\")\n\n elif statistics.mean(RES) <= 60:\n GRADE=(\"B\")\n \n elif statistics.mean(RES) >= 80:\n GRADE=(\"A\")\n \n print(\" \")\n print(\"SAVING...\")\n r=open(\"TEST SCORE FOR \"+str(L_NAME),\"w\")\n r.write((\"FIRST NAME: \")+F_NAME+(\"\\n\"))\n r.write((\"LAST NAME: \")+L_NAME+(\"\\n\"))\n r.write((\"AGE: \")+AGE+(\"\\n\"))\n r.write((\"FORM: \")+FORM+(\"\\n\"))\n r.write((\"GRADE: \")+GRADE+(\"\\n\"))\n r.close()\n print(\"SAVE COMPLETE!\")\n NEXT_STAGE()\n\ndef NEXT_STAGE():\n\n print(\" \")\n print((\"SYSTEM TIME: \")+str(datetime.datetime.now()))\n print(\" \")\n answer = input(\"Would You Like To Enter Another Person? Y/N \")\n if answer == \"Y\":\n SCROLL()\n print(\"LOADING...\")\n print(\" \")\n GRADE_GEN()\n print(\" \")\n \n\n if answer == \"N\":\n SCROLL()\n print(\"GOODBYE!...\")\n print(\" \")\n SCROLL()\n print(\"LOADING...\")\n time.sleep(5)\n os.startfile(\"C:\\\\Users\\\\natda\\\\OneDrive\\\\Sixth Form\\\\Computer Science\\\\CODE\\GRAND CENTRAL v3\\\\GRAND_CENTRAL_v3-TEACH\\\\TK_TEACH_v3.py\")\n sys.exit()\n\n else:\n SCROLL()\n NEXT_STAGE()\n\nTEST_GRADE_GEN()\n","sub_path":"GRAND_CENTRAL_v3-TEACH/TGG-t.py","file_name":"TGG-t.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"358435526","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: vis_callback on CPLID_Detect\n Description :\n Author : Wayne\n Date: 2018/5/21\n Create by : PyCharm\n Check status: https://waynehfut.github.io\n-------------------------------------------------\n\"\"\"\n__author__ = 'Wayne'\nimport pylab as pl\nfrom IPython import display\nfrom keras.callbacks import Callback\n\n\nclass DrawCallback(Callback):\n def __init__(self, runtime_plot=True):\n super().__init__()\n self.init_loss = None\n self.runtime_plot = runtime_plot\n\n self.xdata = []\n self.ydata = []\n\n def _plot(self, epoch=None):\n epochs = self.params.get(\"epochs\")\n pl.ylim(0, int(self.init_loss * 2))\n pl.xlim(0, epochs)\n\n pl.plot(self.xdata, self.ydata)\n pl.xlabel('Epoch {}/{}'.format(epoch or epochs, epochs))\n pl.ylabel('Loss {:.4f}'.format(self.ydata[-1]))\n\n def _runtime_plot(self, epoch):\n self._plot(epoch)\n\n display.clear_output(wait=True)\n display.display(pl.gcf())\n pl.gcf().clear()\n\n def plot(self):\n self._plot()\n pl.show()\n\n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n loss = logs.get(\"loss\")\n if self.init_loss is None:\n self.init_loss = loss\n self.xdata.append(epoch)\n self.ydata.append(loss)\n if self.runtime_plot:\n self._runtime_plot(epoch)\n","sub_path":"VisCallback.py","file_name":"VisCallback.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"311466962","text":"#!/usr/bin/env python\nimport os\nimport argparse\nimport random\nfrom math import *\nimport numpy as np\n# add path\nimport sys\n\ncwd = os.getcwd()\nsys.path.append(cwd)\n\nfrom scene_elements import *\n\n## Define mass\nLarge = 1000000000.0\nSmall = 1.0\n\n## Add arguments\nparser = argparse.ArgumentParser(description='Create my scene')\nparser.add_argument(\"-f\", \"--filename\", type=str, help=\"define the name of output file\")\n\ndef main():\n \n args = parser.parse_args()\n filename = args.filename\n \n ## initial setup\n duration=20.0; integrator=\"forward-backward-euler\"; dt=0.005; bg_color=[0.0, 0.0, 0.1]\n init = []\n init.append(\"\")\n init.append(\"\")\n init.append(\"\".format(duration))\n init.append(\"\".format(integrator, dt))\n init.append(\"\")\n ## define background color.\n r, g, b = bg_color\n init.append(\"\".format(r, g, b))\n ## define viewpoint\n init.append(\"\")\n ## define collision type\n init.append(\"\")\n #init.append(\"\")\n init.append(\"\")\n \n scene = init\n #############################################################\n # Add content here #\n ############################################################# \n # load pixel files\n # pixel = np.load(\"dispicableme.npy\")\n \n # pixel = pixel[:,10:34,:]\n \n # add half plane\n #scene += add_halfplane([0,0], [1,0])\n #scene += add_halfplane([50,0], [-1,0])\n #scene += add_halfplane([0,50], [0,-1])\n #scene += add_halfplane([0,0], [0,1])\n \n base_id = 2*0\n # Part 2: starry night\n # add static large particles\n num_large = 6\n p_r = 0.2\n radius = 0.5\n delta_ang = 2*pi/num_large\n offset_ang = 1.0*pi/num_large\n # add particles\n for i in range(num_large):\n m = Large\n x, y = radius*cos(delta_ang*i+offset_ang), radius*sin(delta_ang*i+offset_ang)\n vx, vy = 0.0, 0.0##v_init*y/radius, -v_init*x/radius\n duration = None\n scene += add_particle(i+base_id, m, x, y, vx, vy, 0, p_r, bg_color, duration)\n \n # add random distributed small particles\n num_small = 1500\n num_flow = 6\n delta_ang = 2*pi/num_flow\n offset_ang = 0.0*pi/num_flow\n radius = [2, 3, 4]\n p_r = 0.2\n num_color = 7\n colors = [(0.4, 0.6, 0.6), (0.6, 0.4, 0.4), (0.8, 0.2, 0.2), (0.5, 0.5, 0.5), (0.3, 0.7, 0.7)]\n for i in range(num_small):\n m = Small\n r = random.uniform(1.0,2)#radius[rand_idx]\n px, py = r*cos(delta_ang*i+offset_ang), r*sin(delta_ang*i+offset_ang)\n vx, vy = 0.0, 0.0\n # other info\n fixed = 0\n cr = float(i%num_color)/num_color\n color = [0.8*cr, cr, 1-cr]\n duration = None\n scene += add_particle(i+num_large+base_id, m, px, py, vx, vy, fixed, p_r, color, duration)\n \n # add vortex force\n kbs = 6\n kvc = 10.0\n for i in range(num_large):\n for j in range(num_large, num_small+num_large):\n scene += add_vortexforce(i+base_id, j+base_id, kbs, kvc)\n \n # add particles\n \n base_id = num_small + num_large\n num_row = 100\n num_col = 100\n idx = 0\n for i in range(num_row):\n for j in range(num_col):\n px = i - 50\n py = j - 50\n m = 1\n duration = None\n cr = 1-0.8*random.random()#float(i%num_color)/num_color\n color = [0.8*cr, cr, 1-cr]\n if (px < -1 or px > 1) and (py<-1 or py>1):\n scene += add_particle(idx+base_id, m, px, py, 0.0, 0.0, 0, 0.25, color, duration)\n idx += 1\n \n \n # add gravity\n # add_gravity(i, j, G)\n #G = 10.118419\n #for i in range(num_particle):\n # scene += add_gravity(i+base, base+num_particle, G)\n \n # add simple gravity\n # scene += add_simplegravity(0.0, -1.0)\n #############################################################\n # End of content #\n ############################################################# \n \n # add end mark into scene\n scene += end_scene()\n \n # write scene into .xml file\n with open(os.path.join(\"../../scenes/\", filename), \"w\") as output:\n for line in scene:\n output.write(line)\n output.write(\"\\n\")\n # END OF CODE\n\n \nif __name__ == \"__main__\":\n main()","sub_path":"src/scenemake/week6_vortex.py","file_name":"week6_vortex.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"150553196","text":"# Copyright (c) 2011-2013, The Tor Project\n# See LICENSE for the license.\n\n# Updated on 25.01.14-28.01.14 to add SOCKS 5 support.\n# Cleaned some parts of the code and abstracted quite a bit to handle the most important SOCKS5\n# functionality like\n# - username/password authentication\n# - gssapi authentication (planned)\n# - CONNECT command (the normal case, there are others: UDP ASSOCIATE and BIND, but they aren't as important. Maybe I will add them\n# in the future. If anyone wants to implement them, the basic structure is already here and the SOCKSv5ClientProtocol should be\n# rather easy extensible (how the actual connection, listening for incoming connections (BIND) and opening a UDP connection (UDP ASSOCIATE)\n# is done in the twisted world, is another question.\n# Added:\n# - SOCKSv4ClientFactory was renamed to SOCKSClientFactory and abstracted to handle all SOCKS 4/4a SOCKS5 (It is still ONE protocol, so one Factory should be logical correct)\n# - added SOCKS5ClientFactory\n# - SOCKSClientProtocol is the base class for all three protocols\n# - SOCKSv4aClientProtocol inherits from SOCKSv4ClientProtocol. I made the deliberate choice to differ between SOCKS 4 and 4a, altough 4a has the exactly same functionality as 4,\n# it might be the case that servers only speak version 4.\n# References:\n# A actively maintained, most recent version of PySocks from https://github.com/Anorov/PySocks\n# The original version of socksclient.py:\n\n# Author: Nikolai Tschacher\n# Contact: incolumitas.com\n\nimport inspect\nimport socket\nimport re\nimport struct\nfrom zope.interface import implements\nfrom twisted.internet import defer\nfrom twisted.internet.interfaces import IStreamClientEndpoint, IReactorTime\nfrom twisted.internet.protocol import Protocol, ClientFactory\nfrom twisted.internet.endpoints import _WrappingFactory\n\nclass SOCKSError(Exception):\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return repr(self.val)\n\nclass SOCKSClientProtocol(Protocol):\n '''\n Base class for SOCKS protocols 4, 4a and 5\n '''\n buf = ''\n\n def noteTime(self, event):\n if self._timer:\n self._timestamps[event] = self._timer.seconds()\n\n def abort(self, errmsg):\n self.transport.loseConnection()\n self.handshakeDone.errback(SOCKSError('SOCKS %s: %s' % (self.proxy_config['version'], errmsg)))\n\n def isHostname(self, string):\n dns_label_regex = re.compile(r'^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{,63}(?H\", port)\n self.transport.write(msg)\n self.noteTime('RELAY_REQUEST_SENT')\n self.protocol_state = 'connection_requested'\n\n def verifySocksReply(self, data):\n where = 'SOCKS5 verifySocksReply'\n\n if len(data) < 10: # all hostname are longer than a IPv4 address\n self.abort('Too few data from server %s.' % where)\n else:\n version, reply, rsv, address_type = struct.unpack('!BBBB', data[:4])\n\n if version != 0x5:\n self.abort('Invalid version')\n return False\n\n if reply != 0x0:\n self.abort('Server reply indicates failure. Reason: %s' % self.SOCKS5_ERRORS.get(reply, \"Unknown error\"))\n return False\n\n if address_type == 0x1: # handle IPv4 address\n self.bound_address, self.bound_port = socket.inet_ntoa(data[4:8]),\\\n struct.unpack('>H', data[8:10])[0]\n elif address_type == 0x3: # handle domain name\n dns_name_len = ord(data[4:5])\n self.bound_address, self.bound_port = data[5:dns_name_len],\\\n struct.unpack('>H', data[(5+dns_name_len):(5+dns_name_len+2)])[0]\n elif address_type == 0x4: # handle Ipv6 address\n self.bound_address, self.bound_port = socket.inet_ntop(socket.AF_INET6, data[4:20]),\\\n struct.unpack('>H', data[20:22])[0]\n\n self.protocol_state = 'connection_verified'\n return True\n\n def connectionMade(self):\n self.noteTime('CONNECTED')\n self.noteTime('NEGOTIATE_AUTH_METHOD')\n self.negotiateAuthenticationMethod()\n\n def dataReceived(self, data):\n self.buf += data\n\n if self.protocol_state == 'do_auth':\n self.authenticate(data)\n elif self.protocol_state == 'check_auth':\n self.checkAuth(data)\n\n if self.protocol_state == 'authenticated':\n host = self.postHandshakeEndpoint._host\n port = self.postHandshakeEndpoint._port\n self.sendRelayRequest(host, port)\n elif self.protocol_state == 'connection_requested':\n if self.verifySocksReply(data):\n self.setupRelay()\n\n\nclass SOCKSv4ClientProtocol(SOCKSClientProtocol):\n SOCKS4_ERRORS = {\n 0x5B: \"Request rejected or failed\",\n 0x5C: \"Request rejected because SOCKS server cannot connect to identd on the client\",\n 0x5D: \"Request rejected because the client program and identd report different user-ids\"\n }\n def sendRelayRequest(self, host, port):\n username = self.proxy_config['version_specific']['username']\n ver, cmd, username = 0x4, 0x1, [b'\\x00', username.encode()+b'\\x00'][not not username]\n try:\n addr = socket.inet_aton(host)\n except socket.error:\n self.abort('Not a valid IPv4 address.')\n return False\n msg = struct.pack('!BBH', ver, cmd, port) + addr + username\n self.transport.write(msg)\n self.noteTime('REQUEST')\n\n def verifySocksReply(self, data):\n \"\"\"\n Return True on success and False on need-more-data or error.\n In the case of an error, the connection is closed and the\n handshakeDone errback is invoked with a SOCKSError exception\n before False is returned.\n \"\"\"\n if len(data) < 8:\n return False\n if ord(data[0]) != 0x0:\n self.abort('Expected 0 bytes')\n return False\n status = ord(data[1])\n if status != 0x5a:\n self.abort('Relay request failed. Reason=%s.' % self.SOCKS4_ERRORS.get(data[0], 'Unknown error'))\n return False\n return True\n\n def connectionMade(self):\n self.noteTime('CONNECT')\n self.noteTime('NEGOTIATE')\n self.sendRelayRequest(self.postHandshakeEndpoint._host, self.postHandshakeEndpoint._port)\n\n def dataReceived(self, data):\n self.buf += data\n if self.verifySocksReply(data):\n self.setupRelay()\n\nclass SOCKSv4aClientProtocol(SOCKSv4ClientProtocol):\n '''Only extends SOCKS 4 to remotely resolve hostnames.'''\n\n def sendRelayRequest(self, host, port):\n username = self.proxy_config['version_specific']['username']\n ver, cmd, username = 0x4, 0x1, [b'\\x00', username.encode()+b'\\x00'][not not username]\n try:\n addr = socket.inet_aton(host)\n except socket.error:\n addr = '\\x00\\x00\\x00\\x01'\n dnsname = '%s\\x00' % host\n msg = struct.pack('!BBH', ver, cmd, port) + addr + username + dnsname\n else:\n msg = struct.pack('!BBH', ver, cmd, port) + addr + username\n self.transport.write(msg)\n self.noteTime('REQUEST')\n\nclass SOCKSClientFactory(ClientFactory):\n\n def __init__(self, proxy_config):\n self.proxy_config = proxy_config\n if self.proxy_config['version'] == '4':\n self.protocol = SOCKSv4ClientProtocol\n elif self.proxy_config['version'] == '4a':\n self.protocol = SOCKSv4aClientProtocol\n elif self.proxy_config['version'] == '5':\n self.protocol = SOCKSv5ClientProtocol\n\n def buildProtocol(self, addr):\n r = ClientFactory.buildProtocol(self, addr)\n r.proxy_config = self.proxy_config\n r.postHandshakeEndpoint = self.postHandshakeEndpoint\n r.postHandshakeFactory = self.postHandshakeFactory\n r.handshakeDone = self.handshakeDone\n r._timestamps = self._timestamps\n r._timer = self._timer\n return r\n\nclass SOCKSWrapper(object):\n '''\n Generic class to wrap all 3 SOCKS protocol versions 4, 4a, 5 around a TCP connection\n '''\n implements(IStreamClientEndpoint)\n\n factory = SOCKSClientFactory\n\n def __init__(self, reactor, endpoint, proxy_config, timestamps=None):\n self._host = proxy_config['host']\n self._port = proxy_config['port']\n self._proxy_config = proxy_config\n\n self._reactor = reactor\n self._endpoint = endpoint\n self._timestamps = None\n self._timer = None\n if timestamps is not None:\n self._timestamps = timestamps\n self._timer = IReactorTime(reactor)\n\n def noteTime(self, event):\n if self._timer:\n self._timestamps[event] = self._timer.seconds()\n\n def connect(self, protocolFactory):\n \"\"\"\n Return a deferred firing when the SOCKS connection is established.\n \"\"\"\n\n def createWrappingFactory(f):\n \"\"\"\n Wrap creation of _WrappingFactory since __init__() doesn't\n take a canceller as of Twisted 12.1 or something.\n \"\"\"\n if len(inspect.getargspec(_WrappingFactory.__init__)[0]) == 3:\n def _canceller(deferred):\n connector.stopConnecting()\n deferred.errback(\n error.ConnectingCancelledError(\n connector.getDestination()))\n return _WrappingFactory(f, _canceller)\n else: # Twisted >= 12.1.\n return _WrappingFactory(f)\n\n self.noteTime('START')\n try:\n # Connect with an intermediate SOCKS factory/protocol,\n # which then hands control to the provided protocolFactory\n # once a SOCKS connection has been established.\n f = self.factory(self._proxy_config)\n\n f.postHandshakeEndpoint = self._endpoint\n f.postHandshakeFactory = protocolFactory\n f.handshakeDone = defer.Deferred()\n f._timestamps = self._timestamps\n f._timer = self._timer\n wf = createWrappingFactory(f)\n self._reactor.connectTCP(self._host, self._port, wf)\n self.noteTime('SOCKET')\n return f.handshakeDone\n except:\n return defer.fail()\n","sub_path":"socksclient.py","file_name":"socksclient.py","file_ext":"py","file_size_in_byte":16432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"356831092","text":"# coding: utf-8\n\n\"\"\"\nLicensed to Cloudera, Inc. under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. Cloudera, Inc. licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass Cluster(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'name': 'str',\n 'instances': 'list[Instance]',\n 'services': 'list[Service]',\n 'url': 'str',\n 'instances_url': 'str',\n 'health': 'Health',\n 'feature_availability': 'dict(str, str)'\n }\n\n attribute_map = {\n 'name': 'name',\n 'instances': 'instances',\n 'services': 'services',\n 'url': 'url',\n 'instances_url': 'instancesUrl',\n 'health': 'health',\n 'feature_availability': 'featureAvailability'\n }\n\n def __init__(self, name=None, instances=None, services=None, url=None, instances_url=None, health=None, feature_availability=None): # noqa: E501\n \"\"\"Cluster - a model defined in Swagger\"\"\" # noqa: E501\n\n self._name = None\n self._instances = None\n self._services = None\n self._url = None\n self._instances_url = None\n self._health = None\n self._feature_availability = None\n self.discriminator = None\n\n self.name = name\n if instances is not None:\n self.instances = instances\n if services is not None:\n self.services = services\n if url is not None:\n self.url = url\n if instances_url is not None:\n self.instances_url = instances_url\n if health is not None:\n self.health = health\n if feature_availability is not None:\n self.feature_availability = feature_availability\n\n @property\n def name(self):\n \"\"\"Gets the name of this Cluster. # noqa: E501\n\n Cluster name # noqa: E501\n\n :return: The name of this Cluster. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this Cluster.\n\n Cluster name # noqa: E501\n\n :param name: The name of this Cluster. # noqa: E501\n :type: str\n \"\"\"\n if name is None:\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def instances(self):\n \"\"\"Gets the instances of this Cluster. # noqa: E501\n\n Instances comprising this cluster # noqa: E501\n\n :return: The instances of this Cluster. # noqa: E501\n :rtype: list[Instance]\n \"\"\"\n return self._instances\n\n @instances.setter\n def instances(self, instances):\n \"\"\"Sets the instances of this Cluster.\n\n Instances comprising this cluster # noqa: E501\n\n :param instances: The instances of this Cluster. # noqa: E501\n :type: list[Instance]\n \"\"\"\n\n self._instances = instances\n\n @property\n def services(self):\n \"\"\"Gets the services of this Cluster. # noqa: E501\n\n Services that belong to this cluster # noqa: E501\n\n :return: The services of this Cluster. # noqa: E501\n :rtype: list[Service]\n \"\"\"\n return self._services\n\n @services.setter\n def services(self, services):\n \"\"\"Sets the services of this Cluster.\n\n Services that belong to this cluster # noqa: E501\n\n :param services: The services of this Cluster. # noqa: E501\n :type: list[Service]\n \"\"\"\n\n self._services = services\n\n @property\n def url(self):\n \"\"\"Gets the url of this Cluster. # noqa: E501\n\n Optional URL for cluster in Cloudera Manager # noqa: E501\n\n :return: The url of this Cluster. # noqa: E501\n :rtype: str\n \"\"\"\n return self._url\n\n @url.setter\n def url(self, url):\n \"\"\"Sets the url of this Cluster.\n\n Optional URL for cluster in Cloudera Manager # noqa: E501\n\n :param url: The url of this Cluster. # noqa: E501\n :type: str\n \"\"\"\n\n self._url = url\n\n @property\n def instances_url(self):\n \"\"\"Gets the instances_url of this Cluster. # noqa: E501\n\n Optional URL for cluster instances in Cloudera Manager # noqa: E501\n\n :return: The instances_url of this Cluster. # noqa: E501\n :rtype: str\n \"\"\"\n return self._instances_url\n\n @instances_url.setter\n def instances_url(self, instances_url):\n \"\"\"Sets the instances_url of this Cluster.\n\n Optional URL for cluster instances in Cloudera Manager # noqa: E501\n\n :param instances_url: The instances_url of this Cluster. # noqa: E501\n :type: str\n \"\"\"\n\n self._instances_url = instances_url\n\n @property\n def health(self):\n \"\"\"Gets the health of this Cluster. # noqa: E501\n\n Overall cluster health # noqa: E501\n\n :return: The health of this Cluster. # noqa: E501\n :rtype: Health\n \"\"\"\n return self._health\n\n @health.setter\n def health(self, health):\n \"\"\"Sets the health of this Cluster.\n\n Overall cluster health # noqa: E501\n\n :param health: The health of this Cluster. # noqa: E501\n :type: Health\n \"\"\"\n\n self._health = health\n\n @property\n def feature_availability(self):\n \"\"\"Gets the feature_availability of this Cluster. # noqa: E501\n\n Availability information for features # noqa: E501\n\n :return: The feature_availability of this Cluster. # noqa: E501\n :rtype: dict(str, str)\n \"\"\"\n return self._feature_availability\n\n @feature_availability.setter\n def feature_availability(self, feature_availability):\n \"\"\"Sets the feature_availability of this Cluster.\n\n Availability information for features # noqa: E501\n\n :param feature_availability: The feature_availability of this Cluster. # noqa: E501\n :type: dict(str, str)\n \"\"\"\n allowed_values = [\"UNKNOWN\", \"UNAVAILABLE\", \"AVAILABLE\"] # noqa: E501\n if not set(feature_availability.values()).issubset(set(allowed_values)):\n raise ValueError(\n \"Invalid values in `feature_availability` [{0}], must be a subset of [{1}]\" # noqa: E501\n .format(\", \".join(map(str, set(feature_availability.values()) - set(allowed_values))), # noqa: E501\n \", \".join(map(str, allowed_values)))\n )\n\n self._feature_availability = feature_availability\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Cluster):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"python-client/cloudera/director/v9/models/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":8874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"288747842","text":"# Game class for the tic tac toe game\nclass Game(object):\n # when constructing a Game object there is an optional paramter for player_first\n # if player_first is 1, the player makes the first move, the player is \"X\"\n # if player_first is 0 (default), the computer makes the first move, the computer is \"X\"\n def __init__(self, player_first = 0):\n # the board 2-d list holds the game board\n self.board = [[\" \", \" \", \" \"],[\" \", \" \", \" \"],[\" \", \" \", \" \"]]\n # indicates if the marker to be used by the player and computer\n self.player_first = player_first\n # if move_count gets to 9 without a winner the game is a draw\n self.move_count = 0\n # set the marker for the player and computer accordingly\n if self.player_first:\n self.player_marker = \"X\"\n self.comp_marker = \"O\"\n else:\n self.player_marker = \"O\"\n self.comp_marker = \"X\"\n \n # when invoked AI_move claims the first available space for the computer\n # returns True to indicate game over\n # return False to indicate continue game\t\n def AI_move(self):\n for row in range(len(self.board)): \n for col in range(len(self.board[row])):\n if self.board[row][col] == \" \":\n return self.place_move(self.comp_marker, (row, col))\n # when invoked player_move claims the space indicated by coordinates\n # returns True to indicate game over\n # returns False to indicate continue game\n def player_move(self, coordinates):\n return self.place_move(self.player_marker, coordinates)\n \n # when invoked place_move changes the board to the indicated marker at the indicated coordinates\n # return True to indicate game over\n # return False to indicate continue game\n def place_move(self, marker, coordinates):\n self.board[coordinates[0]][coordinates[1]] = marker\n return self.check_board(coordinates)\n\n # when invoked print_board prints the information stored in board as a formated tic tac toe board\n def print_board(self):\n '''\n count = 0;\n for line in self.board:\n for pos in range(len(line)):\n print(line[pos], end='')\n if pos == 2:\n print()\n else:\n print(\"|\", end='')\n if count < 2:\n print(\"_|_|_\")\n else:\n print(\" | |\")\n count += 1\n '''\n print(self.board_to_str(), end='')\n\n # when invoked board_to_str converts the board into a string and returns the string object\n def board_to_str(self):\n ret_str = \"\"\n count = 0;\n for line in self.board:\n for pos in range(len(line)):\n ret_str += line[pos]\n if pos == 2:\n ret_str += \"\\n\"\n else:\n ret_str += \"|\"\n if count < 2:\n ret_str += \"_|_|_\\n\"\n else:\n ret_str += \" | | \\n\"\n count += 1\n return ret_str\n\n # when invoked check_coords checks to see if the coordinates are valid for the board\n # returns True if the coordinates are valid\n # returns False if the coordinates are not valid\n def check_coords(self, coordinates):\n return self.board[coordinates[0]][coordinates[1]] == \" \"\n\n # when invoked check_board checks the board to see if there is a winner or stalemate\n # checks possible states based on the most recent move\n # if there is a winner an appropriate message is printed\n # return 1 if there is a winner \n # return -1 if there is a stalemate\n # return 0 if there is not a winner\n def check_board(self, coordinates):\n # increment the move count\n self.move_count += 1\n # flag to indicate win condition\n win_flag = 0\n # check the row of the most recent move\n prev_pos = self.board[coordinates[0]][0]\n for i in range(len(self.board[coordinates[0]])-1):\n curr_pos = self.board[coordinates[0]][i+1]\n if curr_pos != prev_pos:\n win_flag = 0 \n break\n else:\n win_flag = 1\n prev_pos = curr_pos\n # check to see if the entire row matched\n if win_flag:\n # there was a winner\n self.print_winner(curr_pos)\n return 1\n\n # the row did not have a winner check the column \n prev_pos = self.board[0][coordinates[1]]\n for i in range(len(self.board[coordinates[1]])-1):\n curr_pos = self.board[i+1][coordinates[1]]\n if curr_pos != prev_pos:\n win_flag = 0\n break\n else:\n win_flag = 1\n prev_pos = curr_pos\n # check to seee if the entire column matched\n if win_flag:\n # there was a winner\n self.print_winner(curr_pos)\n return 1\n # the column did not have a winner check to see if the coordinates match a diagonal\n if coordinates == (0,0) or coordinates == (1,1) or coordinates == (2,2):\n # check to seee if the entire diagonal matched\n if self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:\n # there was a winner\n self.print_winner(curr_pos)\n return 1\n elif coordinates == (2,0) or coordinates == (1,1) or coordinates == (0,2):\n # check to seee if the entire diagonal matched\n if self.board[2][0] == self.board[1][1] and self.board[1][1] == self.board[0][2]:\n # there was a winner\n self.print_winner(curr_pos)\n return 1 \n # there was not a winner check for a draw\n for row in self.board:\n for col in row:\n if col == \" \":\n # there is still a blank space \n return 0\n # a blank space was not found there was a draw\n print(\"Stalemate! It could have been worse!\")\n return -1\n \n \n def print_winner(self, marker):\n # check to see if the winning marker belongs to the computer or player\n if self.player_marker == marker:\n # the player won\n print(\"Congrats! You won!\")\n else:\n # the computer won\n print(\"You lost! Better luck next time!\")\n'''\n# main to test the class\ndef main():\n print(\"Lets play Tic Tac Toe!\")\n input_flag = 1\n while (input_flag):\n player_first = input(\"Would you like to go first? Y/n: \")\n if isinstance(player_first, str):\n player_first.upper()\n if player_first == \"Y\" or player_first == \"N\":\n input_flag = 0\n else:\n print(\"Please make a valid selection!\")\n else:\n print(\"Please make a valid selection!\")\n if player_first == \"Y\":\n game = Game(1)\n moves = 0\n else:\n game = Game()\n game.AI_move()\n moves = 1\n game_flag = 1\n while(game_flag):\n game.print_board()\n input_flag = 1\n while (input_flag):\n coor_raw = input(\"Enter the coordinates for your move seperated by a space (e.g. \\\"0 2\\\"): \")\n try:\n coordinates_raw = coor_raw.split()\n coordinates = (int(coordinates_raw[0]), int(coordinates_raw[1]))\n if coordinates[0] >= 0 and coordinates[0] <= 2 and coordinates[1] >= 0 and coordinates[1] <= 2:\n input_flag = 0\n else:\n # invalid input\n print(\"Please enter valid coordinates between 0 and 2!\")\n except TypeError: \n print(\"TypeError: Please enter valid coordinates between 0 and 2!\")\n if game.player_move(coordinates):\n game_flag = 0\n moves += 1\n if moves == 9:\n break\n if game.AI_move():\n game_flag = 0\n moves += 1\n if moves == 9:\n game_flag = 0\n game.print_board()\nmain() \n'''\n","sub_path":"TTT_Game.py","file_name":"TTT_Game.py","file_ext":"py","file_size_in_byte":8162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"186841835","text":"'''\nFibonaci\nDe rij van Fibonacci is genoemd naar Leonardo van Pisa, bijgenaamd Fibonacci, die de rij noemt in zijn boek Liber abaci uit 1202. De rij begint met 0 en 1 en vervolgens is elk\nvolgende element van de rij steeds de som van de twee voorgaande elementen. Bij de rij gebruiken we de notatie fn voor het aangeven van het n-de element van de rij. f9 is\nbijvoorbeeld gelijk aan 34. De eerste elementen van de rij zijn dan als volgt:\n0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584\nImplementeer een functie die fn uitrekent gegeven integer n. De functie moet recursief zijn.\n\nMeer oefenen met recursie: implementeer de eerdere sorteer-bereken-controleer opdrachten met recursieve functies.\n'''\n\ndef fibonaci(list, grote,grond):\n if len(list) < grote:\n list.append(list[grond] + list[grond + 1])\n grond += 1\n fibonaci(list, grote, grond)\n else:\n print(list)\n return\n return\n\nlist = [0,1]\nn = 15\ngrond = 0\nfibonaci(list, n,grond)\n\n'''\n#for functie voor fibonaci\nfor i in range(n):\n print(i)\n list.append(list[i]+list[i+1])\n print(list)\n '''","sub_path":"Opdracht 1/fibonaci.py","file_name":"fibonaci.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"491438889","text":"import os\nimport sys\nimport json\nimport pprint\nimport collections\nimport traceback\nimport datetime\nimport time\nimport uuid\nimport datetime\nimport copy\nimport logging\n\nimport zmq\nimport gpudb\n\nlogger = logging.getLogger(\"kml-bbox-sdk\")\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandlerC = logging.StreamHandler(sys.stdout)\nhandlerC.setFormatter(formatter)\nlogger.addHandler(handlerC)\n\nclass KineticaBlackBox(object):\n \"\"\"Kinetica black box class.\"\"\"\n\n socket = None\n schema_inbound = None\n schema_outbound = None\n sink_table_audit = None\n sink_table_results = None\n be_quiet = False\n\n def __init__(self, bb_module, bb_method,\n schema_inbound, schema_outbound,\n zmq_dealer_host, zmq_dealer_port,\n db_table_audit, db_table_results, db_conn_str,\n db_user = \"\", db_pass = \"\", be_quiet = False ):\n \"\"\"Construct a new KineticaBlackBox object.\n\n :param bb_module:\n :type bb_module: dict\n :param bb_method:\n :type bb_method: dict\n :param schema_inbound:\n :type schema_inbound: str\n :param schema_outbound:\n :type schema_outbound: str\n :param zmq_dealer_host:\n :type zmq_dealer_host: str\n :param zmq_dealer_port:\n :type zmq_dealer_port: str\n :param db_table_audit:\n :type db_table_audit: str\n :param db_table_results:\n :type db_table_results: str\n :param db_host: Default \"127.0.0.1\".\n :type db_host: str\n :param db_port: Default \"9191\".\n :type db_port: str\n :param db_user: optional\n :type db_user: str\n :param db_pw: optional\n :type db_pw: str\n\n \"\"\"\n\n logger.info(\"Initializing KineticaBlackBox\")\n logger.info(f\"zmq_dealer_host: {zmq_dealer_host}\")\n logger.info(f\"zmq_dealer_port: {zmq_dealer_port}\")\n logger.info(f\"db_table a: {db_table_audit}\")\n logger.info(f\"db_table r: {db_table_results}\")\n logger.info(f\"db_conn_str: {db_conn_str}\")\n logger.info(f\"db_user: {db_user}\")\n logger.info(f\"db_pass: *******\")\n logger.info(f\"schema_inbound: {schema_inbound}\")\n logger.info(f\"schema_outbound: {schema_outbound}\")\n logger.info(f\"bb_module: {bb_module}\")\n logger.info(f\"bb_method: {bb_method}\")\n\n if be_quiet:\n import logging\n logger.setLevel(logging.INFO)\n\n self.be_quiet = be_quiet\n self.schema_inbound = schema_inbound\n self.schema_outbound = schema_outbound\n\n self.bb_module = bb_module\n self.bb_method = bb_method\n\n # Prepare DB Communications\n logger.info(f\"Attempting to connect to DB at {db_conn_str} to push to {db_table_audit}\")\n if db_user == 'no_cred' or db_pass == 'no_cred':\n db=gpudb.GPUdb(encoding='BINARY',\n host=db_conn_str)\n else:\n db=gpudb.GPUdb(encoding='BINARY',\n host=db_conn_str,\n username=db_user,\n password=db_pass)\n\n self.sink_table_audit = gpudb.GPUdbTable(name = db_table_audit, db = db)\n \n logger.info(f\"DB Results Table {db_table_results}\")\n if db_table_results == \"NOT_APPLICABLE\": \n logger.info(f\"All results will be persisted to Audit DB Table {db_table_audit}\")\n self.sink_table_results = None\n else:\n self.sink_table_results = gpudb.GPUdbTable(name = db_table_results, db = db)\n logger.info(f\"Established connection to sink table\")\n logger.info(self.sink_table_results)\n\n logger.info(self.sink_table_results)\n if self.sink_table_results is None:\n logger.info(f\"All results will be persisted to Audit DB Table only\") \n else:\n logger.info(f\"All results will be persisted to both Audit and output DB Tables {db_table_results}\")\n\n\n logger.info(\"Prepping response with with schema\")\n logger.info(json.dumps(json.loads(schema_outbound)))\n\n # Prepare ZMQ Communications\n zmq_dealer_uri = f\"tcp://{zmq_dealer_host}:{zmq_dealer_port}\"\n context = zmq.Context()\n self.socket = context.socket(zmq.PULL)\n #logger.info(\"Listening for incoming requests on topic: %s via %s\" % (topicfilter,topic_source))\n self.socket.connect(zmq_dealer_uri)\n #self.socket.setsockopt_string(zmq.SUBSCRIBE, topicfilter)\n # end __init__\n\n\n def run(self):\n \"\"\"Run the black box.\"\"\"\n\n schema_decoder = json.dumps(json.loads(self.schema_inbound))\n outfields = json.loads(self.schema_outbound)[\"fields\"]\n\n method_to_call = getattr(__import__(self.bb_module), self.bb_method)\n logger.info(f\"Dynamically loaded function {self.bb_method} from module {self.bb_module} for lambda application\")\n\n block_request_count = 0\n response_count=0\n while True:\n try:\n\n mpr = self.socket.recv_multipart()\n block_request_count += 1\n\n parts_received = len(mpr)\n logger.info(f\"Processing insert notification with {parts_received-1} frames, block request {block_request_count}\")\n \n audit_records_insert_queue=[]\n for mindex, m in enumerate(mpr[1:]): \n inference_inbound_payload=gpudb.GPUdbRecord.decode_binary_data(schema_decoder, m)[0]\n response_count += 1\n\n # wipe out all previous results\n results_package = collections.OrderedDict()\n if 'guid' not in inference_inbound_payload:\n inference_inbound_payload['guid'] = str(uuid.uuid4())\n inference_inbound_payload['receive_dt'] = datetime.datetime.now().replace(microsecond=100).isoformat(' ')[:-3]\n logger.debug(f\"Assigned GUID {inference_inbound_payload['guid']} to serial-free inbound\")\n #results_package[\"guid\"]=inference_inbound_payload['guid']\n #results_package[\"receive_dt\"]=inference_inbound_payload['receive_dt']\n logger.info(f\"Processing frame {1+mindex} of {parts_received}: Message count # {response_count} {inference_inbound_payload['guid']}\")\n\n results_package[\"success\"]=0 # we start with the assumption of failure\n for afield in outfields:\n results_package[afield[\"name\"]]=None\n # by default send back all inputs as well as our calculated outputs\n\n # TODO: Replace this with a deep copy: https://docs.python.org/2/library/copy.html\n for k,v in inference_inbound_payload.items():\n results_package[k]=v\n\n process_start_dt=datetime.datetime.now().replace(microsecond=100).isoformat(' ')[:-3]\n if not self.be_quiet:\n logger.debug(\"\\tDecoded task %s off wire for inference\" % inference_inbound_payload[\"guid\"])\n for k,v in inference_inbound_payload.items():\n logger.debug(\"\\t%s: %s\" % (k,v))\n\n # -------------------------------------------------------------------------\n # BLACKBOX INTERACTION - **STARTING**\n\n inMap = inference_inbound_payload\n #if not self.be_quiet:\n # logger.debug (\"\\tSending to blackbox:\")\n # for ki,vi in inMap.items():\n # logger.debug(\"\\t %s: %s\" % (ki,vi))\n\n inference_success=False\n results_package[\"success\"]=0\n results_package[\"process_start_dt\"]=process_start_dt\n\n try:\n outMaps = method_to_call(inMap)\n\n\n inference_success=True\n results_package[\"success\"]=1\n process_end_dt=datetime.datetime.now().replace(microsecond=100).isoformat(' ')[:-3]\n results_package[\"process_end_dt\"]=process_end_dt\n\n # this enables us to handle responses from blackbox functions\n # that may not return lists, but only single {} outs\n if not isinstance(outMaps, list):\n logger.info (\"Received lone dictionary function output, force listifying\")\n outMaps = [outMaps,]\n else:\n logger.info (f\"Received list of {len(outMaps)} dictionary outputs\")\n\n\n for outMap in outMaps:\n lineitem = copy.deepcopy(results_package)\n for k,v in outMap.items():\n lineitem[k]=v\n audit_records_insert_queue.append(lineitem)\n\n if not self.be_quiet:\n logger.debug (\"\\tResults received from blackbox:\")\n for ko,vo in outMap.items():\n logger.debug(\"\\t %s: %s\" % (ko,vo))\n logger.debug (\"\\t>> Completed\")\n\n except Exception as e:\n # TODO: As discussed at code review on 3 Jan 2019, push stack trace and input body to store_only field in output table\n logger.error(e)\n error_type, error, tb = sys.exc_info()\n logger.error(traceback.format_tb(tb))\n traceback.print_exc(file=sys.stdout)\n results_package[\"errorstack\"]=\"\\n\".join(traceback.format_tb(tb)) \n if e:\n results_package[\"errorlog\"]=str(e)\n audit_records_insert_queue.append(results_package)\n\n # -------------------------------------------------------------------------\n # BLACKBOX INTERACTION - **COMPLETED**\n\n logger.debug(\"Sending response back to DB:\")\n #logger.debug(results_package)\n #audit_records_insert_queue.append(results_package)\n\n _ = self.sink_table_audit.insert_records(audit_records_insert_queue)\n if self.sink_table_results is None:\n logger.info(f\"Response sent back to DB audit table\")\n else:\n _ = self.sink_table_results.insert_records(audit_records_insert_queue)\n logger.info(f\"Response sent back to DB output table and audit table\") \n\n # TODO: examine insert_status and determine if DB insert was a filure\n \n logger.info(f\"Completed Processing block request {block_request_count}\")\n\n except Exception as e:\n # TODO: As discussed at code review on 3 Jan 2019, push stack trace and input body to store_only field in output table\n logger.error(e)\n error_type, error, tb = sys.exc_info()\n logger.error(traceback.format_tb(tb))\n traceback.print_exc(file=sys.stdout)\n\n # end run\n\n# end class KineticaBlackBox\n\n","sub_path":"sdk/kinetica_black_box.py","file_name":"kinetica_black_box.py","file_ext":"py","file_size_in_byte":11529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"50610200","text":"'''\nThis file creates annual means of tau in wombat_jra-iaf_mom025 and concatenates the result in one file.\nTakes data from\n/g/data1a/v45/mtc599/mom5/dec16b/OUTPUTr0/\nand places the outputs in\n/g/data/e14/erd561/wombat_jra-iaf_mom025/\n\nEarl Duran \ncreated: 14-Mar-18\ne.duran@unsw.edu.au\n'''\n\nimport os\n\ninput_path = '/g/data1a/v45/mtc599/mom5/dec16b/OUTPUTr0/'\n\nfile_number = list(range(1958, 2015, 1))\n\noutput_path = '/g/data/e14/erd561/wombat_jra-iaf_mom025/'\n\npls = os.listdir(output_path)\n \nvar = ['u', 'v', 'temp', 'salt', 'eta_t', 'mld_rho']\nx_axis = ['xu_ocean', 'xu_ocean', 'xt_ocean', 'xt_ocean', 'xt_ocean', 'xt_ocean']\ny_axis = ['yu_ocean', 'yu_ocean', 'yt_ocean', 'yt_ocean', 'yt_ocean', 'yt_ocean']\n\nfor n in file_number:\n input_data_path = input_path\n if n in [1984,1985,1986]:\n input_data_path += 'ocean_surface_' + str(n) + '_01.nc ' + \\\n input_path + 'ocean_surface_' + str(n) + '_07.nc'\n else:\n input_data_path += 'ocean_surface_' + str(n) + '_01.nc'\n \n for v,x,y in zip(var,x_axis,y_axis):\n output_data = v + '_' + str(n) + '.nc'\n output_data_path = output_path + output_data\n\n if output_data not in pls:\n os.system('ncra -d ' + y + ',-60.0,-20.0 -d ' + x + ',-260.0,-190.0 -v ' \\\n + v + ' ' + input_data_path + ' ' + output_data_path)\n print(output_data_path + ' OK')\n\n\nfor v,x,y in zip(var,x_axis,y_axis):\n output_data = v + '_' + str(file_number[0]) + '-' + str(file_number[-1]) + '.nc'\n output_data_path = output_path + output_data\n \n if output_data not in pls:\n \n input_data_path = ''\n for n in file_number:\n input_data_path += output_path + v + '_' + str(n) + '.nc '\n \n \n os.system('ncrcat -v ' \\\n + v + ' ' + input_data_path + ' ' + output_data_path)\n print(output_data_path + ' OK')\n \nprint('DONE') \n \n \n \n ","sub_path":"old_stuff/ncra_ncrcat_ocean_surface.py","file_name":"ncra_ncrcat_ocean_surface.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"372511153","text":"from image_features.FeatureModel import *\nfrom skimage import feature\nimport cv2 as cv\nimport numpy as np\nimport task5 as lsh\nimport h5py\nimport os\n\nCURRENT_DIR = os.path.dirname(__file__)\n\nclass LBP(FeatureModel):\n # Initialize the input path\n def __init__(self, ds_folder_path='../Inputs', image_label=ImageLabel.UNSPECIFIED):\n FeatureModel.__init__(self, ds_folder_path, image_label)\n\n def extract_feature_vector(self, image_id):\n image_path = self.get_path_from_id(image_id)\n return self.image_lbp(image_path)\n\n def calculate_image_lbp(self, image, radius=3):\n num_points = 8 * radius\n cell_size = 100 * 100\n interval = 100\n rows = 1200\n columns = 1600\n n_bins = 20\n count = 0\n lbp_local_max = int(2 ** num_points)\n number_of_cell = int(rows * columns / (cell_size))\n number_of_features = int(number_of_cell * n_bins)\n lbp_img = np.zeros(number_of_features)\n for i in range(0, rows, interval):\n for j in range(0, columns, interval):\n lbp_local = feature.local_binary_pattern(image[i:i + 100, j:j + 100], num_points, radius)\n hist, _ = np.histogram(lbp_local, density=False, bins=n_bins, range=(0, lbp_local_max))\n norm_val = np.sqrt(np.sum(hist ** 2) * 1.0)\n if norm_val != 0:\n hist = hist / norm_val\n # Normalization done above\n lbp_img[count * n_bins: (count + 1) * n_bins] = hist\n count += 1\n return lbp_img\n\n def image_lbp(self, image_path):\n img = cv.imread(image_path, 0)\n return self.calculate_image_lbp(img, radius=2)\n\n def extract_feature_feature_vectors(self):\n feature_matrix = []\n input_images = self.get_data_set_files()\n\n # for i in input_images:\n # feature_matrix.append(self.extract_feature_vector(i.image_id))\n\n # extract from the existing features file\n lsh_index = lsh.LSHIndex()\n hdf5_file = CURRENT_DIR + os.sep + '..' + os.sep + '..' + os.sep + 'Metadata' + os.sep + 'feature_vectors_full_data.hdf5'\n data_lbp = None\n with h5py.File(hdf5_file, 'r') as hf:\n data_lbp = hf['lbp_features'][:]\n\n for i in input_images:\n img_idx = lsh_index.image_id_map[i.image_id]\n feature_vector = data_lbp[img_idx]\n feature_matrix.append(feature_vector)\n\n return feature_matrix\n\n def extract_feature_feature_vectors_list(self, input_images):\n feature_matrix = []\n for i in input_images:\n feature_matrix.append(self.extract_feature_vector(i.image_id))\n return feature_matrix\n\n def find_m_similar_images(self, reduced_data_matrix, reduced_query_img_vector, m, dimensionality_reduction_model):\n distances = []\n for i in range(len(reduced_data_matrix)):\n temp = (self._input_images_[i],\n self.euclidean_distance(list(reduced_data_matrix[i]), list(reduced_query_img_vector[0])))\n distances.append(temp)\n\n counter = 0\n sorted_similar_images = []\n for i in sorted(distances, key=lambda x: x[1]):\n if counter < m:\n # custom definition for similarity score\n # similarity score = (reciprocal of distance) times 1000\n # 0.000001 for LDA similarity score computation\n similarity_score = round((1 / i[1] + 0.000001) * 10, 3)\n # similarity_score = i[1]\n\n image_match = ImageMatch(i[0], similarity_score)\n sorted_similar_images.append(image_match)\n\n print(f'{counter + 1}. Image Id: {i[0].image_id} Similarity score: {similarity_score}')\n counter += 1\n\n return sorted_similar_images","sub_path":"Code/image_features/LBP.py","file_name":"LBP.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"354330637","text":" # -*- coding: utf-8 -*-\n'''\nTest Vincent.charts\n-------------------\n\nTests for Vincent chart types, which also serve as reference grammar.\n\n'''\n\nimport pandas as pd\nimport nose.tools as nt\nfrom vincent.charts import (data_type, Chart, Bar, Scatter, Line, Area,\n StackedArea, StackedBar, GroupedBar)\n\n\ndef chart_runner(chart, scales, axes, marks):\n \"\"\"Iterate through each chart element for check for contents\"\"\"\n\n for i, scale in enumerate(scales):\n nt.assert_dict_equal(chart.scales[i].grammar(), scale)\n\n for i, axis in enumerate(axes):\n nt.assert_dict_equal(chart.axes[i].grammar(), axis)\n\n for i, axis in enumerate(marks):\n nt.assert_dict_equal(chart.marks[i].grammar(), axis)\n\n\ndef test_data_type():\n \"\"\"Test automatic data type importing\"\"\"\n\n puts1 = [10, 20, 30, 40, 50]\n puts2 = {'apples': 10, 'bananas': 20, 'oranges': 30}\n\n gets1 = [{'col': 'data', 'idx': 0, 'val': 10},\n {'col': 'data', 'idx': 1, 'val': 20},\n {'col': 'data', 'idx': 2, 'val': 30},\n {'col': 'data', 'idx': 3, 'val': 40},\n {'col': 'data', 'idx': 4, 'val': 50}]\n gets2 = [{'col': 'data', 'idx': 'apples', 'val': 10},\n {'col': 'data', 'idx': 'oranges', 'val': 30},\n {'col': 'data', 'idx': 'bananas', 'val': 20}]\n\n for ins, outs in zip([puts1, puts2], [gets1, gets2]):\n test = data_type(ins)\n nt.assert_list_equal(test.values, outs)\n\n #From Iters\n puts = {'x': [1, 2, 3], 'y': [10, 20, 30], 'z': [40, 50, 60]}\n gets = [{'col': 'y', 'idx': 1, 'val': 10},\n {'col': 'y', 'idx': 2, 'val': 20},\n {'col': 'y', 'idx': 3, 'val': 30},\n {'col': 'z', 'idx': 1, 'val': 40},\n {'col': 'z', 'idx': 2, 'val': 50},\n {'col': 'z', 'idx': 3, 'val': 60}]\n\n test = data_type(puts, iter_idx='x')\n nt.assert_list_equal(test.values, gets)\n\n #Pandas\n df = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})\n series = pd.Series([1, 2, 3], name='test')\n gets1 = [{'col': 'one', 'idx': 0, 'val': 1},\n {'col': 'two', 'idx': 0, 'val': 4},\n {'col': 'one', 'idx': 1, 'val': 2},\n {'col': 'two', 'idx': 1, 'val': 5},\n {'col': 'one', 'idx': 2, 'val': 3},\n {'col': 'two', 'idx': 2, 'val': 6}]\n gets2 = [{'col': 'test', 'idx': 0, 'val': 1},\n {'col': 'test', 'idx': 1, 'val': 2},\n {'col': 'test', 'idx': 2, 'val': 3}]\n test_df = data_type(df)\n test_series = data_type(series)\n nt.assert_list_equal(test_df.values, gets1)\n nt.assert_list_equal(test_series.values, gets2)\n\n #Bad type\n class BadType(object):\n \"\"\"Bad data type\"\"\"\n pass\n\n test = BadType()\n nt.assert_raises(ValueError, data_type, test)\n\n\nclass TestChart(object):\n \"\"\"Test Chart ABC\"\"\"\n\n def test_init(self):\n chart = Chart([0, 1], width=100, height=100)\n nt.assert_equal(chart.width, 100)\n nt.assert_equal(chart.height, 100)\n padding = {'top': 10, 'left': 50, 'bottom': 50, 'right': 100}\n nt.assert_dict_equal(chart.padding, padding)\n\n #Data loading errors\n nt.assert_raises(ValueError, Chart)\n nt.assert_raises(ValueError, Chart, [])\n\n\nclass TestBar(object):\n \"\"\"Test Bar Chart\"\"\"\n\n def test_init(self):\n bar = Bar([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'ordinal'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table'},\n u'properties': {u'enter': {u'width': {u'band': True,\n u'offset': -1,\n u'scale': u'x'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'},\n u'y2': {u'scale': u'y', u'value': 0}},\n u'update': {u'fill': {u'value': u'steelblue'}}},\n u'type': u'rect'}]\n\n chart_runner(bar, scales, axes, marks)\n\n\nclass TestScatter(object):\n \"\"\"Test Scatter Chart\"\"\"\n\n def test_init(self):\n\n scatter = Scatter([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'type': u'linear',\n u'range': u'height',\n u'nice': True},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'size': {u'value': 100},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'}}},\n u'type': u'symbol'}],\n u'type': u'group'}]\n\n chart_runner(scatter, scales, axes, marks)\n\n\nclass TestLine(object):\n \"\"\"Test Line Chart\"\"\"\n\n def test_init(self):\n line = Line([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'type': u'linear',\n u'nice': True,\n u'range': u'height'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'}]},\n u'marks':\n [{u'properties': {u'enter': {u'stroke': {u'field': u'data.col',\n u'scale': u'color'},\n u'strokeWidth': {u'value': 2},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'}}},\n u'type': u'line'}],\n u'type': u'group'}]\n\n chart_runner(line, scales, axes, marks)\n\n\nclass TestArea(object):\n \"\"\"Test Area Chart\"\"\"\n\n def test_init(self):\n area = Area([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'nice': True,\n u'type': u'linear',\n u'range': u'height'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'interpolate': {u'value': u'monotone'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'},\n u'y2': {u'scale': u'y', u'value': 0}}},\n u'type': u'area'}],\n u'type': u'group'}]\n\n chart_runner(area, scales, axes, marks)\n\n\nclass TestStackedArea(object):\n \"\"\"Test Stacked Area Chart\"\"\"\n\n def test_init(self):\n\n stack = StackedArea({'x': [1, 2, 3], 'y': [4, 5, 6], 'z': [7, 8, 9]},\n iter_idx='x')\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear',\n u'zero': False},\n {u'domain': {u'data': u'stats', u'field': u'sum'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n datas = [{u'name': u'table',\n u'values': [{u'col': u'y', u'idx': 1, u'val': 4},\n {u'col': u'y', u'idx': 2, u'val': 5},\n {u'col': u'y', u'idx': 3, u'val': 6},\n {u'col': u'z', u'idx': 1, u'val': 7},\n {u'col': u'z', u'idx': 2, u'val': 8},\n {u'col': u'z', u'idx': 3, u'val': 9}]},\n {u'name': u'stats',\n u'source': u'table',\n u'transform': [{u'keys': [u'data.idx'], u'type': u'facet'},\n {u'type': u'stats', u'value': u'data.val'}]}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'},\n {u'height': u'data.val', u'point': u'data.idx', u'type': u'stack'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'interpolate': {u'value': u'monotone'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'y', u'scale': u'y'},\n u'y2': {u'field': u'y2', u'scale': u'y'}}},\n u'type': u'area'}],\n u'type': u'group'}]\n\n chart_runner(stack, scales, axes, marks)\n\n for i, data in enumerate(datas):\n nt.assert_dict_equal(stack.data[i].grammar(), data)\n\n\nclass TestStackedBar(object):\n \"\"\"Test Stacked Bar Chart\"\"\"\n\n def test_init(self):\n\n stack = StackedBar({'x': [1, 2, 3], 'y': [4, 5, 6], 'z': [7, 8, 9]},\n iter_idx='x')\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'ordinal'},\n {u'domain': {u'data': u'stats', u'field': u'sum'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n datas = [{u'name': u'table',\n u'values': [{u'col': u'y', u'idx': 1, u'val': 4},\n {u'col': u'y', u'idx': 2, u'val': 5},\n {u'col': u'y', u'idx': 3, u'val': 6},\n {u'col': u'z', u'idx': 1, u'val': 7},\n {u'col': u'z', u'idx': 2, u'val': 8},\n {u'col': u'z', u'idx': 3, u'val': 9}]},\n {u'name': u'stats',\n u'source': u'table',\n u'transform': [{u'keys': [u'data.idx'], u'type': u'facet'},\n {u'type': u'stats', u'value': u'data.val'}]}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'},\n {u'height': u'data.val', u'point': u'data.idx', u'type': u'stack'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'width': {u'band': True, u'offset': -1, u'scale': u'x'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'y', u'scale': u'y'},\n u'y2': {u'field': u'y2', u'scale': u'y'}}},\n u'type': u'rect'}],\n u'type': u'group'}]\n\n chart_runner(stack, scales, axes, marks)\n\n for i, data in enumerate(datas):\n nt.assert_dict_equal(stack.data[i].grammar(), data)\n\n\nclass TestGroupedBar(object):\n \"\"\"Test grouped bar chart\"\"\"\n\n def test_init(self):\n\n farm_1 = {'apples': 10, 'berries': 32, 'squash': 21}\n farm_2 = {'apples': 15, 'berries': 40, 'squash': 17}\n data = [farm_1, farm_2]\n index = ['Farm 1', 'Farm 2']\n df = pd.DataFrame(data, index=index)\n\n group = GroupedBar(df)\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'padding': 0.2,\n u'range': u'width',\n u'type': u'ordinal'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n datas = [{u'name': u'table',\n u'values':\n [{u'col': u'apples', u'group': 0, u'idx': u'Farm 1', u'val': 10},\n {u'col': u'berries', u'group': 1, u'idx': u'Farm 1', u'val': 32},\n {u'col': u'squash', u'group': 2, u'idx': u'Farm 1', u'val': 21},\n {u'col': u'apples', u'group': 0, u'idx': u'Farm 2', u'val': 15},\n {u'col': u'berries', u'group': 1, u'idx': u'Farm 2', u'val': 40},\n {u'col': u'squash', u'group': 2, u'idx': u'Farm 2', u'val': 17}]}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.idx'], u'type': u'facet'}]},\n u'marks': [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'width': {u'band': True, u'offset': -1, u'scale': u'pos'},\n u'x': {u'field': u'data.group', u'scale': u'pos'},\n u'y': {u'field': u'data.val', u'scale': u'y'},\n u'y2': {u'scale': u'y', u'value': 0}}},\n u'type': u'rect'}],\n u'properties': {u'enter': {u'width': {u'band': True, u'scale': u'x'},\n u'x': {u'field': u'key', u'scale': u'x'}}},\n u'scales': [{u'domain': {u'field': u'data.group'},\n u'name': u'pos',\n u'range': u'width',\n u'type': u'ordinal'}],\n u'type': u'group'}]\n\n chart_runner(group, scales, axes, marks)\n\n for i, data in enumerate(datas):\n nt.assert_dict_equal(group.data[i].grammar(), data)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tests/test_charts.py","file_name":"test_charts.py","file_ext":"py","file_size_in_byte":16182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"450162284","text":"#####################################################################\n# This module list the drawings according to the inputed key word #\n# change the page nubmer of the drawing requested #\n# preview or edit the drawing #\n#####################################################################\n\nimport kcs_ui\nimport kcs_dex\nimport kcs_util\nimport kcs_draft\nimport KcsObjectCriteria\nfrom KcsObjectCriteria import ObjectCriteria\nfrom wxPython.wx import *\nfrom wxPython.grid import *\n\ndef create(parent):\n\treturn wxFramePreview(parent)\n\n[wxID_WXFRAMEPREVIEW, wxID_WXFRAMEPREVIEWBUTTONCHANGEPAGENO, \nwxID_WXFRAMEPREVIEWBUTTONCLEARLIST, wxID_WXFRAMEPREVIEWBUTTONDWGEDIT, \nwxID_WXFRAMEPREVIEWBUTTONDWGPREVIEW, wxID_WXFRAMEPREVIEWBUTTONEXIT, \nwxID_WXFRAMEPREVIEWBUTTONSAVEDWG, wxID_WXFRAMEPREVIEWBUTTONSEARCHBYBLOCK, \nwxID_WXFRAMEPREVIEWBUTTONSEARCHBYPIECE, wxID_WXFRAMEPREVIEWGAUGE, \nwxID_WXFRAMEPREVIEWLISTCTRLDWGLIST, wxID_WXFRAMEPREVIEWPANEL1, \nwxID_WXFRAMEPREVIEWRADIOBOXCHOOSEDWGTYPE, \nwxID_WXFRAMEPREVIEWSTATICBOXCHANGEPAGE, wxID_WXFRAMEPREVIEWSTATICTEXTKEYIN, \nwxID_WXFRAMEPREVIEWSTATICTEXTNEWPAGE, wxID_WXFRAMEPREVIEWSTATICTEXTSEPARATOR, \nwxID_WXFRAMEPREVIEWTEXTCTRLKEYIN, wxID_WXFRAMEPREVIEWTEXTCTRLNEWPAGE, \nwxID_WXFRAMEPREVIEWTEXTCTRLNEWTOTALPAGE, \nwxID_WXFRAMEPREVIEWTEXTCTRLPAGEPREVIEW, \n] = map(lambda _init_ctrls: wxNewId(), range(21))\n\nclass wxFramePreview(wxFrame):\n\tdef _init_coll_listCtrlDwgList_Columns(self, parent):\n\t\t# generated method, don't edit\n\n\t\tparent.InsertColumn(col=0, format=wxLIST_FORMAT_LEFT,\n\t\t\t heading='Dwg Name', width=-1)\n\t\tparent.InsertColumn(col=1, format=wxLIST_FORMAT_LEFT, heading='Page',\n\t\t\t width=-1)\n\n\tdef _init_ctrls(self, prnt):\n\t\t# generated method, don't edit\n\t\twxFrame.__init__(self, id=wxID_WXFRAMEPREVIEW, name='wxFramePreview',\n\t\t\t parent=prnt, pos=wxPoint(517, 298), size=wxSize(463, 601),\n\t\t\t style=wxDEFAULT_FRAME_STYLE, title='Preview')\n\t\tself.SetClientSize(wxSize(455, 574))\n\n\t\tself.panel1 = wxPanel(id=wxID_WXFRAMEPREVIEWPANEL1, name='panel1',\n\t\t\t parent=self, pos=wxPoint(0, 0), size=wxSize(455, 574),\n\t\t\t style=wxTAB_TRAVERSAL)\n\n\t\tself.radioBoxChooseDwgType = wxRadioBox(choices=['Assembly', 'Cutting',\n\t\t\t 'Nesting'], id=wxID_WXFRAMEPREVIEWRADIOBOXCHOOSEDWGTYPE,\n\t\t\t label='Choose Dwg Type', majorDimension=1,\n\t\t\t name='radioBoxChooseDwgType', parent=self.panel1, point=wxPoint(8,\n\t\t\t 8), size=wxDefaultSize, style=wxRA_SPECIFY_ROWS)\n\n\t\tself.buttonSearchByBlock = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONSEARCHBYBLOCK,\n\t\t\t label='Search', name='buttonSearchByBlock', parent=self.panel1,\n\t\t\t pos=wxPoint(232, 56), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonSearchByBlock,\n\t\t\t wxID_WXFRAMEPREVIEWBUTTONSEARCHBYBLOCK,\n\t\t\t self.OnButtonSearchByBlockButton)\n\n\t\tself.buttonSearchByPiece = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONSEARCHBYPIECE,\n\t\t\t label='Search By', name='buttonSearchByPiece', parent=self.panel1,\n\t\t\t pos=wxPoint(328, 56), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonSearchByPiece,\n\t\t\t wxID_WXFRAMEPREVIEWBUTTONSEARCHBYPIECE,\n\t\t\t self.OnButtonSearchByPieceButton)\n\n\t\tself.staticTextKeyIn = wxStaticText(id=wxID_WXFRAMEPREVIEWSTATICTEXTKEYIN,\n\t\t\t label='Key In', name='staticTextKeyIn', parent=self.panel1,\n\t\t\t pos=wxPoint(8, 64), size=wxSize(30, 13), style=0)\n\n\t\tself.textCtrlKeyIn = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLKEYIN,\n\t\t\t name='textCtrlKeyIn', parent=self.panel1, pos=wxPoint(56, 56),\n\t\t\t size=wxSize(160, 21), style=0, value='')\n\n\t\tself.listCtrlDwgList = wxListCtrl(id=wxID_WXFRAMEPREVIEWLISTCTRLDWGLIST,\n\t\t\t name='listCtrlDwgList', parent=self.panel1, pos=wxPoint(16, 96),\n\t\t\t size=wxSize(424, 248), style=wxLC_REPORT | wxLC_ICON)\n\t\tself._init_coll_listCtrlDwgList_Columns(self.listCtrlDwgList)\n\t\tEVT_LIST_ITEM_SELECTED(self.listCtrlDwgList,\n\t\t\t wxID_WXFRAMEPREVIEWLISTCTRLDWGLIST,\n\t\t\t self.OnListCtrlDwgListListItemSelected)\n\n\t\tself.gauge = wxGauge(id=wxID_WXFRAMEPREVIEWGAUGE, name='gauge',\n\t\t\t parent=self.panel1, pos=wxPoint(16, 360), range=100,\n\t\t\t size=wxSize(424, 16), style=wxGA_HORIZONTAL)\n\n\t\tself.buttonClearList = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONCLEARLIST,\n\t\t\t label='Clear List', name='buttonClearList', parent=self.panel1,\n\t\t\t pos=wxPoint(24, 384), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonClearList, wxID_WXFRAMEPREVIEWBUTTONCLEARLIST,\n\t\t\t self.OnButtonClearListButton)\n\n\t\tself.buttonDwgPreview = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONDWGPREVIEW,\n\t\t\t label='Preview', name='buttonDwgPreview', parent=self.panel1,\n\t\t\t pos=wxPoint(184, 384), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonDwgPreview, wxID_WXFRAMEPREVIEWBUTTONDWGPREVIEW,\n\t\t\t self.OnButtonDwgPreviewButton)\n\n\t\tself.buttonDwgEdit = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONDWGEDIT,\n\t\t\t label='Edit', name='buttonDwgEdit', parent=self.panel1,\n\t\t\t pos=wxPoint(360, 384), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonDwgEdit, wxID_WXFRAMEPREVIEWBUTTONDWGEDIT,\n\t\t\t self.OnButtonDwgEditButton)\n\n\t\tself.staticBoxChangePage = wxStaticBox(id=wxID_WXFRAMEPREVIEWSTATICBOXCHANGEPAGE,\n\t\t\t label='Change Page', name='staticBoxChangePage',\n\t\t\t parent=self.panel1, pos=wxPoint(24, 432), size=wxSize(416, 100),\n\t\t\t style=0)\n\n\t\tself.buttonExit = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONEXIT,\n\t\t\t label='Exit', name='buttonExit', parent=self.panel1,\n\t\t\t pos=wxPoint(360, 544), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonExit, wxID_WXFRAMEPREVIEWBUTTONEXIT,\n\t\t\t self.OnButtonExitButton)\n\n\t\tself.textCtrlPagePreview = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLPAGEPREVIEW,\n\t\t\t name='textCtrlPagePreview', parent=self.panel1, pos=wxPoint(48,\n\t\t\t 472), size=wxSize(64, 21), style=0, value='')\n\n\t\tself.textCtrlNewPage = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLNEWPAGE,\n\t\t\t name='textCtrlNewPage', parent=self.panel1, pos=wxPoint(160, 472),\n\t\t\t size=wxSize(40, 21), style=0, value='')\n\n\t\tself.textCtrlNewTotalPage = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLNEWTOTALPAGE,\n\t\t\t name='textCtrlNewTotalPage', parent=self.panel1, pos=wxPoint(224,\n\t\t\t 472), size=wxSize(48, 21), style=0, value='')\n\n\t\tself.staticTextNewPage = wxStaticText(id=wxID_WXFRAMEPREVIEWSTATICTEXTNEWPAGE,\n\t\t\t label='New', name='staticTextNewPage', parent=self.panel1,\n\t\t\t pos=wxPoint(128, 472), size=wxSize(22, 13), style=0)\n\n\t\tself.staticTextSeparator = wxStaticText(id=wxID_WXFRAMEPREVIEWSTATICTEXTSEPARATOR,\n\t\t\t label='/', name='staticTextSeparator', parent=self.panel1,\n\t\t\t pos=wxPoint(208, 472), size=wxSize(8, 21), style=0)\n\n\t\tself.buttonChangePageNo = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONCHANGEPAGENO,\n\t\t\t label='Change', name='buttonChangePageNo', parent=self.panel1,\n\t\t\t pos=wxPoint(280, 472), size=wxSize(56, 23), style=0)\n\t\tEVT_BUTTON(self.buttonChangePageNo,\n\t\t\t wxID_WXFRAMEPREVIEWBUTTONCHANGEPAGENO,\n\t\t\t self.OnButtonChangePageNoButton)\n\n\t\tself.buttonSaveDwg = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONSAVEDWG,\n\t\t\t label='Save', name='buttonSaveDwg', parent=self.panel1,\n\t\t\t pos=wxPoint(360, 472), size=wxSize(56, 23), style=0)\n\t\tEVT_BUTTON(self.buttonSaveDwg, wxID_WXFRAMEPREVIEWBUTTONSAVEDWG,\n\t\t\t self.OnButtonSaveDwgButton)\n\n\tdef __init__(self, parent):\n\t\tself._init_ctrls(parent)\n\n################################################################################\n# my own function start #\n################################################################################\n\tdef GetDwgType(self):\n\t\tdwg_type_list = [\"Assembly drawing\",\"General drawing\",\"Hull nesting sketch\"]\n\t\t#dwg_DB_list = [\"SB_ASSPDB\",\"SB_PDB\",\"SB_NPL\"]\n\t\tselection \t = self.radioBoxChooseDwgType.GetSelection()\n\t\tdwg_type \t = dwg_type_list[selection]\n\t\treturn dwg_type\n\n#-------------------------------------------------------------------------------\n\tdef GetDwgDB(self,dwg_type):\n\t\ttry:\n\t\t\tdict \t\t= kcs_draft.dwg_type_list_get() #dict is a dictionary of drawing type list\n\t\t\tdwg_dbNames = map(lambda x : x[0],dict.values())\n\t\t\tdwg_DBs \t= map(lambda x : x[1],dict.values())\n\t\t\tDB_keys \t= dict.keys()\n\t\t\ti = 0\n\t\t\twhile i < len(dwg_DBs):\n\t\t\t\tif dwg_dbNames[i] == dwg_type:\n\t\t\t\t\treturn dwg_DBs[i],DB_keys[i]\n\t\t\t\ti+=1\n\t\t\tif i == len(dwg_DBs):\n\t\t\t\tkcs_ui.message_confirm(\"drawing type do not exist in current project\")\n\t\texcept:\n\t\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n#-------------------------------------------------------------------------------\n\tdef GetStmt(self):\n\t\tdwg_type = self.GetDwgType()\n\t\ttext_keyin = self.textCtrlKeyIn.GetValue().upper()\n\t\ttemp = text_keyin\n\t\tif temp == '*' or temp == \"\" :\n\t\t\tstmt = \"DRA('@\"+dwg_type+\"'*).NAM\"\n\t\t\treturn stmt\n\t\t\t\n\t\tif temp[0]=='*':\n\t\t\ttemp=temp[1:len(temp)]\n\t\tif temp[len(temp)-1]=='*':\n\t\t\ttemp=temp[0:len(temp)-1]\n\t\tsplit=temp.split('*')\n\t\tstr=\"\"\n\t\tfor i in split:\n\t\t\tstr += i+\"'*'\"\n\t\tstr=str[0:len(str)-3]\n\t\t\n\t\tprefix = text_keyin[0]\n\t\tpostfix = text_keyin[len(text_keyin)-1]\n\t\tif prefix != '*' and postfix != '*':\n\t\t\tstmt = \"DRA('\"+str+'@'+dwg_type+\"').NAM\"\n\t\telif prefix != '*' and postfix == '*':\n\t\t\tstmt = \"DRA('\"+str+'@'+dwg_type+\"'*).NAM\"\n\t\telif prefix == '*' and postfix != '*':\n\t\t\tstmt = \"DRA(*'\"+str+'@'+dwg_type+\"').NAM\"\n\t\telse:\n\t\t\tstmt = \"DRA(*'\"+str+'@'+dwg_type+\"'*).NAM\"\n\t\treturn stmt\n\n#-------------------------------------------------------------------------------\n\tdef GetDwgNameList(self,stmt_get_dwgname):\n\t\tself.gauge.SetRange(50)\n\t\tdwg_name_list = []\n\t\ttry:\n\t\t\tif kcs_dex.extract(stmt_get_dwgname) == 0 :\n\t\t\t\tdataType = kcs_dex.next_result()\n\t\t\t\tif dataType < 0 :\n\t\t\t\t\tkcs_ui.message_confirm(\"drawngs not found\")\n\t\t\t\t\treturn []\n\t\t\t\tgauge = 0\n\t\t\t\twhile dataType >= 0:\n\t\t\t\t\tif dataType == 3:\n\t\t\t\t\t\tif gauge == 50:\n\t\t\t\t\t\t\tgauge = 0\n\t\t\t\t\t\tgauge += 1\n\t\t\t\t\t\tself.gauge.SetValue(gauge)\n\t\t\t\t\t\tdwg_name_list.append(kcs_dex.get_string())\n\t\t\t\t\t\tdataType = kcs_dex.next_result()\n\t\t\tself.gauge.SetRange(gauge)\n\t\t\tself.gauge.SetValue(gauge)\n\t\t\treturn dwg_name_list\n\t\texcept:\n\t\t\tkcs_ui.message_confirm(kcs_dex.error)\n\n#-------------------------------------------------------------------------------\n\tdef GetColumnText(self,index,col):\n\t\titem = self.listCtrlDwgList.GetItem(index,col)\n\t\treturn item.GetText()\n\n#-------------------------------------------------------------------------------\n\tdef GetTotalNumber(self):\n\t\tdwg_type \t\t = self.GetDwgType()\n\t\tstmt_get_totalNo = \"DRA('\"+self.dwg_name+'@'+dwg_type+\"').TEXT_BY_RULE(8889).ROW(1)\"\n\t\tkcs_dex.extract(stmt_get_totalNo)\n\t\tif kcs_dex.next_result() < 0 :\n\t\t\tdwg_total_no = \" \"\n\t\telse :\n\t\t\tdwg_total_no = kcs_dex.get_string()\n\t\treturn dwg_total_no\n\n#-------------------------------------------------------------------------------\n\tdef GetPageNoList(self,dwg_name_list):\n\t\tself.gauge.SetRange(50)\n\t\tgauge \t = 0\n\t\tdwg_type = self.GetDwgType()\n\t\tdwg_pageNo_list = []\n\t\tfor i in dwg_name_list :\n\t\t\tkcs_dex.extract(\"DRA('\"+i+'@'+dwg_type+\"').TEXT_BY_RULE(8888).ROW(1)\")\n\t\t\tif gauge == 50:\n\t\t\t\tgauge = 0\n\t\t\tgauge += 1\n\t\t\tself.gauge.SetValue(gauge)\n\t\t\tif kcs_dex.next_result() < 0 :\n\t\t\t\tdwg_pageNo_list.append(\" \")\n\t\t\telse :\n\t\t\t\tdwg_pageNo_list.append(kcs_dex.get_string())\n\t\tself.gauge.SetRange(gauge)\n\t\tself.gauge.SetValue(gauge)\n\t\treturn dwg_pageNo_list\n\n#-------------------------------------------------------------------------------\n\tdef SetListCtrl(self,dwg_name_list,dwg_pageNo_list):\n\t\tfor i in range(len(dwg_name_list)):\n\t\t\tself.listCtrlDwgList.InsertStringItem(i,'')\n\t\t\tself.listCtrlDwgList.SetStringItem(i,0,dwg_name_list[i])\n\t\t\tself.listCtrlDwgList.SetStringItem(i,1,dwg_pageNo_list[i])\n\n#-------------------------------------------------------------------------------\n\tdef OpenCurrentDwg(self,mode):\n\t\tif kcs_draft.dwg_current():\n\t\t\tkcs_draft.dwg_close()\n\t\tdwg_type = self.GetDwgType()\n\t\tDB,DBKey = self.GetDwgDB(dwg_type)\n\t\ttry:\n\t\t\tkcs_draft.dwg_open(self.dwg_name,DB,mode)\n\t\texcept:\n\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n################################################################################\n# my own functions end #\n################################################################################\n\n################################################################################\n# Event functions start #\n################################################################################\n\n\tdef OnButtonSearchByBlockButton(self, event):\n\t\tself.listCtrlDwgList.DeleteAllItems()\n\t\t# stmt_get_dwgname = self.GetDwgNameStmt()\n\t\tstmt_get_dwgname = self.GetStmt()\n\t\tdwg_name_list \t = self.GetDwgNameList(stmt_get_dwgname)\n\t\tdwg_PangeNo_list = self.GetPageNoList(dwg_name_list)\n\t\tself.SetListCtrl(dwg_name_list,dwg_PangeNo_list)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonSearchByPieceButton(self, event):\n\t\tself.listCtrlDwgList.DeleteAllItems()\n\t\tstmt_piece_list \t= self.GetStmt()\n\t\tdwg_piece_list\t\t= self.GetDwgNameList(stmt_piece_list)\n\t\tdwg_piece_page_list = self.GetPageNoList(dwg_piece_list)\n\t\tself.SetListCtrl(dwg_piece_list,dwg_piece_page_list)\n\n#-------------------------------------------------------------------------------\n\tdef OnListCtrlDwgListListItemSelected(self, event):\n\t\tcurrent_item = event.m_itemIndex\n\t\tself.dwg_name = self.GetColumnText(current_item,0)\n\t\tdwg_page \t = self.GetColumnText(current_item,1)\n\t\tself.textCtrlPagePreview.SetValue(dwg_page)\n\t\tself.textCtrlNewPage.SetValue(dwg_page)\n\t\tdwg_total_No = self.GetTotalNumber()\n\t\tself.textCtrlNewTotalPage.SetValue(dwg_total_No)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonClearListButton(self, event):\n\t\tself.listCtrlDwgList.DeleteAllItems()\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonDwgPreviewButton(self, event):\n\t\tself.OpenCurrentDwg(kcs_draft.kcsOPENMODE_READONLY)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonDwgEditButton(self, event):\n\t\tself.OpenCurrentDwg(kcs_draft.kcsOPENMODE_READWRITE)\n\t\tif kcs_draft.dwg_current():\n\t\t\tself.Destroy()\n\t\telse:\n\t\t\tevent.skip()\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonExitButton(self, event):\n\t\tself.Destroy()\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonChangePageNoButton(self, event):\n\t\tself.OpenCurrentDwg(kcs_draft.kcsOPENMODE_READWRITE)\n\t\tpage_No \t= self.textCtrlPagePreview.GetValue()\n\t\tnew_page_No = self.textCtrlNewPage.GetValue()\n\t\tif new_page_No != \"\" and page_No != new_page_No:\n\t\t\ttry:\n\t\t\t\tkcs_draft.rule_text_new(new_page_No,8888)\n\t\t\texcept:\n\t\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\t\tnew_total_page \t = self.textCtrlNewTotalPage.GetValue()\n\t\tprevious_total_No = self.GetTotalNumber()\n\t\tif new_total_page != \"\" and previous_total_No != new_total_page :\n\t\t\ttry:\n\t\t\t\tkcs_draft.rule_text_new(new_total_page,8889)\n\t\t\texcept:\n\t\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonSaveDwgButton(self, event):\n\t\ttry:\n\t\t\tkcs_draft.dwg_save()\n\t\texcept:\n\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n################################################################################\n# Event functions end #\n################################################################################\n\n################################################################################\n# main function start #\n################################################################################\n \nclass PreviewApp(wxApp):\n\tdef OnInit(self):\n\t\twxInitAllImageHandlers()\n\t\tself.main = create(None)\n\t\tself.main.Show()\n\t\tself.SetTopWindow(self.main)\n\t\treturn True\n\ndef main():\n\tapplication = PreviewApp(0)\n\tapplication.MainLoop()\n\nif __name__ == '__main__':\n\tmain()\n################################################################################\n# main function ends #\n################################################################################","sub_path":"src/python/tribonM3/PreviewFrame.PM.17.57.py","file_name":"PreviewFrame.PM.17.57.py","file_ext":"py","file_size_in_byte":16070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"197284105","text":"# coding: utf-8\n###################################################################\n# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #\n# #\n# Author: Marius Retegan #\n# #\n# This work is licensed under the terms of the MIT license. #\n# For further information, see https://github.com/mretegan/crispy #\n###################################################################\n\"\"\"The modules provides a class to deal with the configuration.\"\"\"\n\nimport logging\nimport os\nimport sys\n\nfrom PyQt5.QtCore import QSettings, QStandardPaths\n\nfrom crispy import __version__ as version, resourceAbsolutePath\n\nlogger = logging.getLogger(__name__)\n\n\nclass Config:\n @property\n def name(self):\n return \"Crispy\" if sys.platform == \"win32\" else \"crispy\"\n\n @property\n def path(self):\n return os.path.split(self.settings.fileName())[0]\n\n @property\n def settings(self):\n return QSettings(\n QSettings.IniFormat, QSettings.UserScope, self.name, \"settings-new\"\n )\n\n def read(self):\n return self.settings\n\n def loadDefaults(self):\n settings = self.read()\n\n settings.beginGroup(\"Quanty\")\n settings.setValue(\"Path\", self.findQuanty())\n settings.setValue(\"Verbosity\", \"0x0000\")\n settings.setValue(\"DenseBorder\", \"2000\")\n settings.setValue(\"RemoveFiles\", True)\n settings.endGroup()\n\n settings.setValue(\"CheckForUpdates\", True)\n settings.setValue(\"CurrentPath\", os.path.expanduser(\"~\"))\n settings.setValue(\"Version\", version)\n\n settings.sync()\n\n def removeOldFiles(self):\n \"\"\"Function that removes the settings from previous versions.\"\"\"\n root = QStandardPaths.standardLocations(QStandardPaths.GenericConfigLocation)[0]\n\n path = os.path.join(root, self.name)\n\n if version < \"0.7.0\":\n try:\n os.remove(os.path.join(path, \"settings.json\"))\n os.rmdir(path)\n logger.debug(\"Removed old configuration file.\")\n except (IOError, OSError):\n pass\n\n @staticmethod\n def findQuanty():\n if sys.platform == \"win32\":\n executable = \"Quanty.exe\"\n else:\n executable = \"Quanty\"\n\n envPath = QStandardPaths.findExecutable(executable)\n localPath = resourceAbsolutePath(os.path.join(\"quanty\", \"bin\"))\n localPath = QStandardPaths.findExecutable(executable, [localPath])\n\n # Check if Quanty is in the paths defined in the $PATH.\n if envPath:\n path = envPath\n # Check if Quanty is bundled with Crispy.\n elif localPath:\n path = localPath\n else:\n path = None\n\n return path\n","sub_path":"crispy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"486304894","text":"import abc\nimport random\nfrom collections import deque, namedtuple\nfrom typing import Any, Collection, Optional\n\nimport numpy as np\nimport torch\nfrom dataclasses import dataclass\nfrom torch import optim\nfrom torch.nn import functional as f\n\nfrom epsilon_policies import EpsilonGreedyPolicy\nfrom model import DQNModel\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nexperience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"]) #\n\n\n@dataclass\nclass DRLAgent(abc.ABC):\n \"\"\"\n Abstract deep reinforcement learning agent.\n \"\"\"\n state_size: int # size of each state in the state space\n action_size: int # size of the action space\n lr: float # learning rate\n epsilon_greedy_policy: EpsilonGreedyPolicy\n seed: Optional[int] # seed\n buffer_size: int = int(1e5) # experience memory buffer size\n batch_size: int = 64 # experience memory batch size\n update_every: int = 4 # how often the target network is updated\n gamma: float = 0.99 # discount factor\n tau: float = 1e-3 # step-size for soft updating the target network\n \n @abc.abstractmethod\n def step(self, state: Collection[float], action: int, reward: float, next_state: Collection[float],\n done: bool) -> None:\n \"\"\"\n The agent registers a step it took in the environment.\n\n :param state: current state\n :param action: action taken\n :param reward: reward received\n :param next_state: state that resulted from the action\n :param done: if the resulting state was terminal\n \"\"\"\n \n @abc.abstractmethod\n def learn(self, experiences: Collection[experience]) -> None:\n \"\"\"\n The agent learns from previous experiences.\n :param experiences: a minibatch of previous experiences with size=batch_size\n \"\"\"\n \n @abc.abstractmethod\n def act(self, state: Collection[float], train: bool = True) -> int:\n \"\"\"\n The agent acts following a epsilon-greedy policy.\n :param train: if training mode is active, if so the agent will follow the epsilon-greedy policy, otherwise it\n will follow the greedy policy\n :param state: current state\n :return: action selected\n \"\"\"\n \n def soft_update(self) -> None:\n \"\"\"\n Soft-updates the target network with the recently-updated parameters of the local network, with self.tau as\n step-size.\n \"\"\"\n\n\nclass DQNetAgent(DRLAgent):\n \"\"\"\n Deep Q-Network agent.\n \"\"\"\n \n def __init__(self, **data: Any):\n super(DQNetAgent, self).__init__(**data)\n np.random.seed(self.seed)\n \n # Initializes the Local and the Target QNetworks.\n self.q_local = DQNModel(self.state_size, self.action_size, self.seed).to(device)\n self.q_target = DQNModel(self.state_size, self.action_size, self.seed).to(device)\n self.optimizer = optim.Adam(self.q_local.parameters(), lr=self.lr)\n \n # Initializes the experience replay memory\n self.memory = ReplayBuffer(buffer_size=self.buffer_size, batch_size=self.batch_size, seed=self.seed)\n \n # Sets the initial time step to 0, this is used for updating the target network every update_every steps\n self.time_step = 0\n \n def load(self, path: str) -> None:\n \"\"\"\n Load previously trained model.\n :param path: model path\n \"\"\"\n self.q_local.load_state_dict(torch.load(path))\n \n def step(self, state: Collection[float], action: int, reward: float, next_state: Collection[float], done: bool) -> \\\n None:\n # Store experience in memory\n self.memory.add(state, action, reward, next_state, done)\n \n # Learn every update_every time steps\n self.time_step = (self.time_step + 1) % self.update_every\n if self.time_step == 0:\n # Check if there are enough samples in memory, if so, get a sample and learn from it\n if len(self.memory) > self.batch_size:\n experiences = self.memory.sample()\n self.learn(experiences)\n \n def learn(self, experiences: Collection[experience]) -> None:\n \n # Get the informed from the experiences sample.\n states, actions, rewards, next_states, dones = experiences\n \n # Max action value for each episode in the sample\n target_values = self.q_target(next_states).cpu().max(1)[0].unsqueeze(1)\n \n # Calculate the target action-value for taking each action from each origin state in the sample. If the\n # episode is terminal, the action-value is the reward\n target_values = target_values.to(device)\n target_estimate = rewards + self.gamma * target_values * (1 - dones)\n \n # Get the estimates for the local network and gather the action-value for each action taken in the sample.\n local_estimate = self.q_local(states).gather(1, actions)\n \n # Calculate the loss and applies gradient descent\n loss = f.mse_loss(local_estimate, target_estimate)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n # Update the target network\n self.soft_update()\n \n def act(self, state: Collection[float], train: bool = True) -> int:\n epsilon = self.epsilon_greedy_policy.step(self.time_step)\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n \n # Get estimate action values from local network\n self.q_local.eval()\n with torch.no_grad():\n action_values = self.q_local(state)\n self.q_local.train()\n \n # Epsilon-greedy action selection\n if train:\n if np.random.random() > epsilon:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return np.random.choice(np.arange(self.action_size))\n else:\n return np.argmax(action_values.cpu().data.numpy())\n \n def soft_update(self) -> None:\n for target_p, local_p in zip(self.q_target.parameters(), self.q_local.parameters()):\n target_p.data.copy_(self.tau * local_p.data + (1.0 - self.tau) * target_p.data)\n\n\nclass ReplayBuffer:\n \"\"\"\n Buffer for stores experiences and sampling them when requested.\n \"\"\"\n \n def __init__(self, batch_size: int, buffer_size: int, seed: int):\n \"\"\"\n ReplayBuffer constructor\n :param batch_size: number of experiences in a minibatch\n :param buffer_size: max len of memory\n :param seed: random seed\n \"\"\"\n super(ReplayBuffer, self).__init__()\n random.seed(seed)\n self.batch_size = batch_size\n self.memory = deque(maxlen=buffer_size)\n \n def add(self, state: Collection[float], action: int, reward: float, next_state: Collection[float], done: bool) -> \\\n None:\n \"\"\"\n Add a new experience to memory.\n :param state: current state\n :param action: action taken\n :param reward: reward received\n :param next_state: resulting state after action\n :param done: if the resulting state is terminal\n \"\"\"\n exp = experience(state, action, reward, next_state, done)\n self.memory.append(exp)\n \n def sample(self) -> Collection[experience]:\n \"\"\"\n Randomly sample a batch of experiences from memory.\n :return: a minibatch of experiences\n \"\"\"\n samples = random.sample(self.memory, k=self.batch_size)\n samples = np.array(samples, dtype=np.object)\n \n states = torch.from_numpy(np.vstack(samples[:, 0])).float().to(device)\n actions = torch.from_numpy(np.vstack(samples[:, 1])).long().to(device)\n rewards = torch.from_numpy(np.vstack(samples[:, 2])).float().to(device)\n next_states = torch.from_numpy(np.vstack(samples[:, 3])).float().to(device)\n dones = torch.from_numpy(np.vstack(samples[:, 4]).astype(np.uint8)).float().to(\n device)\n return states, actions, rewards, next_states, dones\n \n def __len__(self) -> int:\n \"\"\"Return the current size of internal memory\"\"\"\n return len(self.memory)\n","sub_path":"src/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"651540388","text":"from django.utils import timezone\nfrom webzmap import settings\nimport os\nimport sys\nimport subprocess\nimport time\nimport datetime\n\n\nclass ZmapStatus(object):\n def __init__(self):\n self.read_time = None\n self.time_elapsed = 0\n self.time_remaining = 0\n self.percent_complete = 0\n self.active_send_threads = 0\n self.sent_total = 0\n self.hit_rate = 0\n self.sent_last_one_sec = 0\n self.sent_avg_per_sec = 0\n self.recv_success_total = 0\n self.recv_success_last_one_sec = 0\n self.recv_success_avg_per_sec = 0\n self.recv_total = 0\n self.recv_total_last_one_sec = 0\n self.recv_total_avg_per_sec = 0\n self.pcap_drop_total = 0\n self.drop_last_one_sec = 0\n self.drop_avg_per_sec = 0\n self.sendto_fail_total = 0\n self.sendto_fail_last_one_sec = 0\n self.sendto_fail_avg_per_sec = 0\n\n\nclass ShellExecuteError(BaseException):\n def __init__(self, error_msg):\n super(ShellExecuteError, self).__init__(error_msg)\n\n\ndef create_parent_dir(path):\n parent = os.path.dirname(path)\n if not os.path.exists(parent):\n os.makedirs(parent)\n\n\ndef get_last_line(path):\n cmd = \"tail -n 1 %s\" % path\n p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n return_code = p.wait()\n if return_code == 0:\n return p.stdout.read().strip()\n else:\n raise ShellExecuteError(p.stderr.read())\n\n\ndef get_current_status(status_path):\n \"\"\"\n real-time,\n time-elapsed,\n time-remaining,\n percent-complete,\n hit-rate,\n active-send-threads,\n sent-total,\n sent-last-one-sec,\n sent-avg-per-sec,\n recv-success-total,\n recv-success-last-one-sec,\n recv-success-avg-per-sec,\n recv-total,\n recv-total-last-one-sec,\n recv-total-avg-per-sec,\n pcap-drop-total,\n drop-last-one-sec,\n drop-avg-per-sec,\n sendto-fail-total,\n sendto-fail-last-one-sec,\n sendto-fail-avg-per-sec\n :param status_path:\n :return:\n \"\"\"\n try:\n line = get_last_line(status_path)\n except ShellExecuteError:\n return None\n if line.startswith(\"real-time\"):\n return None\n status = ZmapStatus()\n items = line.split(\",\")\n t = time.strptime(items[0], \"%Y-%m-%d %X\")\n y, m, d, h, M, s = t[0:6]\n status.read_time = datetime.datetime(y, m, d, h, M, s, tzinfo=timezone.LocalTimezone())\n status.time_elapsed = int(items[1])\n status.time_remaining = int(items[2])\n status.percent_complete = float(items[3])\n status.hit_rate = float(items[4])\n status.active_send_threads = int(items[5])\n status.sent_total = long(items[6])\n status.sent_last_one_sec = int(items[7])\n status.sent_avg_per_sec = int(items[8])\n status.recv_success_total = long(items[9])\n status.recv_success_last_one_sec = int(items[10])\n status.recv_success_avg_per_sec = int(items[11])\n status.recv_total = long(items[12])\n status.recv_total_last_one_sec = int(items[13])\n status.recv_total_avg_per_sec = int(items[14])\n status.pcap_drop_total = long(items[15])\n status.drop_last_one_sec = int(items[16])\n status.drop_avg_per_sec = int(items[17])\n status.sendto_fail_total = long(items[18])\n status.sendto_fail_last_one_sec = int(items[19])\n status.sendto_fail_avg_per_sec = int(items[20])\n return status\n\n\nclass Zmap(object):\n def __init__(self, execute_bin='zmap', verbosity=3, cwd=None, logger=None):\n self.execute_bin = execute_bin\n self.verbosity = verbosity\n self.cwd = cwd\n self.logger = logger\n\n def run_job(self, job):\n pass\n\n def scan(self, job, port, subnets=None, output_path=None, log_path=None, bandwidth=2, white_list=None, black_list=None,\n verbosity=None, status_updates_path=None, quiet=False, stdout=None, stderr=None):\n if verbosity:\n self.verbosity = verbosity\n cmd = \"%s -p %s\" % (self.execute_bin, port)\n # if output_path:\n # output_path = os.path.join(self.cwd, output_path)\n # create_parent_dir(output_path)\n # cmd += ' -o %s' % output_path\n if bandwidth:\n # cmd += \" -B %sM\" % bandwidth\n cmd += \" -r %s\" % bandwidth\n if white_list:\n white_list = os.path.join(self.cwd, white_list)\n create_parent_dir(white_list)\n cmd += \" -w %s\" % white_list\n if black_list:\n black_list = os.path.join(self.cwd, black_list)\n create_parent_dir(black_list)\n cmd += \" -b %s\" % black_list\n if status_updates_path:\n status_updates_path = os.path.join(self.cwd, status_updates_path)\n create_parent_dir(status_updates_path)\n cmd += \" -u %s\" % status_updates_path\n if log_path:\n log_path = os.path.join(self.cwd, log_path)\n create_parent_dir(log_path)\n cmd += \" -l %s\" % log_path\n cmd += ' -v %s' % self.verbosity\n if subnets:\n cmd += ' ' + subnets\n if quiet:\n cmd += ' -q'\n if self.logger:\n self.logger.info(\"cmd is \" + cmd)\n cmd = filter(lambda x: x.strip() != '', cmd.split(\" \"))\n r, w = os.pipe()\n zmap_pid = subprocess.Popen(cmd, stdout=w, stderr=sys.stderr)\n service = get_service(port)\n zgrab_arg = [settings.zgrab2_path, service]\n zgrab_pid = subprocess.Popen(zgrab_arg, stdin=r, stderr=sys.stderr)\n self.logger.info(\"cmd is fuck\")\n return zmap_pid, zgrab_pid\n\n\ndef get_service(port):\n port_to_service = {\n 102: \"siemens\",\n 502: \"modbus\",\n 789: \"crimson\",\n 1911: \"fox\",\n 1962: \"pcworx\",\n 2404: \"iec104\",\n 9600: \"omron\",\n 20000: \"dnp3\",\n 20547: \"proconos\",\n 44818: \"ethip\",\n 47808: \"bacnet\",\n }\n return port_to_service[port]\n\n\nif __name__ == '__main__':\n import signal\n zmap = Zmap(logger=None)\n p, q = zmap.scan(\n job=\"ss\",\n subnets='118.25.94.0/24',\n port=80,\n stderr=None,\n stdout=None,\n quiet=False,\n )\n import time\n p_exit_code = p.poll()\n q_exit_code = q.poll()\n while p_exit_code is None:\n print(p.poll())\n if p.poll() == 0:\n q.send_signal(signal.SIGKILL)\n break\n time.sleep(2)\n\n","sub_path":"tools/zmap.py","file_name":"zmap.py","file_ext":"py","file_size_in_byte":6394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"644026677","text":"# -*- coding: utf-8 -*-\r\nimport codecs\r\n\r\nclass Morpheme:\r\n def __init__(self,surface,base,pos,pos1):\r\n self.surface = surface\r\n self.base = base\r\n self.pos = pos\r\n self.pos1 = pos1\r\n\r\nclass Phrase:\r\n def __init__(self,morpheme_surfaces,morpheme_bases,morphemes_poses,modifier_index,phrase_index):\r\n self.morpheme_surfaces = morpheme_surfaces\r\n self.morpheme_bases = morpheme_bases\r\n self.morpheme_poses = morphemes_poses\r\n self.modifier_index = modifier_index\r\n self.phrase_index = phrase_index\r\n\r\nclass Sentence:\r\n def __init__(self, phrases):\r\n self.phrases = phrases\r\n\r\ndef init(sentence):\n sentence = Sentence([])\r\n\r\ndef decisionOutput(phrases):\r\n output_candidate_phrases = []\r\n output_candidate_phrases_modifier_indexs = []\r\n for phrase in phrases:\r\n for output_candidate_phrase in output_candidate_phrases:\r\n modifier_index = int(output_candidate_phrase.split(\"\\t\")[0])\r\n modifiee_index = phrase.phrase_index\r\n if modifier_index == modifiee_index:\r\n if u\"動詞\" in phrase.morpheme_poses:\r\n noun_particle = output_candidate_phrase.split(\"\\t\")[1]\r\n verb_index = phrase.morpheme_poses.index(u\"動詞\")\r\n verb = phrase.morpheme_bases[verb_index]\r\n verb_noun_particle = verb + ' ' + noun_particle\r\n print(verb_noun_particle)\r\n output_candidate_phrases.remove(output_candidate_phrase)\r\n output_candidate_phrases_modifier_indexs.remove(str(modifier_index))\r\n break\r\n if u\"名詞\" in phrase.morpheme_poses and u\"助詞\" in phrase.morpheme_poses:\r\n noun_index = phrase.morpheme_poses.index(u\"名詞\")\r\n noun = phrase.morpheme_surfaces[noun_index]\r\n particle_index = phrase.morpheme_poses.index(u\"助詞\")\r\n particle = phrase.morpheme_surfaces[particle_index]\r\n if phrase.modifier_index not in output_candidate_phrases_modifier_indexs:\r\n output_candidate_phrases_modifier_indexs.append(phrase.modifier_index)\r\n output_candidate_phrases.append(phrase.modifier_index + '\\t' + noun + ' ' + particle)\r\n else:\r\n index = output_candidate_phrases_modifier_indexs.index(phrase.modifier_index)\r\n output_candidate_phrases[index] += (' ' + noun + ' ' + particle)\r\n\r\n\r\ndef main():\r\n input_file = codecs.open(\"doc0000000000.knp.txt\", 'r', \"utf-8\")\r\n phrase = Phrase([], [], [], -1, -1)\r\n sentence = Sentence([])\r\n phrase_index = 0\r\n# 全体的に変数名見直す\r\n for line in input_file.readlines():\r\n\r\n if \"EOS\\n\" == line:\r\n if len(phrase.morpheme_surfaces) != 0:\r\n sentence.phrases.append(phrase)\r\n decisionOutput(sentence.phrases)\r\n sentence = Sentence([])\r\n phrase_index = 0\r\n continue\r\n else:\r\n line_split = line.split(\" \")\r\n identifiers = []\r\n identifiers.append(line_split[0])\r\n identifiers.append(line_split[2][0])\r\n if '*' == identifiers[0] and '<' == identifiers[1]:\r\n continue\r\n if '#' == identifiers[0] and 'U' == identifiers[1]:\r\n continue\r\n elif '+' == identifiers[0] and '<' == identifiers[1]:\r\n if len(phrase.morpheme_surfaces) != 0:\r\n sentence.phrases.append(phrase)\r\n #↑1句終わりとしての処理、↓1句はじめとしての処理\r\n modifier_index = line_split[1][:-1]\r\n phrase = Phrase([], [], [], modifier_index, phrase_index)\r\n phrase_index += 1\r\n else:\r\n surface = line_split[0]\r\n base = line_split[2]\r\n pos = line_split[3]\r\n phrase.morpheme_surfaces.append(surface)\r\n phrase.morpheme_bases.append(base)\r\n phrase.morpheme_poses.append(pos)\r\n\r\n\r\n input_file.close()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"knp_edit.py","file_name":"knp_edit.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"176624511","text":"from django.test import TestCase\nimport datetime\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom .models import Question, Choice\n\n\nclass QuestionModelTest(TestCase):\n def test_was_published_recently_with_future_question(self):\n time = timezone.now() + datetime.timedelta(days=30)\n future_question = Question(pub_date=time)\n self.assertIs(future_question.was_published_recently(), False)\n\n\ndef create_question(question_text, days):\n time = timezone.now() + datetime.datetime(day == days)\n return Question.objects.create(question_text=question_text, pub_date=time)\n\n\nclass QuestionIndexViewTests(TestCase):\n def test_no_question(self):\n r = self.client.get(reverse('polls:index'))\n self.assertEqual(r.status_code, 200)\n self.assertContains(r, \"No polls are avaliable\")\n self.assertQuerysetEqual(r.context['latest_question_list'], [])\n\n def test_past_question(self):\n create_question('Past question', 30)\n r = self.client.get(reverse('polls:index'))\n self.assertQuerysetEqual(\n r.context['latest_question_list'],\n {':Past question'}\n )\n \n","sub_path":"src/mysite/polls/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"329243914","text":"# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\n\nimport numpy as np\n\nfrom sklearn.svm.classes import SVC\nfrom sklearn.datasets import samples_generator\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_regression\nfrom sklearn.pipeline import Pipeline\n\nfrom tests.estimator.classifier.Classifier import Classifier\nfrom tests.language.JavaScript import JavaScript\n\n\nclass SVCJSTest(JavaScript, Classifier, TestCase):\n\n def setUp(self):\n super(SVCJSTest, self).setUp()\n self.estimator = SVC(C=1., kernel='rbf',\n gamma=0.001, random_state=0)\n\n def tearDown(self):\n super(SVCJSTest, self).tearDown()\n\n def test_linear_kernel(self):\n self.estimator = SVC(C=1., kernel='linear',\n gamma=0.001, random_state=0)\n self.load_iris_data()\n self._port_estimator()\n amin = np.amin(self.X, axis=0)\n amax = np.amax(self.X, axis=0)\n preds, ground_truth = [], []\n for _ in range(self.TEST_N_RANDOM_FEATURE_SETS):\n x = np.random.uniform(amin, amax, self.n_features)\n preds.append(self.pred_in_custom(x))\n ground_truth.append(self.pred_in_py(x))\n self._clear_estimator()\n # noinspection PyUnresolvedReferences\n self.assertListEqual(preds, ground_truth)\n\n def test_sigmoid_kernel(self):\n self.estimator = SVC(C=1., kernel='sigmoid',\n gamma=0.001, random_state=0)\n self.load_iris_data()\n self._port_estimator()\n amin = np.amin(self.X, axis=0)\n amax = np.amax(self.X, axis=0)\n preds, ground_truth = [], []\n for _ in range(self.TEST_N_RANDOM_FEATURE_SETS):\n x = np.random.uniform(amin, amax, self.n_features)\n preds.append(self.pred_in_custom(x))\n ground_truth.append(self.pred_in_py(x))\n self._clear_estimator()\n # noinspection PyUnresolvedReferences\n self.assertListEqual(preds, ground_truth)\n\n def test_auto_gamma(self):\n self.estimator = SVC(C=1., gamma='auto', random_state=0)\n self.load_iris_data()\n self._port_estimator()\n amin = np.amin(self.X, axis=0)\n amax = np.amax(self.X, axis=0)\n preds, ground_truth = [], []\n for _ in range(self.TEST_N_RANDOM_FEATURE_SETS):\n x = np.random.uniform(amin, amax, self.n_features)\n preds.append(self.pred_in_custom(x))\n ground_truth.append(self.pred_in_py(x))\n self._clear_estimator()\n # noinspection PyUnresolvedReferences\n self.assertListEqual(preds, ground_truth)\n\n def test_pipeline_estimator(self):\n self.X, self.y = samples_generator.make_classification(\n n_informative=5, n_redundant=0, random_state=42)\n anova_filter = SelectKBest(f_regression, k=5)\n self.estimator = Pipeline([('anova', anova_filter), ('svc', SVC(kernel='linear'))])\n self.estimator.set_params(anova__k=10, svc__C=.1)\n try:\n self._port_estimator()\n except Exception as e:\n self.fail('Unexpected exception raised: {}'.format(e.message))\n finally:\n self._clear_estimator()\n","sub_path":"tests/estimator/classifier/SVC/SVCJSTest.py","file_name":"SVCJSTest.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"200063455","text":"from typing import Sequence, Tuple\n\ndef prereq(courses: Sequence[int], categories: Sequence[Tuple[int, Sequence[int]]]) -> bool:\n taken_in_category = [0] * len(categories)\n for course in courses:\n for ndx, category in enumerate(categories):\n if course in category[1]:\n taken_in_category[ndx] += 1\n for ndx, category in enumerate(categories):\n if taken_in_category[ndx] < category[0]:\n return False\n return True\n\ndef test_1():\n assert prereq([123, 9876, 2222], [(1, [8888, 2222]), (2, [9876, 2222, 7654])]) == True\n\n\ndef test_2():\n assert prereq([123, 9876, 2222], [(2, [8888, 2222]), (2, [9876, 2222, 7654])]) == False\n\n\nif __name__ == '__main__':\n while True:\n line = input()\n if line == '0':\n break\n num_courses, num_categories = map(int, line.split())\n courses = list(map(int, input().split()))\n categories = []\n for c in range(num_categories):\n info = list(map(int, input().split()))\n categories.append((info[1], info[2:]))\n print(['no','yes'][prereq(courses, categories)])\n\n# from 514.1 rank 683 (team 284.4 rank 132)","sub_path":"python/1_8/prerequisites.py","file_name":"prerequisites.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"399605346","text":"#November 6th, 2018 Sebastian \n# I have not given or received any unauthorized assistance on this assignment.” \nimport random\nimport math\nclass ellipse(object):\n 'Class that holds ellipse information'\n \n def __init__(self,Major,Minor):\n 'Set up the primary numbers to calc the ellipse, major and minor axis '\n self.Major = Major # major axis radius \n self.Minor = Minor #minor axis radius \n \n def setFocli(self,Major,Minor,C1):\n 'Figure out what the Folci points are in the ellipse'\n self.focli = round(math.sqrt(Major**2 - Minor**2),2) #formula to obtian focli points in ellipse \n self.F1 = self.focli + C1 # set equal to folci \n self.F2 = self.focli * -1 + C1 # give neg to get opposite side of axis \n \n return (self.F1, self.F2)\n\n def setMajor_Minor_Axis(self,Major,Minor,C1,C2):\n 'Set up the bounds of the ellipse '\n # self.fMajor = Major * 2 # double the major radius to get full major axis\n # self.fMinor = Minor * 2 # doulbe the minor radius to get full minor axis \n self.V1 = Major + C1# upper bound of Major axis \n self.V2 = Major * -1 - C1 # Lower bound of major axis\n self.V3 = Minor + C2 # Upper bound of minor axis \n self.V4 = Minor * -1 + C2 #Lower bound of minor axis \n self.vertList = [self.V1,self.V2,self.V3,self.V4]\n\n return (self.vertList)\n\n def setCenter(self,ellipseOne):\n 'Set Center point of the ellipse'\n self.C1 = int(random.randint(-10,10)) #set center one \n self.C2 = int(random.randint(-10,10)) #set center two \n return (self.C1,self.C2) #return values into ellipse class \n\n def Unit_setCenter(self,ellipseOne,X,Y):\n 'Set up for unit test, to manual set center '\n print(\" Set_Center FN : set up for unit test, to manual set center \") \n self.C1 = X\n self.C2 = Y\n print(\"Center is \" + str(self.C1) + \" \" + str(self.C2))\n return (self.C1,self.C2) #return values into ellipse class \n\n def get(self):\n return (self.focli)\n\n\ndef labMenu(): #set up menu selection greet user\n 'Menu Selection screen' #docstring\n print(\"Hello there! Plese follow the below instructions. \")\n print('Enter 1 for area and circumfrence of ellipse 1. ')\n print('Enter 2 for area and circumfrence of ellipse 2. ')\n print('Enter 3 for overlap of ellipses ')\n print('Enter 4 for unit testing ')\n print('Enter 5 to exit.')\n\ndef Major_Minor():\n 'Set up Major and Minor Axis'\n final = False\n while not final:\n axisA = int(random.randint(3,15)) #random number gen\n axisB = int(random.randint(3,15)) # random number gen \n if axisA == axisB: #make sure ellipse is an ellipse not a circle so points cant equal \n axisA = int(random.randint(3,15))\n axisB = int(random.randint(3,15))\n if axisA > axisB:\n Major = axisA #set axis A as the major axis \n Minor = axisB #set Axis B as the minor axis \n final = True\n\n return Major,Minor\n\n\n\n\n\n\ndef circumference(Major,Minor):\n ' Unit test Calculate the circumference of the ellipse'\n print(\"Unit testCalculate the circumference of the ellipse\")\n\n # formula for circumference of a circle using major and minor axis \n circumference = math.pi * ( 3*(Major+Minor) - math.sqrt( (3*Major + Minor) * (Major + 3*Minor) ) )\n print(\"Circumference is \" + str(circumference))\n return round(circumference,2)\n\ndef area(Major,Minor):\n 'Calculate the area of the ellipse'\n print(\"Calculate the are of the ellipse Unit test\")\n\n area = math.pi * Major * Minor\n print(\"Area is \" + str(area))\n return round(area,2)\n\ndef pointCheck(ellipseObject):\n 'Function used to check points on ellipse, if its in bounds '\n #print(ellipseObject)\n focal1 = [ellipseObject.F1,ellipseObject.C2] # set focal point one on axis \n focal2 = [ellipseObject.F2,ellipseObject.C2] #set focal point 2 on axis \n final = False\n while not final:\n x = random.randint(ellipseObject.V2,ellipseObject.V1) #set up random point \n y = random.randint(ellipseObject.V2,ellipseObject.V1) #set up random point \n point = [x,y] #set cord \n d1 = ((point[0] - (focal1[0]))**2) + ((point[1] - (focal1[1]))**2)\n d2 = ((point[0] - (focal2[0]))**2) + ((point[1] - (focal2[1]))**2)\n\n d1 = math.sqrt(d1)\n d2 = math.sqrt(d2)\n\n dist = d1 + d2 # get distance of points add together \n if d1 + d2 == ellipseObject.Major * 2: #make sure distance of point(x,y) is same equal to sum of major axis distance \n print(\"point is good \")\n final = True \n\n\ndef checkpoint(ellipseObject,point):\n 'Function used to check if point falls into ellipse'\n E1 = 0 # set to 0 \n focal1 = [ellipseObject.F1,ellipseObject.C2] # set focal point one on axis \n focal2 = [ellipseObject.F2,ellipseObject.C2] #set focal point 2 on axis \n\n #point = [x,y] #set cord \n d1 = ((point[0] - (focal1[0]))**2) + ((point[1] - (focal1[1]))**2)\n d2 = ((point[0] - (focal2[0]))**2) + ((point[1] - (focal2[1]))**2)\n\n d1 = math.sqrt(d1)\n d2 = math.sqrt(d2)\n\n dist = d1 + d2 # get distance of points add together \n if dist <= ellipseObject.Major * 2: #make sure distance of point(x,y) is same equal to sum of major axis distance \n E1 = 1 #give value of 1 if its a match \n return E1\n\n\n\ndef boxSetUp(ellipseOne,ellipseTwo):\n 'Set up bounds of box for ellipses'\n boxMaxX = max(ellipseOne.V1,ellipseTwo.V1) # get max x vert ellipse 1 or 2 \n boxMinX= min(ellipseOne.V2,ellipseTwo.V2) # get min x vert of ellipse 1 or 2\n\n boxMaxY = max(ellipseOne.V3,ellipseTwo.V3) # get max vert of y axis \n boxMinY = min(ellipseOne.V4,ellipseTwo.V4) # get min vert of y axis \n\n xBound = [boxMaxX + 0,boxMinX - 0]\n yBound = [boxMaxY + 0, boxMinY - 0] \n\n boxArea = (abs(xBound[0]) + abs(xBound[1])) * (abs(yBound[0] + abs(yBound[1]))) #get area of the box \n\n return xBound, yBound, boxArea\n\n\ndef OverlapFn(ellipseOne,ellipseTwo,xBound, yBound, boxArea):\n 'Calculate the overlap between the two ellipses'\n n = 0 # set to 0\n hit = 0 # set to 0 for amount of times point falls within \n full = False # set while condtion to false, once it hits 10000 then its true \n\n while not full:\n point = [int(random.randint(xBound[1],xBound[0])),int(random.randint(yBound[1],yBound[0]))] # make random points within bounds of box \n #print (point)\n E1 = checkpoint(ellipseOne,point) #check and see if point falls into ellipse 1 \n E2 = checkpoint(ellipseTwo,point) #check and see if point falls into ellipse 2\n\n if E1 == 1 and E2 == 1: #point must fall into both ellipse to be true \n hit += 1 # count how many times point falls between both ellipse \n\n n += 1 # add to counter \n if n == 100000:\n full = True # once all points have been hit, make while true \n OverLapArea = (hit/boxArea) / 2 #Calculate the overlap between the ellipses hits over the box area \n\n return round(OverLapArea,2)\n#(random.randint(xBound[1],xBound[0]))\n\ndone = False\nwhile not done:\n labMenu()\n choice = int(input('Please make an entry: '))\n\n if choice == 1:\n # set up ellipse 1 \n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseOne = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseOne.setCenter(ellipseOne) #get center point / location of ellipse \n focal = ellipseOne.setFocli(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1) #get main focal points\n ellipseOne.setMajor_Minor_Axis(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1,ellipseOne.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseOne.Major,ellipseOne.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseOne.Major,ellipseOne.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 1 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 1 is \" +str(areaCalc))\n\n elif choice == 2:\n #Ellipse 2 setup\n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseTwo = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseTwo.setCenter(ellipseTwo) #get center point / location of ellipse \n focal = ellipseTwo.setFocli(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1) #get main focal points\n ellipseTwo.setMajor_Minor_Axis(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1,ellipseTwo.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseTwo.Major,ellipseTwo.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseTwo.Major,ellipseTwo.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 2 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 2 is \" +str(areaCalc))\n\n elif choice == 3:\n #Get ellipse 1 \n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseOne = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseOne.setCenter(ellipseOne) #get center point / location of ellipse \n focal = ellipseOne.setFocli(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1) #get main focal points\n ellipseOne.setMajor_Minor_Axis(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1,ellipseOne.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseOne.Major,ellipseOne.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseOne.Major,ellipseOne.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 1 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 1 is \" +str(areaCalc))\n\n # Get ellipse 2 \n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseTwo = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseTwo.setCenter(ellipseTwo) #get center point / location of ellipse \n focal = ellipseTwo.setFocli(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1) #get main focal points\n ellipseTwo.setMajor_Minor_Axis(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1,ellipseTwo.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseTwo.Major,ellipseTwo.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseTwo.Major,ellipseTwo.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 2 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 2 is \" +str(areaCalc))\n\n # set up overlap function \n xBound, yBound, boxArea = boxSetUp(ellipseOne,ellipseTwo) #grab the bounds of the box around ellipse / area as well\n\n OverLapArea = OverlapFn(ellipseOne,ellipseTwo,xBound, yBound, boxArea) #overlap function to calc overlap \n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n \n elif choice == 4:\n print(\"Unit test of Ellipse\")\n \n #set up small ellipse 1\n ellipseOne = ellipse(3,1) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 3 and minor axis is 1\")\n ellipseOne.Unit_setCenter(ellipseOne,0,0) #set center to 0 Unit test \n focal = ellipseOne.setFocli(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1) #get main focal points\n ellipseOne.setMajor_Minor_Axis(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1,ellipseOne.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseOne.Major,ellipseOne.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseOne.Major,ellipseOne.Minor) \n print(\"The circumference of the ellipse 1 is \"+ str(circumferenceCalc)) # print our circum of test ellipse \n print(\"The area of the ellipse 1 is \" +str(areaCalc)) #print out area of test ellipse 1 \n\n #Set up large Ellipse 2\n ellipseTwo = ellipse(9,5) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 9 and minor axis is 5\")\n ellipseTwo.Unit_setCenter(ellipseTwo,0,0) #set center to 0 Unit test \n focal = ellipseTwo.setFocli(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1) #get main focal points\n ellipseTwo.setMajor_Minor_Axis(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1,ellipseTwo.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseTwo.Major,ellipseTwo.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseTwo.Major,ellipseTwo.Minor) \n print(\"The circumference of the ellipse 2 is \"+ str(circumferenceCalc)) # print our circum of test ellipse 2\n print(\"The area of the ellipse 2 is \" +str(areaCalc)) #print out area of test ellipse 2\n\n\n #Set up ellipse 3 off centered \n ellipseThree = ellipse(3,1) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 3 and minor axis is 1\")\n ellipseThree.Unit_setCenter(ellipseThree,5,5) #set center to 5,5Unit test no overlap should occur\n focal = ellipseThree.setFocli(ellipseThree.Major,ellipseThree.Minor,ellipseThree.C1) #get main focal points\n ellipseThree.setMajor_Minor_Axis(ellipseThree.Major,ellipseThree.Minor,ellipseThree.C1,ellipseThree.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseThree.Major,ellipseThree.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseThree.Major,ellipseThree.Minor) \n\n print(\"The circumference of the ellipse 3 is \"+ str(circumferenceCalc)) # print our circum of test ellipse 3\n print(\"The area of the ellipse 3 is \" +str(areaCalc)) #print out area of test ellipse 3 \n\n #Set up large ellpise 4 to overlap with ellipse 2 \n ellipseFour = ellipse(11,9) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 11 and minor axis is 9\")\n ellipseFour.Unit_setCenter(ellipseFour,0,0) #set center to 0,0 Unit test \n focal = ellipseFour.setFocli(ellipseFour.Major,ellipseFour.Minor,ellipseFour.C1) #get main focal points\n ellipseFour.setMajor_Minor_Axis(ellipseFour.Major,ellipseFour.Minor,ellipseFour.C1,ellipseFour.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseFour.Major,ellipseFour.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseFour.Major,ellipseFour.Minor) \n\n print(\"The circumference of the ellipse 4 is \"+ str(circumferenceCalc)) # print our circum of test ellipse 4\n print(\"The area of the ellipse 4 is \" +str(areaCalc)) #print out area of test ellipse 4 \n \n print(\"Test Ellipse 1 and 2 overlap area Ellipse one should be within ellipse 2 \")\n #Set up Ellipse 1 and 2, see if the area of overlap = ellipse 1 \n xBound, yBound, boxArea = boxSetUp(ellipseOne,ellipseTwo) #grab the bounds of the box around ellipse / area as well\n\n OverLapArea = OverlapFn(ellipseOne,ellipseTwo,xBound, yBound, boxArea) #overlap function to calc overlap \n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n print(\"Test Ellipse 2 and 1 overlap area, see if points are similar \")\n OverLapArea = OverlapFn(ellipseTwo,ellipseOne,xBound, yBound, boxArea)\n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n print(\"test Ellipse 1 and 3, make sure that overlap area is 0, due to center being off \")\n xBound, yBound, boxArea = boxSetUp(ellipseOne,ellipseThree)\n OverLapArea = OverlapFn(ellipseOne,ellipseThree,xBound, yBound, boxArea)\n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n print(\"test Ellipse 2 and 4, check large overlap area \")\n xBound, yBound, boxArea = boxSetUp(ellipseTwo,ellipseFour)\n OverLapArea = OverlapFn(ellipseTwo,ellipseFour,xBound, yBound, boxArea)\n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n else:\n done = True \n\n","sub_path":"Assignment 4/A4_P4_SZ.py","file_name":"A4_P4_SZ.py","file_ext":"py","file_size_in_byte":16296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"167485654","text":"import uasyncio as asyncio\n\nasync def schedule(cbk, t, *args, **kwargs):\n await asyncio.sleep(t)\n cbk(*args, **kwargs)\n\ndef callback(x, y):\n print('x={} y={}'.format(x, y))\n\nasync def bar():\n asyncio.create_task(schedule(callback, 3, 42, 100))\n for count in range(6):\n print(count)\n await asyncio.sleep(1) # Pause 1s\n\nasyncio.run(bar())","sub_path":"Experimental_exercise/uasyncio_test/2.2.2 Running a callback function.py","file_name":"2.2.2 Running a callback function.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"386610329","text":"#!/usr/bin/env python3\n\n# Functions can be made available through a module by adding\n# the following code to another file.\n#\n# from wordcount import numchars, numlines, numwords\n\ndef numchars(filename='', fileobj=None):\n if not filename and not fileobj:\n raise Exception('No parameters')\n\n f = fileobj\n iopened = False\n nchars = 0\n if not f:\n if filename != '':\n f = open(filename, 'r')\n iopened = True\n else:\n raise FileNotFoundError('No filename given')\n \n f.seek(0)\n nchars = len(f.read())\n\n if iopened:\n f.close()\n\n return nchars\n\ndef numlines(filename='', fileobj=None):\n f = fileobj\n iopened = False\n nlines = 0\n if not f:\n if filename != '':\n f = open(filename, 'r')\n iopened = True\n else:\n raise FileNotFoundError('No filename given')\n \n f.seek(0)\n nlines = len(f.readlines())\n\n if iopened:\n f.close()\n\n return nlines\n\ndef numwords(filename='', fileobj=None):\n f = fileobj\n iopened = False\n nwords = 0\n if not f:\n if filename != '':\n f = open(filename, 'r')\n iopened = True\n else:\n raise FileNotFoundError('No filename given')\n \n f.seek(0)\n nwords = len(f.read().split())\n\n if iopened:\n f.close()\n\n return nwords\n\nif __name__ == '__main__':\n '''\n print(numwords(filename='test1.txt'))\n\n againf = open('test1.txt', 'r')\n print(numwords(fileobj=againf))\n againf.close()\n\n # FileNotFoundError\n print(numwords())\n\n print(numlines(filename='test1.txt'))\n\n againf = open('test1.txt', 'r')\n print(numlines(fileobj=againf))\n againf.close()\n\n # FileNotFoundError\n print(numlines())\n '''\n\n from sys import argv\n from pathlib import Path\n progname = Path(argv[0]).name\n\n if len(argv) < 2:\n print('Usage: %s ' % progname)\n exit(2)\n\n filenames = argv[1:]\n for filename in filenames:\n print('%5d %5d %5d %s' % (\n numchars(filename=filename),\n numwords(filename=filename),\n numlines(filename=filename),\n filename))\n\n","sub_path":"wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"422756900","text":"def get_elo_team(team,team_elo):\n import distance\n output_elo = 0\n \n # Fixed assign\n team_names_panda_fixed = [\"AZ\",\"Astana\",\"Asteras\",\"Rubin\",\"Sion\",\"Celtic\",\"Shakhtar Donetsk\",\"Mönchengladbach\",\"Paris\",\"Krasnodar\",\"Club Brugge\",\"Lokomotiv Moskva\",\"Qarabağ\",\"St-Étienne\",\"Sporting CP\",\"Qäbälä\",\"Plzeň\",\"Liberec\",\"Gent\",\"Athletic\"]\n team_names_elo_fixed = [\"Alkmaar\",\"FK Astana\",\"Asteras Tripolis\",\"Rubin Kazan\",\"Sion\",\"Celtic\",\"Shakhtar\",\"Gladbach\",\"Paris SG\",\"FC Krasnodar\",\"Brugge\",\"Lok Moskva\",\"Karabakh Agdam\",\"Saint-Etienne\",\"Sporting\",\"Gabala\",\"Viktoria Plzen\",\"Slovan Liberec\",\"Gent\",\"Bilbao\"]\n for k in range(len(team_names_panda_fixed)):\n if team == team_names_panda_fixed[k]:\n for j in range(len(team_elo)):\n if team_elo[j][0] == team_names_elo_fixed[k]:\n output_elo = team_elo[j][1]\n \n # Rest\n if output_elo == 0:\n for j in range(len(team_elo)):\n if distance.levenshtein(team,team_elo[j][0]) == 0:\n output_elo = team_elo[j][1]\n break\n elif distance.levenshtein(team,team_elo[j][0]) == 1:\n output_elo = team_elo[j][1]\n break\n elif distance.levenshtein(team,team_elo[j][0]) == 2:\n output_elo = team_elo[j][1]\n break\n\n return float(output_elo)","sub_path":"app_voetbalelo/uefa_leagues/get_elo_team.py","file_name":"get_elo_team.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"588156648","text":"from background_task import background\nfrom django.utils import timezone\nfrom passport_app.models import *\n\nimport psycopg2\nfrom psycopg2 import sql\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # <-- ADD THIS LINE\n\n# @background(schedule=1)\ndef init_classifier():\n print(\"start init classifier\")\n #classificator\n params = [\n {\n 'name':'social',\n 'point':'1.1',\n 'name_ru': \"Социальная инфраструктура\",\n 'descr': ''\n },\n\n {\n 'name': 'transport',\n 'point': '1.2',\n 'name_ru': \"Транспортная доступность\",\n 'descr': ''\n },\n {\n 'name': 'place_info',\n 'point': '1.3',\n 'name_ru': \"Характеристики местоположения\",\n 'descr': ''\n },\n {\n 'name': 'rights',\n 'point': '1.4',\n 'name_ru': \"Права и обременения\",\n 'descr': ''\n },\n {\n 'name': 'architecture',\n 'point': '1.5',\n 'name_ru': \"Архитектура и конструкции\",\n 'descr': ''\n },\n {\n 'name': 'engsys',\n 'point': '1.6',\n 'name_ru': \"Инженерные системы\",\n 'descr': ''\n },\n {\n 'name': 'base',\n 'point': '1.0',\n 'name_ru': \"Основные\",\n 'descr': ''\n },\n ]\n\n for item in params:\n classificator = Classifier(**item)\n classificator.save()\n print(\"finish init classifier\")\n\n# @background(schedule=timezone.now())\ndef init_type_of_value():\n #class TypeOfValue(models.Model):\n #name = models.CharField(max_length=255)\n print(\"start init type of value\")\n params = [\n {\n 'name': 'integer',\n 'name_ru': 'целое число'\n },\n\n {\n 'name': 'float',\n 'name_ru': 'дробное число'\n },\n {\n 'name': 'text',\n 'name_ru': 'текст'\n },\n {\n 'name': 'date',\n 'name_ru': 'дата'\n },\n {\n 'name': 'datetime',\n 'name_ru': 'дата и время'\n },\n ]\n\n for item in params:\n type_of_val = TypeOfValue(**item)\n type_of_val.save()\n print(\"finish init type of value\")\n\n\n# @background(schedule=timezone.now())\ndef init_units():\n print(\"start init unit\")\n #name = models.CharField(max_length=255)\n\n params = [\n\n ]\n\n for item in params:\n unit = Unit(**item)\n unit.save()\n print(\"finish init unit\")\n\n\n# @background(schedule=timezone.now())\ndef init_addreses():\n print(\"start init country\")\n # address\n country = Country(**{'name': 'Россия'})\n country.save()\n print(\"finish init classifier\")\n\n# @background(schedule=timezone.now())\ndef init_social_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'college',\n 'title':'college',\n 'title_rus': \"Высшее учебное заведение\",\n },\n\n {\n 'name': 'school',\n 'title': 'school',\n 'title_rus': \"Общеобразовательная Школа учебное заведение\",\n },\n {\n 'name': 'kindergarten',\n 'title': 'kindergarten',\n 'title_rus': \"Детский сад\",\n },\n {\n 'name': 'atheneum',\n 'title': 'library',\n 'title_rus': \"Читальный зал Билиблиотека Книги\",\n },\n\n {\n 'name': 'shop',\n 'title': 'shop',\n 'title_rus': \"Магазин\",\n },\n {\n 'name': 'domestic_service',\n 'title': 'domestic service',\n 'title_rus': \"Бытовые услуги\",\n },\n {\n 'name': 'rest_space',\n 'title': 'rest space',\n 'title_rus': \"Городской парк\",\n },\n {\n 'name': 'sport_complex',\n 'title': 'sport_complex',\n 'title_rus': \"Спортинвый комплекс\",\n },\n {\n 'name': 'sport_ground',\n 'title': 'sport ground',\n 'title_rus': \"Спортивная площадка\",\n },\n {\n 'name': 'playground',\n 'title': 'playground',\n 'title_rus': \"Детская площадка\",\n },\n {\n 'name': 'polyclinic',\n 'title': 'polyclinic',\n 'title_rus': \"Поликлиника больница\",\n },\n {\n 'name': 'mall',\n 'title': 'mall',\n 'title_rus': \"Торговый центр\",\n },\n\n {\n 'name': 'pharmacy',\n 'title': 'pharmacy',\n 'title_rus': \"Аптека\",\n },\n {\n 'name': 'cafe',\n 'title': 'cafe',\n 'title_rus': \"Пункт Общественного питания\",\n },\n {\n 'name': 'bank',\n 'title': 'bank',\n 'title_rus': \"Банк\"\n },\n {\n 'name': 'water_place',\n 'title': 'water object',\n 'title_rus': \"Водный объект\",\n },\n {\n 'name': 'theatre',\n 'title': 'theatre',\n 'title_rus': \"Театр\",\n },\n {\n 'name': 'religion_object',\n 'title': 'religion_object',\n 'title_rus': \"Религиозный объект\",\n },\n {\n 'name': 'ambulance',\n 'title': 'ambulance',\n 'title_rus': \"Подстанция скорой помощи\",\n },\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='social')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n# @background(schedule=timezone.now())\ndef init_transport_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'metro_stations',\n 'title':'metro stations',\n 'title_rus': \"Станция метро\",\n },\n {\n 'name': 'light_subway_stations',\n 'title': 'light subway stations',\n 'title_rus': \"станция МЦК\",\n },\n {\n 'name': 'stations_of_electric_trains',\n 'title': 'stations_of_electric_trains',\n 'title_rus': \"Станция электропоездов\",\n },\n {\n 'name': 'public_transport_stops',\n 'title': 'public_transport_stops',\n 'title_rus': \"Остановка общественного транспорта автобусы\",\n },\n {\n 'name': 'distance_from_the_center',\n 'title': 'distance_from_the_center',\n 'title_rus': \"Администрация города\",\n },\n {\n 'name': 'parking_spaces_for_paid_and_intercepting_parking_lots',\n 'title': 'parking_spaces_for_paid_and_intercepting_parking_lots',\n 'title_rus': \"Машиноместа платных и перехватывающих парковок\",\n },\n {\n 'name': 'transport_highways',\n 'title': 'transport_highways',\n 'title_rus': \"Транспортные магистрали\",\n },\n\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='transport')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n# @background(schedule=timezone.now())\ndef init_place_info_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'location',\n 'title':'location',\n 'title_rus': \"Местоположение\",\n },\n {\n 'name': 'area',\n 'title': 'area',\n 'title_rus': \"Район\",\n },\n {\n 'name': 'geology',\n 'title': 'geology',\n 'title_rus': \"Геология\",\n },\n {\n 'name': 'snap_to_the_town_plan',\n 'title': 'snap_to_the_town_plan',\n 'title_rus': \"Привязка к градостроительному плану\",\n },\n {\n 'name': 'cadastral_engineer',\n 'title': 'cadastral_engineer',\n 'title_rus': \"Кадастровый инженер\",\n },\n {\n 'name': 'cadastral_number_of_the_block',\n 'title': 'cadastral_number_of_the_block',\n 'title_rus': \"Кадастровый номер квартала\",\n },\n {\n 'name': 'data_of_the_cadastral_passport_of_the_land_plot',\n 'title': 'data_of_the_cadastral_passport_of_the_land_plot',\n 'title_rus': \"Данные кадастрового паспорта земельного участка\",\n },\n {\n 'name': 'land_category',\n 'title': 'land_category',\n 'title_rus': \"Категория земель\",\n },\n {\n 'name': 'kind_of_permitted_use',\n 'title': 'kind_of_permitted_use',\n 'title_rus': \"Вид разрешённого использования\",\n },\n {\n 'name': 'the_accuracy_of_the_boundaries_of_the_land',\n 'title': 'the_accuracy_of_the_boundaries_of_the_land',\n 'title_rus': \"Точность границ земельного участка\",\n },\n {\n 'name': 'the_area_of_​​the_land_plot',\n 'title': 'the_area_of_​​the_land_plot',\n 'title_rus': \"Площадь земельного участка, входящего в состав общего имущества в многоквартирном доме\",\n },\n {\n 'name': 'area_of_​​parking_within_the_boundaries_of_the_land_plot',\n 'title': 'area_of_​​parking_within_the_boundaries_of_the_land_plot',\n 'title_rus': \"Площадь парковки в границах земельного участка\",\n },\n {\n 'name': 'date_of_change_of_information_in_gkn',\n 'title': 'date_of_change_of_information_in_gkn',\n 'title_rus': \"Дата изменения сведений в ГКН\",\n },\n {\n 'name': 'date_of_unloading_of_information_in_gkn',\n 'title': 'date_of_unloading_of_information_in_gkn',\n 'title_rus': \"Дата выгрузки сведений из ГКН\",\n },\n {\n 'name': 'place_info_playground',\n 'title': 'place_info_playground',\n 'title_rus': \"Детская площадка\",\n },\n {\n 'name': 'place_info_sportground',\n 'title': 'place_info_sportground',\n 'title_rus': \"Спортивная площадка\",\n },\n {\n 'name': 'other_elements_of_improvement',\n 'title': 'other_elements_of_improvement',\n 'title_rus': \"Иные элементы благоустройства\",\n },\n {\n 'name': 'place_info_improvement',\n 'title': 'place_info_improvement',\n 'title_rus': \"Благоустройство\",\n },\n ]\n\n\n\n classificator = Classifier.objects.get(name='place_info')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n\n# @background(schedule=timezone.now())\ndef init_rights_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'special_conditions_for_the_use_of_land',\n 'title':'special_conditions_for_the_use_of_land',\n 'title_rus': \"Особые условия использования земельных участков\",\n },\n {\n 'name': 'special_conditions_for_environmental_protection',\n 'title': 'special_conditions_for_environmental_protection',\n 'title_rus': \"Особые условия охраны окружающей среды\",\n },\n {\n 'name': 'information_on_the_inclusion_of_a_property_in_the_register_of_cultural_heritage_sites',\n 'title': 'information_on_the_inclusion_of_a_property_in_the_register_of_cultural_heritage_sites',\n 'title_rus': \"Сведения о включении объекта недвижимости в реестр объектов культурного наследия\",\n },\n {\n 'name': 'other_special_conditions_of_use',\n 'title': 'other_special_conditions_of_use',\n 'title_rus': \"Иные особые условия использования\",\n },\n {\n 'name': 'name_of_the_managing_organization',\n 'title': 'name_of_the_managing_organization',\n 'title_rus': \"Наименование управляющей организации\",\n },\n {\n 'name': 'location_address',\n 'title': 'location_address',\n 'title_rus': \"Адрес местоположения\",\n },\n {\n 'name': 'rights_head_of_organization',\n 'title': 'rights_head_of_organization',\n 'title_rus': \"Глава организации\",\n },\n {\n 'name': 'contact_number',\n 'title': 'contact_phone',\n 'title_rus': \"Контактный телефон\",\n },\n {\n 'name': 'email',\n 'title': 'email',\n 'title_rus': \"Почта\",\n },\n {\n 'name': 'official_website_of_the_company',\n 'title': 'site',\n 'title_rus': \"Официальный сайт компании\",\n },\n {\n 'name': 'management_start_date',\n 'title': 'management_start_date',\n 'title_rus': \"Дата начала управления\",\n },\n {\n 'name': 'management_document',\n 'title': 'management_document',\n 'title_rus': \"Основание управления\",\n },\n {\n 'name': 'date_and_number_document',\n 'title': 'date_and_number_document',\n 'title_rus': \"Дата и номер документа\",\n },\n {\n 'name': 'date_of_contract',\n 'title': 'date_of_contract',\n 'title_rus': \"Дата заключения договора\",\n },\n {\n 'name': 'rate',\n 'title': 'rate',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'information_disclosure',\n 'title': 'information_disclosure',\n 'title_rus': \"Раскрытие информации\",\n },\n {\n 'name': 'overhaul_schedule',\n 'title': 'overhaul_schedule',\n 'title_rus': \"График капитального ремонта\",\n },\n {\n 'name': 'method_of_formation_of_the_capital_repair_fund',\n 'title': 'method_of_formation_of_the_capital_repair_fund',\n 'title_rus': \"Способ формирования фонда капитального ремонта\",\n },\n {\n 'name': 'inn_account_owner',\n 'title': 'inn_account_owner',\n 'title_rus': \"ИНН владельца специального счета\",\n },\n {\n 'name': 'amount_of_the_contribution_for_capital_repairs',\n 'title': 'amount_of_the_contribution_for_capital_repairs',\n 'title_rus': \"Размер взноса на капитальный ремонт\",\n },\n {\n 'name': 'date_number_protocol',\n 'title': 'date_number_protocol',\n 'title_rus': \"Дата и номер протокола собраний владельцев\",\n },\n {\n 'name': 'extra_info',\n 'title': 'extra_info',\n 'title_rus': \"Дополнительная информация\",\n },\n {\n 'name': 'collected_means_of_owners_of_all',\n 'title': 'collected_means_of_owners_of_all',\n 'title_rus': \"Собрано средств собственников всего\",\n },\n {\n 'name': 'current_debt_of_owners_on_contributions',\n 'title': 'current_debt_of_owners_on_contributions',\n 'title_rus': \"Текущая задолженность собственников по взносам\",\n },\n {\n 'name': 'spent_on_work',\n 'title': 'spent_on_work',\n 'title_rus': \"Израсходовано на работы\",\n },\n {\n 'name': 'including_spent_subsidies',\n 'title': 'including_spent_subsidies',\n 'title_rus': \"В т.ч. израсходовано субсидий\",\n },\n {\n 'name': 'balance_of_funds_for_overhauling',\n 'title': 'balance_of_funds_for_overhauling',\n 'title_rus': \"Остаток средств на проведение капремонта\",\n },\n {\n 'name': 'planned_works',\n 'title': 'planned_works',\n 'title_rus': \"Запланировано работ\",\n },\n {\n 'name': 'completed_work',\n 'title': 'completed_work',\n 'title_rus': \"Выполнено работ\",\n },\n {\n 'name': 'year_of_nearest_work',\n 'title': 'year_of_nearest_work',\n 'title_rus': \"Год ближайшей работы\",\n },\n {\n 'name': 'management_report',\n 'title': 'management_report',\n 'title_rus': \"Отчёт по управлению\",\n },\n {\n 'name': 'management_reports_archive',\n 'title': 'management_reports_archive',\n 'title_rus': \"Архив отчетов по управлению\",\n },\n {\n 'name': 'debts_of_owners_before_the_criminal_code',\n 'title': 'debts_of_owners_before_the_criminal_code',\n 'title_rus': \"Задолженность собственников перед УК\",\n },\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='rights')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n# @background(schedule=timezone.now())\ndef init_architecture_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'cadastral_number_of_the_building',\n 'title':'cadastral_number_of_the_building',\n 'title_rus': \"Кадастровый номер здания\",\n },\n {\n 'name': 'cadastral_value_of_the_building',\n 'title': 'cadastral_value_of_the_building',\n 'title_rus': \"Кадастровая стоимость здания\",\n },\n {\n 'name': 'date_of_cadastral_registration',\n 'title': 'date_of_cadastral_registration',\n 'title_rus': \"Дата постановки на кадастровый учёт\",\n },\n {\n 'name': 'architecture_date_of_change_of_information_in_gkn',\n 'title': 'date_of_unloading_of_information_in_gkn',\n 'title_rus': \"Дата изменения сведений в ГКН\",\n },\n {\n 'name': 'architecture_date_of_unloading_of_information_in_gkn',\n 'title': 'date_of_unloading_of_information_in_gkn',\n 'title_rus': \"Дата выгрузки сведений из ГКН\",\n },\n {\n 'name': 'year_of_construction',\n 'title': 'year_of_construction',\n 'title_rus': \"Год постройки\",\n },\n {\n 'name': 'year_of_commissioning',\n 'title': 'metro stations',\n 'title_rus': \"Год ввода в эксплуатацию\",\n },\n {\n 'name': 'total_area',\n 'title': '',\n 'title_rus': \"Общая площадь\",\n },\n {\n 'name': 'total_area_of_​​living_quarters',\n 'title': '',\n 'title_rus': \"Общая площадь жилых помещений\",\n },\n {\n 'name': 'total_area_of_​​non_residential_premises',\n 'title': '',\n 'title_rus': \"Общая площадь нежилых помещений\",\n },\n {\n 'name': 'total_area_of_​​premises_included_in_the_total_property',\n 'title': '',\n 'title_rus': \"Общая площадь помещений, входящих в состав общего имущества\",\n },\n {\n 'name': 'number_of_storeys',\n 'title': '',\n 'title_rus': \"Этажность\",\n },\n {\n 'name': 'number_of_residential_premises',\n 'title': '',\n 'title_rus': \"Количество жилых помещений\",\n },\n {\n 'name': 'number_of_unresidential_premises',\n 'title': '',\n 'title_rus': \"Количество нежилых помещений\",\n },\n {\n 'name': 'underground_floors',\n 'title': '',\n 'title_rus': \"Подземных этажей\",\n },\n {\n 'name': 'functional_purpose_of_the_capital_construction_object',\n 'title': '',\n 'title_rus': \"Функциональное назначение объекта капитального строительства\",\n },\n {\n 'name': 'series_building_type',\n 'title': '',\n 'title_rus': \"Серия, тип постройки здания\",\n },\n {\n 'name': 'type_of_house',\n 'title': '',\n 'title_rus': \"Тип дома\",\n },\n {\n 'name': 'the_house_is_recognized_as_an_emergency',\n 'title': '',\n 'title_rus': \"Дом признан аварийным\",\n },\n {\n 'name': 'type_of_foundation',\n 'title': '',\n 'title_rus': \"Тип фундамента\",\n },\n {\n 'name': 'floor_type',\n 'title': '',\n 'title_rus': \"Тип перекрытий\",\n },\n {\n 'name': 'material_of_bearing_walls',\n 'title': '',\n 'title_rus': \"Материал несущих стен\",\n },\n {\n 'name': 'basement',\n 'title': '',\n 'title_rus': \"Подвал\",\n },\n {\n 'name': 'basement_area',\n 'title': '',\n 'title_rus': \"Площадь подвала\",\n },\n {\n 'name': 'number_of_entrances',\n 'title': '',\n 'title_rus': \"Количество подъездов\",\n },\n {\n 'name': 'facade_type',\n 'title': '',\n 'title_rus': \"Тип фасада\",\n },\n {\n 'name': 'roof_type',\n 'title': '',\n 'title_rus': \"Тип крыши\",\n },\n {\n 'name': 'roofing_type',\n 'title': '',\n 'title_rus': \"Тип кровли\",\n },\n {\n 'name': 'garbage_chute',\n 'title': '',\n 'title_rus': \"Мусоропровод\",\n },\n {\n 'name': 'type_of_garbage_chute',\n 'title': '',\n 'title_rus': \"Тип мусоропровода\",\n },\n {\n 'name': 'number_of_garbage_chutes',\n 'title': '',\n 'title_rus': \"Количество мусоропроводов\",\n },\n {\n 'name': 'object_wear',\n 'title': '',\n 'title_rus': \"Износ объекта\",\n },\n {\n 'name': 'conformity_of_the_building_with_ecological_gost_r_54964-2012',\n 'title': '',\n 'title_rus': \"Соответствие здания экологическому ГОСТ Р 54964-2012\",\n },\n {\n 'name': 'inclusiveness',\n 'title': '',\n 'title_rus': \"Инклюзивность\",\n },\n\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='architecture')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n# @background(schedule=timezone.now())\ndef init_engsys_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'external_networks',\n 'title':'',\n 'title_rus': \"Внешние сети\",\n },\n {\n 'name': 'project_documentation',\n 'title': '',\n 'title_rus': \"Проектная документация\",\n },\n {\n 'name': 'technical_documentation',\n 'title': '',\n 'title_rus': \"Техническая документация\",\n },\n {\n 'name': 'energy_efficiency_class',\n 'title': '',\n 'title_rus': \"Класс энергетической эффективности\",\n },\n {\n 'name': 'power_supply_system',\n 'title': '',\n 'title_rus': \"Система электроснабжения\",\n },\n {\n 'name': 'type_of_power_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы электроснабжения\",\n },\n {\n 'name': 'number_of_entries_in_the_house',\n 'title': '',\n 'title_rus': \"Количество вводов в дом\",\n },\n {\n 'name': 'the_fact_of_providing_the_supply_system_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'supply_system_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_supply_system_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_supply_system_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_supply_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_supply_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_supply_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'heat_supply_system',\n 'title': '',\n 'title_rus': \"Система теплоснабжения\",\n },\n {\n 'name': 'type_of_heat_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы теплоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_heat_supply_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'unit_of_heat_supply_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_heat_supply_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_heat_supply_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_heat_supply_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_heat_supply_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'hot_water_system',\n 'title': '',\n 'title_rus': \"Система горячего водоснабжения\",\n },\n {\n 'name': 'type_of_hot_water_system',\n 'title': '',\n 'title_rus': \"Тип системы горячего водоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_hot_water_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'hot_water_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_hot_water_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_hot_water_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_hot_water_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_hot_water_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_hot_water_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'cold_water_system',\n 'title': '',\n 'title_rus': \"Система холодного водоснабженияs\",\n },\n {\n 'name': 'type_of_cold_water_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы холодного водоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_cold_water_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'unit_of_cold_water_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_cold_water_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_cold_water_metermeter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'type_of_cold_water_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'water_disposal_system',\n 'title': '',\n 'title_rus': \"Система водоотведения\",\n },\n {\n 'name': 'type_of_sewerage_system',\n 'title': '',\n 'title_rus': \"Тип системы водоотведения\",\n },\n {\n 'name': 'the_fact_of_providing_the_disposal_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'disposal_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_disposal_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_disposal_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_disposal_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_disposal_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_disposal_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'volume_of_cesspools',\n 'title': '',\n 'title_rus': \"Объем выгребных ям\",\n },\n {\n 'name': 'gutter_system',\n 'title': '',\n 'title_rus': \"Система водостоков\",\n },\n {\n 'name': 'gutter_system_type',\n 'title': '',\n 'title_rus': \"Тип системы водостоков\",\n },\n {\n 'name': 'gas_supply_system',\n 'title': '',\n 'title_rus': \"Система газоснабжения\",\n },\n {\n 'name': 'type_of_gas_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы газоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_gas_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'gas_supply_system_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_gas_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_gas_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_gas_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_gas_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_gas_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'ventilation_system',\n 'title': '',\n 'title_rus': \"Система вентиляции\",\n },\n {\n 'name': 'type_of_ventilation_system',\n 'title': '',\n 'title_rus': \"Тип системы вентиляции\",\n },\n {\n 'name': 'air_conditioning_system',\n 'title': '',\n 'title_rus': \"Система кондиционирования\",\n },\n {\n 'name': 'weak_system',\n 'title': '',\n 'title_rus': \"Слаботочная система\",\n },\n {\n 'name': 'lifting_equipment',\n 'title': '',\n 'title_rus': \"Подъёмное оборудование\",\n },\n {\n 'name': 'type_of_lift',\n 'title': '',\n 'title_rus': \"Тип лифта\",\n },\n {\n 'name': 'number_of_elevators',\n 'title': '',\n 'title_rus': \"Количество лифтов\",\n },\n {\n 'name': 'year_of_commissioning_of_the_lift_system',\n 'title': '',\n 'title_rus': \"Год ввода в эксплуатацию лифтовой системы\",\n },\n {\n 'name': 'integrated_security_system',\n 'title': '',\n 'title_rus': \"Система комплексной безопасности\",\n },\n {\n 'name': 'video_surveillance',\n 'title': '',\n 'title_rus': \"Видеонаблюдение\",\n },\n {\n 'name': 'fencing',\n 'title': '',\n 'title_rus': \"Ограждение\",\n },\n {\n 'name': 'barrier',\n 'title': '',\n 'title_rus': \"Шлагбаум\",\n },\n {\n 'name': 'integrated_fire_protection_system',\n 'title': '',\n 'title_rus': \"Система комплексной противопожарной защиты\",\n },\n {\n 'name': 'fire_extinguishing_system',\n 'title': '',\n 'title_rus': \"система пожаротушения\",\n },\n {\n 'name': 'type_fire_extinguishing_system',\n 'title': '',\n 'title_rus': \"Тип системы пожаротушения\",\n },\n {\n 'name': 'distance_to_fire_station',\n 'title': '',\n 'title_rus': \"Расстояние до пожарной части\",\n },\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='engsys')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n# @background(schedule=timezone.now())\ndef create_config():\n print (\"create config\")\n try:\n count = SearchConfig.objects.count()\n if count == 0:\n search_config = SearchConfig()\n search_config.save()\n except Exception as e:\n print(str(e))\n pass\n\ndef move_data_to_category():\n #разделы\n\n razdel = Category()\n razdel.name = \"razdel\"\n razdel.point = \"1.0\"\n razdel.comment = \"\"\n razdel.name_ru = \"Раздел\"\n razdel.save()\n\n root_category = Category()\n root_category.name = \"category\"\n root_category.point = \"1.0\"\n root_category.comment = \"\"\n root_category.name_ru = \"Категория\"\n root_category.save()\n\n classifiers = Classifier.objects.all()\n\n for classifier in classifiers:\n try:\n category = Category()\n category.name = classifier.name\n category.point = classifier.point\n category.comment = classifier.descr\n category.name_ru = classifier.name_ru\n category.save()\n category.parent_categories.add(razdel)\n category.save()\n \n razdel.categories.add(category)\n razdel.save()\n except Exception as e:\n print(str(e))\n pass\n\n fields = Field.objects.all()\n\n for item in fields:\n try:\n category = Category()\n category.name = item.name \n category.name_ru = item.title_rus \n category.save()\n if item.classifier:\n classifier_item = Category.objects.filter(name__exact = item.classifier.name)\n if classifier_item: \n print ( \"classifier_item %i\" % classifier_item.count()) \n print ( classifier_item ) \n category.parent_categories.add(classifier_item[0])\n classifier_item[0].categories.add(category)\n classifier_item[0].save()\n else:\n print (\"not found classifier %s\" % item.classifier.name )\n category.save()\n \n # parserparameter = ParserParameter()\n # parserparameter.name = item.name \n \n # # parameter.name_ru = item.title_rus \n # # parameter.unit = item.unit \n\n # parserparameter.save()\n # # category.parameters.add(parameter)\n # category.save()\n\n # field_data = DataField.objects.filter(field = item)\n # for field_data_item in field_data:\n # print (\"try save data parametter\")\n # data_parameter = ParserParameterData()\n # data_parameter.value = field_data_item.value \n # data_parameter.real_estate = field_data_item.real_estate\n # data_parameter.parser_parameter = parserparameter \n # data_parameter.save()\n # print (\"save data parametter\")\n\n except Exception as e:\n print(str(e))\n pass\n\n typeofrealestates = TypeOfRealEstate.objects.all()\n\n for item in typeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus \n category.save()\n category.parent_categories.add(root_category)\n category.save()\n root_category.categories.add(category)\n root_category.save()\n except Exception as e:\n print(str(e))\n pass\n\n subtypeofrealestates = SubtypeOfRealEstate.objects.all()\n\n for item in subtypeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus\n category.save()\n if item.type:\n type_categories = Category.objects.filter(name__exact = item.type.name)\n if type_categories:\n print ( \"type_categories %i \" % type_categories.count())\n print ( type_categories )\n category.parent_categories.add(type_categories[0])\n type_categories[0].categories.add(category)\n type_categories[0].save()\n else:\n print (\"not found type %s\" % item.type.name )\n\n category.save()\n except Exception as e:\n print(str(e))\n pass\n\n subsubtypeofrealestates = SubsubtypeOfRealEstate.objects.all()\n\n for item in subsubtypeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus\n category.save()\n if item.subtype: \n subtype_categories = Category.objects.filter(name = item.subtype.name)\n if subtype_categories:\n print ( \"subtype_categories %i \" % subtype_categories.count())\n print ( subtype_categories )\n category.parent_categories.add(subtype_categories[0])\n subtype_categories[0].categories.add(category) \n subtype_categories[0].save() \n else:\n print (\"not found subtype %s\" % item.subtype.name )\n category.save()\n except Exception as e:\n print(str(e))\n pass\n \n\n subsubsubtypeofrealestates = SubsubsubtypeOfRealEstate.objects.all()\n\n for item in subsubsubtypeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus\n category.save()\n if item.subsubtype:\n subsubtype_categories = Category.objects.filter(name = item.subsubtype.name)\n if subsubtype_categories:\n print ( \"subsubtype_categories %i \" % subsubtype_categories.count())\n print ( subsubtype_categories )\n category.parent_categories.add(subsubtype_categories[0])\n subsubtype_categories[0].categories.add(category) \n subsubtype_categories[0].save() \n else:\n print (\"not found subsubtype %s\" % item.subsubtype.name )\n category.save()\n except Exception as e:\n print(str(e))\n pass\n \n\ndef create_parser_types():\n print(\"create parser types...\")\n parser_type = ParserType()\n parser_type.name = \"google_map\"\n parser_type.name_ru = \"google map\"\n parser_type.save()\n\n\n parser_type = ParserType()\n parser_type.name = \"yandex_map\"\n parser_type.name_ru = \"yandex map\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"yandex_transport\"\n parser_type.name_ru = \"yandex transport\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"wiki_routes\"\n parser_type.name_ru = \"wiki routes\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"rosreestr.ru\"\n parser_type.name_ru = \"rosreestr.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"reformagkh.ru\"\n parser_type.name_ru = \"reformagkh.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"dom.gosuslugi.ru\"\n parser_type.name_ru = \"dom.gosuslugi.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"greenpatrol.ru\"\n parser_type.name_ru = \"greenpatrol.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"ecofactor.ru\"\n parser_type.name_ru = \"ecofactor.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"kartasvalok.ru\"\n parser_type.name_ru = \"kartasvalok.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"fssprus.ru\"\n parser_type.name_ru = \"fssprus.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"egrul.nalog.ru\"\n parser_type.name_ru = \"egrul.nalog.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"sudrf.ru\"\n parser_type.name_ru = \"sudrf.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"notariat.ru\"\n parser_type.name_ru = \"notariat.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"genproc.gov.ru\"\n parser_type.name_ru = \"genproc.gov.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"мвд.рф\"\n parser_type.name_ru = \"мвд.рф\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"mchs.gov.ru\"\n parser_type.name_ru = \"mchs.gov.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"rosinv.ru/o-predpriyatii\"\n parser_type.name_ru = \"rosinv.ru/o-predpriyatii\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"bti-moscow.ru\"\n parser_type.name_ru = \"bti-moscow.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"mobti.ru\"\n parser_type.name_ru = \"mobti.ru\"\n parser_type.save()\n\n print(\"finished\")\n\ndef create_parser_parameters():\n print(\"create parser parameters...\")\n fields = Field.objects.all()\n for item in fields:\n try:\n \n parserparameter = ParserParameter()\n parserparameter.name = item.name \n \n parserparameter.name_ru = item.title_rus\n parserparameter.parser_type = ParserType.objects.get(id = item.parser_type+1)\n parserparameter.save()\n\n field_data = DataField.objects.filter(field = item)\n for field_data_item in field_data:\n print (\"try save data parametter\")\n data_parameter = ParserParameterData()\n data_parameter.value = field_data_item.value\n data_parameter.real_estate = field_data_item.real_estate\n data_parameter.parser_parameter = parserparameter\n data_parameter.save()\n print (\"save data parameter\")\n\n except Exception as e:\n print(str(e))\n pass\n print(\"finished\")\n\ndef create_formula():\n print(\"create empty formulas\")\n categories = Category.objects.all()\n for category in categories:\n try: \n print (\"try save data category formula\") \n category_formula = FormulaCategory() \n category_formula.category = category\n category_formula.value = \"FV_%i\" % (category.id,)\n category_formula.rate = \"FR_%i\" % (category.id,)\n category_formula.formula = \"FF_%i\" % (category.id,)\n category_formula.save()\n print (\"save data category formula\")\n print (category.parameters)\n if category.parameters.exists():\n for parameter in category.parameters.all():\n print (\"try save data parametter formula\")\n parameter_formula = FormulaParameterCategory()\n parameter_formula.category = category\n parameter_formula.parameter = parameter\n parameter_formula.value_label = \"PV_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.rate_label = \"PR_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.formula_label = \"PF_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.value = \"PV_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.rate = \"PR_%i_%i\" % (parameter.id,category.id,) \n parameter_formula.save()\n print (\"save data parametter formula\")\n\n except Exception as e:\n print(str(e))\n break\n print(\"finished\")\n\ndef create_default_search_form():\n # if not SearchForm.objects.get(name = 'default'):\n search_form = SearchForm()\n search_form.name = 'default'\n search_form.name_ru = 'Стандартный'\n search_form.user = User.objects.get(id = 1)\n search_form.save()\n search_form.categories.set(Category.objects.all())\n \n search_form.save()\n\n\n\ndef init_db():\n con = psycopg2.connect(dbname='postgres',\n user='postgres', host='',\n password='postgres')\n\n con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) # <-- ADD THIS LINE\n\n cur = con.cursor()\n\n # Use the psycopg2.sql module instead of string concatenation \n # in order to avoid sql injection attacs.\n cur.execute(sql.SQL(\"CREATE DATABASE {}\").format(\n sql.Identifier('db_passport'))\n )\n\ndef create_yandex_parameter():\n parser_type = ParserType.objects.filter(name = \"google_map\").first()\n parser_type_yandex = ParserType.objects.filter(name = \"yandex_map\").first()\n parser_parameters = ParserParameter.objects.filter(parser_type = parser_type)\n print(\"create_yandex_parameter\")\n #print(parser_type.name)\n #print(parser_type_yandex.name)\n\n for item in parser_parameters:\n parserparameter = ParserParameter()\n parserparameter.name = item.name +\"yandex\" \n parserparameter.name_ru = item.name_ru \n parserparameter.parser_type = parser_type_yandex\n parserparameter.parser_parameter_type = item.parser_parameter_type\n parserparameter.save()\n\ndef tasks():\n print(\"tasks\")\n # init_classifier()\n # init_addreses()\n # init_units()\n #\n # init_type_of_value()\n # init_social_fields()\n # init_transport_fields()\n # init_place_info_fields()\n # init_architecture_fields()\n # init_rights_fields()\n #\n # init_engsys_fields()\n # create_config()\n # move_data_to_category()\n # create_parser_types()\n # create_parser_parameters()\n # create_formula()\n # init_db()\n create_default_search_form()\n # create_yandex_parameter()\n # #create_gkh_parameter()\n\n print(\"finish tasks\")\n\n\n","sub_path":"passport_app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":54851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"330202560","text":"import os\r\nimport time\r\n\r\nfrom openstack import connection\r\n\r\n\r\n\r\n# Please put the endpoints which are not the native OpenStack services.\r\n_endpoints = {\r\n 'OS_DMS_ENDPOINT_OVERRIDE': 'https://dms.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s/',\r\n 'OS_LOAD_BALANCER_ENDPOINT_OVERRIDE': 'https://elb.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s',\r\n 'OS_RDS_ENDPOINT_OVERRIDE': 'https://rds.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s',\r\n 'OS_SMN_ENDPOINT_OVERRIDE': 'https://smn.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s'\r\n}\r\n\r\n_auth = {\r\n 'auth_url': \"https://iam.eu-de.otc.t-systems.com:443/v3\",\r\n 'project_id': 'YOUR-PROJECT-ID',\r\n 'user_domain_id': 'YOUR-DOMAIN-ID',\r\n 'username': 'YOUR-USER-NAME',\r\n 'password': 'YOUR-PASSWORD'\r\n}\r\n\r\n\r\ndef create_queue(conn, queue_name):\r\n queue_obj = None\r\n queues = conn.dms.queues()\r\n for each in queues:\r\n if 0 != cmp(each.name, queue_name):\r\n pass\r\n else:\r\n queue_obj = each\r\n break\r\n\r\n # create a new one\r\n if queue_obj is None:\r\n queue_param = {\r\n 'name': queue_name,\r\n 'description': 'This is a dms demo queue.'\r\n }\r\n queue_obj = conn.dms.create_queue(**queue_param)\r\n else:\r\n pass\r\n\r\n # for debug\r\n #print(queue_obj)\r\n return queue_obj\r\n\r\n\r\ndef create_groups(conn, queue):\r\n print(\"create groups on queue %s\", queue)\r\n groups_new = [\"dms-group-01\"]\r\n\r\n # check if the new groups are already exist.\r\n groups = conn.dms.groups(queue)\r\n groups_exist = [grp.name for grp in groups]\r\n groups_add = list(set(groups_new) - set(groups_exist))\r\n if 0 < len(groups_add):\r\n grps_params = {\"groups\": [{\"name\": i} for i in groups_add ]}\r\n print(conn.dms.create_groups(queue, **grps_params))\r\n else:\r\n pass\r\n\r\n\r\ndef delete_groups(conn, queue):\r\n print(\"delete all groups on queue %s\", queue)\r\n for g in conn.dms.groups(queue):\r\n print(g)\r\n conn.dms.delete_group(queue, g)\r\n\r\n\r\ndef produce_message(conn, queue):\r\n print(\"send message on a queue %s\", queue)\r\n msg_dict = {\r\n \"messages\": [\r\n {\r\n \"body\": \"TEST11\",\r\n \"attributes\":\r\n {\r\n \"attribute1\": \"value1\",\r\n \"attribute2\": \"value2\"\r\n }\r\n }\r\n ]\r\n }\r\n\r\n msgs = conn.dms.send_messages(queue, **msg_dict)\r\n #print(\"send messages %s\" % msgs)\r\n\r\n\r\ndef consume_message(conn, queue):\r\n grps = conn.dms.groups(queue)\r\n\r\n for grp in grps:\r\n print(\"=========consumed message by group %s start...\" % grp.name)\r\n csm_msgs = conn.dms.consume_message(queue, grp.id)\r\n for cm in csm_msgs:\r\n print(\"*****ack consumed message %s\" % cm)\r\n print(conn.dms.ack_consumed_message(cm))\r\n print(\"=========consumed message by group %s end.\" % grp.name)\r\n\r\n\r\ndef consume_message_with_tags(conn, qui, gid):\r\n \"\"\"Consume message by tag list in queue and group\"\"\"\r\n #qid = '673f8fca-9aa1-4974-8fc5-b0eb1c5f9724'\r\n #gid = 'g-a826e437-2e67-46c7-b220-63836b5bb463'\r\n params = {\r\n 'max_msgs': 10,\r\n 'time_wait': 30,\r\n 'tags': ['tag1', 'tag2'],\r\n 'tag_type': 'or'\r\n }\r\n\r\n for c in conn.dms.consume_message(qui, gid, **params):\r\n print(c)\r\n\r\n\r\ndef get_quotas(conn):\r\n for q in conn.dms.quotas():\r\n print(q)\r\n\r\n\r\ndef main():\r\n # set the endpoints\r\n for edp_key in _endpoints:\r\n #print(edp_key, _endpoints[edp_key])\r\n os.environ.setdefault(edp_key, _endpoints[edp_key])\r\n\r\n # connect to OTC\r\n conn = connection.Connection(**_auth)\r\n\r\n queue_name = 'dms-demo-queue'\r\n queue_obj = create_queue(conn, queue_name)\r\n create_groups(conn, queue_obj)\r\n\r\n produce_message(conn, queue_obj)\r\n consume_message(conn, queue_obj)\r\n\r\n get_quotas(conn)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\r\n","sub_path":"example-dms.py","file_name":"example-dms.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"52822411","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\n\nimport radical.utils as ru\nimport radical.pilot as rp\n\n\n# This script has to run as a task within an pilot allocation, and is\n# a demonstration of a task overlay within the RCT framework.\n# It will:\n#\n# - create a master which bootstraps a specific communication layer\n# - insert n workers into the pilot (again as a task)\n# - perform RPC handshake with those workers\n# - send RPC requests to the workers\n# - terminate the worker\n#\n# The worker itself is an external program which is not covered in this code.\n\n\n# ------------------------------------------------------------------------------\n#\nclass MyMaster(rp.task_overlay.Master):\n '''\n This class provides the communication setup for the task overlay: it will\n set up the request / response communication queues and provide the endpoint\n information to be forwarded to the workers.\n '''\n\n # --------------------------------------------------------------------------\n #\n def __init__(self, cfg):\n\n # initialize the task overlay base class. That base class will ensure\n # proper communication channels to the pilot agent.\n rp.task_overlay.Master.__init__(self, cfg=cfg)\n\n\n # --------------------------------------------------------------------------\n #\n def create_work_items(self):\n\n self._prof.prof('create_start')\n\n world_size = self._cfg.n_masters\n rank = self._cfg.rank\n print('=== 2 : ', self._cfg.rank)\n\n # create an initial list of work items to be distributed to the workers.\n # Work items MUST be serializable dictionaries.\n idx = rank\n total = int(eval(self._cfg.workload.total))\n while idx < total:\n\n uid = 'request.%06d' % idx\n print('=== uid:', uid)\n item = {'uid' : uid,\n 'mode': 'call',\n 'data': {'method': 'hello',\n 'kwargs': {'count': idx,\n 'uid' : uid}}}\n self.request(item)\n idx += world_size\n\n self._prof.prof('create_stop')\n\n\n # --------------------------------------------------------------------------\n #\n def result_cb(self, requests):\n\n # result callbacks can return new work items\n new_requests = list()\n for r in requests:\n sys.stdout.write('result_cb %s: %s [%s]\\n' % (r.uid, r.state, r.result))\n sys.stdout.flush()\n\n # count = r.work['data']['kwargs']['count']\n # if count < 10:\n # new_requests.append({'mode': 'call',\n # 'data': {'method': 'hello',\n # 'kwargs': {'count': count + 100}}})\n\n return new_requests\n\n\n# ------------------------------------------------------------------------------\n#\nif __name__ == '__main__':\n\n # This master script runs as a task within a pilot allocation. The purpose\n # of this master is to (a) spawn a set or workers within the same\n # allocation, (b) to distribute work items (`hello` function calls) to those\n # workers, and (c) to collect the responses again.\n cfg_fname = str(sys.argv[1])\n cfg = ru.Config(cfg=ru.read_json(cfg_fname))\n cfg.rank = int(sys.argv[2])\n print('=== 1 : ', cfg.rank)\n\n n_nodes = cfg.nodes\n cpn = cfg.cpn\n gpn = cfg.gpn\n descr = cfg.worker_descr\n worker = os.path.basename(cfg.worker)\n pwd = os.getcwd()\n\n # add data staging to worker: link input_dir, impress_dir, and oe_license\n descr['arguments'] = [os.path.basename(worker)]\n descr['input_staging'] = [\n {'source': '%s/%s' % (pwd, worker),\n 'target': worker,\n 'action': rp.COPY,\n 'flags' : rp.DEFAULT_FLAGS,\n 'uid' : 'sd.0'},\n {'source': '%s/%s' % (pwd, cfg_fname),\n 'target': cfg_fname,\n 'action': rp.COPY,\n 'flags' : rp.DEFAULT_FLAGS,\n 'uid' : 'sd.1'},\n ]\n\n # one node is used by master. Alternatively (and probably better), we could\n # reduce one of the worker sizes by one core. But it somewhat depends on\n # the worker type and application workload to judge if that makes sense, so\n # we leave it for now.\n print('workers: ', (n_nodes / cfg.n_masters) - 1)\n n_workers = int((n_nodes / cfg.n_masters) - 1)\n\n # create a master class instance - this will establish communication to the\n # pilot agent\n master = MyMaster(cfg)\n\n # insert `n` worker tasks into the agent. The agent will schedule (place)\n # those workers and execute them. Insert one smaller worker (see above)\n # NOTE: this assumes a certain worker size / layout\n master.submit(descr=descr, count=n_workers, cores=cpn, gpus=gpn)\n master.submit(descr=descr, count=1, cores=cpn - 1, gpus=gpn)\n\n # wait until `m` of those workers are up\n # This is optional, work requests can be submitted before and will wait in\n # a work queue.\n # master.wait(count=nworkers)\n\n master.run()\n\n # simply terminate\n # FIXME: clean up workers\n\n\n# ------------------------------------------------------------------------------\n\n","sub_path":"examples/misc/task_overlay_master.py","file_name":"task_overlay_master.py","file_ext":"py","file_size_in_byte":5515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"82069621","text":"# -*- coding:UTF-8 -*-\nimport cv2\nfrom PIL import Image\nimport os\nimport shutil\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nimport glob\n\nindex = 0\n\n\ndef show(img):\n global index\n index += 1\n if len(img.shape) == 3:\n image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n plt.title(index)\n plt.imshow(image)\n plt.show()\n if len(img.shape) == 2:\n plt.title(index)\n plt.imshow(img, cmap=plt.gray())\n plt.show()\n\n\ndef find_image_cbox(img):\n img = img.copy()\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 4)\n img = cv2.bitwise_not(img)\n cropped_box = find_image_bbox(img)\n return cropped_box\n\n\ndef find_image_bbox(img):\n height = img.shape[0]\n width = img.shape[1]\n v_sum = np.sum(img, axis=0)\n h_sum = np.sum(img, axis=1)\n left = 0\n right = width - 1\n top = 0\n low = height - 1\n # 从左往右扫描,遇到非零像素点就以此为字体的左边界\n for i in range(width):\n if v_sum[i] > 0:\n left = i\n break\n # 从右往左扫描,遇到非零像素点就以此为字体的右边界\n for i in range(width - 1, -1, -1):\n if v_sum[i] > 0:\n right = i\n break\n # 从上往下扫描,遇到非零像素点就以此为字体的上边界\n for i in range(height):\n if h_sum[i] > 0:\n top = i\n break\n # 从下往上扫描,遇到非零像素点就以此为字体的下边界\n for i in range(height - 1, -1, -1):\n if h_sum[i] > 0:\n low = i\n break\n return left, top, right, low\n\n\ndef same_scale(cv2_img, max_width, max_height):\n cur_height, cur_width = cv2_img.shape[:2]\n ratio_w = float(max_width) / float(cur_width)\n ratio_h = float(max_height) / float(cur_height)\n ratio = min(ratio_w, ratio_h)\n\n new_size = (min(int(cur_width * ratio), max_width),\n min(int(cur_height * ratio), max_height))\n\n new_size = (max(new_size[0], 1),\n max(new_size[1], 1),)\n resized_img = cv2.resize(cv2_img, new_size)\n return resized_img\n\n\ndef same_scale2(cv2_img, max_size):\n cur_height, cur_width = cv2_img.shape[:2]\n ratio_h = float(max_size) / float(cur_height)\n new_width = int(cur_width*ratio_h)\n if new_width == 0:\n new_width = 1\n resized_img = cv2.resize(cv2_img, (new_width, max_size))\n return resized_img\n\n\ndef img_crop2(img):\n img = img.copy()\n left, upper, right, lower = find_image_bbox(img)\n img = img[upper: lower + 1, left: right + 1]\n return img\n\n\n\nTARGET_SIZE = 48\n\n\nclass OcrSpliter(object):\n def __init__(self):\n self.num = 0\n\n def DegreeTrans(self,theda):\n return theda / np.pi * 180\n\n def getNewSize(self,img, angle):\n q_height, q_width = img.shape[0], img.shape[1]\n angle = angle * math.pi / 180.0\n s = math.fabs(math.sin(angle))\n c = math.fabs(math.cos(angle))\n width = int((q_height * s + q_width * c) / 4) * 4\n height = int((q_height * c + q_width * s) / 4) * 4\n return width, height\n\n def rotate(self, img, rotate):\n img = img.copy()\n b, g, r = img[5, 5]\n height, width = img.shape[0], img.shape[1]\n if rotate != 0:\n M = cv2.getRotationMatrix2D(((width - 1) / 2.0, (height - 1) / 2.0), rotate, 1.0)\n new_width, new_height = self.getNewSize(img, rotate)\n img = cv2.warpAffine(img, M, (new_width, new_height), borderValue=(int(b), int(g), int(r)))\n return img\n\n def get_x_y(self, x, y, angle):\n angle = angle * math.pi / 180.0\n x1 = x + math.sqrt(x ** 2 + y ** 2) * math.sin(angle)\n y1 = y\n return [x1, y1]\n\n def line_detection(self, image):\n src = image.copy()\n img_r = src.copy()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # show(gray)\n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n # show(edges)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 160)\n if lines is not None:\n sum = 0\n for line in lines:\n rho, theta = line[0]\n sum += theta\n # show(image)\n avg = sum / len(lines)\n angle = self.DegreeTrans(avg) - 90\n # print(angle)\n img_r = self.rotate(src, angle)\n # show(img_r)\n padding = 30\n img = np.ones([img_r.shape[0], img_r.shape[1] + padding * 2, 3], dtype=np.uint8) * 255\n img[:, padding:padding+img_r.shape[1]] = img_r\n # show(img)\n height, width = img.shape[0], img.shape[1]\n p1 = [0, 0]\n p2 = [int((width - 1)/2), int((height-1)/2)]\n p3 = [0, height - 1]\n matSrc = np.float32([p1,p2,p3]) # 需要注意的是 行列 和 坐标 是不一致的\n img_src = img\n\n def get_count(angle):\n matDst = np.float32(\n [self.get_x_y(p1[0], p1[1], angle), p2,\n self.get_x_y(p3[0], p3[1], -angle)])\n matAffine = cv2.getAffineTransform(matSrc, matDst) # mat 1 src 2 dst 形成组合矩阵\n img = cv2.warpAffine(img_src, matAffine, (img_src.shape[1], img_src.shape[0]), borderValue=(255, 255, 255))\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))\n img = cv2.erode(img, kernel)\n # show(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # show(img)\n ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n # show(img)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))\n img = cv2.erode(img, kernel)\n # show(img)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n img = cv2.dilate(img, kernel)\n # show(img)\n img = cv2.bitwise_not(img)\n # show(img)\n img, _ = img_crop2(img)\n h, w = img.shape[0], img.shape[1]\n count = 0\n for i in range(w):\n for j in range(h):\n if img[j, i] == 255:\n count += 1\n break\n if count == 0:\n count = 10000\n return count\n\n flag = True\n left = -10\n right = 10\n now = 0\n left_count = get_count(left)\n now_count = get_count(now)\n right_count = get_count(right)\n if left_count > now_count and right_count > now_count:\n flag = False\n\n if flag:\n left = -30\n right = 30\n now = 0\n while left <= right-1:\n left_count = get_count(left)\n now_count = get_count(now)\n right_count = get_count(right)\n if left_count < now_count and right_count < now_count:\n if abs(left_count - now_count) > abs(right_count - now_count):\n right = now\n now = (left + right) / 2\n else:\n left = now\n now = (left + right) / 2\n elif left_count < now_count:\n right = now\n now = (left + right) / 2\n elif right_count < now_count:\n left = now\n now = (left + right) / 2\n else:\n left += 2\n right -= 2\n\n rigth_angle = now\n print('rigth_angle:', rigth_angle)\n\n if rigth_angle == 0:\n return img_r\n else:\n matDst = np.float32(\n [self.get_x_y(p1[0], p1[1], rigth_angle), p2,\n self.get_x_y(p3[0], p3[1], -rigth_angle)])\n matAffine = cv2.getAffineTransform(matSrc, matDst) # mat 1 src 2 dst 形成组合矩阵\n img = cv2.warpAffine(img_src, matAffine, (img_src.shape[1], img_src.shape[0]), borderValue=(255, 255, 255))\n return img\n\n # def ocr_split(self, path):\n # src = cv2.imread(path)\n # src = same_scale(src,200,30)\n # # show(src)\n # # pure_name = os.path.basename(path).split('.')[0]\n # # dir_name = os.path.join('images', pure_name)\n # # shutil.rmtree(dir_name, ignore_errors=True)\n # # os.mkdir(dir_name)\n # img = src.copy()\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.erode(img, kernel)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.dilate(img, kernel)\n # img = cv2.bitwise_not(img)\n # img = img_padding(img)\n # # show(img)\n # img = img_crop2(img)\n # img = same_scale(img, 200, 30)\n # _, img = cv2.threshold(img, 127,255, cv2.THRESH_BINARY)\n # img = img_padding(img)\n # # show(img)\n # # src = src[top:bottom + 1, left:right + 1]\n # # src = same_scale(src, 400, 60)\n # # show(src)\n # return img\n\n def ocr_split(self, path, img_src=None):\n if img_src is not None:\n src = img_src.copy()\n else:\n src = cv2.imread(path)\n src = same_scale(src, 200, 30)\n # show(src)\n # pure_name = os.path.basename(path).split('.')[0]\n # dir_name = os.path.join('images', pure_name)\n # shutil.rmtree(dir_name, ignore_errors=True)\n # os.mkdir(dir_name)\n # img = src.copy()\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = src[:, :, 2]\n # show(img)\n ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n # show(img)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.dilate(img, kernel)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.erode(img, kernel)\n img = cv2.bitwise_not(img)\n img = img_padding(img)\n # show(img)\n img = img_crop2(img)\n img = same_scale(img, 200, 30)\n _, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n img = img_padding(img)\n # show(img)\n # src = src[top:bottom + 1, left:right + 1]\n # src = same_scale(src, 400, 60)\n # show(src)\n return img\n\n\n\n\ndef img_padding(img):\n TARGET_HEIGHT = 30\n TARGET_WIDTH = 200\n left = TARGET_WIDTH - img.shape[1] - 1\n top = TARGET_HEIGHT - img.shape[0] - 1\n if left < 0 and top < 0:\n return img\n final_img = np.zeros((TARGET_HEIGHT, TARGET_WIDTH), dtype=np.uint8)\n # if left<=0:\n # start_x=0\n # else:\n # start_x = int(left / 2)\n start_x = 0\n if top<=0:\n start_y=0\n else:\n start_y = int(top / 2)\n img_h, img_w = img.shape[0], img.shape[1]\n final_img[start_y:start_y + img_h, start_x:start_x + img_w] = img\n return final_img\n\n\n\n\n# spliter = OcrSpliter()\n#\n#\n# path = 'IMG_20181120_145731_21.jpg'\n# spliter.ocr_split(path)\n\n\n# paths = glob.glob('images/*.*g')\n# print(len(paths))\n# for i, path in enumerate(paths):\n# spliter.ocr_split(path)\n","sub_path":"slim/ocr_price_utils.py","file_name":"ocr_price_utils.py","file_ext":"py","file_size_in_byte":11261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"343315026","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.contrib import admin\nfrom tinymce.widgets import TinyMCE\n\nfrom bumerang.apps.news.models import NewsCategory, NewsItem\n\n\nclass NewsCategoryAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"title\",)}\n\n\nclass NewsItemForm(forms.ModelForm):\n class Meta:\n model = NewsItem\n widgets = {\n 'text': TinyMCE(attrs={'cols': 80, 'rows': 30}),\n 'preview_text': TinyMCE(attrs={'cols': 80, 'rows': 30})\n }\n\n\nclass NewsItemAdmin(admin.ModelAdmin):\n form = NewsItemForm\n prepopulated_fields = {\"slug\": (\"title\",)}\n\n\nadmin.site.register(NewsCategory, NewsCategoryAdmin)\nadmin.site.register(NewsItem, NewsItemAdmin)\n","sub_path":"bumerang/apps/news/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"232818694","text":"from turtle import Screen, Turtle\nfrom random import randint\n\ns = Screen()\ns.setup(560,560)\ns.title(\"A drunken turtle collecting ...\")\n\ns.tracer(False)\nwriter = Turtle(visible=False)\nwriter.penup()\nwriter.goto(0, -275)\n\ncoins = []\nfor i in range(-4,5):\n for j in range(-4, 5):\n if i == j == 0:\n continue\n c = Turtle(shape=\"circle\")\n c.color(\"\", \"orange\")\n c.shapesize(0.5)\n c.goto(40*i, 40*j)\n coins.append(c)\ns.tracer(True)\n\nDRUNKENNESS = 45 \nt = Turtle(shape=\"turtle\")\nt.color(\"black\",\"\")\npoints = 0\nwhile abs(t.xcor()) < 200 and abs(t.ycor()) < 200:\n t.forward(5)\n t.right(randint(-DRUNKENNESS, DRUNKENNESS))\n found = None\n for c in coins:\n if t.distance(c) < 10:\n found = c\n break\n if found:\n found.hideturtle()\n coins.remove(found)\n t.shapesize(1+points/5., outline=1+points)\n points += 1\n\nwriter.write(\"{0} points\".format(points),\n align=\"center\", font=('Arial', 24, 'bold'))","sub_path":"visoes_1/programas/tartaruga_1/rqndom_walk.py","file_name":"rqndom_walk.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"586253369","text":"# coding=utf-8\n# Copyright 2017 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Collect trajectories from interactions of agent with environment.\"\"\"\n\nimport tensorflow as tf\n\n\ndef define_collect(policy_factory, batch_env, config):\n \"\"\"Collect trajectories.\"\"\"\n memory_shape = [config.epoch_length] + [batch_env.observ.shape.as_list()[0]]\n memories_shapes_and_types = [\n # observation\n (memory_shape + [batch_env.observ.shape.as_list()[1]], tf.float32),\n (memory_shape, tf.float32), # reward\n (memory_shape, tf.bool), # done\n (memory_shape + batch_env.action_shape, tf.float32), # action\n (memory_shape, tf.float32), # pdf\n (memory_shape, tf.float32), # value function\n ]\n memory = [tf.Variable(tf.zeros(shape, dtype), trainable=False)\n for (shape, dtype) in memories_shapes_and_types]\n cumulative_rewards = tf.Variable(\n tf.zeros(config.num_agents, tf.float32), trainable=False)\n\n should_reset_var = tf.Variable(True, trainable=False)\n reset_op = tf.cond(should_reset_var,\n lambda: batch_env.reset(tf.range(config.num_agents)),\n lambda: 0.0)\n with tf.control_dependencies([reset_op]):\n reset_once_op = tf.assign(should_reset_var, False)\n\n with tf.control_dependencies([reset_once_op]):\n\n def step(index, scores_sum, scores_num):\n \"\"\"Single step.\"\"\"\n # Note - the only way to ensure making a copy of tensor is to run simple\n # operation. We are waiting for tf.copy:\n # https://github.com/tensorflow/tensorflow/issues/11186\n obs_copy = batch_env.observ + 0\n actor_critic = policy_factory(tf.expand_dims(obs_copy, 0))\n policy = actor_critic.policy\n action = policy.sample()\n postprocessed_action = actor_critic.action_postprocessing(action)\n simulate_output = batch_env.simulate(postprocessed_action[0, ...])\n pdf = policy.prob(action)[0]\n with tf.control_dependencies(simulate_output):\n reward, done = simulate_output\n done = tf.reshape(done, (config.num_agents,))\n to_save = [obs_copy, reward, done, action[0, ...], pdf,\n actor_critic.value[0]]\n save_ops = [tf.scatter_update(memory_slot, index, value)\n for memory_slot, value in zip(memory, to_save)]\n cumulate_rewards_op = cumulative_rewards.assign_add(reward)\n agent_indices_to_reset = tf.where(done)[:, 0]\n with tf.control_dependencies([cumulate_rewards_op]):\n scores_sum_delta = tf.reduce_sum(\n tf.gather(cumulative_rewards, agent_indices_to_reset))\n scores_num_delta = tf.count_nonzero(done, dtype=tf.int32)\n with tf.control_dependencies(save_ops + [scores_sum_delta,\n scores_num_delta]):\n reset_env_op = batch_env.reset(agent_indices_to_reset)\n reset_cumulative_rewards_op = tf.scatter_update(\n cumulative_rewards, agent_indices_to_reset,\n tf.zeros(tf.shape(agent_indices_to_reset)))\n with tf.control_dependencies([reset_env_op,\n reset_cumulative_rewards_op]):\n return [index + 1, scores_sum + scores_sum_delta,\n scores_num + scores_num_delta]\n\n init = [tf.constant(0), tf.constant(0.0), tf.constant(0)]\n index, scores_sum, scores_num = tf.while_loop(\n lambda c, _1, _2: c < config.epoch_length,\n step,\n init,\n parallel_iterations=1,\n back_prop=False)\n mean_score = tf.cond(tf.greater(scores_num, 0),\n lambda: scores_sum / tf.cast(scores_num, tf.float32),\n lambda: 0.)\n printing = tf.Print(0, [mean_score, scores_sum, scores_num], \"mean_score: \")\n with tf.control_dependencies([printing]):\n return tf.identity(index), memory\n","sub_path":"tensor2tensor/rl/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"145862291","text":"import pgzrun # 导入游戏库\nimport random # 导入随机库\n\nWIDTH = 350 # 设置窗口的宽度\nHEIGHT = 600 # 设置窗口的高度\n\nbackground = Actor('background') # 导入背景图片\nbird = Actor('bird') # 导入小鸟图片\nbird.x = 50 # 设置小鸟的x坐标\nbird.y = HEIGHT/2 # 设置小鸟的y坐标\nbar_up = Actor('bar_up') # 导入障碍物上半部分图片\nbar_up.x = 300 # 设置障碍物上半部分的x坐标\nbar_up.y = 0 # 设置障碍物上半部分的y坐标\nbar_down = Actor('bar_down') # 导入障碍物下半部分图片\nbar_down.x = 300 # 设置障碍物下半部分的x坐标\nbar_down.y = 600 # 设置障碍物下半部分的y坐标\n\n\ndef draw(): # 绘制模块,每帧重复执行\n background.draw() # 绘制背景\n bar_up.draw() # 绘制障碍物上半部分\n bar_down.draw() # 绘制障碍物下半部分\n bird.draw() # 绘制小鸟\n\n\ndef update(): # 更新模块,每帧重复操作\n bird.y = bird.y + 2 # 小鸟y坐标增加,即缓慢下落\n bar_up.x = bar_up.x - 2 # 障碍物上半部分缓慢向左移动\n bar_down.x = bar_down.x - 2 # 障碍物下半部分缓慢向左移动\n # 当障碍物移动到最左边时,让其在最右边重新出现\n if bar_up.x < 0:\n bar_up.x = WIDTH\n bar_down.x = WIDTH\n bar_up.y = random.randint(-200, 200) # 障碍物上半部分上下随机出现\n bar_down.y = 600 + bar_up.y # 上、下部分的障碍物中间空隙高度固定\n\ndef on_mouse_down(): # 当鼠标点击时运行\n bird.y = bird.y - 100 # 小鸟y坐标减少,即上升一段距离\n\npgzrun.go() # 开始执行游戏","sub_path":"PygameZero/python游戏趣味编程代码/第5章/5-4-4.py","file_name":"5-4-4.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"556018383","text":"import sqlite3\n\nvalues = ((\"Jean-Baptiste Zorg\", \"Human\", 122), (\"Korben Dallas\", \"Meat Popssicle\", 100), (\"Ak'not\", \"Mangalore\", -5))\n\nwith sqlite3.connect(\":memory:&db\") as conn:\n c = conn.cursor()\n c.execute(\"DROP TABLE IF EXISTS Roster\")\n c.execute(\"CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)\")\n c.executemany(\"INSERT INTO Roster VALUES(?, ?, ?)\", values) #This inserts all the data in the list to the database\n c.execute(\"UPDATE Roster SET Species = ? WHERE Name = ? AND IQ = ?\", (\"Human\", \"Korben Dallas\", 100)) \n c.execute(\"SELECT Name, IQ FROM Roster WHERE Species is 'Human'\")\n for row in c.fetchall():\n print(row)\n","sub_path":"RAMdd.py","file_name":"RAMdd.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"337666845","text":"#!/usr/bin/env python3\n\nimport os\nSCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))\nFILENAME = '{}/../input.txt'.format(SCRIPT_PATH)\n\n\ndef get_file(name=FILENAME):\n with open(name) as input_file:\n return input_file.read()\n\n\ndef next_index(after, removed):\n n = after + 1\n while n in removed:\n n += 1\n return n\n\n\ndef prev_index(before, removed):\n prev = before - 1\n while prev in removed:\n prev -= 1\n if prev < 0:\n prev = next_index(prev, removed)\n return prev\n\n\noriginal_puzzle = get_file()\n\navailable_units = set()\nfor unit in original_puzzle.lower():\n available_units.add(unit)\n\nsmallest_size = len(original_puzzle)\nfor unit in available_units:\n puzzle = original_puzzle\n lower_puzzle = puzzle.lower()\n removed_elements = set()\n\n unit_upper = unit.upper()\n for index, p in enumerate(puzzle):\n if p in (unit, unit_upper):\n removed_elements.add(index)\n\n cur_index = next_index(-1, removed_elements)\n\n while cur_index < len(puzzle) - 1:\n compare_index = next_index(cur_index, removed_elements)\n if compare_index >= len(puzzle):\n break\n\n if lower_puzzle[cur_index] == lower_puzzle[compare_index] and puzzle[cur_index] != puzzle[compare_index]:\n removed_elements.add(cur_index)\n removed_elements.add(compare_index)\n cur_index = prev_index(cur_index, removed_elements)\n continue\n\n cur_index = next_index(cur_index, removed_elements)\n\n puzzle_size = len(puzzle) - len(removed_elements)\n if puzzle_size < smallest_size:\n smallest_size = puzzle_size\n\nprint('The shortest polymer you can produce is:', smallest_size)\n","sub_path":"2018/day_05/python/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"368466031","text":"from socket import *\n#创建tcp套接字\ns=socket()\ns.bind(('0.0.0.0',10000))\ns.listen(5)\nwhile True:\n c,addr=s.accept()\n print('connect from',addr)\n\n data=c.recv(4096)\n print('*****************')\n print(data)#浏览器发来的http请求\n print('*****************')\n\n #组织响应内容\n data='''HTTP/1.1 200 ok\n Content-Encoding: gzip\n Content-Type: text/html\n\n

Welcome to tedu

\n '''\n c.send(data.encode())\n c.close()\n\ns.close()","sub_path":"网络/pythonNet/day2/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237464075","text":"from PyQt4.Qsci import QsciLexerCPP,QsciStyle,QsciScintilla, QsciLexerJavaScript\nfrom PyQt4.QtCore import QString\nfrom PyQt4.QtGui import QFont, QColor\nfrom globals import config\n\nclass Squirrel(QsciLexerJavaScript):\n words1 = [\n 'base','break','case','catch','class','clone',\n 'continue','const','default','delete','else','enum',\n 'extends','for','foreach','function',' if',' in',\n 'local','null','resume','return','switch','this',\n 'throw','try','typeof','while','yield','constructor',\n 'instanceof','true','false','static'\n ]\n \n words2 = [\n 'init', 'dest', 'onLoad', 'onDispose', 'onGainedFocus','onMotionEvent',\n 'onLostFocus','onUpdate','onFps','onKeyEvent','onSensorEvent',\n 'onControlEvent','onDrawFrame','onError','onLowMemory','onNetCallBack'\n ]\n\n words3 = [\n 'rawdelete', 'rawin', 'array', 'seterrorhandler', 'setdebughook',\n 'enabledebuginfo', 'getroottable', 'setroottable', 'getconsttable',\n 'setconsttable', 'assert', 'print', 'compilestring', 'collectgarbage',\n 'type', 'getstackinfos', 'newthread', 'tofloat', 'tostring',\n 'tointeger', 'tochar', 'weakref', 'slice', 'find', 'tolower',\n 'toupper', 'len', 'rawget', 'rawset', 'clear', 'append', 'push',\n 'extend', 'pop', 'top', 'insert', 'remove', 'resize', 'sort',\n 'reverse', 'call', 'pcall', 'acall', 'pacall', 'bindenv', 'instance',\n 'getattributes', 'getclass', 'getstatus', 'ref'\n ]\n \n def __init__(self,parent):\n QsciLexerJavaScript.__init__(self, parent)\n self.parent = parent\n self.plainFont = QFont()\n self.plainFont.setFamily(config.fontName())\n self.plainFont.setFixedPitch(True)\n self.plainFont.setPointSize(config.fontSize())\n self.boldFont = QFont(self.plainFont)\n self.boldFont.setBold(True)\n self.setFoldCompact(True)\n \n def setColors(self, editStyle):\n self.base = QColor(editStyle[\"base\"]) #This is the font color\n self.back = QColor(editStyle[\"back\"]) #This is the bg color\n self.comment = QColor(editStyle[\"comment\"])\n self.number = QColor(editStyle[\"number\"])\n self.keyword = QColor(editStyle[\"keyword\"])\n self.string = QColor(editStyle[\"string\"])\n self.operator = QColor(editStyle[\"operator\"])\n self.styles = [\n #index description color paper font eol \n QsciStyle(0, QString(\"base\"), self.base, self.back, self.plainFont, True),\n QsciStyle(1, QString(\"comment\"), self.comment, self.back, self.plainFont, True),\n QsciStyle(4, QString(\"number\"), self.number, self.back, self.plainFont, True),\n QsciStyle(5, QString(\"Keyword\"), self.keyword, self.back, self.boldFont, True),\n QsciStyle(6, QString(\"String\"), self.string,self.back, self.plainFont, True),\n QsciStyle(10, QString(\"Operator\"), self.operator, self.back, self.plainFont, False) \n ]\n \n def language(self):\n return 'Squirrel'\n \n def foldCompact(self):\n return self._foldcompact\n\n def setFoldCompact(self, enable):\n self._foldcompact = bool(enable)\n\n def description(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.description()\n return QString(\"\")\n \n def defaultColor(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.color()\n return QsciLexerCPP.defaultColor(self, ix)\n\n def defaultFont(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.font()\n return QsciLexerCPP.defaultFont(self, ix)\n\n def defaultPaper(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.paper()\n return QsciLexerCPP.defaultPaper(self, ix)\n\n def defaultEolFill(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.eolFill()\n return QsciLexerCPP.defaultEolFill(self, ix)\n \n'''\n def styleText(self, start, end):\n editor = self.editor()\n if editor is None:\n return\n SCI = editor.SendScintilla\n GETFOLDLEVEL = QsciScintilla.SCI_GETFOLDLEVEL\n SETFOLDLEVEL = QsciScintilla.SCI_SETFOLDLEVEL\n HEADERFLAG = QsciScintilla.SC_FOLDLEVELHEADERFLAG\n LEVELBASE = QsciScintilla.SC_FOLDLEVELBASE\n NUMBERMASK = QsciScintilla.SC_FOLDLEVELNUMBERMASK\n WHITEFLAG = QsciScintilla.SC_FOLDLEVELWHITEFLAG\n INDIC_SET = QsciScintilla.SCI_INDICSETSTYLE\n INDIC_SETCURRENT = QsciScintilla.SCI_SETINDICATORCURRENT\n INDIC_FILL = QsciScintilla.SCI_INDICATORFILLRANGE\n INDIC_CLEAR = QsciScintilla.SCI_INDICATORCLEARRANGE\n INDIC_START = QsciScintilla.SCI_INDICATORSTART\n INDIC_END = QsciScintilla.SCI_INDICATOREND\n \n # using indicator 7 with Boxed style\n SCI(INDIC_SET, 7 ,QsciScintilla.INDIC_BOX)\n SCI(INDIC_SETCURRENT, 7)\n \n set_style = self.setStyling\n source = ''\n if end > editor.length():\n end = editor.length()\n if end > start:\n source = bytearray(end - start)\n SCI(QsciScintilla.SCI_GETTEXTRANGE, start, end, source)\n if not source:\n return \n #compact = self.foldCompact()\n index = SCI(QsciScintilla.SCI_LINEFROMPOSITION, start)\n self.startStyling(start, 0x1f)\n lineno = -1\n source = source.splitlines(True)\n for line in source:\n lineno += 1 \n length = len(line)\n if length == 0: #lol gg this had to be Zero\n return \n if line.startswith('#'):\n newState = self.styles[1]\n else:\n pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index) - length + 1\n i = 0\n while i < length:\n wordLength = 1\n self.startStyling(i + pos, 0x1f)\n newState = self.styles[0]\n for word in self.words2:\n if line[i:].startswith(word):\n newState = self.styles[4]\n wordLength = len(word)\n \n if chr(line[i]) in '0123456789':\n newState = self.styles[4]\n 'startpos=3, length=3, use current indicator'\n #SCI(INDIC_FILL,pos+line[i],1)\n else:\n if line[i:].startswith('\"'):\n newState = self.styles[1]\n pos2 = line.find('\"',i+1)\n size = pos2 - i\n if(size != 0 and pos2 != -1 ):\n wordLength = size\n #print \"line: \",lineno, \"pos: \",pos1, pos2\n elif line[i:].startswith(\"'\"):\n newState = self.styles[1]\n pos2 = line.find(\"'\",i+1)\n size = pos2 - i\n if(size != 0 and pos2 != -1 ):\n wordLength = size\n #print \"line: \",lineno, \"pos: \",pos1, pos2\n \n elif line[i:].startswith(\"class\"):\n newState = self.styles[5]\n wordLength = 5\n elif line[i:].startswith('function'):\n newState = self.styles[5]\n wordLength = 8\n elif line[i:].startswith('enum'):\n newState = self.styles[5]\n wordLength = 4\n elif line[i:].startswith(' if'):\n newState = self.styles[4]\n wordLength = 3\n elif line[i:].startswith('#'): \n # get end of line position and set word length to that\n newState = self.styles[4]\n pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, lineno)\n wordLength = pos\n #print \"#end\", pos\n #elif line[i:].startswith(','):\n # newState = self.styles[1]\n # wordLength = 1\n i += wordLength\n set_style(wordLength, newState)\n if newState: \n set_style(length, newState)\n pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index)\n index += 1\n'''","sub_path":"editor/squirrel.py","file_name":"squirrel.py","file_ext":"py","file_size_in_byte":8842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"403739562","text":"#!/usr/bin/env python3\n#-*- coding: UTF 8 -*-\n\nimport os\nimport sqlite3\nfrom objs.bot import ExportBot\n\ndatabase = 'miptnews.db'\n\nif not os.path.isfile(database):\n db = sqlite3.connect(database)\n c = db.cursor()\n c.execute('CREATE TABLE miptnews (id INTEGER PRIMARY KEY, text VARCHAR(200), link VARCHAR(100), date UNIX_TIME, publish UNIX_TIME, chat_id INTEGER, message_id INTEGER)')\n\nbot = ExportBot()\nbot.detect()\nbot.public_posts()\n","sub_path":"miptnews.py","file_name":"miptnews.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"529893265","text":"\"\"\"Helper methods for tests of custom Gym environments.\n\nThis is used in our test suite in `tests/test_envs.py`. It is also used in sister\nprojects such as `imitation`, and may be useful in other codebases.\n\"\"\"\n\nimport re\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n)\n\nimport gym\nfrom gym.envs.mujoco import mujoco_env\nimport numpy as np\n\nStep = Tuple[Any, Optional[float], bool, Mapping[str, Any]]\nRollout = Sequence[Step]\n\"\"\"A sequence of 4-tuples (obs, rew, done, info) as returned by `get_rollout`.\"\"\"\n\n\ndef make_env_fixture(\n skip_fn: Callable[[str], None],\n) -> Callable[[str], Iterator[gym.Env]]:\n \"\"\"Creates a fixture function, calling `skip_fn` when dependencies are missing.\n\n For example, in `pytest`, one would use::\n\n env = pytest.fixture(make_env_fixture(skip_fn=pytest.skip))\n\n Then any method with an `env` parameter will receive the created environment, with\n the `env_name` parameter automatically passed to the fixture.\n\n In `unittest`, one would use::\n\n def skip_fn(msg):\n raise unittest.SkipTest(msg)\n\n make_env = contextlib.contextmanager(make_env_fixture(skip_fn=skip_fn))\n\n And then call `with make_env(env_name) as env:` to create environments.\n\n Args:\n skip_fn: the function called when a dependency is missing to skip the test.\n\n Returns:\n A method to create Gym environments given their name.\n \"\"\"\n\n def f(env_name: str) -> Iterator[gym.Env]:\n \"\"\"Create environment `env_name`.\n\n Args:\n env_name: The name of the environment in the Gym registry.\n\n Yields:\n The created environment.\n\n Raises:\n gym.error.DependencyNotInstalled: if a dependency is missing\n other than MuJoCo (for MuJoCo, the test is instead skipped).\n \"\"\"\n env = None\n try:\n env = gym.make(env_name)\n yield env\n except gym.error.DependencyNotInstalled as e: # pragma: no cover\n if e.args[0].find(\"mujoco_py\") != -1:\n skip_fn(\"Requires `mujoco_py`, which isn't installed.\")\n else:\n raise\n finally:\n if env is not None:\n env.close()\n\n return f\n\n\ndef matches_list(env_name: str, patterns: Iterable[str]) -> bool:\n \"\"\"Returns True if `env_name` matches any of the patterns in `patterns`.\"\"\"\n return any(re.match(env_pattern, env_name) for env_pattern in patterns)\n\n\ndef get_rollout(env: gym.Env, actions: Iterable[Any]) -> Rollout:\n \"\"\"Performs sequence of actions `actions` in `env`.\n\n Args:\n env: the environment to rollout in.\n actions: the actions to perform.\n\n Returns:\n A sequence of 4-tuples (obs, rew, done, info).\n \"\"\"\n ret: List[Step] = [(env.reset(), None, False, {})]\n for act in actions:\n ret.append(env.step(act))\n return ret\n\n\ndef assert_equal_rollout(rollout_a: Rollout, rollout_b: Rollout) -> None:\n \"\"\"Checks rollouts for equality.\n\n Raises:\n AssertionError if they are not equal.\n \"\"\"\n for step_a, step_b in zip(rollout_a, rollout_b):\n ob_a, rew_a, done_a, info_a = step_a\n ob_b, rew_b, done_b, info_b = step_b\n np.testing.assert_equal(ob_a, ob_b)\n assert rew_a == rew_b\n assert done_a == done_b\n np.testing.assert_equal(info_a, info_b)\n\n\ndef has_same_observations(rollout_a: Rollout, rollout_b: Rollout) -> bool:\n \"\"\"True if `rollout_a` and `rollout_b` have the same observations.\"\"\"\n obs_list_a = [step[0] for step in rollout_a]\n obs_list_b = [step[0] for step in rollout_b]\n return all(np.all(obs_a == obs_b) for obs_a, obs_b in zip(obs_list_a, obs_list_b))\n\n\ndef test_seed(env: gym.Env, env_name: str, deterministic_envs: Iterable[str]) -> None:\n \"\"\"Tests environment seeding.\n\n If non-deterministic, different seeds should produce different transitions.\n If deterministic, should be invariant to seed.\n\n Raises:\n AssertionError if test fails.\n \"\"\"\n env.action_space.seed(0)\n actions = [env.action_space.sample() for _ in range(10)]\n\n # With the same seed, should always get the same result\n seeds = env.seed(42)\n assert isinstance(seeds, list)\n assert len(seeds) > 0\n rollout_a = get_rollout(env, actions)\n\n env.seed(42)\n rollout_b = get_rollout(env, actions)\n\n assert_equal_rollout(rollout_a, rollout_b)\n\n # For most non-deterministic environments, if we try enough seeds we should\n # eventually get a different result. For deterministic environments, all\n # seeds should produce the same starting state.\n def different_seeds_same_rollout(seed1, seed2):\n new_actions = [env.action_space.sample() for _ in range(10)]\n env.seed(seed1)\n new_rollout_1 = get_rollout(env, new_actions)\n env.seed(seed2)\n new_rollout_2 = get_rollout(env, new_actions)\n return has_same_observations(new_rollout_1, new_rollout_2)\n\n is_deterministic = matches_list(env_name, deterministic_envs)\n same_obs = all(different_seeds_same_rollout(seed, seed + 1) for seed in range(100))\n assert same_obs == is_deterministic\n\n\ndef _check_obs(obs: np.ndarray, obs_space: gym.Space) -> None:\n \"\"\"Check obs is consistent with obs_space.\"\"\"\n if obs_space.shape:\n assert obs.shape == obs_space.shape\n assert obs.dtype == obs_space.dtype\n assert obs in obs_space\n\n\ndef _sample_and_check(env: gym.Env, obs_space: gym.Space) -> bool:\n \"\"\"Sample from env and check return value is of valid type.\"\"\"\n act = env.action_space.sample()\n obs, rew, done, info = env.step(act)\n _check_obs(obs, obs_space)\n assert isinstance(rew, float)\n assert isinstance(done, bool)\n assert isinstance(info, dict)\n return done\n\n\ndef test_rollout_schema(\n env: gym.Env,\n steps_after_done: int = 10,\n max_steps: int = 10000,\n) -> None:\n \"\"\"Check custom environments have correct types on `step` and `reset`.\n\n Args:\n env: The environment to test.\n steps_after_done: The number of steps to take after `done` is True, the nominal\n episode termination. This is an abuse of the Gym API, but we would like the\n environments to handle this case gracefully.\n max_steps: Test fails if we do not get `done` after this many timesteps.\n\n Raises:\n AssertionError if test fails.\n \"\"\"\n obs_space = env.observation_space\n obs = env.reset()\n _check_obs(obs, obs_space)\n\n for _ in range(max_steps):\n done = _sample_and_check(env, obs_space)\n if done:\n break\n\n assert done is True, \"did not get to end of episode\"\n\n for _ in range(steps_after_done):\n _sample_and_check(env, obs_space)\n\n\ndef test_premature_step(env: gym.Env, skip_fn, raises_fn) -> None:\n \"\"\"Test that you must call reset() before calling step().\n\n Example usage in pytest:\n test_premature_step(env, skip_fn=pytest.skip, raises_fn=pytest.raises)\n\n Args:\n env: The environment to test.\n skip_fn: called when the environment is incompatible with the test.\n raises_fn: Context manager to check exception is thrown.\n\n Raises:\n AssertionError if test fails.\n \"\"\"\n if hasattr(env, \"sim\") and hasattr(env, \"model\"): # pragma: no cover\n # We can't use isinstance since importing mujoco_py will fail on\n # machines without MuJoCo installed\n skip_fn(\"MuJoCo environments cannot perform this check.\")\n\n act = env.action_space.sample()\n with raises_fn(Exception): # need to call env.reset() first\n env.step(act)\n\n\ndef test_render(env: gym.Env, raises_fn) -> None:\n \"\"\"Test that render() supports the modes declared.\n\n Example usage in pytest:\n test_render(env, raises_fn=pytest.raises)\n\n Args:\n env: The environment to test.\n raises_fn: Context manager to check NotImplementedError is thrown when\n environment metadata indicates modes are supported.\n\n Raises:\n AssertionError: if test fails. This occurs if:\n (a) `env.render(mode=mode)` fails for any mode declared supported\n in `env.metadata[\"render.modes\"]`; (b) env.render() *succeeds* when\n `env.metadata[\"render.modes\"]` is empty; (c) `env.render(mode=\"rgb_array\")`\n returns different values at the same time step.\n \"\"\"\n env.reset() # make sure environment is in consistent state\n\n render_modes = env.metadata[\"render.modes\"]\n if not render_modes:\n # No modes supported -- render() should fail.\n with raises_fn(NotImplementedError):\n env.render()\n else:\n for mode in render_modes:\n env.render(mode=mode)\n\n # WARNING(adam): there seems to be a memory leak with Gym 0.17.3\n # & MuJoCoPy 1.50.1.68. `MujocoEnv.close()` does not call `finish()`\n # on the viewer (commented out) so the resources are not released.\n # For now this is OK, but may bite if we end up testing a lot of\n # MuJoCo environments.\n is_mujoco = isinstance(env.unwrapped, mujoco_env.MujocoEnv)\n if \"rgb_array\" in render_modes and not is_mujoco:\n # Render should not change without calling `step()`.\n # MuJoCo rendering fails this check, ignore -- not much we can do.\n resa = env.render(mode=\"rgb_array\")\n resb = env.render(mode=\"rgb_array\")\n assert np.allclose(resa, resb)\n\n\nclass CountingEnv(gym.Env):\n \"\"\"At timestep `t` of each episode, has `t == obs == reward / 10`.\n\n Episodes finish after `episode_length` calls to `step()`, or equivalently\n `episode_length` actions. For example, if we have `episode_length=5`,\n then an episode has the following observations and rewards:\n\n ```\n obs = [0, 1, 2, 3, 4, 5]\n rews = [10, 20, 30, 40, 50]\n ```\n \"\"\"\n\n def __init__(self, episode_length: int = 5):\n \"\"\"Initialize a CountingEnv.\n\n Params:\n episode_length: The number of actions before each episode ends.\n \"\"\"\n assert episode_length >= 1\n self.observation_space = gym.spaces.Box(low=0, high=np.inf, shape=())\n self.action_space = gym.spaces.Box(low=0, high=np.inf, shape=())\n self.episode_length = episode_length\n self.timestep = None\n\n def reset(self):\n \"\"\"Reset method for CountingEnv.\"\"\"\n t, self.timestep = 0, 1\n return np.array(t, dtype=self.observation_space.dtype)\n\n def step(self, action):\n \"\"\"Step method for CountingEnv.\"\"\"\n if self.timestep is None: # pragma: no cover\n raise RuntimeError(\"Need to reset before first step().\")\n if np.array(action) not in self.action_space: # pragma: no cover\n raise ValueError(f\"Invalid action {action}\")\n if self.timestep > self.episode_length: # pragma: no cover\n raise ValueError(\"Should reset env. Episode is over.\")\n\n t, self.timestep = self.timestep, self.timestep + 1\n obs = np.array(t, dtype=self.observation_space.dtype)\n rew = t * 10.0\n done = t == self.episode_length\n return obs, rew, done, {}\n","sub_path":"src/seals/testing/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":11209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"131744672","text":"\"\"\" Typings from all qcd module \"\"\"\nfrom typing import List, TypedDict, Tuple\nimport enum\n\n\nclass ResultStates(TypedDict):\n zero_amplitude: List[float]\n one_amplitude: List[complex]\n\n\nclass ResultState(TypedDict):\n zero_amplitude: float\n one_amplitude: complex\n\n\nclass ResultStatesReshaped(TypedDict):\n reshaped_coords_x: List[float]\n reshaped_coords_y: List[float]\n reshaped_coords_z: List[float]\n center: float\n\n\nclass ResultProbabilitiesOneChannel(TypedDict):\n x_input_0: List[float]\n x_input_1: List[float]\n z_output_0: List[float]\n z_output_1: List[complex]\n\n\nclass ResultProbabilities(TypedDict):\n x_input_0: List[List[float]]\n x_input_1: List[List[float]]\n z_output_0: List[List[float]]\n z_output_1: List[List[complex]]\n\n\nclass OneShotResults(TypedDict, total=False):\n initial_states_reshaped: ResultStatesReshaped\n final_states: List[ResultStates]\n final_states_reshaped: List[ResultStatesReshaped]\n probabilities: ResultProbabilities\n attenuation_factors: List[float]\n attenuation_factor_per_state: List[List[float]]\n backend_name: str\n initial_one_state_reshaped: Tuple[float, float, float]\n final_one_state_reshaped: List[Tuple[float, float, float]]\n\n\nclass OptimizationSetup(TypedDict, total=False):\n optimizer_algorithms: List[str]\n optimizer_iterations: List[int]\n eta_partitions: int\n number_channels_to_discriminate: int\n plays: int\n initial_parameters: List[float]\n variable_bounds: List[Tuple[float, float]]\n number_third_channels: int\n\n\nclass TheoreticalOptimizationSetup(TypedDict):\n eta_groups: List[List[float]]\n\n\nclass GuessStrategy(enum.Enum):\n one_bit_same_as_measured = 1\n two_bit_base = 2\n two_bit_neural_network = 3\n\n\nclass CloneSetup(TypedDict, total=False):\n total_clones: int\n id_clone: int\n file_name: str\n path: str\n","sub_path":"qcd/typings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"381640217","text":"from igraph import *\nfrom algorithm import *\n\n# g = Graph([(0,1), (0,2), (2,3), (3,4), (4,2), (2,5), (5,0), (6,3), (5,6)])\n#\n# g.vs[\"name\"] = [\"Alice\", \"Bob\", \"Claire\", \"Dennis\", \"Esther\", \"Frank\", \"George\"]\n# g.vs[\"age\"] = [25, 31, 18, 47, 22, 23, 50]\n# g.vs[\"gender\"] = [\"f\", \"m\", \"f\", \"m\", \"f\", \"m\", \"m\"]\n# g.es[\"is_formal\"] = [False, False, True, True, True, False, True, False, False]\n#\n# layout = g.layout(\"kk\")\n# color_dict = {\"m\": \"blue\", \"f\": \"pink\"}\n# visual_style = {}\n# visual_style[\"vertex_size\"] = 20\n# visual_style[\"vertex_color\"] = [color_dict[gender] for gender in g.vs[\"gender\"]]\n# visual_style[\"vertex_label\"] = g.vs[\"name\"]\n# visual_style[\"edge_width\"] = [1 + 2 * int(is_formal) for is_formal in g.es[\"is_formal\"]]\n# visual_style[\"layout\"] = layout\n# visual_style[\"bbox\"] = (300, 300)\n# visual_style[\"margin\"] = 20\n# plot(g, **visual_style)\n\n# g = Graph([(0, 1), (0, 2), (2, 1), (3, 4)])\n# g.vs[\"name\"] = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n# visual_style = {}\n# visual_style[\"layout\"] = g.layout(\"kk\")\n# visual_style[\"bbox\"] = (300, 300)\n# visual_style[\"margin\"] = 20\n# visual_style[\"vertex_label\"] = g.vs[\"name\"]\n# visual_style[\"vertex_color\"] = [\"green\"] * len(g.vs[\"name\"])\n# #plot(g, **visual_style)\n# g.get_adjacency()\n\n\nfull_adjacency_matrix_sample = np.array([\n [-1, 0, 1], # A\n [ 1,-1, 0], # B\n [ 0,-1,-1] # C\n])\nlabels_sample = [\"A\", \"B\", \"C\"]\nweights_sample = [1, 2, 10]\nfull_adjacency_matrix_sample = np.array([\n [-1, -1, 0, 0], # a\n [-1, 0, -1, 0], # b\n [0, -1, -1, 0], # c\n [0, 0, 0, -1], # d\n [0, 0, 0, -1] # e\n])\nlabels_sample = [\"a\", \"b\", \"c\", \"d\", \"e\"]\nweights_sample = [1, 2, 10, 1]\n\ng = PartiallyDirectedGraph(full_adjacency_matrix_sample, labels_sample, weights_sample)\ng.plot()\n","sub_path":"playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"255149017","text":"from plugins.plugin import Plugin\n\n__all__ = [\"FirstPlugin\"]\n\nclass FirstPlugin(Plugin):\n \n name = \"firstPlugin\"\n description = \"\"\n version = '0.0.1'\n\n def __init__(self):\n Plugin.__init__(self)\n \n def scan(self, options={}):\n return \"exec function\"","sub_path":"plugins/system/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"72897783","text":"import pandas as pd\nimport numpy as np\n\n#############################\n# THIS WAS A GIT REPO TEST ##\n##############################\n\nname = ['Mubarak', 'Jida', 'Jude', 'Eddie', 'Zamani']\ndepartment = ['NOC', 'Management', 'Data', 'Security', 'Tourism']\nstate = ['Kwara', 'Lagos', 'Benue', 'Akwa ibom', 'Plateau']\nstaff_ind =['MU', 'JI', 'JU', 'ED', 'ZA']\n\nstaff_dict = {'name':name, 'department':department, 'state':state}\nstaff = pd.DataFrame(staff_dict)\nstaff.index = staff_ind\n\n# print(staff)\n\n# print(staff['name'])\n\n# print(staff[['name']]) \n\n# print(staff[['name', 'state']]) \n\n# print(staff[0:4])\n\n# print(type(staff[0:4][0:2]))\n\n# print(staff[0:4][0:2])\n\n# To import data from file, use the code below\n# variable = pd.read_csv('path/to/csv'/file)\n\n# below is a more robust way of using indexing and selecting data from a panda data frame\n# - loc - (label oriented)\n# - iloc - (index position oriented)\n\ncars = pd.read_csv('cars.csv', index_col=0)\nprint(cars)\n\n# Print out observation for Japan\nprint(cars.loc['JPN'])\nprint(cars.loc[['JPN']])\n# Print out drives_right value of Morocco\nprint(cars.loc['MOR', 'drives_right'])\n\n# Print sub-DataFrame\nprint(cars.loc[['RU', 'MOR'], ['country', 'drives_right']])\n#print(cars.iloc[[4,5], [1,2]])\n\n# Print out drives_right column as Series\nprint(cars.loc[:,'drives_right'])\n#print(type(cars.loc[:,'drives_right']))\n\n# Print out drives_right column as DataFrame\nprint(cars.loc[:,['drives_right']])\n#print(type(cars.loc[:,['drives_right']]))\n\n\n# Print out cars_per_cap and drives_right as DataFrame\nprint(cars.loc[:,['cars_per_cap', 'drives_right']])\n# Extract drives_right column as Series: dr\ndr = cars['drives_right']\n\n####################################################\n# Code for loop that adds COUNTRY column\nfor l, r in cars.iterrows():\n cars.loc[l, \"COUNTRY\"] = r['country'].upper()\n\n# Use .apply(str.upper)\ncars['COUNTRY'] = cars['country'].apply(str.upper)\n\n# Use dr to subset cars: sel\nsel = cars[dr]\n\n# Print sel\nprint (sel)\n# Print out observations for Australia and Egypt\n# print(cars.loc['AUS', 'EG'])\n# print(cars.loc[['AUS', 'EG']])\n\n# print(staff.iloc[:,[2]])\n\n#COMPARISON\n\n#NUMPY Comparison functions\n#==> logical_and()\n#==> logical_or()\n#==> logical_not()\n\nmy_house = np.array([18.0, 20.0, 10.75, 9.50])\nyour_house = np.array([14.0, 24.0, 14.25, 9.0])\nprint(my_house >= 18)\nprint(my_house < your_house)\n# my_house greater than 18.5 or smaller than 10\nprint(np.logical_or(my_house > 18.5, my_house < 10))\n\n# Both my_house and your_house smaller than 11\nprint(np.logical_and(my_house < 11, your_house < 11))\n\n#CONTROL-FLOW\n#If-elif-else\n\nroom = \"Kitchen\"\narea = 20\n\nif room == 'Kitchen' and area < 20:\n print('This is not the perfect Kitchen for the house')\nelif room == 'bed' and area >= 20:\n print('This a perfect sized bedroom!')\nelse:\n print('This is a perfect kitchen')\n \n \n#loop\n# areas list\nareas = [11.25, 18.0, 20.0, 10.75, 9.50]\n\n# Change for loop to use enumerate() and update print()\nfor index,a in enumerate(areas):\n print('room ' + str(index) + ': ' + str(a))\n \n#Looping with dictionaries\n# Definition of dictionary\neurope = {'spain':'madrid', 'france':'paris', 'germany':'berlin',\n 'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }\n \n# Iterate over europe\nfor k, v in europe.items():\n print('the capital of ' + k + ' is ' + v)\n \n # For loop over np_height\nfor no in np_height:\n print(str(no) + \" inches\")\n\n# For loop over np_baseball\nfor bo in np.nditer(np_baseball):\n print(bo)\n \n # Import cars data\nimport pandas as pd\ncars = pd.read_csv('cars.csv', index_col = 0)\n\n# Adapt for loop\nfor lab, row in cars.iterrows() :\n print(lab)\n print(row)\n# Adapt for loop\nfor lab, row in cars.iterrows() :\n print(str(lab) + ': ' + str(row['cars_per_cap']))\n \n \n####################################################\n#RANDOM\n####################################################\n\nnp.random.seed(123)\n\n# Use randint() to simulate a dice\nprint(np.random.randint(1,7))\n\n# Use randint() again\nprint(np.random.randint(1,7))\n\n# Starting step\nstep = 50\n\n# Roll the dice\ndice = np.random.randint(1,7)\n\n# Finish the control construct\nif dice <= 2 :\n step = step - 1\nelif dice > 2 and dice <= 5:\n step = step + 1\nelse:\n step = step + np.random.randint(1,7)\n\n# Print out dice and step\nprint(dice)\nprint(step)\n\n\n# Initialization\nrandom_walk = [0]\n\nfor x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n\n random_walk.append(step)\n\n# Import matplotlib.pyplot as plt\nimport matplotlib.pyplot as plt\n\n# Plot random_walk\nplt.plot(random_walk)\n\n\n\n# Initialize all_walks (don't change this line)\nall_walks = []\n\n# Simulate random walk 10 times\nfor i in range(10) :\n\n # Code from before\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n random_walk.append(step)\n\n # Append random_walk to all_walks\n all_walks.append(random_walk)\n\n# Print all_walks\nprint(all_walks)\n\n\n# numpy and matplotlib imported, seed set.\n\n# initialize and populate all_walks\nall_walks = []\nfor i in range(10) :\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n random_walk.append(step)\n all_walks.append(random_walk)\n\n# Convert all_walks to Numpy array: np_aw\nnp_aw = np.array(all_walks)\n\n# Plot np_aw and show\nplt.plot(np_aw)\n\n# Clear the figure\nplt.clf()\n\n# Transpose np_aw: np_aw_t\nnp_aw_t = np.transpose(np_aw)\n\n# Plot np_aw_t and show\nplt.plot(np_aw_t)\nplt.show()\n\n\n\n# numpy and matplotlib imported, seed set\n\n# Simulate random walk 250 times\nall_walks = []\nfor i in range(250) :\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n\n # Implement clumsiness\n if np.random.rand() <= 0.001:\n step = 0\n\n random_walk.append(step)\n all_walks.append(random_walk)\n\n# Create and plot np_aw_t\nnp_aw_t = np.transpose(np.array(all_walks))\nplt.plot(np_aw_t)\nplt.show()\n\n\n# numpy and matplotlib imported, seed set\n\n# Simulate random walk 500 times\nall_walks = []\nfor i in range(500) :\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n if np.random.rand() <= 0.001 :\n step = 0\n random_walk.append(step)\n all_walks.append(random_walk)\n\n# Create and plot np_aw_t\nnp_aw_t = np.transpose(np.array(all_walks))\n\n# Select last row from np_aw_t: ends\nends = np_aw_t[-1,:]\n\n# Plot histogram of ends, display plot\nplt.hist(ends)\nplt.show()\n","sub_path":"pandapractice.py","file_name":"pandapractice.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"579305395","text":"from fixture.orm import ORMFixture\nfrom model.contact import Contact\nfrom model.group import Group\n\n\n\ndb = ORMFixture(host=\"127.0.0.1\", name=\"addressbook\", user= \"root\",password = \"\")\ndef test_add_contact_in_group(app,check_ui):\n if len(db.get_contact_list()) == 0:\n app.contact.create(Contact(firstname =\"firstname\",lastname = \"lastname\", address= \"address\", home = \"home\",\n mobile = \"mobile\", work = \"work\", phone_2 = \"phone_2\", email = \"email\", email2 = \"email2\",\n email3= \"email3\"))\n if len(db.get_group_list()) == 0:\n app.group.create(Group(name=\"test\"))\n group=None\n contact=None\n group_list=db.get_group_list()\n for index in range(len(group_list)):\n orm_contacts=db.get_contacts_not_in_group(group_list[index])\n group = group_list[index]\n if len(orm_contacts) > 0:\n contact = orm_contacts[0]\n break\n\n if contact is None:\n contact = db.get_contacts_in_group(group)[0]\n app.contact.remove_contact_from_group(contact.id, group.name)\n\n old_contacts_list = db.get_contacts_in_group(group)\n app.contact.add_contact_in_group(contact.id,group.name)\n new_contacts_list = db.get_contacts_in_group(group)\n assert len(new_contacts_list) == len(old_contacts_list) + 1\n assert contact in new_contacts_list\n\n\n\n\n\n","sub_path":"test/test_add_contact_in_group.py","file_name":"test_add_contact_in_group.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"454992953","text":"# Utilities for the demand-related parts of the assignment\n\nimport os\nimport boto\nfrom time import sleep\nfrom fabric.api import *\nfrom cuisine import *\nfrom pprint import pprint\n\n\ndef add_tag(resource, tag):\n\tfor (k,v) in tag.items():\n\t\ts = resource.add_tag(k,v)\n\ndef wait(resources, desired_states):\n\tstates = [x.update() for x in resources]\n\twhile set(states) != set(desired_states):\n\t\tprint('current states: {s} vs. desired states: {t}'.format(s=set(states), t=set(desired_states)))\n\t\tsleep(10)\n\t\tstates = [x.update() for x in resources]\n\n\ndef get_instances_from_reservations(conn=None, reservations=None):\n\t# Get instances from reservations. A reservation gives the instance id but does not populate\n\t# the rest of the instance properties, so a separate call is needed.\n\treservations_w_instances = conn.get_all_instances(instance_ids=[r.instance_id for r in reservations])\n\tinstances = [r.instances[0] for r in reservations_w_instances]\n\t# Exclude instances that are terminated or terminating (there's nothing that can be done with them)\n\tinstances = [i for i in instances if i.state != 'terminated' and i.state != 'shutting-down']\n\treturn instances\n\n\ndef create_volume(conn, instance, user=None, snapshot=None, tag=None):\n\t# create volumes if they don't exist\n\tif snapshot:\n\t\tprint('Creating volume from existing snapshot {s}'.format(s=snapshot))\n\t\tvolume = conn.create_volume(size=1, zone=instance.placement, snapshot=snapshot, volume_type='standard')\n\t\tadd_tag(volume, tag)\n\telse:\n\t\tprint(\"No existing test EBS volume. Creating a new one.\")\n\t\tvolume = conn.create_volume(size=1, zone=instance.placement, snapshot=None, volume_type='standard')\n\t\tadd_tag(volume, tag)\n\t\n\treturn volume\n\n\ndef mount_volume(conn=None, instance=None, volume=None, key_path=None, device='/dev/sdf', ubuntu_device='/dev/xvdf', format=False):\n\t# wait(resources=[instance], desired_states=['running'])\n\ttry:\n\t\t# Attach\n\t\tconn.attach_volume(volume_id=volume.id, instance_id=instance.id, device=device)\n\t\tprint('Attaching volume to {dev}'.format(dev=device))\n\t\twait(resources=[volume], desired_states=['in-use'])\n\n\t\t# Format\n\t\tenv.host_string = instance.public_dns_name\n\t\tenv.user = 'ubuntu'\n\t\tenv.key_filename = key_path\n\t\tprint('Formatting the new volume.')\n\t\tmode_sudo()\n\t\tsudo('mkfs.ext4 -q {dev}'.format(dev=ubuntu_device))\n\t\tdir_ensure(location='/vol', mode='000')\n\t\tsudo('''echo \"{dev} /vol auto noatime 0 0\" | sudo tee -a /etc/fstab'''.format(dev=ubuntu_device))\n\n\t\t# Mount\n\t\tsudo('mount /vol')\n\t\tprint('mounted {id} at {loc}'.format(id=volume.id, loc=ubuntu_device))\n\n\texcept boto.exception.EC2ResponseError as e:\n\t\tprint('Volume {v} is already mounted to an instance. File system and mounting assumed.'.format(v=volume.id))\n\t\tpprint(volume.attach_data)\t\n\n\ndef create_image(conn, instance, tag):\n\t# Create image of running instance\n\tprint('Creating image of instance ' + instance.id)\n\twait(resources=[instance], desired_states=['running'])\n\tfilter = {'tag-value':tag['user']}\n\t# delete any existing image for that user (only one image per user is allowed)\n\timages = conn.get_all_images(filters=filter)\n\tfor i in images:\n\t\tprint('Replacing existing image {id}'.format(id=i.id))\n\t\ti.deregister(delete_snapshot=True)\n\tnew_ami = instance.create_image('asst1-image-user-' + tag['user'])\n\t# need to query for the full image object before the tag can be added\n\timage = conn.get_image(new_ami)\n\tadd_tag(image, tag)\n\treturn new_ami\n\n\ndef create_snapshot(conn, volume, tag):\n\tfilter = {'tag-value':tag['user']}\n\tsnapshots = conn.get_all_snapshots(filters=filter)\n\tfor s in snapshots:\n\t\tprint('Deleting existing disk snapshots for user ' + tag['user'])\n\t\ts.delete()\n\t# create new snapshot and tag to user\n\tsnapshot = volume.create_snapshot('Snapshot of User Data Volume ' + tag['user'])\n\tadd_tag(snapshot, tag)\n\tprint('Created snapshot of User Data Volume ' + tag['user'])\n\treturn snapshot\n\n\ndef unmount_volume(volume, instance, ubuntu_device='/dev/xvdf'):\n\t# Prepare for cuisine\n\tenv.host_string = instance.public_dns_name\n\tenv.user = 'ubuntu'\n\tenv.key_filename = key_paths[user]\n\tmode_sudo()\n\tprint('Unmounting volume {id}'.format(id=volume.id))\n\tmode_sudo()\n\tsudo('umount {dev}'.format(dev=ubuntu_device))\n\tvolume.detach()\n\treturn volume\n\n\ndef mount_ssh_directory(server_instance, client_instance, key_name=None, path='/vol'):\n\t# Mounts a network file share on the client instance that points to a drive on the server\n\t# instance. It uses the program sshfs, which is installed on a client machine and can mount\n\t# folders from any machine that client has SSH access to as network folders. Nothing is required\n\t# to be installed on the server machine.\n\tssh_relative_path = '~/.ssh/{key_name}'.format(key_name=key_name)\n\tssh_absolute_path = os.path.expanduser(ssh_relative_path)\n\n\tenv.host_string = client_instance.public_dns_name\n\tenv.user = 'ubuntu'\n\tenv.key_filename = ssh_absolute_path\n\t# Install prerequisites on client machine\n\tsudo('apt-get install sshfs')\n\tsudo('modprobe fuse')\n\tdir_ensure(location=path, mode='000')\n\t# Copy SSH key to client machine, so it is authorized to SSH into the server\n\tput(ssh_absolute_path, ssh_relative_path)\n\tsudo('chmod 600 {ssh_file}'.format(ssh_file=ssh_relative_path))\n\t# Map directory on server to the same directory on the client machine\n\tsudo('sshfs -o IdentityFile={ssh} ubuntu@{dns}:{path} -o allow_other {path}'.format(dns=server_instance.public_dns_name, path=path, ssh=ssh_relative_path))\n","sub_path":"demand.py","file_name":"demand.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"4702469","text":"## get all the LR file\n\nimport sys\nsys.dont_write_bytecode = True\nsys.path.append('./scripts/')\nimport dbn_reduction\nimport os\n\nresultfolder = 'dbn_reduced/'\n\nf = open('RNA.list')\nrnas = f.readlines()\nf.close()\n\n# dbn_count = { dbn:[count, [rna1,rna2,...] ] }\ndbn_count = {}\nfor rna in rnas:\n\t# get dbn\n\trna = rna.strip()\n\tfn = 'rlt/'+rna+'/dssr-2ndstrs.dbn'\n\tif not os.path.exists(fn):\n\t\tcontinue\n\tf = open('rlt/'+rna+'/dssr-2ndstrs.dbn')\n\tlines = f.readlines()\n\tf.close()\n\n\t# reduce dbn\n\tdbn = dbn_reduction.dbn_heavy_heavy_reduction(lines[2].strip())\n\n\t# count dbn\n\tif dbn in dbn_count:\n\t\tdbn_count[dbn][0] += 1\n\t\tdbn_count[dbn][1].append(rna)\n\telse:\n\t\tdbn_count[dbn] = [1, [rna] ]\n\n# get classification of the reduced dbn\nfout = open('heavy_heavy_reduction_classification.txt','w')\nfor dbn in dbn_count.iterkeys():\n\tfout.write( dbn +'\\n' )\n\tfout.write( str(dbn_count[dbn][0]) +'\\t'+ ', '.join(dbn_count[dbn][1]) +'\\n' )\n\tfout.write( '~~~~~~~~~~~~~~~' +'\\n' )\nfout.close()\n","sub_path":"bak/heavy_heavy_reduce_dbn.py","file_name":"heavy_heavy_reduce_dbn.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"313946503","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torch.utils.data as Data\n\n\ndef get_dataiter(train=True,batch=256,shuffle=True):\n train_minist,test_minist=download_dataset()\n if train is True:\n data_iter=Data.DataLoader(train_minist,batch,shuffle)\n return data_iter\n else:\n data_iter=Data.DataLoader(test_minist,batch,shuffle)\n return data_iter\n\n\ndef show_data(features, labels):\n _, figs = plt.subplots(1, len(features),figsize=(12,12))\n for fig,feature,label in zip(figs,features,labels):\n fig.imshow(feature.view((28,28)).numpy())\n fig.set_title(label)\n\n plt.show()\n\n\ndef download_dataset():\n \"\"\"\n Download fashion minist dataset from github and store it in ~/Datasets/FashionMNIST. If it exist, return train\n data and test data.\n Data format:\n length is 60000(train)/10000(test) and every element is tuple (tensor,int) every tensor represents picture\n which is 1*28*28 (channel height width) or (C*H*W) which is transformed by (H*W*C)\n :return: train_dataset,test_dataset\n \"\"\"\n minist_train = torchvision.datasets.FashionMNIST(root=\"~/Datasets/FashionMNIST\", train=True, download=True,\n transform=transforms.ToTensor())\n minist_test = torchvision.datasets.FashionMNIST(root=\"~/Datasets/FashionMNIST\", train=False, download=True,\n transform=transforms.ToTensor())\n return minist_train, minist_test\n\n\ndef labels2language(labels):\n language = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']\n return [language[i] for i in labels]\n\n\ndef main():\n minist_train, minist_test = download_dataset()\n ind_list = range(10)\n features=[]\n labels=[]\n for ind in ind_list:\n features.append(minist_train[ind][0])\n labels.append(minist_train[ind][1])\n labels_lan = labels2language(labels)\n show_data(features, labels_lan)\n\nif __name__ == \"__main__\":\n main()","sub_path":"MultiLayer/data_show.py","file_name":"data_show.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"85694362","text":"import tensorflow as tf\nimport numpy as np\n\nsess = tf.Session()\ndata_size = 25\ndata_1d = np.random.normal(size=data_size)\nx_input_1d = tf.placeholder(dtype=tf.float32, shape=[data_size])\n\ndef conv_layer_1d(input_1d, my_filter):\n # Make 1d input into 4d\n input_2d = tf.expand_dims(input_1d, 0)\n input_3d = tf.expand_dims(input_2d, 0)\n input_4d = tf.expand_dims(input_3d, 0)\n # Perfom convolution\n convolution_output = tf.nn.conv2d(input_4d,filter=my_filter,strides=[1,1,1,1], padding=\"VALID\")\n # Now drop extra dimensions\n conv_output_1d = tf.squeeze(convolution_output)\n return(conv_output_1d)\n\nmy_filter = tf.Variable(tf.random_normal(shape=[1,5,1,1]))\nmy_convolution_out = conv_layer_1d(x_input_1d, my_filter)\n\ndef activation(input_1d):\n return(tf.nn.relu(input_1d))\n\nmy_activation_output = activation(my_activation_output)\n\ndef max_pool(input_1d, width):\n # First we make the 1d input 4d\n input_2d = tf.expand_dims(input_1d,0)\n input_3d = tf.expand_dims(input_2d,0)\n input_4d = tf.expand_dims(input_3d,3)\n # Perform the max pool operation\n pool_output = tf.nn.max_pool(input_4d, ksize=[1,1,width,1],strides=[1,1,1,1], padding='VALID')\n pool_output_1d = tf.squeeze(pool_output)\n return(pool_output_1d)\n\nmy_maxpool_output = max_pool(my_activation_output, width=5)\n\ndef fully_connected(input_layer, num_outputs):\n # Create weights\n weight_shapes = tf.squeeze(tf.pack([tf.shape(input_layer)]))\n bias = tf.random_normal(shape=[num_outputs])\n # Make input into 2d\n input_layer_2d = tf.expand_dims(input_layer, 0)\n # perform fully connected operations\n","sub_path":"multi_layer_NN.py","file_name":"multi_layer_NN.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"291063589","text":"#\r\n# Copyright 2018 Chris Bang Sørensen, Niels Hvid, Thomas Lemqvist\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r\n# of the Software, and to permit persons to whom the Software is furnished to do so,\r\n# subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\r\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\r\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n#\r\n# Packages to install: (pip install)\r\n# pandas, matplotlib, numpy\r\n#\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.lines as ln\r\n\r\nSoL = 299792458 # Speed of Light ~300 km/s\r\na = SoL / 2400000000 # 2.4 GHz\r\nb = SoL / 433000000 # 433 MHz\r\nc = SoL / 5800000000 # 5.8 GHz\r\nfreqs = {'a': a, 'b': b, 'c': c}\r\nd1 = list(range(0, 101))\r\nd2 = d1.copy()\r\nd2.reverse()\r\ndf = pd.DataFrame({'d1': d1, 'd2': d2})\r\n# df['d1'] = df['d1'] / 1000\r\n# df['d2'] = df['d2'] / 1000\r\nfor l in ['a', 'b', 'c']:\r\n f = freqs[l]\r\n for n in [1, 2, 3]:\r\n key = \"F%i %s\" % (n, l)\r\n df[key] = np.sqrt(\r\n (n * f * (df['d1'] * df['d2']))\r\n /\r\n (df['d1'] + df['d2'])\r\n )\r\n key_neg = '-' + key\r\n df[key_neg] = -1 * df[key]\r\n\r\nprint(df)\r\n\r\nplt.plot(df['d1'], df['F1 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['F2 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['F3 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['-F1 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['-F2 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['-F3 a'], c='teal', linestyle=':')\r\n\r\nplt.plot(df['d1'], df['F1 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['F2 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['F3 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['-F1 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['-F2 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['-F3 b'], c='orange', linestyle='-.')\r\n\r\nplt.plot(df['d1'], df['F1 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['F2 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['F3 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['-F1 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['-F2 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['-F3 c'], c='lime', linestyle='--')\r\n\r\nplt.legend(handles=[\r\n ln.Line2D([], [], color='teal', label='2.4 GHz', linestyle=':'),\r\n ln.Line2D([], [], color='orange', label='433 MHz', linestyle='-.'),\r\n ln.Line2D([], [], color='lime', label='5.8 GHz', linestyle='--'),\r\n])\r\nplt.xlabel('Distance [m]')\r\nplt.ylabel('Radius [m]')\r\nplt.savefig('freznel.png')\r\nplt.show()\r\n\r\nprint(np.max(df['F1 a']))\r\n","sub_path":"lab 8/freznel.py","file_name":"freznel.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"634551088","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 1 21:33:41 2018\n\n@author: Gadcet\n\"\"\"\n\n# Read in the data from all countries and combine\n\nusa = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/usa_data.csv')\nusa['country'] = 'USA'\nkenya = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/kenya_data.csv')\nkenya['country'] = 'Kenya'\nnigeria = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/nigeria_data.csv')\nnigeria['country'] = 'Nigeria'\nuk = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/uk_data.csv')\nuk['country'] = 'UK'\n\ndummy_df = pd.concat([usa,kenya,nigeria,uk])\ndummy_df = dummy_df[['author','category', 'country', 'post_body', 'published_date', 'title']]\nprint(len(dummy_df))\n\ndummy_df.columns = ['Author', 'Category', 'Country', 'Text', 'Date', 'Title']\n\n# Assign views, comments etc to each article and then calculate overall points based on the performance of each article\n\nimport random\nfor x in range(10):\n print(random.randint(100,10000))\n \n# Views\nviews_list = []\ncomments_list = []\nshares_list = []\nlikes_list = []\nfor x in range(len(dummy_df)):\n views_list.append(random.randint(10000,1000000))\n comments_list.append(random.randint(100,10000))\n shares_list.append(random.randint(100,10000))\n likes_list.append(random.randint(100,2500))\n\ndummy_df['Views'] = views_list\ndummy_df['Comments'] = comments_list\ndummy_df['Shares'] = shares_list\ndummy_df['Likes'] = likes_list\n\nprint(dummy_df.sample(10))\n\npoints_list = []\nfor i in range(len(dummy_df)):\n temp = ((dummy_df.iloc[i]['Views']*1) + (dummy_df.iloc[i]['Comments']*50) + (dummy_df.iloc[i]['Shares']*50) + (dummy_df.iloc[i]['Likes']*100))\n points_list.append(temp)\ndummy_df['Points'] = points_list\n\n# Filter out the articles that don't have a proper title\nprint(len(dummy_df))\n\ndummy_df = dummy_df.dropna(how='any',axis=0) \nprint(dummy_df.sample(10))\n\n# Create a final output of training data for the models\n\ndummy_df.to_csv('/Users/Gadcet/Documents/Ani extraction/recommender_dummy_data.csv')\n\ndummy_df['Country'].value_counts()\n","sub_path":"All FIles/prepare_dummy_data.py","file_name":"prepare_dummy_data.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"78594789","text":"# coding=utf8\r\n\r\nimport random, requests, hashlib, time\r\nfrom urllib import parse\r\n\r\ndef md5(s):\r\n m = hashlib.md5()\r\n m.update(s.encode(encoding='UTF-8'))\r\n return m.hexdigest()\r\n\r\n\r\ndef fanyi(keyword):\r\n appid = '20190813000326267' # 你的appid\r\n secretKey = '4O9PzAHHLXHuiJM1HFXB' # 你的密钥\r\n\r\n myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'\r\n q = parse.quote(keyword)\r\n fromLang = 'en'\r\n toLang = 'zh'\r\n salt = random.randint(32768, 65536)\r\n sign = appid + keyword + str(salt) + secretKey\r\n sign = md5(sign)\r\n myurl = myurl + '?appid=' + appid + '&q=' + q + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(\r\n salt) + '&sign=' + sign\r\n\r\n trans_result = ''\r\n try:\r\n result = requests.get(myurl, timeout=10)\r\n if result.status_code == 200:\r\n data = result.json()\r\n print(data)\r\n trans_result = data['trans_result'][0]['dst']\r\n except Exception as e:\r\n print(e)\r\n time.sleep(1)\r\n return trans_result\r\n\r\n\r\nif __name__ == '__main__':\r\n fanyi('苹果')\r\n","sub_path":"amazon/app/fanyi.py","file_name":"fanyi.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"192104237","text":"'''\r\nProgrammer: Alex Urban\r\n06.08.2016\r\nCompiler: Canopy 1.7.2\r\naurban1_3_8\r\n'''\r\n\r\nfrom __future__ import print_function\r\nimport random\r\n\r\ndef days():\r\n ''' This will give me the day of the week!'''\r\n for day in 'MTWRFSS':\r\n print(day + 'day')\r\n for day in range(5,8):\r\n print('It is the ' + str(day) + 'th of September')\r\n \r\n \r\nimport matplotlib.pyplot as plt\r\nplt.ion()\r\n\r\ndef picks():\r\n a = [] #empty list\r\n \r\n a += [random.choice([1,3,10])]\r\n \r\n for choices in range(5):\r\n a += [random.choice([1,3,10])]\r\n \r\n plt.hist(a)\r\n plt.show()\r\n \r\ndef rollHundredPair():\r\n \r\n rollList = []\r\n \r\n for rolls in range(99):\r\n rollList += [random.choice([1,2,3,4,5,6])]\r\n #print(rollList)\r\n \r\n plt.hist(rollList)\r\n plt.show\r\n \r\ndef dice(n):\r\n \r\n sumList = []\r\n diceSum = 0\r\n for items in range(n):\r\n sumList += [random.choice([1,2,3,4,5,6])]\r\n print(sumList)\r\n diceSum = sum(sumList)\r\n print(diceSum)\r\n \r\ndef hangmanDisplay(guessed, secret):\r\n secretHang = ''\r\n for char in secret:\r\n if char in guessed:\r\n secretHang = secretHang + char\r\n else:\r\n secretHang = secretHang + '_'\r\n print(secretHang)\r\n\r\n\r\ndef matches(ticket, winners):\r\n count = 0\r\n for number in winners:\r\n if number in ticket:\r\n count += 1\r\n print(count)\r\n \r\n \r\ndef report(guess, secret):\r\n rightColor = 0\r\n wrongPlace = 0\r\n for color in secret:\r\n if color in guess:\r\n rightColor += 1\r\n for place in secret:\r\n if guess[place] not in secret[place]:\r\n wrongPlace += 1\r\n print(rightColor)\r\n print(wrongPlace)\r\n ","sub_path":"aurban1_3_8.py","file_name":"aurban1_3_8.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"3961745","text":"import argparse\nimport multiprocessing as mp\nimport os\nimport pickle\nimport sys\n\nimport numpy as np\nfrom ase.io import Trajectory, read\nfrom tqdm import tqdm\n\n\ndef check_relaxed_forces(sid, path, thres):\n \"\"\"\n Check all forces in the final frame of adslab is less than a threshold.\n \"\"\"\n final_atoms = read(path)\n forces = final_atoms.get_forces()\n if not (np.max(np.abs(forces)) <= thres):\n print(f\"{sid} doesn't satisfy the force threshold, check trajectory {path}\")\n\n\ndef check_adsorption_energy(sid, path, ref_energy, adsorption_energy):\n final_energy = read(path)\n if (\n not abs((final_energy.get_potential_energy() - ref_energy) - adsorption_energy)\n < 1e-6\n ):\n print(f\"{sid} doesn't satify energy equation\")\n\n\ndef check_DFT_energy(sid, path, e_tol=0.05):\n \"\"\"\n Given a relaxation trajectory, check to see if 1. final energy is less than the initial\n energy, raise error if not. 2) If the energy decreases throuhghout a trajectory (small spikes are okay).\n And 3) if 2 fails, check if it's just a matter of tolerance being too strict by\n considering only the first quarter of the trajectory and sampling every 10th frame\n to check for _almost_ monotonic decrease in energies.\n If any frame(i+1) energy is higher than frame(i) energy, flag it and plot the trajectory.\n \"\"\"\n traj = Trajectory(path)\n if traj[-1].get_potential_energy() > traj[0].get_potential_energy():\n print(\n \"{} has final DFT energy that's higher than the initial energy, check traj {}\".format(\n sid, path\n )\n )\n energies = [traj[i].get_potential_energy() for i in range(len(traj))]\n is_monotonic = all(\n energies[i + 1] - energies[i] < e_tol for i in range(len(energies) - 1)\n )\n if is_monotonic is False:\n print(\n \"There is a spike in energy during the relaxation of {}, double check its trajectory {}\".format(\n sid, path\n )\n )\n is_almost_monotonic = all(\n energies[i] >= energies[i + 10]\n for i in range(0, int(0.25 * len(energies)) - 10, 10)\n )\n if is_almost_monotonic is False:\n print(\n \"almost_monotonic energy check fails, double check trajectory {}\".format(\n path\n )\n )\n\n\ndef check_positions_across_frames_are_different(sid, path):\n \"\"\"\n Given a relaxation trajectory, make sure positions for two consecutive\n frames are not identical.\n \"\"\"\n traj = Trajectory(path)\n positions = [traj[i].get_positions() for i in range(len(traj))]\n is_different = all(\n (positions[i] != positions[i + 1]).any() for i in range(len(positions) - 1)\n )\n if is_different is False:\n print(f\"{sid} has identical positions for some frames, check {path}\")\n\n\ndef read_pkl(fname):\n return pickle.load(open(fname, \"rb\"))\n\n\ndef run_checks(args):\n sysid_list, force_thres, traj_path_by_sysid, ref_energies, ads_energies = args\n for sysid in sysid_list:\n check_relaxed_forces(sysid, traj_path_by_sysid[sysid], force_thres)\n check_adsorption_energy(\n sysid, traj_path_by_sysid[sysid], ref_energies[sysid], ads_energies[sysid]\n )\n check_DFT_energy(sysid, traj_path_by_sysid[sysid])\n check_positions_across_frames_are_different(sysid, traj_path_by_sysid[sysid])\n\n\ndef create_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--sysid_file\",\n type=str,\n help=\"A txt file constains all the system ids (str) of the dataset\",\n )\n parser.add_argument(\n \"--traj_path_by_sysid\",\n type=str,\n help=\"A pickle file that contains a dictionary that maps trajectory path to system ids\",\n )\n parser.add_argument(\n \"--adsorption_energies\",\n type=str,\n help=\"A pickle file that contains a dictionary that maps adsorption energy to system ids\",\n )\n parser.add_argument(\n \"--ref_energies\",\n type=str,\n help=\"A pickle file that contains a dictionary that maps reference energy (E_slab + E_gas) to system ids\",\n )\n parser.add_argument(\n \"--force_tol\",\n type=float,\n default=0.03,\n help=\"Force threshold at which a relaxation is considered converged\",\n )\n parser.add_argument(\n \"--e_tol\",\n type=float,\n default=0.05,\n help=\"Energy threshold to flag a trajectory if potential energy of step i+1 is higher than step i by this amount\",\n )\n parser.add_argument(\n \"--num_workers\", type=int, help=\"Number of processes or no. of dataset chunk\"\n )\n return parser\n\n\nif __name__ == \"__main__\":\n parser = create_parser()\n args = parser.parse_args()\n sysids = open(args.sysid_file).read().splitlines()\n traj_path_by_sysid = read_pkl(args.traj_path_by_sysid)\n adsorption_energy_by_sysid = read_pkl(args.adsorption_energies)\n ref_energy_by_sysid = read_pkl(args.ref_energies)\n force_thres = args.force_tol\n mp_splits = np.array_split(sysids, args.num_workers)\n pool_args = [\n (\n split,\n force_thres,\n traj_path_by_sysid,\n ref_energy_by_sysid,\n adsorption_energy_by_sysid,\n )\n for split in mp_splits\n ]\n pool = mp.Pool(args.num_workers)\n tqdm(pool.imap(run_checks, pool_args), total=len(pool_args))\n","sub_path":"tests/old_tests/check_energy_and_forces.py","file_name":"check_energy_and_forces.py","file_ext":"py","file_size_in_byte":5452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"628031920","text":"\"\"\"\n Fichier : gestion_types_crud.py\n Auteur : OM 2021.03.16\n Gestions des \"routes\" FLASK et des données pour les types.\n\"\"\"\nimport re\nimport sys\n\nfrom flask import flash, session\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\nfrom flask import redirect\nfrom flask_wtf import form\n\nfrom APP_FILMS import obj_mon_application\nfrom APP_FILMS.database.connect_db_context_manager import MaBaseDeDonnee\nfrom APP_FILMS.erreurs.msg_erreurs import *\nfrom APP_FILMS.erreurs.exceptions import *\nfrom APP_FILMS.essais_wtf_forms.wtf_forms_1 import MonPremierWTForm\n\n\n\n\"\"\"\n Auteur : OM 2021.03.16\n Définition d'une \"route\" /boisson_afficher\n\n Test : ex : http://127.0.0.1:5005/boisson_afficher\n\n Paramètres : order_by : ASC : Ascendant, DESC : Descendant\n Id_boisson_sel = 0 >> tous les types.\n Id_boisson_sel = \"n\" affiche le genre dont l'id est \"n\"\n\"\"\"\n\n\n@obj_mon_application.route(\"/type_boisson_afficher//\", methods=['GET', 'POST'])\ndef type_boisson_afficher(order_by, Id_boisson_sel):\n if request.method == \"GET\":\n try:\n try:\n # Renvoie une erreur si la connexion est perdue.\n MaBaseDeDonnee().connexion_bd.ping(False)\n except Exception as erreur:\n flash(f\"Dans Gestion types ...terrible erreur, il faut connecter une base de donnée\", \"danger\")\n print(f\"Exception grave Classe constructeur Gestiontypes {erreur.args[0]}\")\n raise MaBdErreurConnexion(f\"{msg_erreurs['ErreurConnexionBD']['message']} {erreur.args[0]}\")\n\n with MaBaseDeDonnee().connexion_bd.cursor() as mc_afficher:\n if order_by == \"ASC\" and Id_boisson_sel == 0:\n strsql_boisson_afficher = \"\"\"SELECT Id_boisson, Marque, Prix_boisson, Quantite_boisson, Date_achat_boisson, Date_peremption_boisson,\n GROUP_CONCAT(type) as Boissontype FROM t_type_boisson\n RIGHT JOIN t_boisson ON t_boisson.Id_boisson = t_type_boisson.fk_boisson\n LEFT JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n GROUP BY Id_boisson\"\"\"\n mc_afficher.execute(strsql_boisson_afficher)\n elif order_by == \"ASC\":\n # C'EST LA QUE VOUS ALLEZ DEVOIR PLACER VOTRE PROPRE LOGIQUE MySql\n # la commande MySql classique est \"SELECT * FROM t_personne\"\n # Pour \"lever\"(raise) une erreur s'il y a des erreurs sur les noms d'attributs dans la table\n # donc, je précise les champs à afficher\n # Constitution d'un dictionnaire pour associer l'id du genre sélectionné avec un nom de variable\n valeur_Id_boisson_selected_dictionnaire = {\"value_Id_boisson_selected\": Id_boisson_sel}\n strsql_boisson_afficher = \"\"\"SELECTId_boisson, Prix_boisson, Quantite_boisson,Date_achat_boisson,Date_peremption_boisson,Marque,type FROM t_boisson,t_type WHERE Id_boisson = %(value_Id_boisson_selected)s,id_type = %(value_id_type_selected)s\"\"\"\n\n mc_afficher.execute(strsql_boisson_afficher, valeur_Id_boisson_selected_dictionnaire)\n else:\n strsql_boisson_afficher = \"\"\"SELECT Id_boisson, Prix_boisson, Quantite_boisson,Date_achat_boisson,Date_peremption_boisson,Marque,type FROM t_boisson,t_type ORDER BY Id_boisson,id_type DESC\"\"\"\n\n mc_afficher.execute(strsql_boisson_afficher)\n\n data_type_boisson = mc_afficher.fetchall()\n\n print(\"data_type_boisson \", data_type_boisson, \" Type : \", type(data_type_boisson))\n\n # Différencier les messages si la table est vide.\n if not data_type_boisson and Id_boisson_sel == 0:\n flash(\"\"\"La table \"t_personne\" est vide. !!\"\"\", \"warning\")\n elif not data_type_boisson and Id_boisson_sel > 0:\n # Si l'utilisateur change l'Id_personne dans l'URL et que le genre n'existe pas,\n flash(f\"Le Compte demandé n'existe pas !!\", \"warning\")\n else:\n # Dans tous les autres cas, c'est que la table \"t_personne\" est vide.\n # OM 2020.04.09 La ligne ci-dessous permet de donner un sentiment rassurant aux utilisateurs.\n flash(f\"Comptes affichés !!\", \"success\")\n\n except Exception as erreur:\n print(f\"RGG Erreur générale.\")\n # OM 2020.04.09 On dérive \"Exception\" par le \"@obj_mon_application.errorhandler(404)\" fichier \"run_mon_app.py\"\n # Ainsi on peut avoir un message d'erreur personnalisé.\n flash(f\"RGG Exception {erreur}\")\n raise Exception(f\"RGG Erreur générale. {erreur}\")\n raise MaBdErreurOperation(f\"RGG Exception {msg_erreurs['ErreurNomBD']['message']} {erreur}\")\n\n # Envoie la page \"HTML\" au serveur.\n return render_template(\"genres/type_boisson_afficher.html\", data=data_type_boisson)\n\n\n\"\"\"\n nom: edit_type_boisson_selected\n On obtient un objet \"objet_dumpbd\"\n\n Récupère la liste de tous les genres du film sélectionné par le bouton \"MODIFIER\" de \"films_genres_afficher.html\"\n\n Dans une liste déroulante particulière (tags-selector-tagselect), on voit :\n 1) Tous les genres contenus dans la \"t_genre\".\n 2) Les genres attribués au film selectionné.\n 3) Les genres non-attribués au film sélectionné.\n\n On signale les erreurs importantes\n\n\"\"\"\n\n\n@obj_mon_application.route(\"/edit_type_boisson_selected\", methods=['GET', 'POST'])\ndef edit_type_boisson_selected():\n if request.method == \"GET\":\n try:\n with MaBaseDeDonnee().connexion_bd.cursor() as mc_afficher:\n strsql_genres_afficher = \"\"\"SELECT id_type, type FROM t_type ORDER BY id_type ASC\"\"\"\n mc_afficher.execute(strsql_genres_afficher)\n data_genres_all = mc_afficher.fetchall()\n print(\"dans edit_type_boisson_selected ---> data_genres_all\", data_genres_all)\n\n # Récupère la valeur de \"id_film\" du formulaire html \"films_genres_afficher.html\"\n # l'utilisateur clique sur le bouton \"Modifier\" et on récupère la valeur de \"id_film\"\n # grâce à la variable \"id_film_genres_edit_html\" dans le fichier \"films_genres_afficher.html\"\n # href=\"{{ url_for('edit_type_boisson_selected', id_film_genres_edit_html=row.id_film) }}\"\n id_film_genres_edit = request.values['id_film_genres_edit_html']\n\n # Mémorise l'id du film dans une variable de session\n # (ici la sécurité de l'application n'est pas engagée)\n # il faut éviter de stocker des données sensibles dans des variables de sessions.\n session['session_id_film_genres_edit'] = id_film_genres_edit\n\n # Constitution d'un dictionnaire pour associer l'id du film sélectionné avec un nom de variable\n valeur_id_film_selected_dictionnaire = {\"value_valeur_Id_boisson_selected_dict\": id_film_genres_edit}\n\n # Récupère les données grâce à 3 requêtes MySql définie dans la fonction type_boisson_afficher_data\n # 1) Sélection du film choisi\n # 2) Sélection des genres \"déjà\" attribués pour le film.\n # 3) Sélection des genres \"pas encore\" attribués pour le film choisi.\n # ATTENTION à l'ordre d'assignation des variables retournées par la fonction \"type_boisson_afficher_data\"\n data_genre_film_selected, data_genres_films_non_attribues, data_genres_films_attribues = \\\n type_boisson_afficher_data(valeur_id_film_selected_dictionnaire)\n\n print(data_genre_film_selected)\n lst_data_film_selected = [item['id_boisson'] for item in data_genre_film_selected]\n print(\"lst_data_film_selected \", lst_data_film_selected,\n type(lst_data_film_selected))\n\n # Dans le composant \"tags-selector-tagselect\" on doit connaître\n # les genres qui ne sont pas encore sélectionnés.\n lst_data_genres_films_non_attribues = [item['id_type'] for item in data_genres_films_non_attribues]\n session['session_lst_data_genres_films_non_attribues'] = lst_data_genres_films_non_attribues\n print(\"lst_data_genres_films_non_attribues \", lst_data_genres_films_non_attribues,\n type(lst_data_genres_films_non_attribues))\n\n # Dans le composant \"tags-selector-tagselect\" on doit connaître\n # les genres qui sont déjà sélectionnés.\n lst_data_genres_films_old_attribues = [item['id_type'] for item in data_genres_films_attribues]\n session['session_lst_data_genres_films_old_attribues'] = lst_data_genres_films_old_attribues\n print(\"lst_data_genres_films_old_attribues \", lst_data_genres_films_old_attribues,\n type(lst_data_genres_films_old_attribues))\n\n print(\" data data_genre_film_selected\", data_genre_film_selected, \"type \", type(data_genre_film_selected))\n print(\" data data_genres_films_non_attribues \", data_genres_films_non_attribues, \"type \",\n type(data_genres_films_non_attribues))\n print(\" data_genres_films_attribues \", data_genres_films_attribues, \"type \",\n type(data_genres_films_attribues))\n\n # Extrait les valeurs contenues dans la table \"t_genres\", colonne \"intitule_genre\"\n # Le composant javascript \"tagify\" pour afficher les tags n'a pas besoin de l'id_genre\n lst_data_genres_films_non_attribues = [item['type'] for item in data_genres_films_non_attribues]\n print(\"lst_all_genres gf_edit_genre_film_selected \", lst_data_genres_films_non_attribues,\n type(lst_data_genres_films_non_attribues))\n\n except Exception as Exception_edit_genre_film_selected:\n code, msg = Exception_edit_genre_film_selected.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"Exception edit_type_boisson_selected : {sys.exc_info()[0]} \"\n f\"{Exception_edit_genre_film_selected.args[0]} , \"\n f\"{Exception_edit_genre_film_selected}\", \"danger\")\n\n return render_template(\"genres/boisson_type_modifier_tags_dropbox.html\",\n data_genres=data_genres_all,\n data_film_selected=data_genre_film_selected,\n data_genres_attribues=data_genres_films_attribues,\n data_genres_non_attribues=data_genres_films_non_attribues)\n\n\n\"\"\"\n nom: update_type_boisson_selected\n\n Récupère la liste de tous les genres du film sélectionné par le bouton \"MODIFIER\" de \"films_genres_afficher.html\"\n\n Dans une liste déroulante particulière (tags-selector-tagselect), on voit :\n 1) Tous les genres contenus dans la \"t_genre\".\n 2) Les genres attribués au film selectionné.\n 3) Les genres non-attribués au film sélectionné.\n\n On signale les erreurs importantes\n\"\"\"\n\n\n@obj_mon_application.route(\"/update_type_boisson_selected\", methods=['GET', 'POST'])\ndef update_type_boisson_selected():\n if request.method == \"POST\":\n try:\n # Récupère l'id du film sélectionné\n Id_boisson_selected = session['session_id_film_genres_edit']\n print(\"session['session_id_film_genres_edit'] \", session['session_id_film_genres_edit'])\n\n # Récupère la liste des genres qui ne sont pas associés au film sélectionné.\n old_lst_data_genres_films_non_attribues = session['session_lst_data_genres_films_non_attribues']\n print(\"old_lst_data_genres_films_non_attribues \", old_lst_data_genres_films_non_attribues)\n\n # Récupère la liste des genres qui sont associés au film sélectionné.\n old_lst_data_genres_films_attribues = session['session_lst_data_genres_films_old_attribues']\n print(\"old_lst_data_genres_films_old_attribues \", old_lst_data_genres_films_attribues)\n\n # Effacer toutes les variables de session.\n session.clear()\n\n # Récupère ce que l'utilisateur veut modifier comme genres dans le composant \"tags-selector-tagselect\"\n # dans le fichier \"genres_films_modifier_tags_dropbox.html\"\n new_lst_str_genres_films = request.form.getlist('name_select_tags')\n print(\"new_lst_str_genres_films \", new_lst_str_genres_films)\n\n # OM 2021.05.02 Exemple : Dans \"name_select_tags\" il y a ['4','65','2']\n # On transforme en une liste de valeurs numériques. [4,65,2]\n new_lst_int_genre_film_old = list(map(int, new_lst_str_genres_films))\n print(\"new_lst_genre_film \", new_lst_int_genre_film_old, \"type new_lst_genre_film \",\n type(new_lst_int_genre_film_old))\n\n # Pour apprécier la facilité de la vie en Python... \"les ensembles en Python\"\n # https://fr.wikibooks.org/wiki/Programmation_Python/Ensembles\n # OM 2021.05.02 Une liste de \"id_genre\" qui doivent être effacés de la table intermédiaire \"t_genre_film\".\n lst_diff_genres_delete_b = list(\n set(old_lst_data_genres_films_attribues) - set(new_lst_int_genre_film_old))\n print(\"lst_diff_genres_delete_b \", lst_diff_genres_delete_b)\n\n # Une liste de \"id_genre\" qui doivent être ajoutés à la \"t_genre_film\"\n lst_diff_genres_insert_a = list(\n set(new_lst_int_genre_film_old) - set(old_lst_data_genres_films_attribues))\n print(\"lst_diff_genres_insert_a \", lst_diff_genres_insert_a)\n\n # SQL pour insérer une nouvelle association entre\n # \"fk_film\"/\"id_film\" et \"fk_genre\"/\"id_genre\" dans la \"t_genre_film\"\n strsql_insert_genre_film = \"\"\"INSERT INTO t_type_boisson (id_type_boisson, fk_type, fk_boisson)\n VALUES (NULL, %(value_fk_type)s, %(value_fk_boisson)s)\"\"\"\n\n # SQL pour effacer une (des) association(s) existantes entre \"id_film\" et \"id_genre\" dans la \"t_genre_film\"\n strsql_delete_genre_film = \"\"\"DELETE FROM t_type_boisson WHERE fk_type = %(value_fk_type)s AND fk_boisson = %(value_fk_boisson)s\"\"\"\n\n with MaBaseDeDonnee() as mconn_bd:\n # Pour le film sélectionné, parcourir la liste des genres à INSÉRER dans la \"t_genre_film\".\n # Si la liste est vide, la boucle n'est pas parcourue.\n for id_type_ins in lst_diff_genres_insert_a:\n # Constitution d'un dictionnaire pour associer l'id du film sélectionné avec un nom de variable\n # et \"id_type_ins\" (l'id du genre dans la liste) associé à une variable.\n valeurs_film_sel_genre_sel_dictionnaire = {\"value_fk_boisson\": Id_boisson_selected,\n \"value_fk_type\": id_type_ins}\n\n mconn_bd.mabd_execute(strsql_insert_genre_film, valeurs_film_sel_genre_sel_dictionnaire)\n\n # Pour le film sélectionné, parcourir la liste des genres à EFFACER dans la \"t_genre_film\".\n # Si la liste est vide, la boucle n'est pas parcourue.\n for id_type_del in lst_diff_genres_delete_b:\n # Constitution d'un dictionnaire pour associer l'id du film sélectionné avec un nom de variable\n # et \"id_type_del\" (l'id du genre dans la liste) associé à une variable.\n valeurs_film_sel_genre_sel_dictionnaire = {\"value_fk_boisson\": Id_boisson_selected,\n \"value_fk_type\": id_type_del}\n\n # Du fait de l'utilisation des \"context managers\" on accède au curseur grâce au \"with\".\n # la subtilité consiste à avoir une méthode \"mabd_execute\" dans la classe \"MaBaseDeDonnee\"\n # ainsi quand elle aura terminé l'insertion des données le destructeur de la classe \"MaBaseDeDonnee\"\n # sera interprété, ainsi on fera automatiquement un commit\n mconn_bd.mabd_execute(strsql_delete_genre_film, valeurs_film_sel_genre_sel_dictionnaire)\n\n except Exception as Exception_update_genre_film_selected:\n code, msg = Exception_update_genre_film_selected.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"Exception update_type_boisson_selected : {sys.exc_info()[0]} \"\n f\"{Exception_update_genre_film_selected.args[0]} , \"\n f\"{Exception_update_genre_film_selected}\", \"danger\")\n\n # Après cette mise à jour de la table intermédiaire \"t_genre_film\",\n # on affiche les films et le(urs) genre(s) associé(s).\n return redirect(url_for('type_boisson_afficher',order_by=\"ASC\", Id_boisson_sel=0))\n\n\n\"\"\"\n nom: type_boisson_afficher_data\n\n Récupère la liste de tous les genres du film sélectionné par le bouton \"MODIFIER\" de \"films_genres_afficher.html\"\n Nécessaire pour afficher tous les \"TAGS\" des genres, ainsi l'utilisateur voit les genres à disposition\n\n On signale les erreurs importantes\n\"\"\"\n\n\ndef type_boisson_afficher_data(valeur_Id_boisson_selected_dict):\n print(\"valeur_Id_boisson_selected_dict...\", valeur_Id_boisson_selected_dict)\n try:\n\n strsql_film_selected = \"\"\"SELECT id_boisson, Prix_boisson, Quantite_boisson, Date_achat_boisson, Date_peremption_boisson, Marque, GROUP_CONCAT(id_type) as GenresFilms FROM t_type_boisson\n INNER JOIN t_boisson ON t_boisson.id_boisson = t_type_boisson.fk_boisson\n INNER JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n WHERE id_boisson = %(value_valeur_Id_boisson_selected_dict)s\"\"\"\n\n strsql_genres_films_non_attribues = \"\"\"SELECT id_type, type FROM t_type WHERE id_type not in(SELECT id_type as idGenresFilms FROM t_type_boisson\n INNER JOIN t_boisson ON t_boisson.id_boisson = t_type_boisson.fk_boisson\n INNER JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n WHERE id_boisson = %(value_valeur_Id_boisson_selected_dict)s)\"\"\"\n\n strsql_genres_films_attribues = \"\"\"SELECT id_boisson, id_type, type FROM t_type_boisson\n INNER JOIN t_boisson ON t_boisson.id_boisson = t_type_boisson.fk_boisson\n INNER JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n WHERE id_boisson = %(value_valeur_Id_boisson_selected_dict)s\"\"\"\n\n # Du fait de l'utilisation des \"context managers\" on accède au curseur grâce au \"with\".\n with MaBaseDeDonnee().connexion_bd.cursor() as mc_afficher:\n # Envoi de la commande MySql\n mc_afficher.execute(strsql_genres_films_non_attribues, valeur_Id_boisson_selected_dict)\n # Récupère les données de la requête.\n data_genres_films_non_attribues = mc_afficher.fetchall()\n # Affichage dans la console\n print(\"type_boisson_afficher_data ----> data_genres_films_non_attribues \", data_genres_films_non_attribues,\n \" Type : \",\n type(data_genres_films_non_attribues))\n\n # Envoi de la commande MySql\n mc_afficher.execute(strsql_film_selected, valeur_Id_boisson_selected_dict)\n # Récupère les données de la requête.\n data_film_selected = mc_afficher.fetchall()\n # Affichage dans la console\n print(\"data_film_selected \", data_film_selected, \" Type : \", type(data_film_selected))\n\n # Envoi de la commande MySql\n mc_afficher.execute(strsql_genres_films_attribues, valeur_Id_boisson_selected_dict)\n # Récupère les données de la requête.\n data_genres_films_attribues = mc_afficher.fetchall()\n # Affichage dans la console\n print(\"data_genres_films_attribues \", data_genres_films_attribues, \" Type : \",\n type(data_genres_films_attribues))\n\n # Retourne les données des \"SELECT\"\n return data_film_selected, data_genres_films_non_attribues, data_genres_films_attribues\n except pymysql.Error as pymysql_erreur:\n code, msg = pymysql_erreur.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"pymysql.Error Erreur dans type_boisson_afficher_data : {sys.exc_info()[0]} \"\n f\"{pymysql_erreur.args[0]} , \"\n f\"{pymysql_erreur}\", \"danger\")\n except Exception as exception_erreur:\n code, msg = exception_erreur.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"Exception Erreur dans type_boisson_afficher_data : {sys.exc_info()[0]} \"\n f\"{exception_erreur.args[0]} , \"\n f\"{exception_erreur}\", \"danger\")\n except pymysql.err.IntegrityError as IntegrityError_type_boisson_afficher_data:\n code, msg = IntegrityError_type_boisson_afficher_data.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"pymysql.err.IntegrityError Erreur dans type_boisson_afficher_data : {sys.exc_info()[0]} \"\n f\"{IntegrityError_type_boisson_afficher_data.args[0]} , \"\n f\"{IntegrityError_type_boisson_afficher_data}\", \"danger\")\n\n\n\n\n\n\n\n","sub_path":"APP_FILMS/genres/gestion_type_boisson_crud.py","file_name":"gestion_type_boisson_crud.py","file_ext":"py","file_size_in_byte":22081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"651084735","text":"from FullStackWeb.movie_trailer import media , fresh_tomatoes\r\n\r\n\"\"\"\r\nToy Story Movie Details\r\n\"\"\"\r\nts_title=\"Toy Story\"\r\nts_storyline=\"A cowboy doll is profoundly threatened \" \\\r\n \"and jealous when a new spaceman figure supplants him as top toy in a boy's room.\"\r\nts_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\"\r\nts_trailer_youtube_url=\"https://youtu.be/KYz2wyBy3kc?t=5s\"\r\n\r\ntoy_story = media.Movie(ts_title,ts_storyline,ts_poster_image_url,ts_trailer_youtube_url)\r\n\r\n\"\"\"\r\nAvatar Movie\r\n\"\"\"\r\n\r\na_title=\"Avatar\"\r\na_storyline=\"A paraplegic marine dispatched to the moon Pandora on a \" \\\r\n \"unique mission becomes torn between following his orders \" \\\r\n \"and protecting the world he feels is his home\"\r\na_poster_image_url = \"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\"\r\na_trailer_youtube_url=\"https://youtu.be/d1_JBMrrYw8?t=4s\"\r\n\r\navatar = media.Movie(a_title,a_storyline,a_poster_image_url,a_trailer_youtube_url)\r\n\r\n\"\"\"\r\nThe Boss Baby\r\n\"\"\"\r\n\r\nb_title=\"The Boss Baby\"\r\nb_storyline=\"A suit-wearing, briefcase-carrying baby pairs up with his 7-year old\" \\\r\n \" brother to stop the dastardly plot of the CEO of Puppy Co.\"\r\nb_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/0/0e/The_Boss_Baby_poster.jpg\"\r\nb_trailer_youtube_url=\"https://youtu.be/k397HRbTtWI?t=1s\"\r\n\r\nbossBaby = media.Movie(b_title,b_storyline,b_poster_image_url,b_trailer_youtube_url)\r\n\r\n\r\n\"\"\"\r\nMother!\r\n\"\"\"\r\n\r\nm_title=\"Mother !\"\r\nm_storyline=\"A couple's relationship is tested when uninvited guests arrive at their home, disrupting their tranquil existence.\"\r\nm_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/9/94/Mother%212017.jpg\"\r\nm_trailer_youtube_url=\"https://youtu.be/XpICoc65uh0?t=7s\"\r\n\r\nmother = media.Movie(m_title,m_storyline,m_poster_image_url,m_trailer_youtube_url)\r\n\r\n\r\n\"\"\"\r\nM.S. Dhoni: The Untold Story\r\n\r\n\"\"\"\r\n\r\ndhoni_title=\"M.S. Dhoni: The Untold Story\"\r\ndhoni_storyline=\"The untold story of Mahendra Singh Dhoni's journey from ticket \" \\\r\n \"collector to trophy collector - the world-cup-winning captain of the Indian Cricket Team.\"\r\ndhoni_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/3/33/M.S._Dhoni_-_The_Untold_Story_poster.jpg\"\r\ndhoni_trailer_youtube_url=\"https://youtu.be/6L6XqWoS8tw\"\r\n\r\ndhoni = media.Movie(dhoni_title,dhoni_storyline,dhoni_poster_image_url,dhoni_trailer_youtube_url)\r\n\r\n\r\n\"\"\"\r\nDangal\r\n\"\"\"\r\n\r\nDangal_title=\"Dangal\"\r\nDangal_storyline=\"Former wrestler Mahavir Singh Phogat \" \\\r\n \"and his two wrestler daughters struggle towards glory at \" \\\r\n \"the Commonwealth Games in the face of societal oppression.\"\r\nDangal_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/9/99/Dangal_Poster.jpg\"\r\nDangal_trailer_youtube_url=\"https://youtu.be/x_7YlGv9u1g\"\r\n\r\nDangal = media.Movie(Dangal_title,Dangal_storyline,Dangal_poster_image_url,Dangal_trailer_youtube_url)\r\n\r\n#Creating List of Movies.\r\nmovies=[toy_story,avatar,bossBaby,mother,dhoni,Dangal]\r\n\r\n#Launch the WebSite\r\nfresh_tomatoes.open_movies_page(movies)","sub_path":"movie_trailer/entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"626579427","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 10 13:04:10 2017\r\n\r\nAuthor: Tim Caffrey Chan.\r\n\"\"\"\r\n\r\nimport os\r\nimport cv2\r\nimport dlib\r\n\r\n\r\ndef VideoOpen(_filename, _pathname):\r\n \"\"\"\r\n Open a video file and return a videocapture object.\r\n \r\n :Param:\r\n :_filename: The video file name. (i.e. \"Twitter_01\").\r\n \r\n :_pathname: The file directory that contains the video file. (i.e. \".\\Face Recognition\\Facebook Video\").\r\n \r\n :Return: A video object and a boolean type variable indicates whether the video file is open.\r\n \"\"\"\r\n _file_path = _pathname + \"\\\\\"\r\n _file = _file_path + _filename + \".mp4\"\r\n _video = cv2.VideoCapture(_file)\r\n if _video.isOpened():\r\n return (_video, True)\r\n else:\r\n return (None, False)\r\n\r\ndef Video_2_Image(_video, _timestep, _flag, _filename):\r\n \"\"\"\r\n Transform a video frame to image and then save the image into the file directory \"Video_Trans\".\r\n \r\n :Param:\r\n :_video: A video object.\r\n \r\n :_timestep: The time interval for extracting frames.\r\n \r\n :_flag: A boolean variable indicates whether the video object is available. \r\n \"\"\"\r\n _image_id = 0\r\n _file_path = \".\\Face Recognition\\\\Video_Trans\\\\\" + _filename\r\n # Check the directory\r\n if os.path.exists(_file_path):\r\n pass\r\n else:\r\n os.makedirs(_file_path)\r\n # Save image\r\n while _flag:\r\n _flag, _frame = _video.read()\r\n if (_video.get(cv2.CAP_PROP_POS_FRAMES) - 1) % _timestep == 0:\r\n cv2.imwrite(_file_path + \"\\\\\" + \\\r\n str(_image_id) + \".jpg\", _frame)\r\n _image_id += 1\r\n _video.release()\r\n\r\n\r\ndef List_File(_parrent_path, _filetype=\"mp4\"):\r\n \"\"\"\r\n List all the video file (image file) included in the file directory \"_parrent_path\"\r\n \r\n :Param:\r\n :_parrent_path: The file directory. (i.e. \".\\Face Recognition\\\\\")\r\n \r\n :_filetype: The file type, \"jpg\" or \"mp4\"\r\n \"\"\"\r\n _path = []\r\n _file = []\r\n _children_path = os.listdir(_parrent_path)\r\n for _path_temp in _children_path:\r\n if os.path.isdir(_parrent_path + _path_temp):\r\n _files_list = os.listdir(_parrent_path + _path_temp)\r\n for _file_list in _files_list:\r\n if _file_list[-3:] == _filetype:\r\n _path.append(_parrent_path + _path_temp)\r\n _file.append(_file_list[:-4])\r\n return (_path, _file)\r\n\r\ndef Video_Process():\r\n \"\"\"\r\n Main function of the video to image proccess.\r\n \"\"\"\r\n path_name, file_name = List_File(\".\\Face Recognition\\\\\")\r\n for i in range(len(file_name)):\r\n video, flag = VideoOpen(file_name[i], path_name[i])\r\n if flag:\r\n Video_2_Image(video, 150, flag, file_name[i])\r\n else:\r\n print(\"Error Arise\" + str(i))\r\n\r\ndef Boundary_Check(_imgshape=None, _icon=None):\r\n \"\"\"\r\n Make sure the icon boundaries are within the image. And return the extended boundaries. \r\n \r\n :Param:\r\n :_imgshape: The shape of original image.\r\n \r\n :_icon: A rectangle object produces by the face detector.\r\n \r\n :Return: A trimmed tuple representation of the extended boundaries in (left, right, top, bottom) order.\r\n \"\"\"\r\n if _imgshape is None or _icon is None:\r\n return [0, 0, 0, 0]\r\n else:\r\n _iconpos = []\r\n _iconshape = [max(0, _icon.left()), min(_imgshape[1], _icon.right()), \\\r\n max(0, _icon.top()), min(_imgshape[0], _icon.bottom())]\r\n _iconwidth = _iconshape[1] - _iconshape[0]\r\n _iconheight = _iconshape[3] - _iconshape[2]\r\n _iconpos.append(max(0, _iconshape[0] - round(0.6 * _iconwidth)))\r\n _iconpos.append(min(_imgshape[1], _iconshape[1] + round(0.6 * _iconwidth)))\r\n _iconpos.append(max(0, _iconshape[2] - round(0.6 * _iconheight)))\r\n _iconpos.append(min(_imgshape[0], _iconshape[3] + round(0.6 * _iconheight)))\r\n return _iconpos\r\n\r\ndef Image_Cut(_pathname, _filename, counter=0):\r\n \"\"\"\r\n Read the image and check if there are faces, and then cut out faces from the original image \r\n and save them as new jpg file.\r\n \r\n :Param:\r\n \r\n :_pathname: The directory where the image file is located.\r\n \r\n :_filename: The original image file name which you want to run the face detection.\r\n \r\n :counter: A counter that is used to note down the number of icons have been detected.\r\n \r\n :Return: The number of icons have been detected.\r\n \r\n \"\"\"\r\n image_name = _pathname + \"\\\\\" + _filename + \".jpg\"\r\n img = cv2.imread(image_name)\r\n img_temp = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n detector = dlib.get_frontal_face_detector()\r\n faces = detector(img_temp, 1)\r\n if len(faces) > 0:\r\n for i in range(len(faces)):\r\n iconpos = Boundary_Check(img.shape, faces[i])\r\n icon = img[iconpos[2]: iconpos[3], iconpos[0]: iconpos[1], :]\r\n cv2.imwrite(\".\\Face Recognition\\\\Icon_Detection\\\\\" + _pathname[41:] + \"_\" + \\\r\n _filename + \"_\" + str(counter) + \".jpg\", \\\r\n icon)\r\n counter += 1\r\n else:\r\n with open(\".\\Face Recognition\\log.txt\", \"a\") as logfile:\r\n logfile.write(image_name)\r\n logfile.write(\"\\n\")\r\n cv2.imwrite(\".\\Face Recognition\\\\Icon_Undetected\\\\\" + _pathname[41:] + \"_\" + \\\r\n _filename + \".jpg\", img)\r\n return counter\r\n \r\ndef Icon_Detection(_parentpath, _filetype=\"jpg\"):\r\n \"\"\"\r\n Main fnction of face detection.\r\n \"\"\"\r\n path_name, file_name = List_File(_parentpath, _filetype)\r\n counter = 0\r\n for k in range(len(file_name)):\r\n counter = Image_Cut(path_name[k], file_name[k], counter)\r\n","sub_path":"Data_Pretreat.py","file_name":"Data_Pretreat.py","file_ext":"py","file_size_in_byte":5756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"23200620","text":"import random\n\nfrom django.db.models import Count, F\nfrom django.http import HttpResponse\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom api import constants, utilities_notion\nfrom api.models import (\n Question,\n Category,\n Tag,\n Quiz,\n QuestionStat,\n QuizStat,\n Contribution,\n)\nfrom api.serializers import (\n QuestionSerializer,\n CategorySerializer,\n TagSerializer,\n QuizSerializer,\n QuizFullSerializer,\n QuestionStatSerializer,\n QuizStatSerializer,\n ContributionSerializer,\n)\n\n\ndef api_home(request):\n return HttpResponse(\n \"\"\"\n

Welcome to the 'Know Your Planet' API.

\n

Available endpoints:

\n
    \n
  • GET /api/questions
  • \n
  • GET /api/questions/:id
  • \n
  • POST /api/questions/:id/stats
  • \n
  • GET /api/questions/random
  • \n
  • GET /api/questions/stats
  • \n
  • GET /api/categories
  • \n
  • GET /api/tags
  • \n
  • GET /api/authors
  • \n
  • GET /api/quizzes
  • \n
\n \"\"\"\n )\n\n\n@api_view([\"GET\"])\ndef question_list(request):\n \"\"\"\n List all published questions (return them in a random order)\n Optional query parameters:\n - 'category' (string)\n - 'tag' (string)\n - 'author' (string)\n \"\"\"\n questions = Question.objects.published().order_by(\"?\")\n if request.GET.get(\"category\"):\n questions = questions.for_category(request.GET.get(\"category\"))\n if request.GET.get(\"tag\"):\n questions = questions.for_tag(request.GET.get(\"tag\"))\n if request.GET.get(\"author\"):\n questions = questions.for_author(request.GET.get(\"author\"))\n\n serializer = QuestionSerializer(questions, many=True)\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef question_detail(request, pk):\n \"\"\"\n Retrieve a question\n \"\"\"\n try:\n question = Question.objects.get(pk=pk)\n except Question.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n serializer = QuestionSerializer(question)\n return Response(serializer.data)\n\n\n@api_view([\"POST\"])\ndef question_detail_stats(request, pk):\n \"\"\"\n Update the question stats\n \"\"\"\n try:\n question = Question.objects.get(pk=pk)\n except Question.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == \"POST\":\n question_stat = QuestionStat.objects.create(\n question=question,\n answer_choice=request.data[\"answer_choice\"],\n source=request.data[\"source\"],\n )\n\n serializer = QuestionStatSerializer(question_stat)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n@api_view([\"GET\"])\ndef question_random(request):\n \"\"\"\n Retrieve a random question\n Optional query parameters:\n - 'current' (question id)\n - 'category' (string)\n - 'tag' (string)\n - 'author' (string)\n \"\"\"\n questions = Question.objects.published()\n if request.GET.get(\"current\"):\n questions = questions.exclude(pk=request.GET.get(\"current\"))\n if request.GET.get(\"category\"):\n questions = questions.for_category(request.GET.get(\"category\"))\n if request.GET.get(\"tag\"):\n questions = questions.for_tag(request.GET.get(\"tag\"))\n if request.GET.get(\"author\"):\n questions = questions.for_author(request.GET.get(\"author\"))\n\n questions_ids = questions.values_list(\"id\", flat=True)\n questions_random_id = random.sample(list(questions_ids), 1)\n\n question_random = Question.objects.get(pk=questions_random_id[0])\n\n serializer = QuestionSerializer(question_random)\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef question_stats(request):\n \"\"\"\n Retrieve stats on all the data\n \"\"\"\n # question_publish_stats = (\n # Question.objects.values(\"publish\")\n # .annotate(count=Count(\"publish\"))\n # .order_by(\"-count\")\n # )\n question_publish_count = Question.objects.published().count()\n\n return Response(question_publish_count)\n\n\n@api_view([\"GET\"])\ndef category_list(request):\n \"\"\"\n List all categories (with the number of questions per category)\n \"\"\"\n categories = Category.objects.all()\n\n serializer = CategorySerializer(categories, many=True)\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef tag_list(request):\n \"\"\"\n List all tags (with the number of questions per tag)\n \"\"\"\n tags = Tag.objects.all().order_by(\"name\")\n\n serializer = TagSerializer(tags, many=True)\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef author_list(request):\n \"\"\"\n List all authors (with the number of questions per author)\n \"\"\"\n authors = (\n Question.objects.published()\n .values(name=F(\"author\"))\n .annotate(question_count=Count(\"author\"))\n .order_by(\"-question_count\")\n )\n\n return Response(authors)\n\n\n@api_view([\"GET\"])\ndef difficulty_list(request):\n \"\"\"\n List all difficulty levels (with the number of questions per difficulty)\n \"\"\"\n difficulty_levels_query = (\n Question.objects.published()\n .values(value=F(\"difficulty\"))\n .annotate(question_count=Count(\"difficulty\"))\n )\n\n difficulty_levels = []\n for x, y in constants.QUESTION_DIFFICULTY_CHOICES:\n difficulty_levels.append(\n {\n \"name\": y,\n \"value\": x,\n \"question_count\": next(\n (\n item[\"question_count\"]\n for item in difficulty_levels_query\n if item[\"value\"] == x\n ),\n 0,\n ), # noqa\n }\n )\n\n return Response(difficulty_levels)\n\n\n@api_view([\"GET\"])\ndef quiz_list(request):\n \"\"\"\n List all quizzes (with the number of questions per quiz)\n Optional query parameters:\n - 'author' (string)\n - 'full' (string)\n \"\"\"\n quizzes = Quiz.objects.published()\n if request.GET.get(\"author\"):\n quizzes = quizzes.for_author(request.GET.get(\"author\"))\n\n if request.GET.get(\"full\"):\n serializer = QuizFullSerializer(quizzes, many=True)\n else:\n serializer = QuizSerializer(quizzes, many=True)\n\n return Response(serializer.data)\n\n\n@api_view([\"POST\"])\ndef quiz_detail_stats(request, pk):\n \"\"\"\n Update the quiz stats\n \"\"\"\n try:\n quiz = Quiz.objects.get(pk=pk)\n except Quiz.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == \"POST\":\n quiz_stat = QuizStat.objects.create(\n quiz=quiz, answer_success_count=request.data[\"answer_success_count\"]\n )\n\n serializer = QuizStatSerializer(quiz_stat)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n@api_view([\"POST\"])\ndef contribute(request):\n \"\"\"\n Add a contribution\n \"\"\"\n if request.method == \"POST\":\n contribution = Contribution.objects.create(\n text=request.data[\"text\"],\n description=request.data[\"description\"],\n type=request.data[\"type\"],\n )\n\n try:\n utilities_notion.add_contribution_row(\n contribution_text=contribution.text,\n contribution_description=contribution.description,\n contribution_type=contribution.type,\n )\n except Exception as e:\n Contribution.objects.create(text=e)\n\n serializer = ContributionSerializer(contribution)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n@api_view([\"GET\"])\ndef stats(request):\n \"\"\"\n Retrieve stats on all the data\n \"\"\"\n # question_publish_stats = (\n # Question.objects.values(\"publish\")\n # .annotate(count=Count(\"publish\"))\n # .order_by(\"-count\")\n # )\n question_publish_count = Question.objects.published().count()\n question_validation_status_in_progress_count = Question.objects.for_validation_status(\n constants.QUESTION_VALIDATION_STATUS_IN_PROGRESS\n ).count()\n quiz_publish_stats = (\n Quiz.objects.values(\"publish\")\n .annotate(count=Count(\"publish\"))\n .order_by(\"-count\")\n )\n question_answer_count = QuestionStat.objects.count()\n question_category_stats = (\n Category.objects.values(\"name\")\n .annotate(count=Count(\"questions\"))\n .order_by(\"-count\")\n )\n question_tag_stats = (\n Tag.objects.values(\"name\").annotate(count=Count(\"questions\")).order_by(\"-count\")\n )\n question_author_stats = (\n Question.objects.values(name=F(\"author\"))\n .annotate(count=Count(\"author\"))\n .order_by(\"-count\")\n )\n\n return Response(\n {\n \"question_publish_count\": question_publish_count,\n \"question_validation_status_in_progress_count\": question_validation_status_in_progress_count, # noqa\n \"quiz_publish\": quiz_publish_stats,\n \"answer_count\": question_answer_count,\n \"category\": question_category_stats,\n \"tag\": question_tag_stats,\n \"author\": question_author_stats,\n # \"answer\": question_answer_stats\n }\n )\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"251418103","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/11/8 16:34\n# @Author : StephenZ\n# @Site : \n# @File : Case301.py\n# @Purpose :\n# @Software : PyCharm\n# @Copyright: (c) zhangjian 2019\n# @Licence : <@2019>\n\n\"\"\"\n删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。\n\n说明: 输入可能包含了除 ( 和 ) 以外的字符。\n\n示例 1:\n\n输入: \"()())()\"\n输出: [\"()()()\", \"(())()\"]\n示例 2:\n\n输入: \"(a)())()\"\n输出: [\"(a)()()\", \"(a())()\"]\n示例 3:\n\n输入: \")(\"\n输出: [\"\"]\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/remove-invalid-parentheses\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\nfrom logzero import logger\nfrom functools import reduce\nimport copy\n\n\nclass Solution:\n def removeInvalidParentheses(self, s: str) -> list():\n left_quote = s.count(\"(\")\n logger.debug(\"left_quote:\" + str(left_quote))\n right_quote = s.count(\")\")\n logger.debug(\"right_quote\" + str(right_quote))\n left_locate = []\n right_locate = []\n for index, i in enumerate(s):\n if i == \"(\":\n left_locate.append(index)\n elif i == \")\":\n right_locate.append(index)\n logger.debug(\"left_locate:\" + str(left_locate))\n logger.debug(\"right_locate:\" + str(right_locate))\n result = []\n s_list = list(s)\n logger.debug(s_list)\n if left_quote < right_quote:\n for i in right_locate[1:-1]:\n logger.debug(\"s_list:\" + str(s_list))\n new_list = copy.copy(s_list)\n logger.debug(\"new_list:\" + str(new_list))\n # logger.debug(new_list)\n logger.debug(\"i:\" + str(i))\n new_list.pop(i)\n logger.debug(new_list)\n new_ele = reduce(lambda x, y: x + y, new_list)\n logger.debug(\"new_ele:\" + new_ele)\n result.append(new_ele)\n logger.debug(result)\n\n\ns = Solution()\ns.removeInvalidParentheses(\"()())()\")\n\n# s.removeInvalidParentheses(\"(a)())()\")\n# s.removeInvalidParentheses(\")(\")\n\n\n# s.removeInvalidParentheses(\"()()()\")\n# s.removeInvalidParentheses(\"(())()\")\n","sub_path":"Case/Case301.py","file_name":"Case301.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"496312012","text":"import requests\nfrom bs4 import BeautifulSoup\nimport random\nimport pymysql\nfrom multiprocessing import Pool\nimport time\nimport sys\nimport re\nimport get_login_session\nimport cookies_generator as c\nimport asyncio\nimport aiohttp\n\nconn=pymysql.connect(host=\"localhost\",user=\"root\",port=3306,passwd=\"202238\",use_unicode=True,charset=\"utf8\")\ncur=conn.cursor()\ncur.execute(\"USE spider\")\nnon_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)\n\ncur.execute('select * from testfilm')\nDataAll = cur.fetchall()\n\nclass Movie:\n def __init__(self):\n self.entered_links = set() # 已打开过的链接\n self.toenter_links = set() # 将要打开的链接\n self.num = 0 # 统计已抓取的链接数\n self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} # 请求头\n #self.IPList = Proxies.get()\n #起始链接的集合\n #for i in range(10):\n # url = 'https://movie.douban.com/top250?start=%d&filter='%(i*25)\n # req = requests.get(url,cookies = c.get_cookies(),headers = self.headers)\n # for link in re.findall(r'href=\"(https://movie.douban.com/subject/.*?/)\"',req.text):\n # self.toenter_links.add(link)\n\n for link in DataAll:\n self.toenter_links.add(link[-2])\n #print(link[-2])\n #获取电影名\n def MovieName(self,html):\n bs = BeautifulSoup(html,'lxml')\n if bs.find('span',{'property':'v:itemreviewed'}):\n return bs.find('span',{'property':'v:itemreviewed'}).get_text()\n else:\n print(bs)\n return ' '\n\n\n #获取评分 \n def MovieRate(self,html):\n bs = BeautifulSoup(html,'lxml') \n rate_sum = bs.find('div',{'class':'rating_self clearfix','typeof':'v:Rating'})\n rate_list = bs.find('div',{'class':'ratings-on-weight'}).findAll('span')\n if rate_sum.find('a'):\n ratesum = rate_sum.find('a').get_text()\n else:\n ratesum = ' '\n if rate_sum.find('strong'):\n rate = rate_sum.find('strong').get_text()\n else:\n rate = ' '\n RATE = []\n RATE.append(ratesum)\n RATE.append(rate)\n for i in range(1,10,2):\n RATE.append(rate_list[i].get_text())#依次是评价人数、评分、5星,4星,3星,2星,1星\n return RATE\n\n #获取新的电影链接\n def new_links(self,html):\n bs = BeautifulSoup(html,'lxml')\n for link in bs.find('div',{'class':'recommendations-bd'}).findAll('a'):\n self.toenter_links.add(link.attrs['href']) \n self.toenter_links = self.toenter_links - self.entered_links # 防止重复访问\n \n async def output(self,sourcelink):\n try:\n asyncio.sleep(random.random()) # 控制访问频率\n async with aiohttp.ClientSession(cookies = c.get_cookies(),headers = self.headers) as session:\n #ip = random.choice(self.IPList)['https']\n #print(ip)\n ip = 'http://163.44.169.65:8181'\n req = await session.get(sourcelink,proxy = ip,timeout = 5)\n source = await req.text() # 获取电影所在网页源码\n if '200' in str(req) and source and not self.isNeedLogin(str(source)):# 成功获得电影所在页面源码才解析网页\n moviename = self.MovieName(source)\n RATE = self.MovieRate(source)\n cur.execute('insert into testFilm(name,ratenumber,rate,five_star,four_star,three_star,two_star,one_star,film_url)value(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")'%\n (moviename,RATE[0],RATE[1],RATE[2],RATE[3],RATE[4],RATE[5],RATE[6],sourcelink)) # 将电影信息存入数据库\n conn.commit()\n self.num += 1\n print(self.num)\n self.new_links(source) # 获取其他链接\n self.entered_links.add(sourcelink) # 标记为已访问\n except WindowsError as e: # 处理切换IP时发生的错误\n asyncio.sleep(10) #等待IP切换完毕\n except Exception as e:# 处理其他错误\n with open('logging.txt','a') as f:\n f.write((str(e)+'\\n').translate(non_bmp_map))\n \n def isNeedLogin(self,s):# 检测是否被重定向\n if '你的 IP 发出,请' in s[:100]:\n return True\n else:\n return False\n \n def start(self):\n start = time.time()\n loop = asyncio.get_event_loop()\n while(len(self.toenter_links)>0):\n try:\n tasks = [self.output(link) for link in self.toenter_links]\n if(len(tasks) >=200 ):# 控制最大并发数\n for i in range(len(tasks)//200):\n subtask = tasks[i*200:i*200 + 200]\n loop.run_until_complete(asyncio.wait(subtask))\n else:\n loop.run_until_complete(asyncio.wait(tasks))\n except Exception as e:\n with open('logging.txt','a') as f:\n print(e)\n f.write((str(e)+'\\n').translate(non_bmp_map))\n print('%0.2f'%(time.time()-start))\nM=Movie()\nM.start()\n","sub_path":"competition/GetFilm.py","file_name":"GetFilm.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"271446550","text":"\"\"\" Compiled: 2020-09-18 10:38:55 \"\"\"\n\n#__src_file__ = \"extensions/UCITS/etc/FUCITSPartyMethods.py\"\n\"\"\"-------------------------------------------------------------------------------------------------------\nMODULE\n FUCITSPartyMethods\n\n (c) Copyright 2015 SunGard FRONT ARENA. All rights reserved.\n\nDESCRIPTION\n\n-------------------------------------------------------------------------------------------------------\"\"\"\nimport acm\nimport FUCITSHooks\n\nGOVERNMENT_OR_STRONG_ENTITY = ['Government', 'Strong Entity']\nAUTHORISED_CI = \"Authorised Credit Institution\"\nISSUER_OR_ULTIMATE_ISSUER = ['Issuer', 'UCITS UltimateIssuer',]\nNO_UCITS_ISSUER_STATUS = 'No UCITS IssuerStatus'\n'-------------------------------------------------------------------'\ndef IssuerStatusFromHook(party):\n try:\n return FUCITSHooks.IssuerStatus(party)\n except Exception:\n return None\n'-------------------------------------------------------------------'\ndef UCITSIssuerStatus(party):\n issuerStatus = IssuerStatusFromHook(party)\n if str(issuerStatus) in GOVERNMENT_OR_STRONG_ENTITY:\n issuerStatus = \"/\".join(GOVERNMENT_OR_STRONG_ENTITY)\n return issuerStatus if issuerStatus else NO_UCITS_ISSUER_STATUS\n'-------------------------------------------------------------------'\ndef UCITSPartyIsACI(party):\n issuerStatus = UCITSIssuerStatus(party)\n return issuerStatus if issuerStatus == AUTHORISED_CI else \"Other\"\n'-------------------------------------------------------------------'\ndef UltimateIssuerFromHook(party):\n try:\n return FUCITSHooks.UltimateIssuer(party)\n except Exception:\n return None\n'-------------------------------------------------------------------'\ndef UCITSUltimateIssuer(party):\n return UltimateIssuerFromHook(party)\n'-------------------------------------------------------------------'\ndef TotalIssuedDebtFromHook(party):\n try:\n return FUCITSHooks.TotalIssuedDebt(party)\n except Exception:\n return None\n'-------------------------------------------------------------------'\ndef UCITSTotalIssuedDebt(party):\n if party.RiskCountry() is None:\n raise ValueError(\"No country of risk specified\")\n return acm.DenominatedValue(TotalIssuedDebtFromHook(party), CurrencyFromCountry(party.RiskCountry().Name()), None, None)\n'-------------------------------------------------------------------'\ndef CurrencyFromCountry(countryAsString):\n conversionDict = FUCITSHooks.CountryToCurrencyDict()\n return conversionDict.get(str(countryAsString), 'EUR')\n'-------------------------------------------------------------------'\ndef IsPartyGrouping(grouping):\n groupingValue = grouping.GroupingValue()\n if hasattr(groupingValue, 'IsKindOf'):\n return groupingValue.IsKindOf(acm.FParty)\n return False\n'-------------------------------------------------------------------'\ndef IsIssuerOrUltimateIssuerGrouping(grouping):\n return str(grouping.Grouper().DisplayName()) in ISSUER_OR_ULTIMATE_ISSUER","sub_path":"Extensions/_ucits_py/FPythonCode/FUCITSPartyMethods.py","file_name":"FUCITSPartyMethods.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"57909441","text":"from Set3_18 import CTR_Cipher, repeated_xor\r\nfrom Set1_7 import aes128_decrypt\r\n\r\nclass ReadWrite_API(CTR_Cipher):\r\n\r\n def __init__(self):\r\n super(ReadWrite_API, self).__init__(chr(0)*8)\r\n\r\n def edit(self, ciphertext, offset, newtext):\r\n plaintext = self.encrypt(ciphertext)\r\n plaintext = plaintext[:offset] + newtext + plaintext[offset + len(newtext):]\r\n new_ciphertext = self.encrypt(plaintext)\r\n return new_ciphertext\r\n\r\n\r\na = open('25.txt', 'rb')\r\nctext = a.read()\r\na.close()\r\n\r\nAPI = ReadWrite_API()\r\nplaintext = aes128_decrypt(ctext, 'YELLOW SUBMARINE')\r\nciphertext = API.encrypt(plaintext)\r\n\r\n\r\nlength = len(ciphertext)\r\nkeystream = API.edit(ciphertext, 0, chr(0) * length)\r\nguessed_plaintext = repeated_xor(keystream, ciphertext)\r\n","sub_path":"Set4_25.py","file_name":"Set4_25.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"626955494","text":"class test_machine(object):\r\n \"\"\"description of class\"\"\"\r\n\r\n \"\"\"\r\n Function Name: __execute_test__\r\n Input:\r\n Output:\r\n Description:\r\n \"\"\"\r\n def __execute_test__(self, test_files_list, LOGFILE):\r\n for files in test_files_list:\r\n if files:\r\n LOGFILE.write(\"\\nStarting to run test: \" + str(files))\r\n cmd = \"python.exe \" + str(files)\r\n LOGFILE.write(\"\\n\" + cmd)\r\n returnCode = os.system(cmd)\r\n LOGFILE.write(\"\\nTest Results for \" + files + \": \" + str(returnCode))\r\n","sub_path":"scripts/pri-build/test_machine.py","file_name":"test_machine.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"99799472","text":"import os\nimport subprocess\nimport sys\nfrom tokenizer import *\n\n# This script reads in a unigrams file that must be formatted\n# as \"textid, token, count.\"\n\n# If you want to force comma-delimited or tab-delimited splitting (instead of the current\n# whitespace splitting), change this variable.\nsep=None\n\n\n# For now, you have to create these files. (I'd recommend doing it as a named pipe)\n\nunigrams = \"../unigrams.txt\"\nbigrams = \"../bigrams.txt\"\n\n# Bookwormdir is defined in the call.\n\n\n\ndef writeWordIDs():\n \"\"\"\n The wordids are counted directly from the unigrams file.\n \"\"\"\n \n output = open(\"files/texts/wordlist/wordlist.txt\",\"w\")\n global sep\n wordcounts = dict()\n for line in open(unigrams):\n (bookid,word,count) = line.split(sep)\n count = int(count)\n try:\n wordcounts[word] += count\n except KeyError:\n wordcounts[word] = count\n tuples = [(v,k) for k,v in wordcounts.iteritems()]\n tuples.sort()\n tuples.reverse()\n wordid = 0\n for (count,word) in tuples:\n wordid += 1\n output.write(\"\\t\".join([str(wordid),word,str(count)]) + \"\\n\")\n\n\nif sys.argv[1]==\"wordIds\":\n writeWordIDs()\n\n\nif sys.argv[1]==\"encode\":\n encodePreTokenizedStream(open(\"../unigrams.txt\"),levels=[\"unigrams\"])\n #encodePreTokenizedStream(open(\"../bigrams\"),levels=[\"bigrams\"])\n","sub_path":"bookworm/ingestFeatureCounts.py","file_name":"ingestFeatureCounts.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"160057080","text":"# -*- coding: utf-8 -*-\n\nimport distutils.core\nfrom pyramid.config import Configurator\nfrom c2cgeoportal_geoportal import locale_negotiator, add_interface, INTERFACE_TYPE_NGEO\nfrom c2cgeoportal_geoportal.lib.authentication import create_authentication\nfrom testgeomapfish_geoportal.resources import Root\n\n\ndef main(global_config, **settings):\n \"\"\"\n This function returns a Pyramid WSGI application.\n \"\"\"\n del global_config # Unused\n\n config = Configurator(\n root_factory=Root, settings=settings,\n locale_negotiator=locale_negotiator,\n authentication_policy=create_authentication(settings)\n )\n\n # Workaround to not have the error: distutils.errors.DistutilsArgError: no commands supplied\n distutils.core._setup_stop_after = 'config'\n config.include('c2cgeoportal_geoportal')\n distutils.core._setup_stop_after = None\n\n config.add_translation_dirs('testgeomapfish_geoportal:locale/')\n\n # scan view decorator for adding routes\n config.scan()\n\n # add the interfaces\n add_interface(config, 'desktop', INTERFACE_TYPE_NGEO, default=True)\n add_interface(config, 'mobile', INTERFACE_TYPE_NGEO)\n\n return config.make_wsgi_app()\n","sub_path":"geoportal/testgeomapfish_geoportal/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"342800320","text":"from django.conf.urls import patterns, url\n\nfrom data import views, staff_view, public_view, snipet\n\nfrom django.views.generic import RedirectView\nfrom snipet import TaskPdf, StaffProjectPdf, PublicProjectPdf\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n\n url(r'^staff/index/$', views.staff_admin, name='staff_index'),\n\n # data entry\n url(r'^projects/$', views.staff_projects, name='staff_projects_list'),\n url(r'^staff/projects/(?P\\w+)/$', views.staff_project_detail, name='admin_project_details'),\n\n url(r'^entry/projects/$', views.projects_create, name='projects_new'),\n url(r'^projects/delete/(?P\\d+)$', views.projects_delete, name='projects_delete'),\n url(r'^projects/edit/(?P\\d+)$', views.projects_edit, name='projects_edit'),\n\n # url(r'^/public/projects/$', views.staff_projects, name='public projects list'),\n# url(r'^/public/projects/(?P\\d+)/$', views.public_project_detail, name='public project details'),\n\n\turl(r'^agreement/$', views.staff_agreement, name='staff_agreement_list'),\n\turl(r'^entry/agreement/$', views.agreements_create, name='agreement_new'),\n\turl(r'^agreement/edit/(?P\\d+)$', views.agreements_edit, name='agreements_edit'),\n\turl(r'^agreement/delete/(?P\\d+)$', views.agreement_delete, name='agreements_delete'),\n\n url(r'^tasks/$', views.staff_task, name='staff_tasks_list'),\n url(r'^entry/tasks/$', views.tasks_create, name='tasks_new'),\n url(r'^tasks/edit/(?P\\d+)$', views.tasks_edit, name='tasks_edit'),\n url(r'^tasks/delete/(?P\\d+)$', views.tasks_delete, name='tasks_delete'),\n\n url(r'^staff/mda/create/$', views.mda_create, name='mda_new'),\n\n #staff view\n url(r'^staff/projects/$', staff_view.staff_projects, name='projects_list'),\n url(r'^projects/detail/(?P\\w+)/$', staff_view.public_project_detail, name='staff_project_details'),\n url(r'^staff/agreement/$', staff_view.staff_agreement, name='agreement_list'),\n url(r'^staff/agreement/(?P\\w+)/$', staff_view.staff_agreement_detail, name='staff_agreement_detail'),\n url(r'^staff/tasks/$', staff_view.staff_task, name='tasks_list'),\n\n #public view\n url(r'^public/projects/$', public_view.staff_projects, name='public_projects_list'),\n url(r'^public/projects/(?P\\w+)/$', public_view.public_project_detail, name='public_project_details'),\n \n #editor\n url(r'^admin/$', views.admin_data, name='entry'),\n\n url(r'^csv/(?P\\w+)/(?P\\w+)$', snipet.csv_export, name='csv'),\n url(r'^task/(?P\\w+)/(?P\\w+)$', snipet.task_export, name='task'),\n\n url(r'^xls/(?P\\w+)/(?P\\w+)$', snipet.project_xls, name='xls'),\n url(r'^task_xls/(?P\\w+)/(?P\\w+)$', snipet.task_xls, name='task_xls'),\n\n # url(r'^task_pdf/$', snipet.HelloPDFView, name='task_pdf'),\n url(r\"^task.pdf$\", TaskPdf.as_view(), name='task_pdf'),\n url(r\"^staff_project.pdf$\", StaffProjectPdf.as_view(), name='staff_project_pdf'),\n url(r\"^public_project.pdf$\", PublicProjectPdf.as_view(), name='public_project_pdf'),\n)","sub_path":"data/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"595164838","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n\r\ndef steer1(x,y,img): # had to do this operation again and again for many points so created a seperate function for it(this will give steering angle for that particular point)\r\n\r\n if (x - (img.shape[1]/2)) != 0: \r\n theta = math.atan((y-img.shape[0])/(x - (img.shape[1]/2)))\r\n else:\r\n theta = 0\r\n theta = theta*180/math.pi\r\n if theta>0:\r\n theta = -(90 - theta)\r\n else:\r\n theta = (90 + theta)\r\n return theta/90\r\ndef drawBox(img,bbox):# this function will be used if no object is detected only lane is detected\r\n x, y, w, h = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])\r\n X, Y = int(x+w/2) , int(y+ h/2) # here we find the center of the lane tracker\r\n cv2.rectangle(img, (x, y), ((x + w), (y + h)), (255, 0, 255), 3, 3 )\r\n cv2.circle(img, (X,Y), 2, (255,0,0),-1)\r\n cv2.line(img, (X,Y), (int(img.shape[1]/2),img.shape[0]), (0,255,0))# these functions are just for visualisation\r\n steer = steer1(X, Y, img)\r\n cv2.putText(img, str(steer), (320, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)\r\n\r\ndef drawBox1(img,bbox,bbox1):# this will be used if both lane and object are detected\r\n x, y, w, h = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])\r\n X, Y = int(x+w/2) , int(y+ h/2)\r\n x1, y1, w1, h1 = int(bbox1[0]), int(bbox1[1]), int(bbox1[2]), int(bbox1[3])\r\n X1, Y1 = int(x1+w1/2) , int(y1+ h1/2)\r\n steer2 = steer1(X, Y, img)# here both center of object and lane trackers or calculated \r\n a = w1*h1\r\n if a<600:# checks whether object tracker is above the area threshold or not.if not then value by lane tracker would be used \r\n cv2.putText(img, str(steer2), (320, 200), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)\r\n else:# if it is above the threshold then steering values corresponding to the midpoints of the breath lines of the lane tracker rectangle will be calculated, the value corresponding to the centre of the object will also be calculated\r\n steero = steer1(X1, Y1, img)#steering value for center of object tracker.\r\n steerl = steer1(x, y/2, img)# steering value of midpoint of left breath line\r\n steerr = steer1(x+w, y/2, img)# for right line\r\n if (steero>steerl and steero60: myColor = (20,230,20)\r\n elif fps>20: myColor = (230,20,20)\r\n else: myColor = (20,20,230)\r\n cv2.putText(img,str(int(fps)), (75, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, myColor, 2);\r\n cv2.imshow(\"result\",img)\r\n count = count + 1\r\n if cv2.waitKey(1)==ord('q'):\r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()","sub_path":"FinalIP.py","file_name":"FinalIP.py","file_ext":"py","file_size_in_byte":8355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"210762715","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 1 Sep 2016\n\n@author: blaine\n\nthreshold dynamics on undirected graphs\nfixed fractional threshold\n\"\"\"\n\nimport random\n#import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport networkx as nx\n# from networkx.utils import powerlaw_sequence\n# from networkx.generators.classic import empty_graph\n# from networkx.generators.random_graphs import _random_subset\n# from scipy.stats import gaussian_kde\n# from itertools import groupby\n\npath='D:/src/Python Scripts/csd/' \naxis_font = {'fontname':'Arial', 'size':'25'}\n\n\nS=5 # num of realizations (ensemble size)\nT=800 # time steps \nT0=400 # assumed time to ensure stationary state\nntSize=2000 # networks size\nphi0=0.2 # fraction of nodes alive to keep the network 'alive' \n# init_d=0.0 \nlambda0=0.0025 # rate of spontaneous death\n\n\ngtype='rd' # rd (poisson), sf (power law), BA (Barabasi-Albert) \nth=0.50001 #threshold for death spreading\nsurvTh=1-th #threshold for survival\nk_max=500 #cutoff deg\nk_mean=30 #mean deg (rd)\na=3.0 #exponent (sf) \nm=5 #num of added edges (BA)\nk_min=m #min deg (sf)\n\n\n\nif gtype=='rd': \n print ('P_k = Pois(k,z)')\n print (' = ' + str(k_mean) )\n gparam=gtype+'_th'+str(round(th,2))+'z'+str(k_mean)\n \n#==============================================================================\n# continuous power law distr f(x)=(a-1)*x**-a x>=1\n# z=(a-1)/(a-2), or a=2+1./(z-1) 2 = ' + str(deg_avg)) \n gparam=gtype+'_th'+str(round(th,2))+'a'+str(a)+'m'+str(m)\n seq_powerlaw=[]\n ntSize_a=0\n for k in range(k_min,k_max):\n n_k = int(ntSize*c*k**-a)\n seq_powerlaw += n_k*[k]\n ntSize_a += n_k\n ntSize = ntSize_a\n if sum(seq_powerlaw)%2 != 0:\n seq_powerlaw[-1] += 1\nelif gtype=='BA':\n print ('P_k = 2*m*(m+1)/[k*(k+1)*(k+2)]')\n print (' = ' + str(2*m)) \n gparam=gtype+'_th'+str(round(th,2))+'m'+str(m)\n\nprint ('------------------------------------------')\nprint ('threshold = ' + str(th))\n \n\n\n\n'''\nrandom_degree_sequence_graph(sequence[, ...])\t\n simple random graph with the given degree sequence\n\n create_degree_sequence(n[, sfunction, max_tries])\n powerlaw_sequence(n, exponent=2.0) \n discrete_sequence(n, distribution=None, cdistribution=None) \n\nexpected_degree_graph(w, seed=None, selfloops=True)\n random graph with given expected degrees.\n \nfast_gnp_random_graph(n, p[, seed, directed])\ngnp_random_graph(n, p[, seed, directed])\n G_{n,p} random graph, Erdős-Rényi \n\nbarabasi_albert_graph(n, m[, seed])\n growing preferential attachment graph, power law degree distribution \n \n//random_powerlaw_tree(n[, gamma, seed, tries])\n tree with a power law degree distribution\n\nIn general, should draw degree sequence from certain distribution\n and then use random_degree_sequence_graph;\nFor simplicity, use fast_gnp_random_graph for Poisson\n'''\n\n\n##################################\n# input current graph (unstable after initial deaths), \n# original graph (for threshold check), \n# and initial deaths\n# output current graph after cascade (stable)\n# Cascade deaths independent of update order, irrelevant of update scheme\ndef cascade(cgraph,ograph,nodes_d1): \n nodes_d=nodes_d1 \n while nodes_d: \n # find vunerable nodes, i.e. nodes affected by deaths in recent microstep \n nodes_vnr=[]\n for x in nodes_d:\n nodes_vnr += [y for y in ograph.neighbors(x) \n if y not in nodes_vnr and y in cgraph.nodes()] \n# for y in ograph.neighbors(x):\n# if y not in nodes_vnr and y in cgraph.nodes():\n# nodes_vnr.append(y) \n # check survivability of vunerable nodes, record cascade deaths if any \n nodes_d=[]\n for x in nodes_vnr: \n # threshold check\n if len(cgraph.neighbors(x)) < survTh*cgraph.node[x]['sup_num']: \n cgraph.remove_node(x)\n nodes_d.append(x)\n \n return cgraph\n \n \n##################################\n# input current graph, original graph, and recovery rate\n# output current graph after recovery\n# For recovery to be independent of update order, use synchronous update: \n# Admit all potential recovery, then cascade. \ndef recover(cgraph,ograph,lambda1):\n nodes_dead = [x for x in ograph.nodes() if x not in cgraph.nodes()] \n num_r=np.random.binomial(len(nodes_dead),lambda1)\n nodes_r=random.sample(nodes_dead, num_r) \n# nodes_r = [u for u in nodes_dead if random.random() <= lambda1]\n ### recover nodes and attached edges\n for x in nodes_r: \n cgraph.add_node(x)\n cgraph.node[x]['sup_num']=len(ograph.neighbors(x))\n cneighbor = [y for y in ograph.neighbors(x) if y in cgraph.nodes()]\n cgraph.add_edges_from(zip(cneighbor,[x]*len(cneighbor)))\n ### check recovered nodes, cascade to kill unsurvivable ones\n nodes_d=[]\n # first microstep of cascade, assuming all recovered nodes vunerable\n for x in nodes_r: \n if len(cgraph.neighbors(x)) < survTh*cgraph.node[x]['sup_num']: \n cgraph.remove_node(x)\n nodes_d.append(x)\n # ensuing microsteps of cascade \n nodes_d1=nodes_d\n cgraph=cascade(cgraph,ograph,nodes_d1)\n \n return cgraph\n\n\n##################################\n# threshold dynamics on 'grph' for T steps\ndef thrshd_dynam(grph,lambda_ratio,rate_d=lambda0,N=ntSize):\n phi_data=[] \n# csd_data=[]\n rate_r=lambda_ratio*rate_d\n\n grph_live=grph.copy()\n nodes_live=grph_live.nodes()\n num_live=len(nodes_live)\n \n for t in range(0,T+1):\n phi=float(num_live)/N\n phi_data.append(phi)\n if (phiT0 and num_d2<0.3*N: \n# csd_data.append(num_d2)\n# # print num_d2 \n#==============================================================================\n \n grph_live=recover(grph_live,grph,rate_r)\n nodes_live=grph_live.nodes() \n num_live=len(nodes_live)\n \n return (phi_data,t) # data_csd\n \n\n##################################\n# run threshold dynamics for S realizations\ndef dynam_stats(R,rate_d=lambda0,N=ntSize,phi_e=0):\n simParam=gparam+'_R'+str(R)[:6]+'d'+str(rate_d)+'N'+str(N)+'T'+str(T)+'S'+str(S)\n scounter=0 # num of steady realizations \n phi_avg=np.zeros(T+1)\n phi_eq=0\n phi_eq_std=0\n t_c_sim=[]\n t_c=0\n t_c_std=0\n phi_c_sim=[]\n phi_c=0\n phi_c_std=0\n print ('R = ' + str(R))\n \n plt.figure(1,figsize=(15,15),dpi=600) \n plt.title(r'$Poisson, z = 30; \\, R = %.4f$' %R, fontsize = 30) #manual set of fig title\n plt.xlabel(r'$t$', fontsize=30) #**axis_font\n plt.ylabel(r'$\\phi$', fontsize=30)\n plt.tick_params(axis = 'x', top ='off', labelsize = 25)\n plt.tick_params(axis = 'y', right = 'off', labelsize = 25)\n ## with comparison to theoretical phi(t)\n plt.figure(2,figsize=(15,15),dpi=600) \n plt.title(r'$Poisson, z = 30; \\, R = %.4f$' %R, fontsize = 30) \n plt.xlabel(r'$t$', fontsize=30)\n plt.ylabel(r'$\\phi$', fontsize=30)\n plt.tick_params(axis = 'x', top ='off', labelsize = 25)\n plt.tick_params(axis = 'y', right = 'off', labelsize = 25)\n \n for s in range(S):\n time0=time.time()\n ### generate grph\n if gtype == 'rd':\n p=float(k_mean)/N\n grph=nx.fast_gnp_random_graph(N,p) \n elif gtype == 'sf': \n ## simple graph powerlaw sequence configuration model\n grph=nx.random_degree_sequence_graph(seq_powerlaw,tries=1000) \n# powerlaw_a = lambda x: powerlaw_sequence(x, exponent=a)\n# seq=nx.utils.create_degree_sequence(N,powerlaw_a,max_tries=1000)\n# grph=nx.random_degree_sequence_graph(seq,tries=1000)\n ## approximate powerlaw sequence configuration model\n# seq_avg=powerlaw_sequence(N, exponent=a)\n# grph=nx.expected_degree_graph(seq_avg) \n elif gtype == 'BA':\n m=k_mean//2\n grph=nx.barabasi_albert_graph(N,m) \n \n# print '------------------------------------------'\n# print 'graph generated' \n# print 'time = %.2f' %(time.time()-time0) \n for i in range(N):\n grph.node[i]['sup_num']=len(grph.neighbors(i)) \n \n phi_data, endt = thrshd_dynam(grph,R) \n plt.figure(1)\n plt.plot(phi_data,linewidth=3)\n plt.figure(2)\n plt.plot(phi_data,linewidth=3)\n print ('------------------------------------------')\n print ('realization %d complete' %(s+1))\n print ('time = %.2f' %(time.time()-time0)) \n ### sum of phi for steady realizations, phi_c & t_c for collapsing ones\n if endt==T:\n scounter+=1\n phi_array=np.asarray(phi_data)\n phi_avg=np.add(phi_avg,phi_array) # sum over realizations\n else:\n t_c_sim.append(endt)\n print ('t_c = %d' %endt)\n phi_c_sim.append(phi_data[-2])\n print ('phi_c = %.4f' %phi_data[-2]) \n \n ## extract theoretical estimation of phi(t), phi_thry\n fn_phithry = 'phiT_'+gparam+'_R'+str(R)+'.txt'\n fp_phithry = path + fn_phithry\n with open(fp_phithry) as f:\n lines = f.read().splitlines()\n dt_line=[x for x in lines]\n dt=[[x for x in line.rstrip().split()] for line in dt_line]\n phi_thry=[float(x[1]) for x in dt] \n \n ## if a realization is steady, consider active phase, otherwise collapsing phase\n if scounter>0:\n phi_avg=phi_avg/scounter # average over realizations\n phi_eq=np.average(phi_avg[T0:T])\n phi_eq_std=np.std(phi_avg[T0:T])\n np.savetxt('phi_'+simParam+'.txt', phi_avg, fmt='%.4f')\n # adjust axis and save plot for simulations\n plt.figure(1)\n x1,x2,y1,y2 = plt.axis()\n plt.axis((x1,x2,0.5,1))\n plt.savefig('phi_'+simParam+'.jpg')\n # plot phi_thry as comparison, add legend and save\n plt.figure(2) \n plt.axis((x1,x2,0.5,1))\n lineThry,=plt.plot(phi_thry,'k--',linewidth=6,label='theory')\n plt.legend(handles=[lineThry], loc=1, fontsize=30)\n plt.savefig('phi_'+simParam+'_compare.jpg')\n else:\n t_c=np.average(t_c_sim)\n t_c_std=np.std(t_c_sim)\n phi_c=np.average(phi_c_sim)\n phi_c_std=np.std(phi_c_sim)\n # save plot for simulations\n plt.figure(1)\n plt.savefig('phi_'+simParam+'.jpg')\n # plot phi_thry as comparison, add legend and save\n plt.figure(2) \n phi_c_thry=phi_thry[-1]\n t_c_thry=len(phi_thry)\n lineThry,=plt.plot(phi_thry,'k--',linewidth=6,label='theory')\n plt.plot(np.ones(10)*t_c_thry,np.linspace(0,phi_c_thry,num=10),'k--')\n plt.legend(handles=[lineThry], loc=1, fontsize=30) \n plt.savefig('phi_'+simParam+'_compare.jpg')\n \n \n# fig1=plt.figure(1) \n# ax=fi1g.add_subplot(111) \n# plt.text(1.02, 1,r'$\\bar{\\phi} = %.4f$' %phi_eq, transform=ax.transAxes)\n# plt.text(1.02, 0.9,r'$\\phi_{e} = %.4f$' %phi_e, transform=ax.transAxes)\n \n \n if t_c>0:\n print ('------------------------------------------')\n print (' = %.2f' %t_c)\n print ('std(t_c) = %.2f' %t_c_std)\n print (' = %.4f' %phi_c)\n print ('std(t_c) = %.4f' %phi_c_std)\n print ('------------------------------------------')\n # read data from file and add theoretical phi(t)\n \n plt.show() \n \n return phi_avg, phi_eq, phi_eq_std, t_c, t_c_std, phi_c, phi_c_std\n \n\n \n################################## main ##################################\n\n###### simulaton with designated R (active or collapsing phase)\nfp = gparam+'N'+str(ntSize)+'S'+str(S)+'_R'\nRlist=[1.0]\nsv_data_c=[]\n\n\nfor R in Rlist:\n fp = fp+'_'+str(R)[:3]\n phi_avg, phi_eq, phi_eq_std, t_c, t_c_std, phi_c, phi_c_std \\\n = dynam_stats(R,phi_e=0) \n sv_data_c.append((R, t_c, t_c_std, phi_c, phi_c_std)) \n\nnp.savetxt('Tc_Sim_'+fp+'.txt',sv_data_c,fmt='%.4f %.2f %.2f %.4f %.4f')\n\n###### active phase with R calculated theoretically given eta \n#==============================================================================\n# fp = gparam+'N'+str(ntSize)+'T'+str(T)+'S'+str(S)\n# RidxList=[29] \n# Rlist=[]\n# etaList=[]\n# rhoList=[]\n# rhoSimList=[]\n# #rhoTrivList=[]\n# phiList=[]\n# phiSimList=[]\n# sv_R_rho_rhoSim=[] \n# \n# ## get R list (with respect to eta-rho points before cidx) to use for simulation \n# fn_Rdata = 'lambdaRatio_'+gparam+'.txt'\n# fp_Rdata = path + fn_Rdata\n# with open(fp_Rdata) as f:\n# lines = f.read().splitlines()\n# data=[x for x in lines]\n# L=len(data) # L=cidx, idx \\in [1,cidx]\n# dt=[[x for x in line.rstrip().split()] for line in data]\n# dt_R=[float(x[1]) for x in dt] \n# \n# R_array=np.asarray(dt_R) \n# \n# ## get theoretical rho before cidx for comparison, and extend at cidx \n# fn_eta_rho = 'eta-rho_'+gparam+'.txt'\n# fp_eta_rho = path + fn_eta_rho\n# with open(fp_eta_rho) as f1:\n# lines1 = f1.read().splitlines()\n# data1=[x for x in lines1]\n# dt1=[[x for x in line.rstrip().split()] for line in data1]\n# dt_eta_rho=[(int(x[0]),float(x[1]),float(x[2])) for x in dt1] \n# \n# rhoArray=np.asarray([y[2] for y in dt_eta_rho])[:L]\n# rho_extend=np.linspace(rhoArray[-1],1.0,num=10)\n# R_extend=np.ones(10)*R_array[-1]\n# \n# \n# ##\n# for idx in RidxList:\n# R=dt_R[idx-1]\n# Rlist.append(R)\n# # fp = fp+'_R'+str(R)[:4]\n# print '------------------------------------------'\n# eta_eff=dt_eta_rho[idx][1] \n# rho_eff=dt_eta_rho[idx][2]\n# phi_eff=1-rho_eff\n# etaList.append(eta_eff)\n# rhoList.append(rho_eff)\n# phiList.append(phi_eff)\n# \n# ## run simulation using lambda ratio R \n# phi_avg, phi_eq, phi_eq_std, t_c, t_c_std, phi_c, phi_c_std \\\n# = dynam_stats(R,phi_e=phi_eff) \n# \n# rho_eq=1-phi_eq\n# rhoSimList.append(rho_eq) \n# phiSimList.append(phi_eq) \n# print 'rho = '+str(rho_eff)\n# print 'rhoSim = '+str(rho_eq) \n# \n# # rho_trv=1./(1+R)\n# # rhoTrivList.append(rho_trv)\n# # print 'rho_trv = ' + str(rho_trv)\n# # print '------------------------------------------' \n# # sv_R_rho_rhoSim.append((R,rho_eff,rho_eq,rho_trv))\n# \n# sv_R_rho_rhoSim.append((R,rho_eff,rho_eq))\n# np.savetxt('compareRho_'+fp+'.txt',sv_R_rho_rhoSim,fmt='%.4f %.4f %.4f') \n# \n# \n# \n# \n# plt.figure(3,figsize=(10,10), dpi=100)\n# #plt.set_title('axes title')\n# plt.xlabel(r'$R$', **axis_font)\n# plt.ylabel(r'$\\rho^{*}$', **axis_font)\n# line1,=plt.plot(R_array,rhoArray,'b-',label='theory')\n# line2,=plt.plot(R_extend,rho_extend,'b--')\n# lineSim,=plt.plot(Rlist,rhoSimList,'ro',label='simulation')\n# plt.legend(handles=[line1,lineSim], loc=1)\n# plt.savefig('R-rho_'+fp+'_.jpg') \n# plt.show()\n#==============================================================================\n\n#plt.figure(3)\n#plt.xlabel(r'$\\eta$')\n#plt.ylabel(r'$\\rho$')\n#plt.plot(etaList,rhoList,'b-',etaList,rhoSimList,'ro',etaList,rhoTrivList,'g--')\n#plt.savefig('compareRho_'+fp+'.jpg') \n#plt.show()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"matrix/csd_sim_nanxin.py","file_name":"csd_sim_nanxin.py","file_ext":"py","file_size_in_byte":16504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"306799948","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n__author__ = 'zhoutaotao'\n\n\n###4.11 同时迭代多个序列\n\nxpts = [1, 5, 4, 2, 10, 7]\nypts = [101, 78, 37, 15, 62, 99]\nfor x, y in zip(xpts, ypts):\n print(x,y)\n\n\na = [1, 2, 3]\nb = ['w', 'x', 'y', 'z']\nfor i in zip(a,b):\n print(i)\n\n\nfrom itertools import zip_longest\nfor i in zip_longest(a,b):\n print(i)\n\n","sub_path":"IteratorsAndGenerators/Learn11.py","file_name":"Learn11.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"85172186","text":"\"\"\"empty message\n\nRevision ID: ee16c9e05dd4\nRevises: d1a9c75a5078\nCreate Date: 2020-06-13 06:12:20.170141\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ee16c9e05dd4'\ndown_revision = 'd1a9c75a5078'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('vendor',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('cnpj', sa.String(), nullable=False),\n sa.Column('city', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('cnpj')\n )\n op.create_table('product',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('code', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('price', sa.Float(), nullable=False),\n sa.Column('vendor_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['vendor_id'], ['vendor.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_table('tb_vendor')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('tb_vendor',\n sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column('cnpj', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column('city', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='tb_vendor_pkey')\n )\n op.drop_table('product')\n op.drop_table('vendor')\n # ### end Alembic commands ###\n","sub_path":"app/migrations/versions/ee16c9e05dd4_.py","file_name":"ee16c9e05dd4_.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"165943502","text":"'''\n子系统自身信息:\nIP:192.168.127.11\nslave:11\nport:5001\n\n子系统需要检测的信息 上传速度100k/s\n电源电压采样 value1:05 03 07 data crc1 crc2----registerid=07 datatype=float\n电源电流采样 value1:05 03 08 data crc1 crc2----registerid=08 datatype=float\n\n'''\n\n\n\n\n\n\n\n\nimport datetime\n\n\nPort = 5011\n#当前未采用\nurl = ('115.156.163.107', 5001)\n\n\n#upload speed\nTime_interal=0.00000 #1000k/s\n\nimport socket\nimport time\n# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# # 建立连接:\n# s.bind(('115.156.163.107', 6001))\nimport socket\n\n# import crcmod\nimport time\nimport nis_hsdd_configfile\nimport socket\nimport struct\ndef high_pricision_delay(delay_time):\n '''\n it is seconds\n :param delay_time:\n :return:\n '''\n _ = time.perf_counter_ns()+delay_time*1000000000\n while time.perf_counter_ns() < _ :\n pass\n\ndef crccreate(b,length):\n crc16_func = crcmod.mkCrcFun(0x18005, initCrc=0xFFFF, rev=True, xorOut=0x0000)\n return crc16_func(b[0:length])\n\n# 将要发送的数据转换成的ieee 754标准\ndef get_send_msgflowbytes(slave,func,register,length,data):\n if length == 2:\n a = struct.pack('!bbbbh', slave, func, register, length, data) #h 代表的是short\n # print(len(a))\n b=struct.pack('H',crccreate(a[0:6], length=6))\n a=a + b + b'xx'\n elif length==4:\n # print('data',data)\n a = struct.pack('!bbbbf', slave, func, register, length, data)\n # print(len(a))\n b=struct.pack('H',crccreate(a[0:8], length=8))\n a=a + b\n # print(a)\n return a\n\n\n\n\n\ndef level1_udp_send():\n global flag_start\n\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n #不需要建立连接:\n # s.sendto(b'helloworld', ('192.168.100.60', 5000))\n\n # s channels numdata channel1+data+us channel2+data+us ....\n\n\n msg=b''\n import random\n import datetime\n\n from waveproduce import sin_wave,triangle_wave\n\n xsin, ysin = sin_wave(start=0, zhouqi=6.28, midu=0.0628, xdecimals=2, ydecimals=2)\n xtriangle, ytriangle = triangle_wave(start=0, zhouqi=6.28, midu=0.0628, xdecimals=2, ydecimals=2)\n datax = 0\n\n wholemsg_list1 = []\n wholemsg_list2 = []\n\n data1=0\n data2=0\n start_time = time.perf_counter()\n Time_interal = 1\n Time_last = 10\n\n for i in range(10000):\n\n\n msg1 = b''\n msg2 = b''\n channelid1 = struct.pack('!H', 1)\n channelid2 = struct.pack('!H', 2)\n fenmiaocnt =struct.pack('!B', 100)\n length = struct.pack('!B', 100)\n # 将当前的时间转化成对应的sec,然后进行数据的上传\n nowtime = str(datetime.datetime.now())\n curTime = nowtime[11:19]\n us_stampe = int(nowtime[20:26])\n sec = int(curTime[0:2]) * 60 * 60 + int(curTime[3:5]) * 60 + int(curTime[6:8])\n sec_encodee = struct.pack('!I', sec) # 4个字节\n msg1 = channelid1 + length + fenmiaocnt + sec_encodee\n msg2 = channelid2 + length + fenmiaocnt + sec_encodee\n for item in range(100):\n # nowtime = str(datetime.datetime.now())\n data1 = ysin[item]\n data2 = ytriangle[item]\n msg1 += struct.pack('!f', data1) + struct.pack('!I', us_stampe)\n msg2 += struct.pack('!f', data2) + struct.pack('!I', us_stampe)\n\n print(len(msg1),' ',len(msg2))\n\n\n\n print('about to send the data')\n '''\n 子系统需要检测的信息 采集速度1Mhz\n 电源电压采样 value1:10 03 07 04 data crc1 crc2 ----registerid=07 datatype=float\n 电源电流采样 value1:10 03 08 04 data crc1 crc2 ----registerid=08 datatype=float\n '''\n # msg = sec+channels+channel_data_cnt+struct.pack('!f',data)+us_stampe\n # high_pricision_delay(Time_interal)\n time.sleep(Time_interal)\n\n client_socket.sendto(msg1, (nis_hsdd_configfile.hs1_udp_recv_addr,nis_hsdd_configfile.hs1_udp_recv_port))\n client_socket.sendto(msg2, (nis_hsdd_configfile.hs1_udp_recv_addr,nis_hsdd_configfile.hs1_udp_recv_port))\n end_time = time.perf_counter()\n\n\n\n #发送停止数据信号\n msg = b'stopstopst'\n # client_socket.send(msg)\n print('Sys','08 eg power',' 2 channels')\n print('Package nums: ',Time_last/Time_interal)\n print('Sending Speed: ',Time_interal)\n print('Sending Port: ', Port)\n print('Sending Time Cost: ',end_time-start_time)\n client_socket.close()\n\n\n\n\n\n# 可认为是水冷系统,其会上传每10条数据,进行合并一下,然后一起上传。\n# 对于这样10条数据,来说,我们应当能够保证,其采样的时间是十分准确的\n# 10条通过并不是同时采样的,我们如何打上一个合适的时标呢?\ndef zmq_monitor_thread():\n global flag_start\n context = zmq.Context()\n monitored_zmq = context.socket(zmq.SUB)\n monitored_zmq.setsockopt(zmq.SUBSCRIBE,b'')\n monitored_zmqaddr ='tcp://192.168.100.99:7878'\n # monitored_zmq.setsockopt(zmq.IDENTITY,b'udp_11')\n\n monitored_zmq.connect(monitored_zmqaddr)\n # monitored_zmq.setsockopt(zmq.RCVTIMEO,2000)\n jiange=0\n while True:\n\n try:\n x = monitored_zmq.recv()\n if x==b'start':\n flag_start = True\n print(b'start received')\n time.sleep(1)\n udpthread = threading.Thread(target=level1_udp_send)\n udpthread.start()\n except:\n print('time out in zmq')\n\nif __name__=='__main__':\n import zmq\n import threading\n\n global flag_start\n # flag_start = False\n # t1= threading.Thread(target=zmq_monitor_thread)\n # t1.start()\n\n level1_udp_send()\n\n","sub_path":"level2_level3_related/hs1_board_simulate_2020121.py","file_name":"hs1_board_simulate_2020121.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"77563794","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.shortcuts import render, HttpResponse\nimport ConfigParser\nfrom cmdb.models import HostGroup,Host\nimport os\nfrom django.middleware import csrf\nfrom django.contrib.auth.decorators import login_required\nfrom accounts.permission import permission_verify\nfrom django.contrib.auth import get_user_model\nfrom lib.log import dic\nimport json\n\n\n\n\n@login_required()\n@permission_verify()\ndef index(request):\n '''\n [04/Nov/2017 21:22:01] \"GET /dbmanage/?\n csrfmiddlewaretoken=AGmegYcTyfSVvXHZ5TpXLM44ToAuvCphfHyXgx91cCfXWF8gEnimyt8wRzCtkRbV\n &group=1\n &host=0 \n HTTP/1.1\" 200 11575\n :param request: \n :return: \n '''\n temp_name = 'dbmanage/dbmanage_header.html'\n select_group_id=request.GET.get('group')\n select_host_id = request.GET.get('host')\n group = HostGroup.objects.all()\n group_list = []\n host_list = []\n for g in group:\n group_list.append({'group_id': g.id, 'group_name': g.name})\n if select_group_id is None:\n select_group_id = 0\n if int(select_group_id) > 0:\n selected_group_name = HostGroup.objects.values('name').filter(id=select_group_id)[0]['name']\n\n h = Host.objects.values('id','hostname','ip').filter(group=int(select_group_id)).order_by('hostname')\n for hi in h:\n host_list.append({'host_id':hi['id'],'hostname':hi['hostname'],'host_ip':hi['ip']})\n\n return render(request,'dbmanage/index.html',locals())\n\n@login_required()\n@permission_verify()\ndef edit_conf(request):\n if request.GET.get('host') > 0:\n host_id = request.GET.get('host')\n\n if host_id:\n hostname,host_ip = Host.objects.values_list('hostname','ip').get(id=host_id)\n\n temp_name = \"dbmanage/dbmanage_header.html\"\n display_control = \"True\"\n dirs = os.path.dirname(os.path.abspath(__file__))\n config = ConfigParser.ConfigParser()\n all_level = dic\n configfile = dirs+'/conf/base.conf'\n f = dirs+'/conf/{hostname}_{ip}.conf'.format(hostname=hostname,ip='_'.join(host_ip.split('.')))\n configfile_exists = 0\n if os.path.isfile(f):\n configfile = f\n configfile_exists =1\n\n select_group_id = request.GET.get('group')\n select_host_id = request.GET.get('host')\n group = HostGroup.objects.all()\n group_list = []\n host_list = []\n for g in group:\n group_list.append({'group_id': g.id, 'group_name': g.name})\n if select_group_id is None:\n select_group_id = 0\n if int(select_group_id) > 0:\n selected_group_name = HostGroup.objects.values('name').filter(id=select_group_id)[0]['name']\n\n h = Host.objects.values('id', 'hostname', 'ip').filter(group=int(select_group_id)).order_by('hostname')\n for hi in h:\n host_list.append({'host_id': hi['id'], 'hostname': hi['hostname'], 'host_ip': hi['ip']})\n\n if int(select_host_id) > 0:\n for l in host_list:\n if l['host_id'] == int(select_host_id):\n selected_hostname = l['hostname']\n\n\n with open(configfile, 'r') as cfgfile:\n config.readfp(cfgfile)\n\n xbs_decrypt = config.get('Xbstream', 'xbs_decrypt')\n xbstream = config.get('Xbstream', 'xbstream')\n remote_stream = config.get('Xbstream', 'remote_stream')\n xbstream_options = config.get('Xbstream', 'xbstream_options')\n stream = config.get('Xbstream', 'stream')\n remote_dir = config.get('Remote', 'remote_dir')\n remote_conn = config.get('Remote', 'remote_conn')\n remove_original = config.get('Compress', 'remove_original')\n compress = config.get('Compress', 'compress')\n compress_chunk_size = config.get('Compress', 'compress_chunk_size')\n compress_threads = config.get('Compress', 'compress_threads')\n decompress = config.get('Compress', 'decompress')\n chown_command = config.get('Commands', 'chown_command')\n start_mysql_command = config.get('Commands', 'start_mysql_command')\n stop_mysql_command = config.get('Commands', 'stop_mysql_command')\n mysql_password = config.get('MySQL', 'mysql_password')\n mysql_host = config.get('MySQL', 'mysql_host')\n datadir = config.get('MySQL', 'datadir')\n mycnf = config.get('MySQL', 'mycnf')\n mysql_socket = config.get('MySQL', 'mysql_socket')\n mysqladmin = config.get('MySQL', 'mysqladmin')\n mysql_user = config.get('MySQL', 'mysql_user')\n mysql_port = config.get('MySQL', 'mysql_port')\n mysql = config.get('MySQL', 'mysql')\n encrypt = config.get('Encrypt', 'encrypt')\n xbcrypt = config.get('Encrypt', 'xbcrypt')\n encrypt_key = config.get('Encrypt', 'encrypt_key')\n remove_original = config.get('Encrypt', 'remove_original')\n decrypt = config.get('Encrypt', 'decrypt')\n encrypt_chunk_size = config.get('Encrypt', 'encrypt_chunk_size')\n encrypt_threads = config.get('Encrypt', 'encrypt_threads')\n encrypt_key_file = config.get('Encrypt', 'encrypt_key_file')\n xtra_prepare_options = config.get('Backup', 'xtra_prepare_options')\n backup_tool = config.get('Backup', 'backup_tool')\n archive_dir = config.get('Backup', 'archive_dir')\n prepare_tool = config.get('Backup', 'prepare_tool')\n pid_dir = config.get('Backup', 'pid_dir')\n full_backup_interval = config.get('Backup', 'full_backup_interval')\n max_archive_size = config.get('Backup', 'max_archive_size')\n xtra_prepare = config.get('Backup', 'xtra_prepare')\n xtra_options = config.get('Backup', 'xtra_options')\n tmpdir = config.get('Backup', 'tmpdir')\n partial_list = config.get('Backup', 'partial_list')\n xtra_backup = config.get('Backup', 'xtra_backup')\n max_archive_duration = config.get('Backup', 'max_archive_duration')\n pid_runtime_warning = config.get('Backup', 'pid_runtime_warning')\n optional = config.get('Backup', 'optional')\n backupdir = config.get('Backup', 'backupdir')\n gitcmd = config.get('TestConf', 'gitcmd')\n mysql_options = config.get('TestConf', 'mysql_options')\n ps_branches = config.get('TestConf', 'ps_branches')\n xb_configs = config.get('TestConf', 'xb_configs')\n testpath = config.get('TestConf', 'testpath')\n incremental_count = config.get('TestConf', 'incremental_count')\n\n cfgfile.close()\n # return HttpResponse('success')\n return render(request, 'dbmanage/edit.html',locals())\n else:\n return render(request,'dbmanage/index.html',locals())\n\n\n@login_required()\n@permission_verify()\ndef config_save(request):\n temp_name = \"config/config-header.html\"\n if request.method == 'POST':\n # path info\n ansible_path = request.POST.get('ansible_path')\n roles_path = request.POST.get('roles_path')\n pbook_path = request.POST.get('pbook_path')\n scripts_path = request.POST.get('scripts_path')\n # db info\n engine = request.POST.get('engine')\n host = request.POST.get('host')\n port = request.POST.get('port')\n user = request.POST.get('user')\n password = request.POST.get('password')\n database = request.POST.get('database')\n # cmdb_api_token\n token = request.POST.get('token')\n ssh_pwd = request.POST.get('ssh_pwd')\n # log info\n log_path = request.POST.get('log_path')\n log_level = request.POST.get('log_level')\n # mongodb info\n mongodb_ip = request.POST.get('mongodb_ip')\n mongodb_port = request.POST.get('mongodb_port')\n mongodb_user = request.POST.get('mongodb_user')\n mongodb_pwd = request.POST.get('mongodb_pwd')\n mongodb_collection = request.POST.get('mongodb_collection')\n # webssh domain\n webssh_domain = request.POST.get('webssh_domain')\n\n config = ConfigParser.RawConfigParser()\n dirs = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n config.add_section('config')\n config.set('config', 'ansible_path', ansible_path)\n config.set('config', 'roles_path', roles_path)\n config.set('config', 'playbook_path', pbook_path)\n config.set('config', 'scripts_path', scripts_path)\n config.add_section('db')\n config.set('db', 'engine', engine)\n config.set('db', 'host', host)\n config.set('db', 'port', port)\n config.set('db', 'user', user)\n config.set('db', 'password', password)\n config.set('db', 'database', database)\n config.add_section('token')\n config.set('token', 'token', token)\n config.set('token', 'ssh_pwd', token)\n config.add_section('log')\n config.set('log', 'log_path', log_path)\n config.set('log', 'log_level', log_level)\n config.add_section('mongodb')\n config.set('mongodb', 'mongodb_ip', mongodb_ip)\n config.set('mongodb', 'mongodb_port', mongodb_port)\n config.set('mongodb', 'mongodb_user', mongodb_user)\n config.set('mongodb', 'mongodb_pwd', mongodb_pwd)\n config.set('mongodb', 'collection', mongodb_collection)\n config.add_section('webssh')\n config.set('webssh', 'domain', webssh_domain)\n tips = u\"保存成功!\"\n display_control = \"\"\n with open(dirs+'/adminset.conf', 'wb') as cfgfile:\n config.write(cfgfile)\n with open(dirs+'/adminset.conf', 'r') as cfgfile:\n config.readfp(cfgfile)\n a_path = config.get('config', 'ansible_path')\n r_path = config.get('config', 'roles_path')\n p_path = config.get('config', 'playbook_path')\n s_path = config.get('config', 'scripts_path')\n engine = config.get('db', 'engine')\n host = config.get('db', 'host')\n port = config.get('db', 'port')\n user = config.get('db', 'user')\n password = config.get('db', 'password')\n database = config.get('db', 'database')\n token = config.get('token', 'token')\n ssh_pwd = config.get('token', 'ssh_pwd')\n log_path = config.get('log', 'log_path')\n mongodb_ip = config.get('mongodb', 'mongodb_ip')\n mongodb_port = config.get('mongodb', 'mongodb_port')\n mongodb_user = config.get('mongodb', 'mongodb_user')\n mongodb_pwd = config.get('mongodb', 'mongodb_pwd')\n mongodb_collection = config.get('mongodb', 'collection')\n webssh_domain = config.get('webssh', 'domain')\n else:\n display_control = \"none\"\n return render(request, 'config/index.html', locals())\n\n\ndef get_dir(args):\n config = ConfigParser.RawConfigParser()\n dirs = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n with open(dirs+'/adminset.conf', 'r') as cfgfile:\n config.readfp(cfgfile)\n a_path = config.get('config', 'ansible_path')\n r_path = config.get('config', 'roles_path')\n p_path = config.get('config', 'playbook_path')\n s_path = config.get('config', 'scripts_path')\n token = config.get('token', 'token')\n ssh_pwd = config.get('token', 'ssh_pwd')\n log_path = config.get('log', 'log_path')\n log_level = config.get('log', 'log_level')\n mongodb_ip = config.get('mongodb', 'mongodb_ip')\n mongodb_port = config.get('mongodb', 'mongodb_port')\n mongodb_user = config.get('mongodb', 'mongodb_user')\n mongodb_pwd = config.get('mongodb', 'mongodb_pwd')\n mongodb_collection = config.get('mongodb', 'collection')\n webssh_domain = config.get('webssh', 'domain')\n # 根据传入参数返回变量以获取配置,返回变量名与参数名相同\n if args:\n return vars()[args]\n else:\n return HttpResponse(status=403)\n\n\n@login_required()\n@permission_verify()\ndef get_token(request):\n if request.method == 'POST':\n new_token = get_user_model().objects.make_random_password(length=12, allowed_chars='abcdefghjklmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY3456789')\n return HttpResponse(new_token)\n else:\n return True\n","sub_path":"dbmanage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"553700069","text":"\n\n#calss header\nclass _MIDDY():\n\tdef __init__(self,): \n\t\tself.name = \"MIDDY\"\n\t\tself.definitions = [u'a beer glass of medium size, containing 285 ml']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_middy.py","file_name":"_middy.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"73792044","text":"from tensorflow.examples.tutorials.mnist import input_data\r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\nINPUT_LAYER_SIZE = 28 * 28\r\nHIDDEN_LAYER_SIZE = 500\r\nOUTPUT_LAYER_SIZE = 10\r\n# cnn\r\nFULL_SIZE = 512\r\nIMAGE_SIZE = 28\r\nNUM_CHANNELS = 1\r\nCONV1_SIZE = 5\r\nCONV1_DEEP = 32\r\nCONV2_SIZE = 5\r\nCONV2_DEEP = 64\r\n# basic\r\nbatch_size = 100\r\nLR_base = 0.1\r\nLR_decay = 0.99\r\nL2_rate = 0.0001\r\nmoving_average_decay = 0.99\r\ntraining_step = 50000\r\n\r\n\r\ndef fcnet(input_tensor, regularizer):\r\n with tf.variable_scope(\"layer1\"):\r\n weight = tf.get_variable('weight', [INPUT_LAYER_SIZE, HIDDEN_LAYER_SIZE], tf.float32,\r\n initializer=tf.truncated_normal_initializer(stddev=0.1))\r\n bias = tf.get_variable('bias', [1, HIDDEN_LAYER_SIZE], tf.float32, initializer=tf.constant_initializer(0.1))\r\n hidden_layer = tf.nn.relu(tf.add(tf.matmul(input_tensor, weight), bias))\r\n if regularizer is not None:\r\n tf.add_to_collection('losses', regularizer(weight))\r\n with tf.variable_scope('layer2'):\r\n weight = tf.get_variable('weight', [HIDDEN_LAYER_SIZE, OUTPUT_LAYER_SIZE], tf.float32,\r\n initializer=tf.truncated_normal_initializer(stddev=0.1))\r\n bias = tf.get_variable('bias', [1, OUTPUT_LAYER_SIZE], tf.float32, initializer=tf.constant_initializer(0.1))\r\n if regularizer is not None:\r\n tf.add_to_collection('losses', regularizer(weight))\r\n output_layer = tf.add(tf.matmul(hidden_layer, weight), bias)\r\n return output_layer\r\n\r\n\r\ndef leNet(input_tensor, keep_prob, regularizer):\r\n with tf.variable_scope(\"layer1-conv1\"):\r\n weight = tf.get_variable(\"weight\", [CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_DEEP],\r\n initializer=tf.truncated_normal_initializer(stddev=0.1))\r\n bias = tf.get_variable(\"bias\", [CONV1_DEEP], initializer=tf.constant_initializer(0.0))\r\n conv1 = tf.nn.conv2d(input_tensor, weight, [1, 1, 1, 1], 'SAME')\r\n relu1 = tf.nn.relu(tf.nn.bias_add(conv1, bias))\r\n pool1 = tf.nn.max_pool2d(relu1, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\r\n with tf.variable_scope(\"layer2-conv2\"):\r\n weight = tf.get_variable(\"weight\", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP],\r\n initializer=tf.truncated_normal_initializer(stddev=0.1))\r\n bias = tf.get_variable(\"bias\", [CONV2_DEEP], initializer=tf.constant_initializer(0.0))\r\n conv2 = tf.nn.conv2d(pool1, weight, [1, 1, 1, 1], 'SAME')\r\n relu2 = tf.nn.relu(tf.nn.bias_add(conv2, bias))\r\n pool2 = tf.nn.max_pool2d(relu2, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\r\n pool2_shape = pool2.get_shape().as_list()\r\n pool2_size = pool2_shape[1] * pool2_shape[2] * pool2_shape[3]\r\n pool2_flat = tf.reshape(pool2, [-1, pool2_size])\r\n with tf.variable_scope(\"layer3-fc1\"):\r\n weight = tf.get_variable(\"weight\", [pool2_size, FULL_SIZE], initializer=tf.truncated_normal_initializer(stddev=0.1))\r\n bias = tf.get_variable(\"bias\", [FULL_SIZE], initializer=tf.constant_initializer(0.1))\r\n if regularizer is not None:\r\n tf.add_to_collection(\"losses\", regularizer(weight))\r\n fc1 = tf.nn.relu(tf.nn.bias_add(tf.matmul(pool2_flat, weight), bias))\r\n fc1 = tf.nn.dropout(fc1, keep_prob)\r\n with tf.variable_scope(\"layer4-fc2\"):\r\n weight = tf.get_variable(\"weight\", [FULL_SIZE, OUTPUT_LAYER_SIZE], initializer=tf.truncated_normal_initializer(stddev=0.1))\r\n bias = tf.get_variable(\"bias\", [OUTPUT_LAYER_SIZE], initializer=tf.constant_initializer(0.1))\r\n if regularizer is not None:\r\n tf.add_to_collection(\"losses\", regularizer(weight))\r\n fc2 = tf.nn.bias_add(tf.matmul(fc1, weight), bias)\r\n return fc2\r\n\r\n\r\ndef train(input_tensor):\r\n # init\r\n x = tf.placeholder(tf.float32, [None, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS], name='x-input')\r\n y = tf.placeholder(tf.float32, [None, OUTPUT_LAYER_SIZE], name='y-input')\r\n is_train = tf.placeholder(tf.bool, name='is_train')\r\n l2 = tf.contrib.layers.l2_regularizer(L2_rate)\r\n # forward\r\n # y_ = fcnet(x, l2)\r\n if is_train == 1:\r\n y_ = leNet(x, 0.5, l2)\r\n else:\r\n y_ = leNet(x, 1.0, None)\r\n global_step = tf.get_variable('global', initializer=0, trainable=False)\r\n variable_average = tf.train.ExponentialMovingAverage(moving_average_decay, global_step)\r\n variable_average_op = variable_average.apply(tf.trainable_variables())\r\n # loss\r\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y_, labels=tf.argmax(y, 1))\r\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\r\n if is_train == 1:\r\n loss = cross_entropy_mean + tf.add_n(tf.get_collection(\"losses\"))\r\n else:\r\n loss = cross_entropy_mean\r\n # optimizer\r\n lr = tf.train.exponential_decay(LR_base, global_step, input_tensor.train.num_examples / batch_size, LR_decay)\r\n optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss, global_step=global_step)\r\n train_op = tf.group(optimizer, variable_average_op)\r\n correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1))\r\n acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n # start_train\r\n saver = tf.train.Saver()\r\n with tf.Session() as sess:\r\n tf.global_variables_initializer().run()\r\n val_x = np.reshape(input_tensor.validation.images, (-1, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))\r\n validation_feed = {\r\n x: val_x,\r\n y: input_tensor.validation.labels,\r\n is_train: 0\r\n }\r\n for i in range(training_step):\r\n if i % 1000 == 0:\r\n validation_acc = sess.run(acc, feed_dict=validation_feed)\r\n print(\"After %d training steps, validation accuracy :%g \" %\r\n (i, validation_acc))\r\n xs, ys = input_tensor.train.next_batch(batch_size)\r\n xs = np.reshape(xs, (batch_size, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))\r\n sess.run(train_op, feed_dict={x: xs, y: ys, is_train: 1})\r\n if i % 100 == 0:\r\n loss_train = sess.run(loss, feed_dict={x: xs, y: ys, is_train: 1})\r\n print(\"After %d training steps, loss :%g \" %\r\n (i, loss_train))\r\n saver.save(sess, \"./mnist_model\")\r\n # start test\r\n with tf.Session() as sess:\r\n saver.restore(sess, \"./mnist_model\")\r\n test_x = np.reshape(input_tensor.test.images, (-1, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))\r\n test_feed = {\r\n x: test_x,\r\n y: input_tensor.test.labels,\r\n is_train: 0\r\n }\r\n test_acc = sess.run(acc, feed_dict=test_feed)\r\n print(\"Test accuracy : %g\" % test_acc)\r\n saver = tf.train.Saver(variable_average.variables_to_restore())\r\n # test using average\r\n with tf.Session() as sess:\r\n saver.restore(sess, './mnist_model')\r\n test_x = np.reshape(input_tensor.test.images, (-1, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))\r\n test_feed = {\r\n x: test_x,\r\n y: input_tensor.test.labels,\r\n is_train: 0\r\n }\r\n test_acc = sess.run(acc, feed_dict=test_feed)\r\n print(\"Test average accuracy : %g\" % test_acc)\r\n\r\n\r\ndef main(argv=None):\r\n mnist = input_data.read_data_sets(\"./\", one_hot=True)\r\n train(mnist)\r\n\r\n\r\nif __name__ == '__main__':\r\n tf.app.run()\r\n","sub_path":"tensor_mnist.py","file_name":"tensor_mnist.py","file_ext":"py","file_size_in_byte":7435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"464404388","text":"# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/\r\n\r\n\"\"\"\r\n给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。\r\n示例 1:输入: 1->2->3->3->4->4->5;输出: 1->2->5\r\n示例 2:输入: 1->1->1->2->3;输出: 2->3\r\n\"\"\"\r\n\r\n\r\nclass ListNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\n\r\n\r\nclass ListNode_handle:\r\n def Creatlist(self, li):\r\n \"\"\"\r\n 从列表创建一个链表\r\n :param li: 列表\r\n :return: 头结点\r\n \"\"\"\r\n if len(li) <= 0:\r\n return False\r\n if len(li) == 1:\r\n return ListNode(li[0]) # 只有一个节点\r\n else:\r\n root = ListNode(li[0])\r\n tmp = root\r\n for i in range(1, len(li)):\r\n tmp.next = ListNode(li[i])\r\n tmp = tmp.next\r\n return root\r\n\r\n def print_linked(self, root: ListNode):\r\n \"\"\"\r\n 打印链表\r\n :param root: 头结点\r\n :return: 打印链表\r\n \"\"\"\r\n value = []\r\n tmp = root\r\n while tmp.next != None:\r\n value.append(str(tmp.val))\r\n tmp = tmp.next\r\n value.append(str(tmp.val))\r\n print(\"->\".join(value))\r\n\r\n def length(self, root):\r\n \"\"\"\r\n 计算链表的长度\r\n :param root:\r\n :return:\r\n \"\"\"\r\n\r\n tmp = root\r\n root_length = 0\r\n while tmp.next != None:\r\n root_length = root_length + 1\r\n tmp = tmp.next\r\n root_length = root_length + 1\r\n return root_length\r\n\r\n def insert_link(self, root, num, position):\r\n \"\"\"\r\n 向链表插入数据\r\n :param root: 头结点\r\n :param num: 插入的数据\r\n :return: 头结点\r\n \"\"\"\r\n root_length = ListNode_handle.length(root)\r\n if position <= 0 or position > root_length + 2:\r\n print(\"the position is not right\")\r\n return root\r\n elif position == 1:\r\n tmp = ListNode(num)\r\n tmp.next = root\r\n return tmp\r\n else:\r\n tmp = ListNode(0)\r\n tmp.next = root\r\n i = 1\r\n while i < position:\r\n tmp = tmp.next\r\n i = i + 1\r\n insert_node = ListNode(num)\r\n insert_node.next = tmp.next\r\n tmp.next = insert_node\r\n return root\r\n\r\n def delete_link(self, root, position):\r\n \"\"\"\r\n 删除链表中的元素\r\n :param root: 头结点\r\n :param position: 删除的位置\r\n :return: 返回新链表的头结点\r\n \"\"\"\r\n if position < 1 or position > ListNode_handle.length(root):\r\n print(\"the position is not right\")\r\n return root\r\n elif position == 1:\r\n return root.next\r\n else:\r\n tmp = ListNode(0)\r\n tmp.next = root\r\n i = 1\r\n while i < position:\r\n tmp = tmp.next\r\n i = i + 1\r\n tmp.next = tmp.next.next\r\n return root\r\n\r\n\r\n# *****************************************************#\r\n# ******************真正的题目在这里*********************#\r\n# *****************************************************#\r\n# 执行用时 : 56 ms, 在所有 python3 提交中击败了56.83%的用户\r\n# 内存消耗 : 13.8 MB, 在所有 python3 提交中击败了5.26%的用户\r\nclass Solution:\r\n def deleteDuplicates(self, head: ListNode) -> ListNode:\r\n dummy = ListNode(0)\r\n dummy.next = head\r\n slow = dummy\r\n fast = dummy.next\r\n while fast != None:\r\n if fast.next != None and fast.val == fast.next.val:\r\n tmp = fast.val\r\n while fast != None and fast.val == tmp:\r\n fast = fast.next\r\n else:\r\n slow.next = fast\r\n slow = slow.next\r\n fast = fast.next\r\n slow.next = fast\r\n return dummy.next\r\n\r\n\r\nif __name__ == \"__main__\":\r\n nums = [1, 1, 1, 2, 3]\r\n handle = ListNode_handle()\r\n a = handle.Creatlist(nums)\r\n handle.print_linked(a)\r\n solution = Solution()\r\n result = solution.deleteDuplicates(a)\r\n handle.print_linked(result)\r\n","sub_path":"leetcode/0001-0100/0082.删除排序链表中的重复元素Ⅱ.py","file_name":"0082.删除排序链表中的重复元素Ⅱ.py","file_ext":"py","file_size_in_byte":4336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"473694161","text":"# import sys\n# import subprocess\n# import webbrowser\nimport json\nimport time\nfrom io import StringIO\n\n# import getpass\n# import os\nimport requests\n\nfilename = \"/home/neo/Documents/Python/Chat/msg.txt\"\n\n\ndef delline(del_line, filename):\n with open(filename, \"r\") as textobj:\n liste = list(textobj) # puts all lines in a list\n\n del liste[del_line - 1] # delete regarding element\n\n # rewrite the textfile from liste contents/elements:\n with open(filename, \"w\") as textobj:\n for n in liste:\n textobj.write(n)\n\n\nwhile True:\n # if True:\n with open(filename, \"r\") as msgfile:\n msglst = msgfile.read().split(\"\\n\")\n # for item in msglst:\n for item, line in enumerate(msglst):\n # print(line)\n if item == \"\":\n continue\n io = StringIO(item)\n try:\n msglst = json.load(io)\n except json.decoder.JSONDecodeError:\n delline(line, filename)\n continue\n url = \"http://\" + str(msglst[\"notifyhost\"]) + \":18522/\"\n data = {\n \"user\": str(msglst[\"user\"]),\n \"host\": str(msglst[\"sendhost\"]),\n \"msg\": str(msglst[\"msg\"]),\n }\n try:\n resp = requests.post(url, data=data)\n print(\"Send\")\n delline(line, filename)\n except requests.exceptions.ConnectionError:\n pass\n time.sleep(5)\n","sub_path":"Chat/serveur_send.py","file_name":"serveur_send.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"322009946","text":"from random import random, gauss, uniform, choice\r\nimport numpy as np\r\nimport itertools\r\nfrom ortools.linear_solver import pywraplp\r\nfrom ortools.algorithms import pywrapknapsack_solver\r\n\r\nFAKE_ZERO = 0.00000000001\r\nclass TimeoutError(Exception):\r\n pass\r\n\r\nclass TaskSet:\r\n def __init__(self, setUtil, util_ranges, periodMin, periodMax, strength_stdev, friend_stdev, strength_mean, friend_mean, period_count = 5):\r\n \"\"\"Creates taskSet made of SmartTasks\"\"\"\r\n self.setUtil = setUtil\r\n self.utilRanges = util_ranges\r\n self.periodMin = periodMin\r\n self.periodMax = periodMax\r\n self.strength_stdev = strength_stdev\r\n self.friend_stdev = friend_stdev\r\n self.strength_mean = strength_mean\r\n self.friend_mean = friend_mean\r\n self.allTasks = []\r\n self.partitionList = [None] * Partition.ENUM_END\r\n self.period_divs = period_count\r\n\r\n # Add tasks until we reach our target starting utilization\r\n self.totalUtil = 0\r\n while self.totalUtil < setUtil:\r\n self.addTask()\r\n\r\n def addTask(self):\r\n nTotal = permID = len(self.allTasks)\r\n util_range = choice(self.utilRanges)\r\n util = uniform(util_range[0], util_range[1])\r\n # This subdivides the period range into `period_divs` divisions and chooses one\r\n period = np.floor(random()*self.period_divs)/self.period_divs * (self.periodMax - self.periodMin) + self.periodMin\r\n friend = gauss(self.friend_mean, self.friend_stdev)\r\n resil = gauss(self.strength_mean, self.strength_stdev)\r\n task = SmartTask(util, period, friend, resil, permID)\r\n self.allTasks.append(task)\r\n self.totalUtil = self.totalUtil + util\r\n nTotal += 1\r\n task.symAdj = [] # What speed multiplier we run at vs some other tasks\r\n # Compute what our multiplier is versus every other task\r\n for i in range(nTotal):\r\n sym = (task.resil + self.allTasks[i].friend) / 2.0\r\n sym = min(1, sym) # Ceiling at 1\r\n sym = max(FAKE_ZERO, sym) # Floor at (near) 0\r\n task.symAdj.append(sym)\r\n # Being 'run' with ourselves indicates we just run alone\r\n task.symAdj[permID] = 1\r\n # Add an entry to every other task representing how well they run with us\r\n for i in range(nTotal-1):\r\n sym = (self.allTasks[i].resil + task.friend) / 2.0\r\n sym = min(1, sym) # Ceiling at 1\r\n sym = max(FAKE_ZERO, sym) # Floor at (near) 0\r\n self.allTasks[i].symAdj.append(sym)\r\n\r\n def canPartition(self, method, m):\r\n try:\r\n self.partitionList[method] = Partition(self.allTasks, method, m)\r\n return self.partitionList[method] != None\r\n except AssertionError:\r\n return False\r\n except TimeoutError:\r\n return None\r\n\r\n def partitionTasks(self, method, maxCores):\r\n \"\"\"Creates a partition of all tasks in set. Original tasks are not altered.\"\"\"\r\n self.partitionList[method] = Partition(self.allTasks, method, maxCores)\r\n\r\n\r\nclass Partition:\r\n ALL_PHYS = 0 # Off\r\n OBLIVIOUS = 1 \r\n AWARE_START_THREAD = 2\r\n AWARE_START_PHYS = 3\r\n AWARE_START_OBLIV = 4\r\n OPTIMAL = 5 # Output, but always 0 unless configured\r\n ALL_THREAD = 6 # Off\r\n OBLIVIOUS_PLUS = 7 # Off\r\n CERT_MT = 8\r\n CERT_MT_GREEDY = 9\r\n PARTITIONED_EDF = 10\r\n ENUM_END = 11\r\n #MAX_LOOPS = len(someTasks)\r\n\r\n def __init__(self, someTasks, method, maxCores):\r\n self.MAX_LOOPS=len(someTasks)\r\n self.threadedTasks = {}\r\n self.physTasks = {}\r\n if method == Partition.ALL_THREAD:\r\n for task in someTasks:\r\n parTask = PartitionedTask(task)\r\n parTask.threadUtil = task.util / min(task.symAdj)\r\n self.threadedTasks[task.permID] = parTask\r\n elif method == Partition.ALL_PHYS:\r\n self.allPhysical(someTasks)\r\n elif method == Partition.OBLIVIOUS:\r\n self.oblivious(someTasks)\r\n elif method == Partition.OBLIVIOUS_PLUS:\r\n self.oblivious(someTasks)\r\n self.updateThreadedUtil(someTasks)\r\n elif method == Partition.AWARE_START_PHYS:\r\n self.allPhysical(someTasks)\r\n self.threadBestPhysPair(someTasks)\r\n self.updateThreadedUtil(someTasks)\r\n self.greedyMin(self.MAX_LOOPS, someTasks)\r\n elif method == Partition.AWARE_START_THREAD:\r\n # start with tasks threaded unless oblivious threaded util>1\r\n for task in someTasks:\r\n parTask = PartitionedTask(task)\r\n tempThreadUtil = task.util / min(task.symAdj)\r\n if tempThreadUtil <= 1:\r\n parTask.threadUtil = tempThreadUtil\r\n self.threadedTasks[task.permID] = parTask\r\n else:\r\n self.physTasks[task.permID] = parTask\r\n # print (\"testing\", parTask)\r\n if len(self.threadedTasks) == 1:\r\n #print(\"Only one threaded task. Reverting to physical.\")\r\n self.allPhysical(someTasks)\r\n self.updateThreadedUtil(someTasks)\r\n self.greedyMin(self.MAX_LOOPS, someTasks)\r\n elif method == Partition.AWARE_START_OBLIV:\r\n self.oblivious(someTasks)\r\n self.updateThreadedUtil(someTasks)\r\n self.greedyMin(self.MAX_LOOPS, someTasks)\r\n elif method == Partition.OPTIMAL:\r\n self.optimalPartition(someTasks)\r\n elif method == Partition.CERT_MT:\r\n self.partitionCERT_MT(someTasks, maxCores)\r\n elif method == Partition.CERT_MT_GREEDY:\r\n self.partitionCERT_MT_greedy(someTasks, maxCores)\r\n elif method == Partition.PARTITIONED_EDF:\r\n self.partitioned_EDF(someTasks, maxCores)\r\n else:\r\n print(\"Invalid partition method. Default to all physical.\")\r\n self.allPhysical(someTasks)\r\n # find total thread util and total phys util\r\n self.totalPhysUtil = 0\r\n self.totalThreadUtil = 0\r\n for p in self.physTasks:\r\n task = self.physTasks[p]\r\n self.totalPhysUtil = self.totalPhysUtil + task.util\r\n if task.util > 1: print(\"Warning: physUtil>1\")\r\n for t in self.threadedTasks:\r\n task = self.threadedTasks[t]\r\n self.totalThreadUtil = self.totalThreadUtil + task.threadUtil\r\n if task.threadUtil > 1:\r\n print(\"Warning: threadUtil>1\")\r\n if task.threadUtil < 0:\r\n print(\"Warning: threadUtil<0\")\r\n self.coresNeededNoShared();\r\n self.coresNeededShared();\r\n\r\n # This would probably be better housed in `TaskSet`, but it's here right now as `Partition`\r\n # methods don't have direct access to their `TaskSet`.\r\n def calc_CERT_MT_style_utils(self, tasks, m):\r\n n = len(tasks)\r\n # Our execution cost, plus the other execution cost, multiplied by the fraction of compute required\r\n e = [[tasks[i].cost * tasks[i].symAdj[j] + tasks[j].cost * tasks[j].symAdj[i] for j in range(n)] for i in range(n)]\r\n # Our execution cost is unchanged when executing with \"ourselves\" (no pair/container)\r\n for i in range(n):\r\n e[i][i] = tasks[i].cost\r\n # task periods\r\n T = [tasks[i].period for i in range(n)]\r\n # task utilizations relative to every-other task\r\n u_raw = [[e[i][j]/T[i] if T[i] == T[j] else 0 for j in range(n)] for i in range(n)]\r\n return u_raw\r\n\r\n def printU(self,u_raw):\r\n for l in u_raw:\r\n print(\"[\", end='')\r\n for item in l:\r\n print(\"{0:0.2f}, \".format(item), end='')\r\n print(\"]\")\r\n\r\n def partitioned_EDF(self, tasks, m):\r\n u = [task.util for task in tasks]\r\n self.sched_partitioned_EDF(u, m)\r\n\r\n def partitionCERT_MT_greedy(self, tasks, m):\r\n DEBUG = False\r\n raw_n = len(tasks)\r\n u_raw = self.calc_CERT_MT_style_utils(tasks, m)\r\n if DEBUG:\r\n print(\"***Utilizations Table***\")\r\n self.printU(u_raw)\r\n # Sort utilizations in increasing order per-period set\r\n # Complexity: O(n^2 + nlogn)\r\n utils_per_periods = {}\r\n util_queue = []\r\n for i in range(raw_n):\r\n for j in range(raw_n):\r\n if tasks[i].period == tasks[j].period:\r\n if not tasks[i].period in utils_per_periods:\r\n utils_per_periods[tasks[i].period] = []\r\n utils_per_periods[tasks[i].period].append((i,j,tasks[i].symAdj[j]))\r\n if DEBUG:\r\n print(\"***Utils per Period***\")\r\n print(utils_per_periods)\r\n containers = []\r\n # Keep pulling out the cheapest container pair choice until all tasks are in containers\r\n # Complexity: O(n)\r\n for utils in utils_per_periods.values():\r\n util_queue = sorted(utils, key=lambda tup: tup[2])\r\n while util_queue != []:\r\n to_cut = util_queue[0]\r\n containers.append(to_cut)\r\n # Remove all pairs involving the tasks we just paired\r\n util_queue = list(filter(lambda tup: tup[0] != to_cut[0] and tup[0] != to_cut[1] and tup[1] != to_cut[0] and tup[1] != to_cut[1], util_queue))\r\n if DEBUG:\r\n print(\"***Chosen Utilizations***\")\r\n print(containers)\r\n exit()\r\n u = [u_raw[tup[0]][tup[1]] for tup in containers]\r\n self.sched_partitioned_EDF(u, m)\r\n\r\n def sched_partitioned_EDF(self, u, m):\r\n assert sum(u) <= m\r\n # Bin pack with an ILP\r\n # Complexity: O(m^n) ???\r\n solver = pywraplp.Solver(\"binpack_ilp\", pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\r\n n = len(u)\r\n p = [[solver.BoolVar(\"p\"+str(l)+\":\"+str(i)) for i in range(n)] for l in range(m)]\r\n # Each core has utilization between 0 and 1\r\n for l in range(m):\r\n constraint = solver.Constraint(0, 1) # 0 <= ? <= 1\r\n for i in range(n):\r\n constraint.SetCoefficient(p[l][i], u[i]) # + p^l_i * u_i\r\n\r\n # Each task is assigned to only one core\r\n for i in range(n):\r\n constraint = solver.Constraint(1,1)\r\n for l in range(m):\r\n constraint.SetCoefficient(p[l][i], 1)\r\n\r\n # Minimize scheduled utilization\r\n \"\"\"\r\n objective = solver.Objective()\r\n for l in range(m):\r\n for i in range(n):\r\n objective.SetCoefficient(p[l][i], u[i]) # + p^l_i * u_i\r\n objective.SetMinimization()\r\n \"\"\"\r\n\r\n solver.SetTimeLimit(10*1000) # Time limit in ms\r\n result_status = solver.Solve()\r\n if result_status == pywraplp.Solver.NOT_SOLVED:\r\n raise TimeoutError\r\n assert result_status == pywraplp.Solver.FEASIBLE or (result_status == pywraplp.Solver.OPTIMAL and solver.VerifySolution(1e-7, True)) \r\n\r\n def partitionCERT_MT(self, tasks, m):\r\n \"\"\"\r\n Reminder on available task fields:\r\n self.util\r\n self.period\r\n self.cost\r\n self.friend\r\n self.resil\r\n self.symAdj # List of length n\r\n \"\"\"\r\n n = len(tasks)\r\n u = self.calc_CERT_MT_style_utils(tasks, m)\r\n\r\n solver = pywraplp.Solver(\"schedule_ilp\", pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\r\n # p[l][i][j] is a decision variable stating if tasks i and j are scheduled together on core l\r\n p = [[[solver.BoolVar(\"p\"+str(l)+\":\"+str(i)+\":\"+str(j)) for j in range(n)] for i in range(n)] for l in range(m)]\r\n\r\n # Each task is assigned to only one core\r\n for i in range(n):\r\n constraint = solver.Constraint(1, 1) # = 1\r\n for l in range(m):\r\n for j in range(i,n):\r\n constraint.SetCoefficient(p[l][i][j], 1) # + p^l_ij\r\n for j in range(0,i):\r\n constraint.SetCoefficient(p[l][j][i], 1) # + p^l_ji\r\n\r\n # Each core has utilization between 0 and 1\r\n for l in range(m):\r\n constraint = solver.Constraint(0, 1) # 0 <= ? <= 1\r\n for i in range(n):\r\n for j in range(i,n):\r\n constraint.SetCoefficient(p[l][i][j], u[i][j]) # + p^l_ij * u_ij\r\n\r\n # Co-scheduling does not occur if periods do not match\r\n for l in range(m):\r\n for i in range(n):\r\n for j in range(i,n):\r\n if tasks[i].period != tasks[j].period:\r\n solver.Add(p[l][i][j] == 0)\r\n\r\n\r\n # Minimize scheduled utilization\r\n \"\"\"\r\n objective = solver.Objective()\r\n for l in range(m):\r\n for i in range(n):\r\n for j in range(i,n):\r\n objective.SetCoefficient(p[l][i][j], u[i][j]) # + p^l_ij * u_ij\r\n objective.SetMinimization()\r\n \"\"\"\r\n\r\n solver.SetTimeLimit(10*1000) # Time limit in ms\r\n result_status = solver.Solve()\r\n if result_status == pywraplp.Solver.NOT_SOLVED:\r\n raise TimeoutError\r\n assert result_status == pywraplp.Solver.FEASIBLE or (result_status == pywraplp.Solver.OPTIMAL and solver.VerifySolution(1e-7, True)) \r\n\r\n def coresNeededNoShared(self):\r\n self.coresNeededNoShared = np.ceil(self.totalPhysUtil) + np.ceil(self.totalThreadUtil / 2)\r\n\r\n def testUmaFunk(self, m):\r\n uEffective=self.totalPhysUtil+.5*self.totalThreadUtil\r\n if uEffective>m:\r\n return (0, 0)\r\n #assume we set minimum pi^p; don't need to test\r\n mh=np.floor(uEffective-self.totalPhysUtil)\r\n ah = 1 - (self.totalPhysUtil - np.floor(self.totalPhysUtil))\r\n #sort threaded utilizations\r\n threadedUtilList=[]\r\n for t in self.threadedTasks:\r\n threadedUtilList.append(self.threadedTasks[t].threadUtil)\r\n threadedUtilList.sort()\r\n nh = len(threadedUtilList)\r\n # add some zeros to list if its too short\r\n while nh < 2 * (mh + 1):\r\n threadedUtilList.append(0)\r\n nh = nh + 1\r\n # largest 2mh+1 items in list\r\n #note sum is exclusive of last index\r\n sum1 = sum(threadedUtilList[0:int(2 * mh + 1)])\r\n if sum1<2*mh or sum1<2*(mh+ah)-threadedUtilList[0]:\r\n Uma=1\r\n else:\r\n Uma=0\r\n # Disable funk for now\r\n #sum2 = sum1 + threadedUtilList[int(2 * mh + 1)]\r\n #if sum1 <= 2 * mh + ah and sum2 <= 2 * (mh + ah):\r\n # Funk=1\r\n #else:\r\n # Funk=0\r\n return(Uma, 0)#Funk)\r\n\r\n def coresNeededShared(self):\r\n threadedUtilList = []\r\n uEffective = self.totalPhysUtil + .5 * self.totalThreadUtil\r\n #print(\"Phys util:\", self.totalPhysUtil)\r\n #print(\"Thread util:\", self.totalThreadUtil)\r\n #print(\"Effective util: \", uEffective)\r\n # schedulable with uEffective cores?\r\n m = np.ceil(uEffective)\r\n mh = np.floor(m - self.totalPhysUtil)\r\n ah = 1 - (self.totalPhysUtil - np.floor(self.totalPhysUtil))\r\n # get sorted threaded utilizations\r\n for t in self.threadedTasks:\r\n threadedUtilList.append(self.threadedTasks[t].threadUtil)\r\n threadedUtilList.sort()\r\n nh = len(threadedUtilList)\r\n # add some zeros to list if its too short\r\n while nh < 2 * (mh + 1):\r\n threadedUtilList.append(0)\r\n nh = nh + 1\r\n # largest 2mh+1 items in list\r\n sum1 = sum(threadedUtilList[0:int(2 * mh + 1)])\r\n sum2 = sum1 + threadedUtilList[int(2 * mh + 1)]\r\n if sum1 <= 2 * mh + ah and sum2 < 2 * (mh + ah):\r\n self.coresNeededShared = m\r\n else:\r\n self.coresNeededShared = m + 1\r\n\r\n def allPhysical(self, someTasks):\r\n self.threadedTasks = {}\r\n self.physTasks = {}\r\n for task in someTasks:\r\n parTask = PartitionedTask(task)\r\n self.physTasks[task.permID] = parTask\r\n\r\n def oblivious(self, someTasks):\r\n for task in someTasks:\r\n parTask = PartitionedTask(task)\r\n tempThreadUtil = task.util / min(task.symAdj)\r\n if tempThreadUtil < 1 and task.util / tempThreadUtil >= .5:\r\n parTask.threadUtil = tempThreadUtil\r\n self.threadedTasks[task.permID] = parTask\r\n else:\r\n self.physTasks[task.permID] = parTask\r\n if len(self.threadedTasks) == 1:\r\n # revert to all physical\r\n #print(\"Only one threaded task. Reverting to all tasks physical.\")\r\n self.allPhysical(someTasks)\r\n\r\n def updateThreadedUtil(self, someTasks):\r\n for i in self.threadedTasks:\r\n task = someTasks[i]\r\n minS = 1\r\n for j in self.threadedTasks: # requires that partition belong to a task set\r\n if task.symAdj[j] < minS:\r\n minS = task.symAdj[j]\r\n self.threadedTasks[i].threadUtil = someTasks[i].util / minS\r\n\r\n def threadBestPhysPair(self, someTasks):\r\n maxDecrease = -1\r\n #if len(self.threadedTasks) > 0:\r\n #(\"Caution: attempting to find best phys pair with pre-existing threaded.\")\r\n for p1 in self.physTasks:\r\n for p2 in range(p1 + 1, len(self.physTasks) - 1):\r\n decreaseP1 = self.physTasks[p1].util - .5 * someTasks[p1].util / someTasks[p1].symAdj[p2]\r\n decreaseP2 = self.physTasks[p2].util - .5 * someTasks[p2].util / someTasks[p1].symAdj[p2]\r\n totalDecrease = decreaseP1 + decreaseP2\r\n if totalDecrease > maxDecrease \\\r\n and someTasks[p1].util / someTasks[p1].symAdj[p2] < 1 \\\r\n and someTasks[p2].util / someTasks[p2].symAdj[p1] < 1:\r\n maxDecrease = totalDecrease\r\n bestP1 = p1\r\n bestP2 = p2\r\n if maxDecrease > 0:\r\n self.threadedTasks[bestP1] = self.physTasks.pop(bestP1)\r\n self.threadedTasks[bestP1].threadUtil = someTasks[bestP1].util / someTasks[bestP1].symAdj[bestP2]\r\n self.threadedTasks[bestP2] = self.physTasks.pop(bestP2)\r\n self.threadedTasks[bestP2].threadUtil = someTasks[bestP2].util / someTasks[bestP2].symAdj[bestP1]\r\n #else:\r\n #print(\"No pair of physTasks could be threaded.\")\r\n\r\n def greedyMin(self, maxLoops, someTasks):\r\n # indicies for tuples returned by picking methods\r\n WHAT_TASK = 0\r\n IMPROVEMENT = 1\r\n for i in range(1, maxLoops):\r\n # optional: test for feasibility and stop if feasible\r\n if len(self.threadedTasks) > 1:\r\n bestPhys = self.pickBestPhysToThread2(someTasks)\r\n else:\r\n break\r\n if len(self.threadedTasks) > 2:\r\n bestThread = self.pickBestThreadToPhys(someTasks)\r\n else:\r\n # don't want to move any threaded task to physical\r\n bestThread = (-1, -1)\r\n if bestPhys[IMPROVEMENT] > bestThread[IMPROVEMENT] and bestPhys[IMPROVEMENT] > 0:\r\n # update threaded utilization values\r\n taskIndex = bestPhys[WHAT_TASK]\r\n makeThreaded = someTasks[taskIndex]\r\n self.physTasks[taskIndex].threadUtil = -1\r\n for t in self.threadedTasks:\r\n if makeThreaded.util / makeThreaded.symAdj[t] > self.physTasks[taskIndex].threadUtil:\r\n self.physTasks[taskIndex].threadUtil = makeThreaded.util / makeThreaded.symAdj[t]\r\n if self.threadedTasks[t].threadUtil < someTasks[t].util / someTasks[t].symAdj[taskIndex]:\r\n self.threadedTasks[t].threadUtil = someTasks[t].util / someTasks[t].symAdj[taskIndex]\r\n # remove bestPhys from physIn and add to threadIn\r\n self.threadedTasks[taskIndex] = self.physTasks.pop(taskIndex)\r\n # print(\"Moving\", taskIndex, \"to threaded.\")\r\n elif bestThread[IMPROVEMENT] > 0:\r\n # update utilizations of remaining threaded tasks\r\n # if bestThread was the worst for some other threaded tasks, reduce that task's util\r\n t1 = bestThread[WHAT_TASK]\r\n for t2 in self.threadedTasks:\r\n # if t1 is the worst for t2 among currently threaded tasks\r\n if self.threadedTasks[t2].threadUtil == someTasks[t2].util / someTasks[t2].symAdj[t1]:\r\n # find new threadUtil for t2\r\n self.threadedTasks[t2].threadUtil = 0\r\n for t3 in self.threadedTasks:\r\n if t3 != t2 and t3 != t1:\r\n if someTasks[t2].util / someTasks[t2].symAdj[t3] > self.threadedTasks[t2].threadUtil:\r\n self.threadedTasks[t2].threadUtil = someTasks[t2].util / someTasks[t2].symAdj[t3]\r\n # else t1 is NOT worst-case for t2, so t2 does not get to reduce its threadUtil\r\n # move bestThread to phys\r\n self.threadedTasks[t1].threadUtil = -1\r\n self.physTasks[t1] = self.threadedTasks.pop(t1)\r\n # print(\"Moving\", t1, \"to physical.\")\r\n else:\r\n # move random theaded task to phys?\r\n #print(\"Tasks moved:\", i)\r\n break # no improvement possible; need to quit\r\n\r\n def greedyMin2(self, maxLoops, someTasks):\r\n WHAT_TASK = 0\r\n IMPROVEMENT = 1\r\n for i in range(1, maxLoops):\r\n if len(self.threadedTasks) > 1:\r\n bestPhysToThread = self.pickBestPhysToThread2(someTasks)\r\n else:\r\n break\r\n if bestPhysToThread[IMPROVEMENT] > 0:\r\n moveToThread = bestPhysToThread[WHAT_TASK]\r\n for t in self.threadedTasks:\r\n if someTasks[moveToThread].util / someTasks[moveToThread].symAdj[t] > self.physTasks[\r\n moveToThread].threadUtil:\r\n self.physTasks[moveToThread].threadUtil = someTasks[moveToThread].util / \\\r\n someTasks[moveToThread].symAdj[t]\r\n if self.threadedTasks[t].threadUtil > someTasks[t].util / someTasks[t].symAdj[moveToThread]:\r\n self.threadedTasks[t].threadUtil = someTasks[t].util / someTasks[t].symAdj[moveToThread]\r\n self.threadedTasks[moveToThread] = self.physTasks.pop(moveToThread)\r\n else:\r\n break\r\n #print(\"Tasks moved\", i)\r\n\r\n def pickBestPhysToThread2(self, someTasks):\r\n maxDecrease = -1\r\n bestP = -1\r\n for p in self.physTasks:\r\n skip = False\r\n candidate = someTasks[p]\r\n physUtil = candidate.util\r\n utilIfThread = 0\r\n increaseToThreaded = 0\r\n for t in self.threadedTasks:\r\n temp = physUtil / candidate.symAdj[t]\r\n if temp > 1:\r\n skip = True\r\n # t=-1\r\n break\r\n if temp > utilIfThread:\r\n utilIfThread = temp\r\n temp = someTasks[t].util / someTasks[t].symAdj[p]\r\n if temp > 1:\r\n skip = True\r\n # t=-1\r\n break\r\n if temp > self.threadedTasks[t].threadUtil:\r\n increaseToThreaded = increaseToThreaded + temp - self.threadedTasks[t].threadUtil\r\n if skip:\r\n continue\r\n totalDecrease = physUtil - .5 * (utilIfThread + increaseToThreaded)\r\n if totalDecrease > maxDecrease:\r\n bestP = p\r\n maxDecrease = totalDecrease\r\n return bestP, maxDecrease\r\n\r\n def pickBestPhysToThread(self, someTasks):\r\n bestP = -1\r\n maxImprovement = 0\r\n decreaseUtil = {}\r\n for p in self.physTasks:\r\n tempThreadUtil = 0\r\n decreaseUtil[p] = 0\r\n skip = False\r\n for t in self.threadedTasks:\r\n # what happens to p if we move it to threaded?\r\n if tempThreadUtil < someTasks[p].util / someTasks[p].symAdj[t]:\r\n tempThreadUtil = someTasks[p].util / someTasks[p].symAdj[t]\r\n if tempThreadUtil > 1:\r\n skip = True\r\n #print(\"Moving\", p, \"to threaded would give\", p, \"util>1.\")\r\n break\r\n # what happens to already threaded tasks if we move p to threaded?\r\n newUtil = someTasks[t].util / someTasks[t].symAdj[p]\r\n if newUtil > 1:\r\n skip = True\r\n #print(\"Moving\", p, \"to threaded would give\", t, \"util>1.\")\r\n break\r\n if self.threadedTasks[t].threadUtil < newUtil:\r\n decreaseUtil[p] = decreaseUtil[p] - .5 * (newUtil - self.threadedTasks[t].threadUtil)\r\n if skip: continue\r\n decreaseUtil[p] = decreaseUtil[p] - .5 * tempThreadUtil + someTasks[p].util\r\n if decreaseUtil[p] > maxImprovement:\r\n maxImprovement = decreaseUtil[p]\r\n bestP = p\r\n # print (\"bestP=\", bestP)\r\n return bestP, maxImprovement\r\n\r\n def pickBestThreadToPhys(self, someTasks):\r\n # assumes that at least three tasks are threaded\r\n for t1 in self.threadedTasks:\r\n maxImprovement = -2\r\n bestT = -1\r\n increaseThisTask = someTasks[t1].util - self.threadedTasks[t1].threadUtil / 2\r\n decreaseOtherTasks = 0\r\n for t2 in self.threadedTasks:\r\n # if t1 is the worst for t2 among currently threaded tasks\r\n if self.threadedTasks[t2].threadUtil == someTasks[t2].util / someTasks[t2].symAdj[t1]:\r\n # find new threadUtil for t2\r\n newThreadUtil = 0\r\n for t3 in self.threadedTasks:\r\n if t3 != t2 and t3 != t1:\r\n if someTasks[t2].util / someTasks[t2].symAdj[t3] > newThreadUtil:\r\n newThreadUtil = someTasks[t2].util / someTasks[t2].symAdj[t3]\r\n decreaseOtherTasks = decreaseOtherTasks + (self.threadedTasks[t2].threadUtil - newThreadUtil) / 2\r\n # else t1 is NOT worst-case for t2, so t2 does not get to reduce its threadUtil\r\n if decreaseOtherTasks - increaseThisTask > maxImprovement:\r\n maxImprovement = decreaseOtherTasks - increaseThisTask\r\n bestT = t1\r\n return bestT, maxImprovement\r\n\r\n def optimalPartition(self, someTasks):\r\n bestThreaded = {}\r\n n = len(someTasks)\r\n utilAllPhys = 0\r\n for p in someTasks:\r\n utilAllPhys = utilAllPhys + p.util\r\n minTEU = utilAllPhys\r\n # check all partitions with 3 to n-1 threaded tasks, inclusive\r\n # 2 threaded tasks covered by greedy physStart\r\n # n threaded tasks covered by greedy threadStart\r\n for threadCount in range(2, n+1):\r\n # get set of all partitions that have threadCount threaded tasks\r\n allThreadedOfSize = itertools.combinations(someTasks, threadCount)\r\n for threadSet in allThreadedOfSize:\r\n self.threadedTasks={}\r\n skip=False\r\n for t1 in threadSet:\r\n index=t1.permID\r\n self.threadedTasks[index] = PartitionedTask(someTasks[index])\r\n for interfere in threadSet:\r\n if self.threadedTasks[index].threadUtil < self.threadedTasks[index].util / someTasks[index].symAdj[\r\n interfere.permID]:\r\n self.threadedTasks[index].threadUtil = self.threadedTasks[index].util / someTasks[index].symAdj[\r\n interfere.permID]\r\n if self.threadedTasks[index].threadUtil > 1:\r\n skip = True\r\n break\r\n if skip:\r\n break\r\n if skip:\r\n continue\r\n tempTEU = utilAllPhys\r\n for t2 in threadSet:\r\n tempTEU = tempTEU - someTasks[t2.permID].util + .5 * self.threadedTasks[t2.permID].threadUtil\r\n if tempTEU < minTEU:\r\n minTEU = tempTEU\r\n bestThreaded = self.threadedTasks.copy()\r\n #partition to match the best found\r\n self.allPhysical(someTasks)\r\n self.threadedTasks=bestThreaded\r\n for t in self.threadedTasks:\r\n del self.physTasks[t]\r\n\r\n\r\n def __str__(self):\r\n physString = \" \"\r\n\r\n threadString = \" \"\r\n\r\n for p in self.physTasks:\r\n physString = physString + str(self.physTasks[p]) + \"\\n\"\r\n\r\n for t in self.threadedTasks:\r\n threadString = threadString + str(self.threadedTasks[t]) + \"\\n\"\r\n\r\n return physString + threadString\r\n\r\n\r\nclass SmartTask:\r\n\r\n def __init__(self, util, period, friend, resil, permID):\r\n self.util = float(util)\r\n self.period = period\r\n self.cost = util * period\r\n self.friend = friend\r\n self.resil = resil\r\n self.symAdj = [] # all values in range (0, 1]\r\n # every task needs a unique ID that holds across all partitions\r\n self.permID = permID\r\n\r\n def __str__(self):\r\n return \"τ{0}: ({1:0.2f}U, {2:0.0f}T, {3})\".format(self.permID, self.util, self.period, str(self.symAdj))\r\n\r\n def __repr__(self):\r\n return self.__str__()\r\n\r\n\r\nclass PartitionedTask:\r\n\r\n def __init__(self, parent):\r\n self.util = parent.util\r\n self.period = parent.period\r\n self.permID = parent.permID\r\n self.threadUtil = -1 # has no meaning in isolation\r\n\r\n def __str__(self):\r\n self.status = \"\"\r\n self.printUtil = \"\"\r\n if self.threadUtil == -1:\r\n self.status = \"phys\"\r\n self.printUtil = str(self.util)\r\n else:\r\n self.status = \"threaded\"\r\n self.printUtil = str(self.threadUtil)\r\n return str(str(self.permID) + \" \" + self.status + \" \" + self.printUtil)\r\n\r\n","sub_path":"gaussian-average/SMART.py","file_name":"SMART.py","file_ext":"py","file_size_in_byte":30587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"196982707","text":"from parse import *\nimport re\nimport os\nimport random\nimport math\n\nimport networkx as nx\n\nimport utils\n\n#constants\nn = 50\nG = nx.Graph()\nk = max(2, math.ceil(n/(2*math.log2(n))))\nnum_rooms = math.ceil(n/k)\n\ndef random_decimal(a, b):\n a, b = int(a), int(b)\n return round(((b - a) * random.random() + a)/n, 3)\n\n#initialize graph\nfor i in range(n):\n\tG.add_node(i)\n\tfor j in range(n):\n\t\tif i != j:\n\t\t\tG.add_node(j)\n\t\t\tG.add_edge(i, j, happiness = -1, stress = -1)\n\n#initialize edges\nmax_room_stress = 0\nnodes = list(G.nodes)\nrooms = {}\nr = 0\nwhile len(nodes):\n\troom_stress = 0\n\trandom.shuffle(nodes)\n\troom = nodes[0:k]\n\tnodes = nodes[k:]\n\tfor i in room:\n\t\trooms[i] = r\n\tr += 1\n\t#initialize edges in room\n\tfor i in room:\n\t\tfor j in room:\n\t\t\tif i < j:\n\t\t\t\trand_h = random_decimal(20, 40)\n\t\t\t\trand_s = random_decimal(5, 25)\n\t\t\t\tG[i][j]['happiness'] = rand_h\n\t\t\t\tG[i][j]['stress'] = rand_s\n\t\t\t\troom_stress += G[i][j]['stress']\n\n\t#initialize edges out of room\n\tfor i in room:\n\t\tfor j in nodes:\n\t\t\trand_h = random_decimal(5, 25)\n\t\t\trand_s = random_decimal(20, 40)\n\t\t\tG[i][j]['happiness'] = rand_h\n\t\t\tG[i][j]['stress'] = rand_s\n\n\t#update max stress per room\n\tmax_room_stress = max(room_stress, max_room_stress)\n\n#set the stress budget\nstress_budget = math.ceil(max_room_stress*num_rooms + 0.1)\npath_in = \"./{}.in\".format(n)\npath_out = \"./{}.out\".format(n)\nwrite_input_file(G, stress_budget, path_in)\nwrite_output_file(rooms, path_out)\nprint(\"Input file validation: \" + str(read_input_file(path_in)))\nprint(\"Output file validation: \" + str(read_output_file(path_out, G, stress_budget)))\n\n","sub_path":"create_input.py","file_name":"create_input.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"45403397","text":"from discord.ext import commands\nimport discord\nimport datetime\nimport json\nimport os\nimport requests\n\nstart_time = datetime.datetime.utcnow()\n\n\nURBAN_API_KEY = os.getenv('URBAN_API_KEY')\n\nclass misc(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def about(self, ctx):\n servers = self.bot.guilds\n guilds = len(self.bot.guilds)\n servers.sort(key=lambda x: x.member_count, reverse=True)\n y = 0\n for x in self.bot.guilds:\n y += x.member_count\n embed = discord.Embed(color=0x2f3136, timestamp=datetime.datetime.utcnow())\n embed.set_author(name=f\"Fendi Information!\", icon_url='https://cdn.discordapp.com/icons/839142238529126420/ddb43f3a83d6a09c28505cc91e900e0a.webp?size=1024')\n embed.add_field(name=\"**General Statistics**\", value=f\"`Current Users` — {y}\\n`Current Guilds` — {guilds}\\n`Created Date` — 11/5/20\\n`Creator` — <@781761427664142345>\", inline=False)\n embed.add_field(name=f\"**Prefix:**\", value=f\"`— >`\\n\", inline=False)\n embed.add_field(name=f\"**Credits**\", value=f\"`— kazion\\n— who ever eles needs Credits\\n — Goonie 3Hunna/Sny`\", inline=False)\n embed.set_footer(text=\"Requested by {}\".format(ctx.message.author))\n embed.set_thumbnail(url='https://cdn.discordapp.com/icons/839142238529126420/ddb43f3a83d6a09c28505cc91e900e0a.webp?size=1024')\n await ctx.send(embed=embed)\n\n @commands.command()\n async def uptime(self, ctx):\n uptime = datetime.datetime.utcnow() - start_time\n uptime = str(uptime).split('.')[0]\n await ctx.send(f\"`Current Uptime:` \"+''+uptime+'')\n\n @commands.command()\n async def ping(self, ctx):\n message = await ctx.send(content=\"`Pinging...`\")\n await message.edit(content=f\"`PONG!` - Latency is {round(self.bot.latency * 1000)}ms\")\n\n @commands.command()\n async def invite(self, ctx):\n try:\n embed = discord.Embed(description=f\"thank you for using me\", color=0x2f3136, timestamp=datetime.datetime.utcnow())\n embed.add_field(name=f\"**Invite Me**\", value=f\"[Here](https://discord.com/oauth2/authorize?client_id=804567395124904006&scope=bot&permissions=8589934591)\\n\", inline=False)\n embed.add_field(name=f\"**Support Server**\", value=f\"[Server Invite](https://discord.gg/hB4Vmygqza)\\n\", inline=False)\n embed.set_author(name=f\"Links!\", icon_url=ctx.guild.icon_url)\n embed.set_footer(text=f\"{ctx.guild.name}\")\n embed.set_thumbnail(url=ctx.guild.icon_url)\n await ctx.author.send(embed=embed)\n await ctx.channel.send(f\"I have sent you an invite, Check your DM! {ctx.author.mention}\")\n except:\n await ctx.channel.send(embed=embed)\n\n @commands.command()\n async def bots(self, ctx):\n bots = []\n for member in ctx.guild.members:\n if member.bot:\n bots.append(\n str(member.name).replace(\"`\", \"\\`\").replace(\"*\", \"\\*\").replace(\"_\", \"\\_\") + \"#\" + member.discriminator)\n bottiez = discord.Embed(description=f\"**Bots ({len(bots)})**\\n{', '.join(bots)} - {ctx.bot.user.id}\", color=0x2f3136)\n await ctx.send(embed=bottiez)\n\n @commands.command(name='urban')\n async def urban(self, ctx, *args, user: discord.Member = None):\n if user is None:\n user = ctx.author \n url = \"https://mashape-community-urban-dictionary.p.rapidapi.com/define\"\n\n querystring = {\"term\":' '.join(map(str,args))}\n\n headers = {\n 'x-rapidapi-host': \"mashape-community-urban-dictionary.p.rapidapi.com\",\n 'x-rapidapi-key': URBAN_API_KEY\n }\n\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n urbanObject = json.loads(response.content)\n\n Embed = discord.Embed(title=f\"{' '.join(map(str,args))} | Urban\", color=0x2f3136)\n Embed.add_field(name='Definition', value=str(urbanObject['list'][0]['definition']), inline=False)\n Embed.add_field(name='Example', value=str(urbanObject['list'][0]['example']), inline=False)\n Embed.add_field(name='URL', value=str(urbanObject['list'][0]['permalink']), inline=False)\n Embed.set_thumbnail(url=user.avatar_url)\n Embed.set_footer(text=\"Requested by {}\".format(ctx.message.author))\n await ctx.send(embed=Embed)\n\n\n @commands.command()\n async def members(self, ctx):\n guild = ctx.guild\n embed = discord.Embed(color=0x2f3136, timestamp=datetime.datetime.utcnow())\n embed.set_author(name=f\"Links!\", icon_url=ctx.guild.icon_url)\n embed.add_field(name=f\"Member Count:\", value=f\"> {len(guild.members)}\")\n embed.set_footer(text=f\"{ctx.guild.name}\")\n embed.set_thumbnail(url=ctx.guild.icon_url)\n await ctx.channel.send(embed=embed)\n","sub_path":"cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"311264788","text":"from browser import document, alert, ajax\n\ndef on_complete(req):\n alert(req.text)\n\ndef send():\n req = ajax.ajax()\n req.bind('complete',on_complete)\n req.open(document['req_method'].value, '/ajax', True)\n req.set_header('content-type', 'application/x-www-form-urlencoded')\n req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)\n req.send({'param_name': 'param_value'})\n\ndocument['mybutton'].bind('click', send)\n","sub_path":"paw/paw/static/frontend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"527151838","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n\n# 防止pandas输出结果省略\npd.set_option('display.max_columns', 1000)\npd.set_option('display.width', 1000)\npd.set_option('display.max_colwidth', 1000)\n\nimport os\n\nos.environ[\"PATH\"] += os.pathsep + \"D:/Graphviz/bin/\"\n\n\n# sl:satisfaction_level---False:MinMaxScaler;True:StandardScaler\n# le:last_evaluation---False:MinMaxScaler;True:StandardScaler\n# npr:number_project---False:MinMaxScaler;True:StandardScaler\n# tsc:time_spend_company---False:MinMaxScaler;True:StandardScaler\n# wa:Work_accident---False:MinMaxScaler;True:StandardScaler\n# pl5:promotion_last_5years---False:MinMaxScaler;True:StandardScaler\n# dp:department---False:LabelEncoding;True:OneHotEncoding\n# slr:salary---False:LabelEncoding;True:OneHotEncoding\n# ldn:降维---False:不降维;True:降维\n# ld_n:Dimension\ndef hr_preprocessing(sl=False, le=False, npr=False, tsc=False, wa=False, p15=False, dp=False, slr=False, lower_d=False,\n ld_n=1):\n df = pd.read_csv(\"./data/HR_.csv\")\n # 1.清洗数据\n df = df.dropna(subset=[\"satisfaction_level\", \"last_evaluation\"])\n df = df[df[\"satisfaction_level\"] <= 1][df[\"salary\"] != \"nme\"]\n # 2.得到标注\n label = df[\"left\"]\n # 把left列删掉\n df = df.drop(\"left\", axis=1)\n # 3.特征选择\n # 4.特征处理\n scaler_list = [sl, le, npr, tsc, wa, p15]\n column_list = [\"satisfaction_level\", \"last_evaluation\", \"number_project\", \"time_spend_company\", \"Work_accident\",\n \"promotion_last_5years\"]\n # 经过处理satisfaction_level列数据都变小\n for i in range(len(scaler_list)):\n if not scaler_list[i]:\n df[column_list[i]] = \\\n MinMaxScaler().fit_transform(df[column_list[i]].values.reshape(-1, 1)).reshape(1, -1)[0]\n else:\n df[column_list[i]] = \\\n StandardScaler().fit_transform(df[column_list[i]].values.reshape(-1, 1)).reshape(1, -1)[0]\n scaler_list = [slr, dp]\n column_list = [\"salary\", \"department\"]\n for i in range(len(scaler_list)):\n if not scaler_list[i]:\n if column_list[i] == \"salary\":\n df[column_list[i]] = [map_salary(s) for s in df[\"salary\"].values]\n else:\n # 处理department\n df[column_list[i]] = LabelEncoder().fit_transform(df[column_list[i]])\n else:\n # 独热化\n df = pd.get_dummies(df, columns=[column_list[i]])\n if lower_d:\n return PCA(n_components=ld_n).fit_transform(df.values), label\n return df, label\n\n\nd = dict([(\"low\", 0), (\"medium\", 1), (\"high\", 2)])\n\n\ndef map_salary(s):\n # key不存在dict.keys()中时,返回0\n return d.get(s, 0)\n\n\ndef hr_modeling(features, label):\n from sklearn.model_selection import train_test_split\n f_v = features.values\n f_names = features.columns.values\n l_v = label.values\n X_tt, X_validation, Y_tt, Y_validation = train_test_split(f_v, l_v, test_size=0.2)\n X_train, X_test, Y_train, Y_test = train_test_split(X_tt, Y_tt, test_size=0.25)\n print(len(X_train), len(X_validation), len(X_test))\n\n # KNN\n from sklearn.metrics import accuracy_score, recall_score, f1_score\n from keras.models import Sequential\n from keras.layers.core import Dense, Activation\n from keras.optimizers import SGD\n mdl = Sequential()\n mdl.add(Dense(50, input_dim=len(f_v[0])))\n mdl.add(Activation(\"sigmoid\"))\n mdl.add(Dense(2))\n mdl.add(Activation(\"softmax\"))\n # 最陡梯度下降,lr:学习率\n sgd = SGD(lr=0.03)\n # adam优化器提升性能显著\n mdl.compile(loss=\"mean_squared_error\", optimizer=\"adam\")\n # 输出结果,Loss是损失值\n # epochs:Number of epochs to train the model;batch_size:Number of samples per evaluation step.\n mdl.fit(X_train, np.array([[0, 1] if i == 1 else [1, 0] for i in Y_train]), epochs=1000, batch_size=2048)\n xy_lst = [(X_train, Y_train), (X_validation, Y_validation), (X_test, Y_test)]\n # 对代码6-2的优化\n for i in range(len(xy_lst)):\n X_part = xy_lst[i][0]\n Y_part = xy_lst[i][1]\n Y_pred = mdl.predict_classes(X_part)\n print(i)\n print(\"NN\", \"ACC:\", accuracy_score(Y_part, Y_pred))\n print(\"NN\", \"REC:\", recall_score(Y_part, Y_pred))\n print(\"NN\", \"F1\", f1_score(Y_part, Y_pred))\n return\n\n models = []\n models.append((\"KNN\", KNeighborsClassifier(n_neighbors=3)))\n models.append((\"GaussianNB\", GaussianNB()))\n models.append((\"BernoulliNB\", BernoulliNB()))\n models.append((\"DecisionTree\", DecisionTreeClassifier()))\n models.append((\"DecisionTreeEntropy\", DecisionTreeClassifier(criterion=\"entropy\")))\n # C是惩罚度,越高精准度越高,运算速度越慢\n # models.append((\"SVM Classifier\",SVC(C=1000)))\n # models.append((\"OriginalRandomForest\",RandomForestClassifier()))\n # models.append((\"RandomForest\", RandomForestClassifier(n_estimators=1000,max_features=None)))\n # models.append((\"AdaBoost\",AdaBoostClassifier(n_estimators=1000)))\n # 优化参数依然Logistic依然效果不好,\n models.append((\"LogisticRegression\", LogisticRegression(C=1000, tol=1e-10, solver=\"sag\", max_iter=10000)))\n for clf_name, clf in models:\n clf.fit(X_train, Y_train)\n xy_lst = [(X_train, Y_train), (X_validation, Y_validation), (X_test, Y_test)]\n # 对代码6-2的优化\n for i in range(len(xy_lst)):\n X_part = xy_lst[i][0]\n Y_part = xy_lst[i][1]\n Y_pred = clf.predict(X_part)\n print(i)\n print(clf_name, \"ACC:\", accuracy_score(Y_part, Y_pred))\n print(clf_name, \"REC:\", recall_score(Y_part, Y_pred))\n print(clf_name, \"F1\", f1_score(Y_part, Y_pred))\n\n\ndef regr_test(features, label):\n print(\"X\", features)\n print(\"Y\", label)\n from sklearn.linear_model import LinearRegression\n regr = LinearRegression()\n # 岭回归\n # regr = Ridge(alpha=0.8)\n # Lasso\n # regr = Lasso(alpha=0.2)\n regr.fit(features.values, label.values)\n Y_pred = regr.predict(features.values)\n print(\"Coef:\", regr.coef_)\n from sklearn.metrics import mean_squared_error\n # 误差\n print(\"MSE:\", mean_squared_error(Y_pred, label.values))\n pass\n\n\ndef main():\n features, labels = hr_preprocessing()\n regr_test(features[[\"number_project\", \"average_monthly_hours\"]], features[\"last_evaluation\"])\n hr_modeling(features, labels)\n\n\n# if __name__ == '__main__'的意思是:当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;\n# 当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。\nif __name__ == \"__main__\":\n main()\n","sub_path":"第6章 挖掘建模/6-12 回归-分类-人工神经网络-2.py","file_name":"6-12 回归-分类-人工神经网络-2.py","file_ext":"py","file_size_in_byte":6842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"206295280","text":"\"\"\"\nImplements the base class for the fitting software controllers.\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nimport numpy\n\nfrom fitbenchmarking.utils.exceptions import ControllerAttributeError, \\\n UnknownMinimizerError\n\n\nclass Controller:\n \"\"\"\n Base class for all fitting software controllers.\n These controllers are intended to be the only interface into the fitting\n software, and should do so by implementing the abstract classes defined\n here.\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n VALID_FLAGS = [0, 1, 2, 3]\n\n def __init__(self, cost_func):\n \"\"\"\n Initialise anything that is needed specifically for the\n software, do any work that can be done without knowledge of the\n minimizer to use, or function to fit, and call\n ``super(Controller, self).__init__(problem)``\n (the base class's ``__init__`` implementation).\n In this function, you must initialize the a dictionary,\n ``self.algorithm_type``, such that the **keys** are given by:\n\n - ``all`` - all minimizers\n - ``ls`` - least-squares fitting algorithms\n - ``deriv_free`` - derivative free algorithms (these are algorithms\n that cannot use derivative information. For example, the\n ``Simplex`` method in ``Mantid`` does not require Jacobians, and so\n is derivative free.\n However, ``lm-scipy-no-jac`` in ``scipy_ls`` is designed to use\n derivatives, but calculates an approximation internally if one is not\n supplied.)\n - ``general`` - minimizers which solve a generic `min f(x)`.\n\n The **values** of the dictionary are given as a list of minimizers\n for that specific controller that fit into each of the above\n categories. See for example the ``GSL`` controller.\n\n :param cost_func: Cost function object selected from options.\n :type cost_func: subclass of\n :class:`~fitbenchmarking.cost_func.base_cost_func.CostFunc`\n \"\"\"\n self.cost_func = cost_func\n # Problem: The problem object from parsing\n self.problem = self.cost_func.problem\n\n # Jacobian: The Jacobian object\n self.jacobian = None\n\n # Data: Data used in fitting. Might be different from problem\n # if corrections are needed (e.g. startX)\n self.data_x = self.problem.data_x\n self.data_y = self.problem.data_y\n self.data_e = self.problem.data_e\n\n # Initial Params: The starting values for params when fitting\n self.initial_params = None\n # Staring Valuess: The list of starting parameters\n self.starting_values = self.problem.starting_values\n # Parameter set: The index of the starting parameters to use\n self.parameter_set = None\n # Minimizer: The current minimizer to use\n self.minimizer = None\n\n # Final Params: The final values for the params from the minimizer\n self.final_params = None\n\n # Flag: error handling flag\n self._flag = None\n\n # Algorithm check: this is used to check whether the selected\n # minimizer/minimizers from the options is within the softwares\n # algorithms. It also used to filter out algorithms based on the keys\n # of the dictionary\n self.algorithm_check = {'all': [None],\n 'ls': [None],\n 'deriv_free': [None],\n 'general': [None]}\n\n @property\n def flag(self):\n \"\"\"\n | 0: `Successfully converged`\n | 1: `Software reported maximum number of iterations exceeded`\n | 2: `Software run but didn't converge to solution`\n | 3: `Software raised an exception`\n \"\"\"\n\n return self._flag\n\n @flag.setter\n def flag(self, value):\n\n if value not in self.VALID_FLAGS:\n raise ControllerAttributeError(\n 'controller.flag must be one of {}. Got: {}.'.format(\n list(self.VALID_FLAGS), value))\n self._flag = int(value)\n\n def prepare(self):\n \"\"\"\n Check that function and minimizer have been set.\n If both have been set, run self.setup().\n \"\"\"\n\n if (self.minimizer is not None) and (self.parameter_set is not None):\n self.initial_params = \\\n list(self.starting_values[self.parameter_set].values())\n self.setup()\n else:\n raise ControllerAttributeError('Either minimizer or parameter_set '\n 'is set to None.')\n\n def eval_chisq(self, params, x=None, y=None, e=None):\n \"\"\"\n Computes the chisq value\n\n :param params: The parameters to calculate residuals for\n :type params: list\n :param x: x data points, defaults to self.data_x\n :type x: numpy array, optional\n :param y: y data points, defaults to self.data_y\n :type y: numpy array, optional\n :param e: error at each data point, defaults to self.data_e\n :type e: numpy array, optional\n\n :return: The sum of squares of residuals for the datapoints at the\n given parameters\n :rtype: numpy array\n \"\"\"\n out = self.cost_func.eval_cost(params=params, x=x, y=y, e=e)\n return out\n\n def validate_minimizer(self, minimizer, algorithm_type):\n \"\"\"\n Helper function which checks that the selected minimizer from the\n options (options.minimizer) exists and whether the minimizer is in\n self.algorithm_check[options.algorithm_type] (this is a list set in\n the controller)\n\n :param minimizer: string of minimizers selected from the\n options\n :type minimizer: str\n :param algorithm_type: the algorithm type selected from the options\n :type algorithm_type: str\n \"\"\"\n minimzer_selection = self.algorithm_check[algorithm_type]\n result = minimizer in minimzer_selection\n\n if not result:\n message = 'The minimizer selected, {0}, is not within ' \\\n 'algorithm_check[options.algorithm_type] = {1}\\n'.format(\n minimizer, minimzer_selection)\n raise UnknownMinimizerError(message)\n\n def check_attributes(self):\n \"\"\"\n A helper function which checks all required attributes are set\n in software controllers\n \"\"\"\n values = {'_flag': int, 'final_params': numpy.ndarray}\n\n for attr_name, attr_type in values.items():\n attr = getattr(self, attr_name)\n if attr_type != numpy.ndarray:\n if not isinstance(attr, attr_type):\n raise ControllerAttributeError(\n 'Attribute \"{}\" in the controller is not the expected '\n 'type. Expected \"{}\", got {}.'.format(\n attr_name, attr_type, type(attr)))\n else:\n # Mantid multifit produces final params as a list of final\n # params.\n if not self.problem.multifit:\n attr = [attr]\n for a in attr:\n if any(numpy.isnan(n) or numpy.isinf(n) for n in a):\n raise ControllerAttributeError(\n 'Attribute \"{}\" in the controller is not the '\n 'expected numpy ndarray of floats. Expected a '\n 'list or numpy ndarray of floats, got '\n '{}'.format(attr_name, attr))\n\n @abstractmethod\n def jacobian_information(self):\n \"\"\"\n Sets up Jacobian information for the controller.\n\n This should return the following arguments:\n\n - ``has_jacobian``: a True or False value whether the controller\n requires Jacobian information.\n - ``jacobian_free_solvers``: a list of minimizers in a specific software\n that do not require Jacobian information to be passed into the fitting\n algorithm. For example in the ``ScipyLS`` controller this would return\n ``lm-scipy-no-jac``.\n\n :return: (``has_jacobian``, ``jacobian_free_solvers``)\n :rtype: (`string`, `list`)\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def setup(self):\n \"\"\"\n Setup the specifics of the fitting.\n\n Anything needed for \"fit\" that can only be done after knowing the\n minimizer to use and the function to fit should be done here.\n Any variables needed should be saved to self (as class attributes).\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def fit(self):\n \"\"\"\n Run the fitting.\n\n This will be timed so should include only what is needed to fit the data.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def cleanup(self):\n \"\"\"\n Retrieve the result as a numpy array and store results.\n\n Convert the fitted parameters into a numpy array, saved to\n ``self.final_params``, and store the error flag as ``self.flag``.\n\n The flag corresponds to the following messages:\n\n .. automethod:: fitbenchmarking.controllers.base_controller.Controller.flag()\n :noindex:\n \"\"\"\n raise NotImplementedError\n","sub_path":"fitbenchmarking/controllers/base_controller.py","file_name":"base_controller.py","file_ext":"py","file_size_in_byte":9378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"610662274","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 7 13:15:47 2018\n\n@author: chenhx1992\n\"\"\"\n\nimport glob, os\nimport shutil\nimport re\n\nos.chdir('./training_raw/')\n\nfor file in glob.glob('*.hea'):\n with open(file) as from_file:\n\n line = from_file.readline().strip()\n\n # make any changes to line here\n p = re.compile('(?P\\S+)\\s(?P\\S+)\\s(?P\\S+)\\s(?P\\S+)\\s(?P\\d+)-(?P\\d+)-(?P\\d+)\\s(?P
\\d+):(?P\\d+):(?P\\d+)')\n info = p.search(line)\n\n new_line = '{} {} {} {} {}:{}:{} {}/{}/{} \\n'.format(info.group('name'), info.group('num'), info.group('freq'), info.group('length'), info.group('hr'), info.group('min'), info.group('sec'), info.group('day'), info.group('month'), info.group('year'))\n\n with open(file, 'w') as to_file:\n to_file.write(new_line)\n shutil.copyfileobj(from_file, to_file)","sub_path":"wfdb_header.py","file_name":"wfdb_header.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"586950220","text":"import logging\n\n\nclass Tool():\n options = {}\n\n def __init__(self, parser=None):\n self.parser = None\n if parser is not None:\n self.parser = parser.add_parser(self.command, help=self.help)\n\n def prepare(self, opts):\n for option, option_type in self.options.items():\n default_value = None\n if type(option_type) is tuple:\n option_type, default_value = option_type\n setattr(self, option, opts.get(option, default_value))\n\n def run(self, args):\n raise NotImplementedError\n\n def output(self, output_data, output_file, output_format, force=False):\n if output_file is None:\n output_data = output_format().join(None, output_file, output_data)\n print(output_data)\n else:\n if type(output_data) is dict:\n for extension, data in output_data.items():\n data = output_format().join(extension, output_file, data)\n self.write_file(output_file.with_suffix(f'.{extension}'), data, force)\n else:\n output_data = output_format().join(None, output_file, output_data)\n self.write_file(output_file, output_data, force)\n\n def write_file(self, output_file, output_data, force=False):\n if output_file.exists() and not force:\n raise ValueError(f'Refusing to overwrite {output_file} (use force)')\n else:\n logging.info(f'Writing {output_file}')\n if type(output_data) is str:\n open(output_file, 'wb').write(output_data.encode('utf-8'))\n else:\n open(output_file, 'wb').write(output_data)\n","sub_path":"src/ttblit/core/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"492123211","text":"'''\nGiven a natural number input, calculate the sum\nof that number of primes beginning at 2.\n\nJared Neumann\n27 June 2015\n'''\n\n#Define a function to check whether a number is prime.\n#Only numbers >= 2 will be passed since is_prime will\n#only be called in the add_primes function.\ndef is_prime(n):\n if n == 2:\n return True\n \n if not n & 1:\n return False\n \n for x in range(3, int(n**0.5)+1, 2):\n if n % x == 0:\n return False\n \n return True\n \n#Define the function to add a number of primes\n#beginning with 2 up to the prime corresponding\n#to the last index (e.g., the 1000th prime is 7919).\ndef add_primes(number_of_primes):\n\n #Create a list of primes up to an upperbound.\n i = 2\n primes = []\n for i in range(2, 10*number_of_primes):\n if is_prime(i) == True:\n primes.append(i)\n \n #Chop off unnecessary primes.\n primes = primes[:number_of_primes]\n \n #Add up all the elements in the list.\n sum_of_primes = sum(primes)\n\n return sum_of_primes\n","sub_path":"addprimes.py","file_name":"addprimes.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"51843094","text":"data = []\n\nwith open(\"test.json\") as f:\n for line in f:\n idSt = line.find(\"identifier\") + 13\n idEn = line.find(\"\\\"\", idSt)\n ident = line[idSt:idEn]\n \n inp = open(\"all/test-\" + ident + \"-0.txt\")\n pixels = inp.readlines()[0][21:].split(\", \")\n inp.close()\n pixels[-1] = pixels[-1][:-3]\n data.append(pixels)\n\nprint(\"Datareading done\")\n \nduplicates = 0\nfor x in range(0, 989):\n if (x % 100 == 0):\n print (x)\n image = data[x]\n for y in range(x+1, 990):\n image2 = data[y]\n same = True\n for p in range(0, 4096):\n if image[p] != image2[p]:\n same = False\n break\n if same:\n duplicates = duplicates + 1\n break\n \nprint(duplicates)","sub_path":"Archive/CS412 - 2021/Blue triangles/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"474536261","text":"#!/usr/bin/env python3.4\nimport webSocketClient\nimport motorInterface\nimport json\n\n# axis and button labels\naxis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight']\nbuttons = ['A', 'B', 'X', 'Y', 'LB', 'RB']\n\n# trim to adjust for buoyancy of the miniROV\ntrimUp = {\n 'center': 0.0\n}\n\n# don't know what that means\n# ||\n# \\/\n# these are in a row\n\n\n# this motor is IN3/4 on the edge of the motor controller\n# these pins are based on how the 2019 miniROV was wired up\nm1 = motorInterface.motor(16, 26) # vertical\nm2 = motorInterface.motor(12, 13) # unused\n\n# 2nd motor controller\nm3 = motorInterface.motor(27, 23) # side (maybe left)\nm4 = motorInterface.motor(4, 18) # side (maybe right)\n\n# functions for no real reason\ndef move1(pow):\n m1.set(pow)\n\ndef move2(pow):\n m2.set(pow)\n\ndef move3(pow):\n m3.set(pow)\n\ndef move4(pow):\n m4.set(pow)\n\n# Used to keep track when a button is pressed and when released\n# so that functions won't fire twice from one button press\njustPressed = [\n {\n 'A': False,\n 'B': False,\n 'X': False,\n 'Y': False,\n 'LB': False,\n 'RB': False\n },\n {\n 'A': False,\n 'B': False,\n 'X': False,\n 'Y': False,\n 'LB': False,\n 'RB': False\n }\n]\n\ndef buttonPressed(button, num):\n # this function is called whenever a button is pressed,\n # any button releated features should be added here\n global trimUp\n # num is 0 or 1, representing if it's the first or second xbox controller\n\n # 0 is 1st controller\n # 1 is 2nd controller\n\n # LB and RB are used to set the trim of the miniROV\n if num == 1: # 2nd controller\n if button == 'LB':\n trimUp['center'] += 1 # trim up when LB is pressed\n elif button == 'RB':\n trimUp['center'] -= 1 # trim down when RB is pressed\n\n\n\ndef process(data):\n # this function processes received joystick data\n\n # turn the data json string into a list \n # data contains the value of the joysticks buttons/axis\n joysticks = json.loads(data)\n # make sure it has the right number of buttons/axis\n assert len(joysticks) == 24\n\n # axis and buttons are the labels\n\n # match up the labels with the data values to make a dictionary\n joystick1 = dict(zip(axis + buttons, joysticks[:12]))\n joystick2 = dict(zip(axis + buttons, joysticks[12:]))\n\n old = [] # for debugging\n\n del data\n\n global justPressed\n\n stickNum = 0\n # for each xbox controller\n # (joystick1, joystick2) is a tuple of two dicts\n # justPressed is a list of two dicts\n for stick, jPressed in zip((joystick1, joystick2), justPressed):\n # stick is a dictionary containing the labels and values of each button/axis on\n # one of the joysticks\n\n # jPressed is one of the dictionaries from the justPressed list\n\n # for every button/axis on this xbox controller\n for k in stick:\n # k is the button/axis label\n\n # ignore axis\n if k not in buttons:\n continue\n\n # v is the value of button k\n v = stick[k]\n\n # if button k is pressed and wasn't pressed already\n if v == 1 and not jPressed[k]:\n # process that this button was just pressed\n buttonPressed(k, stickNum)\n\n # \n # Update jPressed so that buttonPressed() \n # won't fire twice for one button press\n # \n jPressed[k] = True\n\n # if button k is not pressed but it was pressed before\n elif v == 0 and jPressed[k]:\n # Button k was just released\n\n # Update that jPressed is no longer pressed\n # so that buttonPressed() will activate again if it is pressed again\n jPressed[k] = False\n\n # if button k has a value other than the normal 0 or 1\n elif v not in [1, 0]:\n # should never happen\n raise ValueError('Got {0}, expected 0 or 1'.format(v))\n\n # if button k hasn't changed status\n else:\n pass\n\n # add one to stickNum\n # it is needed for buttonPressed()\n stickNum += 1\n\n del stickNum\n\n # for mixing controls\n yLeft = 50 * joystick2['yLeft']\n yRight = 50 * joystick2['yRight']\n\n # triggerRight and triggerLeft have values of -1 to +1,\n # so adjust them to be 0 to +1\n joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2\n joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2\n\n # vertical power level\n vertical = 0\n\n if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1:\n pass # do nothing cause both are pressed\n else:\n # the axis might not go to exact 0 so the if statements try to cut it out\n\n if joystick2['triggerRight'] > 0.1:\n vertical = joystick2['triggerRight'] * 50\n\n if joystick2['triggerLeft'] > 0.1:\n vertical = -joystick2['triggerLeft'] * 50\n\n\n # Mini-ROV motor setup\n # top view\n # ____\n # | |\n # /a\\| |/b\\\n # |____|\n # (up)\n #\n\n motor_a = yLeft\n\n motor_b = yRight\n\n global trimUp\n\n # add the trim to the vertical power level\n motor_up = trimUp['center'] + vertical\n\n \n def bounds(x):\n # makes sure that values stay between -50 to 50\n # max power is -100 to 100\n if x < -50:\n return -50\n if x > 50:\n return 50\n\n # round the result just to have cleaner decimals\n return round(x, 2)\n\n # make sure each is within allowed bounds\n motor_a = bounds(motor_a)\n motor_b = bounds(motor_b)\n motor_up = bounds(motor_up)\n \n # set the motors\n # which motor is which depends on the wiring of the miniROV\n # This is set to the wiring of the 2019 miniROV\n move1(motor_up)\n move4(motor_a)\n move3(motor_b)\n\n # ----- print information -----\n\n # clear the console window\n for i in range(30):\n # \\r goes the the front of the line on the console\n # \\033[A goes up a line\n # \\033[K clears the line\n print('\\r\\033[A\\033[K', end='')\n\n # display trim\n print('Trim: {0}'.format(trimUp['center']))\n # display joystick values\n print(joystick1)\n print(joystick2)\n # display power levels\n print(motor_a, motor_b)\n print(motor_up)\n print()\n\n #\n # for debugging\n # anything added to the old list will be printed here\n #\n # !!! IMPORTANT FOR DEBUGGING !!!\n # because of the screen clearing,\n # nothing printed before it will actually be visible\n # as it will be deleted by the screen clearing.\n # thus, any debug info to pring must be added to old\n # so that it is printed here after the screen clearing\n #\n index = 0\n for i in old:\n print(index, i)\n index += 1\n\n# start the code\n# ip should be of the surface pi\n# type is 'miniROV'\nwebSocketClient.start('miniROV', process, ip=\"192.168.1.2\")\n","sub_path":"code/mini-rov/hydrogenMiniROVClient2020.py","file_name":"hydrogenMiniROVClient2020.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"495331448","text":"from pyrez.api import PaladinsAPI\nimport json\n\nfile_name = \"token\"\n# Gets ID and KEY from a file\nwith open(file_name, 'r') as f:\n TOKEN = f.readline().strip() # Does nothing\n PREFIX = f.readline() # Does nothing\n ID = int(f.readline())\n KEY = f.readline()\nf.close()\n\npaladinsAPI = PaladinsAPI(devId=ID, authKey=KEY)\n\n\"\"\"\ntry:\n player = paladinsAPI.getPlayer(\"Bubbles\")\n print(player)\n player = paladinsAPI.getPlayerId(\"Bubbles\", \"22\")\n player = paladinsAPI.getPlayer(player[0].playerId)\n print(player)\nexcept BaseException:\n print(\"could not find\")\n\"\"\"\n\n\ndef get_player_id(player_name):\n if str(player_name).isnumeric():\n return player_name\n with open(\"player_ids\") as json_f:\n player_ids = json.load(json_f)\n\n # This player is already in the dictionary and therefor we don't need to waste an api call to get the player id.\n if player_name in player_ids:\n return player_ids[player_name]\n else:\n try:\n original_name = player_name\n if \"\\\"\" not in player_name:\n player = paladinsAPI.getPlayer(player_name)\n else: # Console name\n player_name, platform = player_name.replace('\\\"', \"\").rsplit(' ', 1)\n players = paladinsAPI.searchPlayers(player_name)\n\n platform = platform.lower()\n if platform == \"xbox\":\n platform = \"10\"\n elif platform == \"ps4\":\n platform = \"9\"\n elif platform == \"switch\":\n platform = \"22\"\n else:\n # ```md\\nInvalid platform name. Valid platform names are:\\n1. Xbox\\n2. PS4\\n3. Switch```\n return -2\n\n players = [player for player in players if player.playerName.lower() == player_name.lower() and\n player['portal_id'] == platform]\n num_players = len(players)\n if num_players > 1:\n return -3 # too many names (name overlap in switch)\n\n # The one player name\n player = players.pop()\n\n except BufferError:\n return -1 # invalid name\n new_id = int(player.playerId)\n player_ids[original_name] = new_id # store the new id in the dictionary\n\n # need to update the file now\n print(\"Added a new player the dictionary: \" + player_name)\n with open(\"player_ids\", 'w') as json_f:\n json.dump(player_ids, json_f)\n return new_id\n\n\n# print(get_player_id(\"AndrewChicken\"))\n# print(get_player_id(\"\\\"GUNZJESTER PS4\\\"\"))\n# print(get_player_id(\"\\\"Tadd Nasty xbox\\\"\"))\n# print(get_player_id(710620894))\n\n# player = paladinsAPI.getPlayer(710620894)\n# print(player)\napi_calls = paladinsAPI.getDataUsed()\nprint(api_calls)\napi_calls = api_calls.totalRequestsToday\nprint(api_calls)\n\n# paladins_data = paladinsAPI.getMatchHistory(7241948)\n# print(paladins_data)\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"519557230","text":"from pathlib import Path\nfrom setuptools import setup, find_packages\n\n\nPROJECT_DIR = Path(__file__).parent.resolve(strict=True)\n\n\ndef get_version() -> str:\n \"\"\"Return the package version as a str\"\"\"\n VERSION_FILE = PROJECT_DIR / \"sr\" / \"_version.py\"\n _globals = {}\n with open(VERSION_FILE) as f:\n exec(f.read(), _globals)\n\n return _globals[\"__version__\"]\n\n\nsetup(\n name=\"pydicom-data-sr\",\n packages=find_packages(),\n include_package_data=True,\n version=get_version(),\n zip_safe=False,\n description=\"\",\n long_description=\"\",\n long_description_content_type=\"text/markdown\",\n author=\"scaramallion\",\n author_email=\"scaramallion@users.noreply.github.com\",\n url=\"https://github.com/pydicom/pydicom-sr-data\",\n license=\"MIT\",\n keywords=\"dicom python pydicom sr structuredreports\",\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Healthcare Industry\",\n \"Intended Audience :: Science/Research\",\n \"Development Status :: 1 - Planning\",\n \"Natural Language :: English\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Operating System :: OS Independent\",\n \"Topic :: Scientific/Engineering :: Medical Science Apps.\",\n \"Topic :: Software Development :: Libraries\",\n ],\n python_requires=\">=3.6\",\n setup_requires=[\"setuptools>=18.0\"],\n install_requires=[],\n extras_require={\n \"dev\": [\n \"beautifulsoup4==4.9.3\",\n \"requests==2.25.1\",\n \"black==21.6b0\",\n \"mypy==0.902\",\n \"types-requests==0.1.11\",\n \"pytest==6.2.4\",\n ]\n },\n entry_points={\n \"pydicom.data.sr\": \"pydicom-data-sr = sr:foo\",\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"374900869","text":"#!/usr/bin/python3\n'''\nThis script accesses a subreddit, filters its top ten 'hot' posts,\nand then returns the title of each post.\n'''\nimport requests\n\n\ndef top_ten(subreddit):\n '''\n Prints out the top ten 'hot' post titles for a given subreddit, or 'None'\n if the subreddit doesn't exists.\n '''\n url = 'https://reddit.com/r/{}/hot.json?limit=10'.format(subreddit)\n headers = {'User-Agent': 'My User Agent 1.0',\n 'From': '364@holbertonschool.com'}\n r = requests.get(url, headers=headers)\n\n try:\n result = r.json()\n for x in result['data']['children']:\n print(x['data']['title'])\n except BaseException:\n print('None')\n","sub_path":"0x16-api_advanced/1-top_ten.py","file_name":"1-top_ten.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"337941293","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport unittest\n\n# run script from peano directory\nimport sys\nimport os\nsys.path.append(os.path.dirname(sys.argv[0]) + '/../lib')\n\nfrom examples import *\nfrom fractal_curve import FractalCurve\nfrom curve_sat_adapter import CurveSATAdapter\n\nclass TestCurve(unittest.TestCase):\n def setUp(self):\n self.curves = [\n get_peano_curve().forget(),\n get_meurthe_curve().forget(),\n ]\n\n def test_curves(self):\n for pcurve in self.curves:\n for curve in FractalCurve.gen_possible_curves(pcurve):\n adapter = CurveSATAdapter(dim=pcurve.dim)\n adapter.init_curve(pcurve)\n model = adapter.get_model_from_curve(curve)\n juncs = curve.get_junctions()\n for junc in juncs:\n junc_var = adapter.get_junc_var(junc)\n if not model[junc_var]:\n raise Exception(\"Bad junc_var: False for existent junc!\")\n# for junc in junc_info:\n# if junc not in juncs:\n# junc_var = adapter.get_junc_var(junc)\n# if model[junc_var]:\n# raise Exception(\"Bad junc_var: True for non-existent junc!\")\n print('.', end='', flush=True)\n\n print('*', flush=True)\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"test/sat.py","file_name":"sat.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"560897077","text":"\"\"\"\nsentry.utils.http\n~~~~~~~~~~~~~~~~~\n\n:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.\n:license: BSD, see LICENSE for more details.\n\"\"\"\nfrom __future__ import absolute_import\n\nfrom collections import namedtuple\n\nimport six\nfrom django.conf import settings\nfrom six.moves.urllib.parse import urlencode,urlparse\n\nParsedUriMatch=namedtuple('ParsedUriMatch',['scheme','domain','path'])\n\ndef origin_from_url(url):\n if not url:\n return url\n url=urlparse(url)\n return '%s://%s'%(url.scheme,url.netloc)\n\ndef safe_urlencode(params,doseq=0):\n \"\"\"\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n \"\"\"\n # Snippet originally from pysolr: https://github.com/toastdriven/pysolr\n\n if hasattr(params,\"items\"):\n params=params.items()\n\n new_params=list()\n\n for k,v in params:\n k=k.encode(\"utf-8\")\n\n if isinstance(v,six.string_types):\n new_params.append((k,v.encode(\"utf-8\")))\n elif isinstance(v,(list,tuple)):\n new_params.append((k,[i.encode(\"utf-8\") for i in v]))\n else:\n new_params.append((k,six.text_type(v)))\n\n return urlencode(new_params,doseq)\n\ndef is_same_domain(url1,url2):\n \"\"\"\n Returns true if the two urls should be treated as if they're from the same\n domain (trusted).\n \"\"\"\n url1=urlparse(url1)\n url2=urlparse(url2)\n return url1.netloc==url2.netloc\n\ndef get_origins(project=None):\n if settings.SENTRY_ALLOW_ORIGIN=='*':\n return frozenset(['*'])\n\n if settings.SENTRY_ALLOW_ORIGIN:\n result=settings.SENTRY_ALLOW_ORIGIN.split(' ')\n else:\n result=[]\n\n if project:\n optval=project.get_option('sentry:origins',['*'])\n if optval:\n result.extend(optval)\n\n # lowercase and strip the trailing slash from all origin values\n # filter out empty values\n return frozenset(filter(bool,map(lambda x:x.lower().rstrip('/'),result)))\n\ndef parse_uri_match(value):\n if '://' in value:\n scheme,value=value.split('://',1)\n else:\n scheme='*'\n\n if '/' in value:\n domain,path=value.split('/',1)\n else:\n domain,path=value,'*'\n\n if ':' in domain:\n domain,port=value.split(':',1)\n else:\n port=None\n\n # we need to coerce our unicode inputs into proper\n # idna/punycode encoded representation for normalization.\n if type(domain)==six.binary_type:\n domain=domain.decode('utf8')\n domain=domain.encode('idna')\n\n if port:\n domain='%s:%s'%(domain,port)\n\n return ParsedUriMatch(scheme,domain,path)\n\ndef is_valid_origin(origin,project=None,allowed=None):\n \"\"\"\n Given an ``origin`` which matches a base URI (e.g. http://example.com)\n determine if a valid origin is present in the project settings.\n\n Origins may be defined in several ways:\n\n - http://domain.com[:port]: exact match for base URI (must include port)\n - *: allow any domain\n - *.domain.com: matches domain.com and all subdomains, on any port\n - domain.com: matches domain.com on any port\n - *:port: wildcard on hostname, but explicit match on port\n \"\"\"\n if allowed is None:\n allowed=get_origins(project)\n\n if not allowed:\n return False\n\n if '*' in allowed:\n return True\n\n if not origin:\n return False\n\n # we always run a case insensitive check\n origin=origin.lower()\n\n # Fast check\n if origin in allowed:\n return True\n\n # XXX: In some cases origin might be localhost (or something similar) which causes a string value\n # of 'null' to be sent as the origin\n if origin=='null':\n return False\n\n if type(origin)==six.binary_type:\n origin=origin.decode('utf-8')\n\n parsed=urlparse(origin)\n\n if parsed.hostname is None:\n parsed_hostname=''\n else:\n try:\n parsed_hostname=parsed.hostname.encode('idna')\n except UnicodeError:\n # We sometimes shove in some garbage input here, so just opting to ignore and carry on\n parsed_hostname=parsed.hostname\n\n if parsed.port:\n domain_matches=(\n '*',\n parsed_hostname,\n # Explicit hostname + port name\n '%s:%d'%(parsed_hostname,parsed.port),\n # Wildcard hostname with explicit port\n '*:%d'%parsed.port,\n )\n else:\n domain_matches=('*',parsed_hostname)\n\n for value in allowed:\n try:\n bits=parse_uri_match(value)\n except UnicodeError:\n # We hit a bad uri, so ignore this value\n continue\n\n # scheme supports exact and any match\n if bits.scheme not in ('*',parsed.scheme):\n continue\n\n # domain supports exact, any, and prefix match\n if bits.domain[:2]=='*.':\n if parsed_hostname.endswith(bits.domain[1:]) or parsed_hostname==bits.domain[2:]:\n return True\n continue\n elif bits.domain not in domain_matches:\n continue\n\n # path supports exact, any, and suffix match (with or without *)\n path=bits.path\n if path=='*':\n return True\n if path.endswith('*'):\n path=path[:-1]\n if parsed.path.startswith(path):\n return True\n return False\n\ndef origin_from_request(request):\n \"\"\"\n Returns either the Origin or Referer value from the request headers,\n ignoring \"null\" Origins.\n \"\"\"\n rv=request.META.get('HTTP_ORIGIN','null')\n # In some situation, an Origin header may be the literal value\n # \"null\". This means that the Origin header was stripped for\n # privacy reasons, but we should ignore this value entirely.\n # Behavior is specified in RFC6454. In either case, we should\n # treat a \"null\" Origin as a nonexistent one and fallback to Referer.\n if rv in ('','null'):\n rv=origin_from_url(request.META.get('HTTP_REFERER'))\n return rv\n","sub_path":"launcher/utils/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":5524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"225671470","text":"\"\"\"A prompt-toolkit inspired shortcut collection.\"\"\"\n\nimport pygments.lexer\nfrom pygments.token import Token\n\nfrom prompt_toolkit.buffer import Buffer, AcceptAction\nfrom prompt_toolkit.document import Document\nfrom prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER\nfrom prompt_toolkit.filters import IsDone, HasFocus, RendererHeightIsKnown, to_simple_filter, to_cli_filter, Condition\nfrom prompt_toolkit.history import InMemoryHistory\nfrom prompt_toolkit.interface import CommandLineInterface, Application, AbortAction\nfrom prompt_toolkit.key_binding.manager import KeyBindingManager\nfrom prompt_toolkit.layout import Window, HSplit, VSplit, FloatContainer, Float\nfrom prompt_toolkit.layout.containers import ConditionalContainer\nfrom prompt_toolkit.layout.controls import BufferControl, TokenListControl\nfrom prompt_toolkit.layout.dimension import LayoutDimension\nfrom prompt_toolkit.layout.lexers import PygmentsLexer\nfrom prompt_toolkit.layout.menus import CompletionsMenu, MultiColumnCompletionsMenu\nfrom prompt_toolkit.layout.processors import PasswordProcessor, ConditionalProcessor, AppendAutoSuggestion\nfrom prompt_toolkit.layout.prompt import DefaultPrompt\nfrom prompt_toolkit.layout.screen import Char\nfrom prompt_toolkit.styles import PygmentsStyle\nfrom prompt_toolkit.layout.toolbars import ValidationToolbar, SystemToolbar, ArgToolbar, SearchToolbar\nfrom prompt_toolkit.layout.utils import explode_tokens\nfrom prompt_toolkit.utils import is_conemu_ansi, is_windows, DummyContext\nfrom prompt_toolkit.shortcuts import (create_prompt_application, \n create_eventloop, create_asyncio_eventloop, create_output, \n _split_multiline_prompt)\n\ntry:\n from prompt_toolkit.styles import DEFAULT_STYLE\nexcept ImportError:\n DEFAULT_STYLE = None\n\ntry:\n from prompt_toolkit.layout.highlighters import (SearchHighlighter, \n SelectionHighlighter, ConditionalHighlighter)\nexcept ImportError:\n SearchHighlighter = SelectionHighlighter = ConditionalHighlighter = None\n\n\nclass Prompter(object):\n\n def __init__(self, cli=None, *args, **kwargs):\n \"\"\"Implements a prompt that statefully holds a command-line \n interface. When used as a context manager, it will return itself\n on entry and reset itself on exit.\n\n Parameters\n ----------\n cli : CommandLineInterface or None, optional\n If this is not a CommandLineInterface object, such an object\n will be created when the prompt() method is called.\n \"\"\"\n self.cli = cli\n\n def __enter__(self):\n self.reset()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n #self.reset()\n pass\n\n def prompt(self, message='', **kwargs):\n \"\"\"Get input from the user and return it.\n\n This is a wrapper around a lot of prompt_toolkit functionality and \n can be a replacement for raw_input. (or GNU readline.) If you want \n to keep your history across several calls, create one \n `~prompt_toolkit.history.History instance and pass it every \n time. This function accepts many keyword arguments. Except for the \n following. they are a proxy to the arguments of \n create_prompt_application().\n\n Parameters\n ----------\n patch_stdout : file-like, optional\n Replace ``sys.stdout`` by a proxy that ensures that print \n statements from other threads won't destroy the prompt. (They\n will be printed above the prompt instead.)\n return_asyncio_coroutine : bool, optional\n When True, return a asyncio coroutine. (Python >3.3)\n\n Notes\n -----\n This method was forked from the mainline prompt-toolkit repo.\n Copyright (c) 2014, Jonathan Slenders, All rights reserved.\n \"\"\"\n patch_stdout = kwargs.pop('patch_stdout', False)\n return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)\n if return_asyncio_coroutine:\n eventloop = create_asyncio_eventloop()\n else:\n eventloop = kwargs.pop('eventloop', None) or create_eventloop()\n\n # Create CommandLineInterface.\n if self.cli is None:\n cli = CommandLineInterface(\n application=self.create_prompt_application(message, **kwargs),\n eventloop=eventloop,\n output=create_output())\n self.cli = cli\n else:\n cli = self.cli\n\n # Replace stdout.\n patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()\n\n # Read input and return it.\n if return_asyncio_coroutine:\n # Create an asyncio coroutine and call it.\n exec_context = {'patch_context': patch_context, 'cli': cli}\n exec_(textwrap.dedent('''\n import asyncio\n @asyncio.coroutine\n def prompt_coro():\n with patch_context:\n document = yield from cli.run_async(reset_current_buffer=False)\n if document:\n return document.text\n '''), exec_context)\n return exec_context['prompt_coro']()\n else:\n # Note: We pass `reset_current_buffer=False`, because that way \n # it's easy to give DEFAULT_BUFFER a default value, without it \n # getting erased. We don't have to reset anyway, because this is \n # the first and only time that this CommandLineInterface will run.\n try:\n with patch_context:\n document = cli.run(reset_current_buffer=False)\n\n if document:\n return document.text\n finally:\n eventloop.close()\n\n def reset(self):\n \"\"\"Resets the prompt and cli to a pristine state on this object.\"\"\"\n self.cli = None\n\n def create_prompt_layout(self, message='', lexer=None, is_password=False,\n reserve_space_for_menu=8, get_prompt_tokens=None, \n get_bottom_toolbar_tokens=None, display_completions_in_columns=False,\n extra_input_processors=None, multiline=False, wrap_lines=True):\n \"\"\"Create a Container instance for a prompt.\n\n Parameters\n ----------\n message : Text to be used as prompt.\n lexer : ~prompt_toolkit.layout.lexers.Lexer to be used for\n the highlighting.\n is_password : bool or ~prompt_toolkit.filters.CLIFilter.\n When True, display input as '*'.\n reserve_space_for_menu : Space to be reserved for the menu. When >0,\n make sure that a minimal height is allocated in the terminal, in order\n to display the completion menu.\n get_prompt_tokens : An optional callable that returns the tokens to be\n shown in the menu. (To be used instead of a `message`.)\n get_bottom_toolbar_tokens : An optional callable that returns the\n tokens for a toolbar at the bottom.\n display_completions_in_columns : `bool` or\n :class:`~prompt_toolkit.filters.CLIFilter`. Display the completions in\n multiple columns.\n multiline : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.\n When True, prefer a layout that is more adapted for multiline input.\n Text after newlines is automatically indented, and search/arg input is\n shown below the input, instead of replacing the prompt.\n wrap_lines : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.\n When True (the default), automatically wrap long lines instead of\n scrolling horizontally.\n\n Notes\n -----\n This method was forked from the mainline prompt-toolkit repo.\n Copyright (c) 2014, Jonathan Slenders, All rights reserved.\n\n WARNING; This method is due for removal once prompt-toolkit >v0.54 \n is released.\n \"\"\"\n assert isinstance(message, str)\n assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens)\n assert get_prompt_tokens is None or callable(get_prompt_tokens)\n assert not (message and get_prompt_tokens)\n\n display_completions_in_columns = to_cli_filter(display_completions_in_columns)\n multiline = to_cli_filter(multiline)\n\n if get_prompt_tokens is None:\n get_prompt_tokens = lambda _: [(Token.Prompt, message)]\n\n get_prompt_tokens_1, get_prompt_tokens_2 = _split_multiline_prompt(get_prompt_tokens)\n\n # `lexer` is supposed to be a `Lexer` instance. But if a Pygments lexer\n # class is given, turn it into a PygmentsLexer. (Important for\n # backwards-compatibility.)\n try:\n if issubclass(lexer, pygments.lexer.Lexer):\n lexer = PygmentsLexer(lexer)\n except TypeError: # Happens when lexer is `None` or an instance of something else.\n pass\n\n # Create highlighters and processors list.\n if ConditionalHighlighter is None:\n highlighters = None\n highlighters_kwargs = {}\n else:\n highlighters = [\n ConditionalHighlighter(\n # By default, only highlight search when the search\n # input has the focus. (Note that this doesn't mean\n # there is no search: the Vi 'n' binding for instance\n # still allows to jump to the next match in\n # navigation mode.)\n SearchHighlighter(preview_search=True),\n HasFocus(SEARCH_BUFFER)),\n SelectionHighlighter()]\n highlighters_kwargs = {'highlighters': highlighters}\n\n input_processors = [\n ConditionalProcessor(AppendAutoSuggestion(), HasFocus(DEFAULT_BUFFER) & ~IsDone()),\n ConditionalProcessor(PasswordProcessor(), is_password)]\n\n if extra_input_processors:\n input_processors.extend(extra_input_processors)\n\n # Show the prompt before the input (using the DefaultPrompt processor.\n # This also replaces it with reverse-i-search and 'arg' when required.\n # (Only for single line mode.)\n # (DefaultPrompt should always be at the end of the processors.)\n input_processors.append(ConditionalProcessor(\n DefaultPrompt(get_prompt_tokens), ~multiline))\n\n # Create bottom toolbar.\n if get_bottom_toolbar_tokens:\n toolbars = [ConditionalContainer(\n Window(TokenListControl(get_bottom_toolbar_tokens,\n default_char=Char(' ', Token.Toolbar)),\n height=LayoutDimension.exact(1)),\n filter=~IsDone() & RendererHeightIsKnown())]\n else:\n toolbars = []\n\n def get_height(cli):\n # If there is an autocompletion menu to be shown, make sure that our\n # layout has at least a minimal height in order to display it.\n if reserve_space_for_menu and not cli.is_done:\n return LayoutDimension(min=reserve_space_for_menu)\n else:\n return LayoutDimension()\n\n # Create and return Container instance.\n return HSplit([\n ConditionalContainer(\n Window(\n TokenListControl(get_prompt_tokens_1),\n dont_extend_height=True),\n filter=multiline,\n ),\n VSplit([\n # In multiline mode, the prompt is displayed in a left pane.\n ConditionalContainer(\n Window(\n TokenListControl(get_prompt_tokens_2),\n dont_extend_width=True,\n ),\n filter=multiline,\n ),\n # The main input, with completion menus floating on top of it.\n FloatContainer(\n Window(\n BufferControl(\n input_processors=input_processors,\n lexer=lexer,\n wrap_lines=wrap_lines,\n # Enable preview_search, we want to have immediate feedback\n # in reverse-i-search mode.\n preview_search=True, \n **highlighters_kwargs),\n get_height=get_height,\n ),\n [\n Float(xcursor=True,\n ycursor=True,\n content=CompletionsMenu(\n max_height=16,\n scroll_offset=1,\n extra_filter=HasFocus(DEFAULT_BUFFER) &\n ~display_completions_in_columns)),\n Float(xcursor=True,\n ycursor=True,\n content=MultiColumnCompletionsMenu(\n extra_filter=HasFocus(DEFAULT_BUFFER) &\n display_completions_in_columns,\n show_meta=True))\n ]\n ),\n ]),\n ValidationToolbar(),\n SystemToolbar(),\n\n # In multiline mode, we use two toolbars for 'arg' and 'search'.\n ConditionalContainer(ArgToolbar(), multiline),\n ConditionalContainer(SearchToolbar(), multiline),\n ] + toolbars)\n\n\n def create_prompt_application(self,\n message='',\n multiline=False,\n wrap_lines=True,\n is_password=False,\n vi_mode=False,\n complete_while_typing=True,\n enable_history_search=False,\n lexer=None,\n enable_system_bindings=False,\n enable_open_in_editor=False,\n validator=None,\n completer=None,\n reserve_space_for_menu=8,\n auto_suggest=None,\n style=None,\n history=None,\n clipboard=None,\n get_prompt_tokens=None,\n get_bottom_toolbar_tokens=None,\n display_completions_in_columns=False,\n get_title=None,\n mouse_support=False,\n extra_input_processors=None,\n key_bindings_registry=None,\n on_abort=AbortAction.RAISE_EXCEPTION,\n on_exit=AbortAction.RAISE_EXCEPTION,\n accept_action=AcceptAction.RETURN_DOCUMENT,\n default=''):\n \"\"\"Create an :class:`~Application` instance for a prompt.\n\n (It is meant to cover 90% of the prompt use cases, where no extreme\n customization is required. For more complex input, it is required to create\n a custom :class:`~Application` instance.)\n\n message : Text to be shown before the prompt.\n mulitiline : Allow multiline input. Pressing enter will insert a\n newline. (This requires Meta+Enter to accept the input.)\n wrap_lines : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.\n When True (the default), automatically wrap long lines instead of\n scrolling horizontally.\n is_password : Show asterisks instead of the actual typed characters.\n vi_mode : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. If\n True, use Vi key bindings.\n complete_while_typing : `bool` or\n :class:`~prompt_toolkit.filters.CLIFilter`. Enable autocompletion while\n typing.\n enable_history_search : `bool` or\n :class:`~prompt_toolkit.filters.CLIFilter`. Enable up-arrow parting\n string matching.\n lexer : :class:`~prompt_toolkit.layout.lexers.Lexer` to be used for\n the syntax highlighting.\n validator : :class:`~prompt_toolkit.validation.Validator` instance\n for input validation.\n completer : :class:`~prompt_toolkit.completion.Completer` instance\n for input completion.\n reserve_space_for_menu : Space to be reserved for displaying the menu.\n (0 means that no space needs to be reserved.)\n auto_suggest : :class:`~prompt_toolkit.auto_suggest.AutoSuggest`\n instance for input suggestions.\n style : Pygments style class for the color scheme.\n enable_system_bindings : `bool` or\n :class:`~prompt_toolkit.filters.CLIFilter`. Pressing Meta+'!' will show\n a system prompt.\n enable_open_in_editor : `bool` or\n :class:`~prompt_toolkit.filters.CLIFilter`. Pressing 'v' in Vi mode or\n C-X C-E in emacs mode will open an external editor.\n history : :class:`~prompt_toolkit.history.History` instance.\n clipboard : :class:`~prompt_toolkit.clipboard.base.Clipboard` instance.\n (e.g. :class:`~prompt_toolkit.clipboard.in_memory.InMemoryClipboard`)\n get_bottom_toolbar_tokens : Optional callable which takes a\n :class:`~prompt_toolkit.interface.CommandLineInterface` and returns a\n list of tokens for the bottom toolbar.\n display_completions_in_columns : `bool` or\n :class:`~prompt_toolkit.filters.CLIFilter`. Display the completions in\n multiple columns.\n get_title : Callable that returns the title to be displayed in the\n terminal.\n mouse_support : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`\n to enable mouse support.\n default : The default text to be shown in the input buffer. (This can\n be edited by the user.)\n\n Notes\n -----\n This method was forked from the mainline prompt-toolkit repo.\n Copyright (c) 2014, Jonathan Slenders, All rights reserved.\n\n WARNING; This method is due for removal once prompt-toolkit >v0.54 \n is released.\n \"\"\"\n if key_bindings_registry is None:\n key_bindings_registry = KeyBindingManager.for_prompt(\n enable_vi_mode=vi_mode,\n enable_system_bindings=enable_system_bindings,\n enable_open_in_editor=enable_open_in_editor).registry\n\n # Make sure that complete_while_typing is disabled when enable_history_search\n # is enabled. (First convert to SimpleFilter, to avoid doing bitwise operations\n # on bool objects.)\n complete_while_typing = to_simple_filter(complete_while_typing)\n enable_history_search = to_simple_filter(enable_history_search)\n multiline = to_simple_filter(multiline)\n\n complete_while_typing = complete_while_typing & ~enable_history_search\n\n # Accept Pygments styles as well for backwards compatibility.\n try:\n if issubclass(style, pygments.style.Style):\n style = PygmentsStyle(style)\n except TypeError: # Happens when style is `None` or an instance of something else.\n pass\n\n # Create application\n return Application(\n layout=self.create_prompt_layout(\n message=message,\n lexer=lexer,\n is_password=is_password,\n reserve_space_for_menu=(reserve_space_for_menu if completer is not None else 0),\n multiline=Condition(lambda cli: multiline()),\n get_prompt_tokens=get_prompt_tokens,\n get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,\n display_completions_in_columns=display_completions_in_columns,\n extra_input_processors=extra_input_processors,\n wrap_lines=wrap_lines),\n buffer=Buffer(\n enable_history_search=enable_history_search,\n complete_while_typing=complete_while_typing,\n is_multiline=multiline,\n history=(history or InMemoryHistory()),\n validator=validator,\n completer=completer,\n auto_suggest=auto_suggest,\n accept_action=accept_action,\n initial_document=Document(default),\n ),\n style=style or DEFAULT_STYLE,\n clipboard=clipboard,\n key_bindings_registry=key_bindings_registry,\n get_title=get_title,\n mouse_support=mouse_support,\n on_abort=on_abort,\n on_exit=on_exit)\n","sub_path":"xonsh/ptk/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":20304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"201264571","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC \n# MAGIC # GDW FactForecast\n# MAGIC COPYRIGHT: Columbia Sportswear 2020
\n# MAGIC * To be used in the Enterprise Sales AAS Model. \n# MAGIC * Combines forecast data from TM1 and Logility\n# MAGIC * Still in progress. For now, DTC $ amounts are not available\n# MAGIC \n# MAGIC ###### MODIFICATION LOG\n# MAGIC | Programmmer | Work Item | Date | Change Description |\n# MAGIC |----------------------|-----------------|------------|--------------------------------------------------------------------|\n# MAGIC | Matt Kleiman | 111866 | 03/26/2020 | Initial Build from mapping doc |\n# MAGIC | Matt Kleiman | 111866 | 04/06/2020 | Added in currency for Logility and took out TM1 until currency decisions are made\n\n# COMMAND ----------\n\n## General configuration\ndbutils.widgets.text(\"schmNm\", \"\", \"\")\ndbutils.widgets.text(\"tblNm\", \"\", \"\")\ndbutils.widgets.text(\"deltaTS\", \"\", \"\")\ndbutils.widgets.text(\"initFlg\", \"\", \"\")\n\nschema_name = dbutils.widgets.get(\"schmNm\").lower()\ntable_name = dbutils.widgets.get(\"tblNm\").lower()\nschema_table = schema_name + '.' + table_name\n\ndeltaTS = dbutils.widgets.get(\"deltaTS\").replace(\"T\", \"\")\ninitFlg = dbutils.widgets.get(\"initFlg\")\n\n## Destination path configuration\nbase_path = '/mnt/entadls/published/eim/managed/'\nschema_path = base_path + schema_name.lower() + '/'\ndelta_path = schema_path + table_name.lower()\n\n## Source table configuration\nTM1_SOURCE_TABLE = 'ENTPR_PLANNING.TM1_MERCH_PLAN_HISTORY'\nLOGILITY_SOURCE_TABLE = 'ENTPR_PLANNING.LGTY_MTRL_FAM_COLR_FCST'\n\nTM1_SNAPSHOT_SOURCE_TABLES = ['ENTPR_PLANNING.TM1_MERCH_PLAN_SNAPSHOT', 'ENTPR_PLANNING.TM1_MERCH_PLAN_SNAPSHOT_HISTORY']\nLOGILITY_SNAPSHOT_SOURCE_TABLE = 'ENTPR_PLANNING.LGTY_MTRL_FAM_COLR_FCST_SNPST'\n\nPDM_SOURCE_TABLE = 'ENTPR_PRODUCT.PDM_PRCG_HIST'\n\n# COMMAND ----------\n\n# DBTITLE 1,Output Table Configuration\n# 'X': drop & recreate table. Can be used if we are adding/removing columns.\nif initFlg == 'X':\n dbutils.fs.rm(delta_path, True)\n drop_table = f'DROP TABLE IF EXISTS {schema_table}'\n spark.sql(drop_table)\n\nspark.sql(f\"CREATE DATABASE IF NOT EXISTS {schema_name} LOCATION '{schema_path}'\")\n\nspark.sql(f\"\"\"\nCREATE TABLE IF NOT EXISTS {schema_table} (\n ForecastType string,\n ForecastSnapshotName string,\n ForecastSnapshotDate date,\n ForecastDate date,\n ForecastMonth int,\n ForecastYear int,\n DimDateForecastKey int,\n ForecastSeasonCode string,\n RegionCode string,\n MaterialFamilyNumber string,\n LocalCurrencyCode string,\n RegionalCurrencyCode string,\n SubChannel string,\n ForecastQuantity long,\n ForecastSalesAmount double,\n ForecastDiscountAmount double,\n DimProductKey int,\n DimRegionKey int,\n DimProductRegionKey int,\n DimProductRegionSeasonKey int,\n DimSubChannelKey int,\n DimSeasonKey int,\n EDW_CRT_TS timestamp,\n EDW_UPDT_TS timestamp,\n EDW_ACTV_FLG string\n)\nUSING DELTA\nPARTITIONED BY (ForecastSnapshotDate)\n\"\"\")\n\n# COMMAND ----------\n\n# DBTITLE 1,Retrieve source data\nimport pyspark.sql.functions as fn\nfrom pyspark.sql.functions import lit, col\nfrom pyspark.sql.types import ArrayType, IntegerType, StringType\n\n# TODO: replace with python lib version\ndef dataframe_column_prefix(dataframe, prefix):\n \"\"\"\n Adds prefixes to each column\"\"\"\n for column in dataframe.columns:\n dataframe = dataframe.withColumnRenamed(column, f'{prefix}_{column}')\n return dataframe\n\nPDM_COLUMNS = [\n 'pdm_SEAS_CD',\n 'pdm_RGN_CD',\n 'pdm_MTRL_FAM_NBR',\n 'pdm_CURR_CD',\n 'pdm_NET_BASE_PRC_AMT',\n 'pdm_MIN_ADVTZ_PRC_AMT'\n]\n\n## Retrieve base tables\ntm1_base_df = spark.table(TM1_SOURCE_TABLE).filter(\"CUR_HIST_FLG='Y' and CHNL in ('Wholesale', 'DTC')\")\nlgty_base_df = (spark.table(LOGILITY_SOURCE_TABLE).filter(\"EDW_ACTV_FLG='Y'\")\n .withColumnRenamed('PDM_RGN_CD', 'LGTY_PDM_RGN_CD'))\n\ntm1_snapshot_base_df = (spark.table(TM1_SNAPSHOT_SOURCE_TABLES[0])\n .union(spark.table(TM1_SNAPSHOT_SOURCE_TABLES[1])\n .filter(\"CHNL in ('Wholesale', 'DTC')\")))\nlgty_snapshot_base_df = (spark.table(LOGILITY_SNAPSHOT_SOURCE_TABLE)\n .withColumnRenamed('PDM_RGN_CD', 'LGTY_PDM_RGN_CD'))\n\n## Rename PDM fields to avoid conflicts and cleanup PDM data before joining\npdm_base_prc_hist_df = dataframe_column_prefix(spark.table(PDM_SOURCE_TABLE).filter(\"EDW_CUR_HIST_FLG='Y'\").alias('pdm'), 'pdm')\n\npdm_prc_hist_df = (pdm_base_prc_hist_df\n .select(PDM_COLUMNS)\n .distinct()\n )\n\nPDM_COLUMNS = PDM_COLUMNS + ['pdm_HIST_BEG_DT', 'PDM_HIST_END_DT']\n\npdm_snapshot_prc_hist_df = (pdm_base_prc_hist_df\n .select(PDM_COLUMNS)\n .distinct()\n )\n\n## Create our pre-transformation datasets\ntm1_df = tm1_base_df.join(pdm_prc_hist_df, (tm1_base_df.SEAS_CD == pdm_prc_hist_df.pdm_SEAS_CD) & (tm1_base_df.RGN_CD == pdm_prc_hist_df.pdm_RGN_CD) & (tm1_base_df.MTRL_FAM_NBR == pdm_prc_hist_df.pdm_MTRL_FAM_NBR), how='left')\n\nlgty_df = lgty_base_df.join(pdm_prc_hist_df, (lgty_base_df.SEAS_CD == pdm_prc_hist_df.pdm_SEAS_CD) & (lgty_base_df.LGTY_PDM_RGN_CD == pdm_prc_hist_df.pdm_RGN_CD) & (lgty_base_df.MTRL_FAM_NBR == pdm_prc_hist_df.pdm_MTRL_FAM_NBR), how='left')\n\ntm1_snapshot_df = (tm1_snapshot_base_df.join(pdm_snapshot_prc_hist_df,\n (tm1_snapshot_base_df.SEAS_CD == pdm_snapshot_prc_hist_df.pdm_SEAS_CD) &\n (tm1_snapshot_base_df.RGN_CD == pdm_snapshot_prc_hist_df.pdm_RGN_CD) &\n (tm1_snapshot_base_df.MTRL_FAM_NBR == pdm_snapshot_prc_hist_df.pdm_MTRL_FAM_NBR) &\n (tm1_snapshot_base_df.SNPST_DT >= pdm_snapshot_prc_hist_df.pdm_HIST_BEG_DT) &\n (tm1_snapshot_base_df.SNPST_DT <= pdm_snapshot_prc_hist_df.PDM_HIST_END_DT), how='left'))\n\nlgty_snapshot_df = (lgty_snapshot_base_df.join(pdm_snapshot_prc_hist_df,\n (lgty_snapshot_base_df.SEAS_CD == pdm_snapshot_prc_hist_df.pdm_SEAS_CD) &\n (lgty_snapshot_base_df.LGTY_PDM_RGN_CD == pdm_snapshot_prc_hist_df.pdm_RGN_CD) &\n (lgty_snapshot_base_df.MTRL_FAM_NBR == pdm_snapshot_prc_hist_df.pdm_MTRL_FAM_NBR) &\n (lgty_snapshot_base_df.SNPST_DT >= pdm_snapshot_prc_hist_df.pdm_HIST_BEG_DT) &\n (lgty_snapshot_base_df.SNPST_DT <= pdm_snapshot_prc_hist_df.PDM_HIST_END_DT), how='left'))\n\n## Shared grain across TM1, Logility dataframes after transformation\nforecast_dimensions = ['ForecastType',\n 'ForecastSnapshotName',\n 'ForecastSnapshotDate',\n 'ForecastDate',\n 'ForecastMonth',\n 'ForecastYear',\n 'DimDateForecastKey',\n 'ForecastSeasonCode',\n 'RegionCode',\n 'MaterialFamilyNumber',\n 'RegionalCurrencyCode',\n 'LocalCurrencyCode',\n 'SubChannel']\n\n# COMMAND ----------\n\n# DBTITLE 1,Create TM1 Forecast DataFrame\n# final_tm1_df = (tm1_df\n# .withColumn('ForecastType', lit('GMP Consensus Version'))\n# .withColumn('ForecastSnapshotName', lit('Current'))\n# .withColumn('ForecastSnapshotDate', fn.current_date())\n# .withColumn('ForecastDate', lit(None).cast('date'))\n# .withColumn('ForecastMonth', lit(None).cast('int'))\n# .withColumn('ForecastYear', lit(None).cast('int'))\n# .withColumn('DimDateForecastKey', lit(-1))\n# .withColumnRenamed('SEAS_CD', 'ForecastSeasonCode')\n# .withColumnRenamed('RGN_CD', 'RegionCode')\n# .withColumnRenamed('MTRL_FAM_NBR', 'MaterialFamilyNumber')\n# .withColumnRenamed('pdm_CURR_CD', 'RegionalCurrencyCode')\n# )\n\n# final_tm1_df = final_tm1_df.selectExpr(\"*\",\n# \"\"\"\n# min(pdm_NET_BASE_PRC_AMT) over (partition by ForecastSeasonCode, RegionCode, MaterialFamilyNumber) as min_net_base_prc\n# \"\"\",\n# \"\"\"\n# case\n# when CHNL = 'DTC' then 'Undesignated DTC'\n# when CHNL = 'Wholesale' and RegionCode = 'INTL' then 'Distributors'\n# when CHNL = 'Wholesale' and RegionCode != 'INTL' then CHNL\n# end as SubChannel\n# \"\"\")\n\n# final_tm1_df = (final_tm1_df\n# .selectExpr(\"*\",\n# \"case when CHNL = 'Wholesale' then QTY * min_net_base_prc end AS ForecastSalesAmount\",\n# \"case when CHNL = 'Wholesale' then QTY * (pdm_MIN_ADVTZ_PRC_AMT - min_net_base_prc) end as ForecastDiscountAmount\")\n# .groupby(forecast_dimensions)\n# .agg({'QTY': 'sum', 'ForecastSalesAmount': 'sum', 'ForecastDiscountAmount': 'sum'})\n# .withColumnRenamed('sum(QTY)', 'ForecastQuantity')\n# .withColumnRenamed('sum(ForecastSalesAmount)', 'ForecastSalesAmount')\n# .withColumnRenamed('sum(ForecastDiscountAmount)', 'ForecastDiscountAmount')\n# )\n\n# print(final_tm1_df.count())\n\n\n# COMMAND ----------\n\n# DBTITLE 1,Create Logility Forecast DataFrame\n## Subchannel logic is the legwork for OMNI (not live yet)\n# For Forecast entry at subchannel level in the future\n# For every non-INTL subchannel, we need to split the row and create an 'Undesignated DTC' row with RTL FCST QTY as zero\nfrom pyspark.sql.types import ArrayType, IntegerType, StringType\nrow_duplicate = fn.udf(lambda x: list(range(x)), ArrayType(IntegerType()))\nmonth_formatter = fn.udf(lambda x: '0' + str(x) if x < 10 else str(x), StringType())\n\nfinal_lgty_df = (lgty_df\n .withColumn('ForecastDateString', fn.concat(col('FCST_MTH_NBR'), lit('-01-'), col('FCST_YR_NBR')))\n .withColumn('DimDateForecastKey', fn.concat(col('FCST_YR_NBR'), month_formatter(col('FCST_MTH_NBR')), lit('01')).cast('int'))\n .withColumn('ForecastType', lit('Logility Demand Plan'))\n .withColumn('ForecastSnapshotName', lit('Current'))\n .withColumn('ForecastSnapshotDate', fn.current_date())\n .withColumn('ForecastDate', fn.to_date(col('ForecastDateString')))\n .withColumnRenamed('FCST_MTH_NBR', 'ForecastMonth')\n .withColumnRenamed('FCST_YR_NBR', 'ForecastYear')\n .withColumnRenamed('SEAS_CD', 'ForecastSeasonCode')\n .withColumnRenamed('LGTY_PDM_RGN_CD', 'RegionCode')\n .withColumnRenamed('MTRL_FAM_NBR', 'MaterialFamilyNumber')\n .withColumnRenamed('pdm_CURR_CD', 'RegionalCurrencyCode')\n .withColumnRenamed('STD_COST_CURR_CD', 'LocalCurrencyCode')\n .withColumn('subchannel_stage_1', fn.when(col('PDM_RGN_CD') == 'INTL', 1).otherwise(2))\n .withColumn('subchannel_stage_2', fn.explode(row_duplicate(col('subchannel_stage_1'))))\n )\n\nfinal_lgty_df = (final_lgty_df.selectExpr(\"*\",\n \"\"\"\n case\n when PDM_RGN_CD = 'INTL' then 'Distributors'\n when PDM_RGN_CD != 'INTL' and subchannel_stage_2 = 1 then 'Wholesale'\n else 'Undesignated DTC' end as SubChannel\n \"\"\",\n \"\"\"min(pdm_NET_BASE_PRC_AMT) over (partition by ForecastSeasonCode, RegionCode, MaterialFamilyNumber) as min_net_base_prc\"\"\",\n )\n )\n\n\"\"\"\n## From mapping document ##\n\nForecastQuantity logic:\nFor 'Wholesale' and 'Distributors': sum(RSLT_FCST_QTY - RTL_FCST_QTY)\nFor 'Undesignated DTC': sum(RTL_FCST_QTY)\n\nForecastSalesAmount logic:\n\"For 'Wholesale' and 'Distributors': sum((RSLT_FCST_QTY - RTL_FCST_QTY) * min(NET_BASE_PRC_AMT) )\nFor 'Undesignated DTC': sum(RTL_FCST_QTY * (min(MIN_ADVTZ_PRC_AMT) - min(MIN_ADVTZ_PRC_AMT)*DSCNT_PCT))\"\n\nForecastDiscountAmount logic:\n\"For 'Wholesale' and 'Distributors': sum((RSLT_FCST_QTY - RTL_FCST_QTY) * (MIN_ADVTZ_PRC_AMT-NET_BASE_PRC_AMT) where NET_BASE_PRC_AMT=min(NET_BASE_PRC_AMT))\nFor 'Undesignated DTC': sum(RTL_FCST_QTY * min(MIN_ADVTZ_PRC_AMT)*DSCNT_PCT)\"\n\n\"\"\"\n\nfinal_lgty_df = (final_lgty_df.selectExpr(\"*\",\n \"\"\"\n case\n when SubChannel = 'Distributors' then RSLT_FCST_QTY - RTL_FCST_QTY\n when SubChannel = 'Wholesale' then RSLT_FCST_QTY\n else RTL_FCST_QTY end as RetailForecastQuantity \n \"\"\",\n \"\"\"\n case\n when SubChannel = 'Distributors' then (RSLT_FCST_QTY - RTL_FCST_QTY) * min_net_base_prc\n when SubChannel = 'Wholesale' then RSLT_FCST_QTY * min_net_base_prc\n end as ForecastSalesAmount\n \"\"\",\n \"\"\"\n case\n when SubChannel = 'Distributors' then (RSLT_FCST_QTY - RTL_FCST_QTY) * (pdm_MIN_ADVTZ_PRC_AMT - min_net_base_prc)\n when SubChannel = 'Wholesale' then RSLT_FCST_QTY * (pdm_MIN_ADVTZ_PRC_AMT - min_net_base_prc)\n end as ForecastDiscountAmount\n \"\"\")\n .groupBy(forecast_dimensions)\n .agg({'RetailForecastQuantity': 'sum', 'ForecastSalesAmount': 'sum', 'ForecastDiscountAmount': 'sum'})\n .withColumnRenamed('sum(RetailForecastQuantity)', 'ForecastQuantity')\n .withColumnRenamed('sum(ForecastSalesAmount)', 'ForecastSalesAmount')\n .withColumnRenamed('sum(ForecastDiscountAmount)', 'ForecastDiscountAmount')\n )\n\nprint(final_lgty_df.count())\n\n\n# COMMAND ----------\n\n# DBTITLE 1,Prepare Final Dataset\n# Add in foreign keys + EDW columns\n# fact_forecast_df = (final_lgty_df.union(final_tm1_df)\n# .withColumn('DimProductKey', lit(-1).cast('int'))\n# .withColumn('DimRegionKey', lit(-1).cast('int'))\n# .withColumn('DimProductRegionKey', lit(-1).cast('int'))\n# .withColumn('DimProductRegionSeasonKey', lit(-1).cast('int'))\n# .withColumn('DimSubChannelKey', lit(-1).cast('int'))\n# .withColumn('DimSeasonKey', lit(-1).cast('int'))\n# .withColumn('EDW_CRT_TS', fn.current_timestamp())\n# .withColumn('EDW_UPDT_TS', fn.current_timestamp())\n# .withColumn('EDW_ACTV_FLG', lit('Y')))\n# .fillna({'ForecastQuantity': 0, 'ForecastSalesAmount': 0, 'ForecastDiscountAmount': 0})\n\n# Add in foreign keys + EDW columns\nfact_forecast_df = (final_lgty_df\n .withColumn('DimProductKey', lit(-1).cast('int'))\n .withColumn('DimRegionKey', lit(-1).cast('int'))\n .withColumn('DimProductRegionKey', lit(-1).cast('int'))\n .withColumn('DimProductRegionSeasonKey', lit(-1).cast('int'))\n .withColumn('DimSubChannelKey', lit(-1).cast('int'))\n .withColumn('DimSeasonKey', lit(-1).cast('int'))\n .withColumn('EDW_CRT_TS', fn.current_timestamp())\n .withColumn('EDW_UPDT_TS', fn.current_timestamp())\n .withColumn('EDW_ACTV_FLG', lit('Y'))\n .fillna({'ForecastQuantity': 0, 'ForecastSalesAmount': 0, 'ForecastDiscountAmount': 0}))\n\n# Number of records\nprint(fact_forecast_df.count(), 'records in FactForecast dataframe')\n\n# COMMAND ----------\n\n# Persist data in databricks and prep it for ADW by creating a global temp\nfact_forecast_df.write.saveAsTable(schema_table, mode='append', format='delta')\nfact_forecast_df.createOrReplaceGlobalTempView('FactForecast')\n\n# COMMAND ----------\n\n# Land data in ADW\ndbutils.notebook.run(\"/Users/svceimdbrx@columbia.com/edw_admin/adw_integration_write\", 3600, {\"schemaNm\": f\"{schema_name}_LND\", \"tableNm\": table_name, \"dbrxTable\": \"FactForecast\", \"writeMode\": \"overwrite\"})\n\nspark.sql(\"DROP VIEW IF EXISTS global_temp.factforecast\")\nspark.sql(f\"OPTIMIZE {schema_table}\")\n","sub_path":"C1-SIT3/gdw/fact_forecast.py","file_name":"fact_forecast.py","file_ext":"py","file_size_in_byte":15849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"533494266","text":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.utils import shuffle\nimport pandas as pd\nimport numpy as np\nfrom detect_features import add_features\nfrom detect_features import append_df_to_excel\n\nnp.random.seed(0)\n\n\n\ndef categorize_ratings(rating):\n '''\n replace ratings into catergories ( can add more categories once this works)\n [1, 3) --> 0 (most disorderly)\n [3, 5) --> 1\n [5, 7) --> 2 (most orderly)\n\n :param rating:\n :return: new rating\n '''\n\n if (rating >= 1 and rating < 4):\n rating = 0\n elif (rating >= 4 and rating < 6):\n rating = 1\n elif (rating >= 6 and rating < 7):\n rating = 2\n\n return rating\n\ndef check_num_per_classification(df, train, test):\n\n zero_count = 0\n one_count = 0\n two_count = 0\n for val in test['Order']:\n if (val == 0):\n zero_count += 1\n elif (val == 1):\n one_count += 1\n elif (val == 2):\n two_count += 1\n\n print(\"zero count:\", zero_count)\n print(\"one count:\", one_count)\n print(\"two_count:\", two_count)\n\n '''\n \n [1, 3) --> 0 (most disorderly)\n [3, 5) --> 1\n [5, 7) --> 2 (most orderly)\n \n total:\n zero count: 159\n one count: 418\n two_count: 528\n\n train:\n zero count: 150\n one count: 397\n two_count: 499\n\n test:\n zero count: 9\n one count: 21\n two_count: 29\n \n 63 percent accuracy\n '''\n\n '''\n \n [1, 4) --> 0 (most disorderly)\n [4, 6) --> 1\n [6, 7) --> 2 (most orderly)\n \n total:\n zero count: 258\n one count: 682\n two_count: 165\n \n train:\n zero count: 248\n one count: 640\n two_count: 158\n \n test:\n zero count: 10\n one count: 42\n two_count: 7\n \n 73 percent accuracy \n '''\n\n '''\n [1, 4.5) --> 0 (most disorderly)\n [4.5, 5.5) --> 1\n [5.5, 7) --> 2 (most orderly)\n \n total:\n zero count: 396\n one count: 389\n two_count: 320\n \n train:\n zero count: 378\n one count: 363\n two_count: 305\n \n test:\n zero count: 18\n one count: 26\n two_count: 15 \n \n 47 percent accuracy\n '''\n\n\ndef create_random_forest():\n df = pd.read_excel(\n r'C:\\Users\\SamaahMachine\\Documents\\Argonne\\Images with Ratings\\training_data.xlsx')\n\n # categorize ratings\n df['Order'] = df['Order'].apply(categorize_ratings)\n\n column_names = ['SED', 'Entropy', 'sdValue', 'sdSat', 'sdHue', 'Mean Value', 'Mean Hue', 'Mean Sat', 'ED']\n\n for i in range(len(column_names)):\n df[column_names[i]] = (df[column_names[i]] - df[column_names[i]].min()) / (df[column_names[i]].max() - df[column_names[i]].min())\n\n # shuffle data set so that the training and test data can have a mix of all labels\n df = shuffle(df)\n\n # assign 90 percent of the data as training data,\n # assign 10 percent of the data for testing later\n df['is_train'] = np.random.uniform(0, 1, len(df)) <= 0.95\n\n # creating dataframes with test rows and training rows\n train = df[df['is_train'] == True]\n test = df[df['is_train'] == False]\n\n # TODO: check how many samples I have in each class\n\n # check_num_per_classification(df, train, test)\n\n # create a list of the feature columns\n\n # deleting edge density and entropy is making no difference\n # deleting sdValue increases accuracy\n # deleting sdSat increases accuracy even more\n # deleting mean value increases accuracy\n\n del df['Mean Value']\n del df['sdSat']\n del df['sdValue']\n features = df.columns[2:8]\n print(features)\n\n features_train = train[features]\n labels_train = train['Order']\n features_test = test[features]\n labels_test = test['Order']\n\n # Creating a random forest classifier\n # look up which parameters would be the best\n model = RandomForestClassifier(n_estimators = 1000, max_features = 5, max_depth = 6, min_samples_leaf =3)\n\n # Training the classifier\n model.fit(features_train, labels_train)\n\n accuracy = model.score(features_test, labels_test)\n print(accuracy) # 76 percent accuracy\n\ndef main():\n create_random_forest()\n\nif __name__ == '__main__':\n main()","sub_path":"Khan/random_forest_model.py","file_name":"random_forest_model.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"496254575","text":"\"\"\"Test Topo module and related methods.\"\"\"\nimport numpy as np\nfrom visbrain import Topo\n\ntp = Topo()\n\n\nclass TestTopo(object):\n \"\"\"Test topo.py.\"\"\"\n\n def test_add_topoplot(self):\n \"\"\"Test function brain_creation.\"\"\"\n name = 'Topo_1'\n channels = ['C3', 'C4', 'Cz', 'Fz', 'Pz']\n data = [10., 20., 30., 10., 10.]\n connect = np.random.rand(len(data), len(data))\n title = 'Basic topoplot illustration'\n cblabel = 'Colorbar label'\n tp.add_topoplot(name, data, channels=channels, title=title,\n cblabel=cblabel, c_connect=connect)\n\n def test_add_shared_colorbar(self):\n \"\"\"Test function add_shared_colorbar.\"\"\"\n kwargs = {'cmap': 'viridis', 'clim': (-1.02, 1.01), 'vmin': -.81,\n 'under': 'gray', 'vmax': .85, 'over': 'red'}\n tp.add_shared_colorbar('Shared', col=2, row_span=2,\n rect=(0.1, -2, 1.6, 4),\n cblabel='Shared colorbar', **kwargs)\n","sub_path":"visbrain/topo/tests/test_topo.py","file_name":"test_topo.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"83100108","text":"import os\n\nfrom accessors.patient_accessor import PatientAccessor\nfrom accessors.s3_accessor import S3Accessor, S3Exception\nfrom parsers.oncomine_control_panel_parser import OncomineControlPanelParser\nfrom parsers.qc_var_rpt_parser import VariantReportTsvParser\nfrom parsers.vcf_to_graph_data_parser import VcfToGraphDataParser\nfrom resources.db_resource import DbResource\nfrom resources.auth0_resource import requires_auth\n\nfrom pprint import pformat\n\n\nclass VariantReportResource(DbResource):\n def __init__(self):\n super(VariantReportResource, self).__init__(PatientAccessor())\n\n UNWIND_BIOP_STEP = {\"$unwind\": \"$biopsies\"}\n UNWIND_NEXT_GEN_SEQ_STEP = {\"$unwind\": \"$biopsies.nextGenerationSequences\"}\n REPLACE_ROOT_STEP = {\"$replaceRoot\": {'newRoot': \"$biopsies\"}}\n PROJECT_STEP = {\"$project\": {'biopsySequenceNumber': 1,\n 'dateReceived': '$nextGenerationSequences.dateReceived',\n 'molecularSequenceNumber':\n '$nextGenerationSequences.ionReporterResults.molecularSequenceNumber',\n 'dnaBamFilePath': '$nextGenerationSequences.ionReporterResults.dnaBamFilePath',\n 'rnaBamFilePath': '$nextGenerationSequences.ionReporterResults.rnaBamFilePath',\n 'vcfFilePath': '$nextGenerationSequences.ionReporterResults.vcfFilePath',\n 'variantReport': '$nextGenerationSequences.ionReporterResults.variantReport'}}\n\n PROJECT_FILES_STEP = {\"$project\": {'biopsySequenceNumber': 1,\n 'dnaBamFilePath': '$nextGenerationSequences.ionReporterResults.dnaBamFilePath',\n 'rnaBamFilePath': '$nextGenerationSequences.ionReporterResults.rnaBamFilePath',\n 'vcfFilePath': '$nextGenerationSequences.ionReporterResults.vcfFilePath'}}\n\n VAR_RPT_FIELD = 'biopsies.nextGenerationSequences.ionReporterResults.variantReport'\n ANALYSIS_ID_FIELD = 'biopsies.nextGenerationSequences.ionReporterResults.jobName'\n\n FIELD_EXISTS = {\"$exists\": True}\n\n @classmethod\n def get_pipe_line_start(cls, patient_id):\n return [\n {\"$match\": {'patientSequenceNumber': patient_id}},\n cls.UNWIND_BIOP_STEP,\n cls.UNWIND_NEXT_GEN_SEQ_STEP,\n ]\n\n @classmethod\n def get_analysis_id_match_step(cls, analysis_id):\n return [\n {\"$match\": {cls.VAR_RPT_FIELD: cls.FIELD_EXISTS,\n cls.ANALYSIS_ID_FIELD: analysis_id}},\n ]\n\n def get_analysis_data(self, patient_id, analysis_id):\n pipeline = self.get_pipe_line_start(patient_id) + \\\n self.get_analysis_id_match_step(analysis_id) + \\\n [self.REPLACE_ROOT_STEP, self.PROJECT_STEP]\n\n results = self.accessor.aggregate(pipeline)\n self.logger.debug(\"get_analysis_data results =\\n{}\".format(pformat(results)))\n return results[0] if results else None\n\n def download_from_s3(self, filename):\n self.logger.info(\"Downloading file {} from S3\".format(filename))\n s3 = S3Accessor()\n downloaded_file = s3.download(filename)\n return downloaded_file\n\n @staticmethod\n def get_vcf_for_download(biopsy_info):\n vcf_file = biopsy_info['vcfFilePath']\n if vcf_file.startswith('s3://'):\n vcf_file = vcf_file[5:]\n return vcf_file\n\n def get_file_paths(self, patient_id, analysis_id):\n pipeline = self.get_pipe_line_start(patient_id) + \\\n self.get_analysis_id_match_step(analysis_id) + \\\n [self.REPLACE_ROOT_STEP, self.PROJECT_FILES_STEP]\n\n results = self.accessor.aggregate(pipeline)\n return results[0] if results else None\n\n\nclass VariantReports(VariantReportResource):\n \"\"\"\n REST resource to return all variant reports for a patient.\n \"\"\"\n MATCH_STEP = {\"$match\": {VariantReportResource.VAR_RPT_FIELD: VariantReportResource.FIELD_EXISTS}}\n # REPLACE_ROOT_STEP = {\"$replaceRoot\": {'newRoot': \"$\" + VariantReportResource.VAR_RPT_FIELD}}\n\n @requires_auth\n def get(self, patient_id):\n \"\"\"\n Gets all Variant Reports for the patient.\n \"\"\"\n pipeline = self.get_pipe_line_start(patient_id) + [self.MATCH_STEP, self.REPLACE_ROOT_STEP, self.PROJECT_STEP]\n return self.accessor.aggregate(pipeline)\n\n\nclass VariantReport(VariantReportResource):\n \"\"\"\n REST resource to return a single variant report for a patient.\n \"\"\"\n @requires_auth\n def get(self, patient_id, analysis_id):\n \"\"\"\n Gets the Variant Report for the patient for the specified analysis ID.\n \"\"\"\n results = self.get_analysis_data(patient_id, analysis_id)\n return results\n\n\nclass VariantReportParserResource(VariantReportResource):\n \"\"\"\n Parent class for resources that must download a file from S3 and parse it.\n \"\"\"\n @requires_auth\n def get(self, patient_id, analysis_id):\n \"\"\"\n Gets the parsed data from the patient's specified Variant Report.\n \"\"\"\n self.logger.debug(\"Getting biopsy info for {}/{}\".format(patient_id, analysis_id))\n return_data = None\n try:\n biopsy_info = self.get_analysis_data(patient_id, analysis_id)\n if biopsy_info:\n self.logger.debug(\"Biopsy data is available.\")\n vcf_file = self.get_vcf_for_download(biopsy_info)\n return_data = self.download_and_parse(vcf_file)\n\n for field in ['biopsySequenceNumber', 'molecularSequenceNumber', 'dateReceived']:\n return_data[field] = biopsy_info[field] if field in biopsy_info else None\n\n except S3Exception as s3_exc:\n self.logger.error(str(s3_exc))\n return_data = str(s3_exc), s3_exc.error_code\n\n except Exception as e:\n self.logger.exception(str(e))\n return_data = str(e), 500\n\n return return_data\n\n def download_and_parse(self, vcf_file):\n self.logger.debug(\"vcf_file={}\".format(vcf_file))\n downloaded_file = None\n try:\n downloaded_file = self.download_file(vcf_file)\n self.logger.debug(\"downloaded_file={}\".format(downloaded_file))\n parsed_data = self.parse(downloaded_file)\n\n finally:\n if downloaded_file and os.path.isfile(downloaded_file):\n os.remove(downloaded_file)\n\n return parsed_data\n\n def download_file(self, vcf_file):\n self.logger.debug(\"Downloading {} from S3\".format(vcf_file))\n return self.download_from_s3(vcf_file)\n\n def parse(self, downloaded_file):\n raise NotImplementedError(\"Inherited class must implement the parse method.\")\n\n\nclass QualityControlReport(VariantReportParserResource):\n \"\"\"\n REST resource to return a single Quality Control Report from a patient's specified Variant Report.\n \"\"\"\n\n def download_file(self, vcf_file):\n tsv_file = vcf_file[:-3] + 'tsv'\n return self.download_from_s3(tsv_file)\n\n def parse(self, downloaded_file):\n return VariantReportTsvParser().parse(downloaded_file)\n\n\nclass CopyNumberReport(VariantReportParserResource):\n \"\"\"\n REST resource to return a single Copy Number Report from a patient's specified Variant Report.\n \"\"\"\n\n def parse(self, downloaded_file):\n return VcfToGraphDataParser().parse(downloaded_file)\n\n\nclass OncomineControlPanel(VariantReportParserResource):\n \"\"\"\n REST resource to return a single Oncomine Control Panel from a patient's specified Variant Report.\n \"\"\"\n\n def parse(self, downloaded_file):\n self.logger.debug(\"About to parse {}\".format(downloaded_file))\n return OncomineControlPanelParser().parse(downloaded_file)\n\n\nclass VariantReportFileInfo(VariantReportResource):\n \"\"\"\n REST resource to return a list of files for the specified Variant Report.\n \"\"\"\n @requires_auth\n def get(self, patient_id, analysis_id):\n results = self.get_file_paths(patient_id, analysis_id)\n return results\n","sub_path":"resources/variant_report.py","file_name":"variant_report.py","file_ext":"py","file_size_in_byte":8147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"346690542","text":"from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider\nfrom PIL import Image\nimport cv2\nfrom pyzbar.pyzbar import decode\nimport json\nimport time\n#import datetime\nfrom datetime import datetime\nfrom datetime import date\nimport os\nimport sys\n# GPIO\nimport RPi.GPIO as GPIO #raspri import\nservoPIN = 17\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(servoPIN, GPIO.OUT)\np = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz\np.start(0) # Initialization\n# --- GPIO-End-----\n\n\nimport private_key_infrastructure as pk\n\n# capture | Decode Qrcode\ndef capture_qr():\n cap = cv2.VideoCapture(0)\n token_before = 'Null2'\n while True:\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n ret, frame = cap.read()\n cv2.imshow('Current',frame)\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n image = Image.fromarray(gray)\n qr_decode = decode(image)\n token = 'NULL'\n if qr_decode:\n token = qr_decode[0].data\n token = token.decode('utf-8')\n if token != token_before :\n token_before = token\n print(token)\n auth(token)\n return\n \n \n \ndef auth(token):\n global contract\n global web3\n transact = contract.functions.auth(token).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().auth(token)\n result = str(result)\n print(result)\n if result == '0':\n auth_worker(token)\n elif result == '1':\n #check revoke permation\n transact = contract.functions.check_revoke(token).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().check_revoke(token)\n result = str(result)\n if result == '1':\n print ('Access Denied -> Revoked permation')\n else:\n print ('Access')\n #access log\n transact = contract.functions.track_in_out(token,'Access Gate1',str(datetime.now())).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().track_in_out(token,'Access Gate1',str(datetime.now()))\n print(str(result))\n SetAngle(180)\n time.sleep(2)\n SetAngle(0)\n else:\n print('Error')\n\n\ndef auth_worker(token):\n global contract\n global web3\n transact = contract.functions.auth_worker(token).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().auth_worker(token)\n result = str(result)\n print(result)\n #handeling string \n result = result.replace('[','')\n result = result.replace(']','')\n result = result.replace(\"'\",\"\")\n result = result.replace(' ','')\n result = result.split(',')\n # final \n date_a = result[0]\n days = result[1]\n print(date_a)\n print(days)\n if date_a != 'NULL':\n if date_time_com(date_a,days):\n # check revoke\n transact = contract.functions.check_revoke(token).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().check_revoke(token)\n result = str(result)\n\n if result == '1':\n print ('Access Denied -> Revoked permation')\n else:\n #open_gate\n print('Access')\n transact = contract.functions.track_in_out_worker(token,'Access Gate1',str(datetime.now())).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().track_in_out_worker(token,'Access Gate1',str(datetime.now()))\n print(str(result))\n SetAngle(180)\n time.sleep(2)\n SetAngle(0)\n\n else:\n print('Access Denied')\n else:\n auth_res(token)\n\n\ndef auth_res(token):\n global contract\n global web3\n transact = contract.functions.auth_resdent(token).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().auth_resdent(token)\n result = str(result)\n print(result)\n if result == '0':\n print('Access Denied')\n elif result == '1':\n #check revoke permation\n transact = contract.functions.check_revoke(token).transact({'from': web3.eth.defalutAccount}) # transaction\n result = contract.call().check_revoke(token)\n result = str(result)\n print (result+' -> revoke')\n\n if result == '1':\n print ('Access Denied -> Revoked permation')\n else:\n print('Access')\n SetAngle(180)\n time.sleep(2)\n SetAngle(0)\n\n\ndef date_time_com(Date_time,days):\n current_date = datetime.now()\n current_week_name = date.today().weekday()\n temp_year = Date_time[6:10] # index of string \n temp_month = Date_time[3:5]\n temp_day = Date_time[0:2]\n\n temp_date = datetime(int(temp_year), int(temp_month), int(temp_day))\n\n if temp_date > current_date and str(current_week_name) in days:\n return 1\n else:\n return 0\n\n\n\n\n\n# Servo-motor controll\n\ndef SetAngle(angle):\n\tduty = angle / 18 + 2\n\tGPIO.output(17, True)\n\tp.ChangeDutyCycle(duty)\n\ttime.sleep(1)\n\tGPIO.output(17, False)\n\tp.ChangeDutyCycle(0)\n#--------------------\n\n\n## Block Chaine prepare ##\nif __name__ == '__main__':\n \n \n\n web3 = Web3(HTTPProvider('http://192.168.43.23:8545'))\n con_abi = open('../contracts/con_abi','r')\n con_abi = con_abi.read()\n con_add = open('../contracts/con_add','r')\n con_add = con_add.read()\n con_byte_code = open('../contracts/con_byte_code','r')\n con_byte_code = con_byte_code.read()\n\n # ----- Gate account ----- #\n # new methods of private keys\n file_f = open('../contracts/dev_acc','r')\n lines = file_f.readlines()\n gate_account = lines[0]\n gate_account = gate_account.replace('\\n','')\n print(gate_account)\n web3.eth.defalutAccount = gate_account\n #------- End -------- #\n #web3.eth.defalutAccount = web3.eth.accounts[5]\n con_add = web3.toChecksumAddress(con_add)\n bid_abi=json.loads(con_abi)\n\n contract = web3.eth.contract(abi=con_abi,address = con_add)\n\n #tx_hash = contract.constructor().transact()\n\n\n #test_trans = contract.functions.set_I('ahmeed','33').transact({'from': web3.eth.defalutAccount})\n #tx = contract.functions.save('aa','aa','aa','aa','aa','aa').transact({'from': web3.eth.defalutAccount})\n\n\n #print(test_trans)\n\n\n\n while True:\n capture_qr()\n #os.execv(__file__, sys.argv) # Run a new iteration of the current script, providing any command line args from the current iteration.\n\n\n\n","sub_path":"Auth/Gate_BC.py","file_name":"Gate_BC.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"156098940","text":"\nimport argparse\nimport os\nimport sys\n\n##############################################\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--epochs', type=int, default=100)\nparser.add_argument('--batch_size', type=int, default=32)\nparser.add_argument('--alpha', type=float, default=1e-2)\nparser.add_argument('--decay', type=float, default=1.)\nparser.add_argument('--eps', type=float, default=1.)\nparser.add_argument('--act', type=str, default='tanh')\nparser.add_argument('--bias', type=float, default=0.)\nparser.add_argument('--dropout', type=float, default=0.5)\nparser.add_argument('--gpu', type=int, default=0)\nparser.add_argument('--dfa', type=int, default=0)\nparser.add_argument('--sparse', type=int, default=0)\nparser.add_argument('--rank', type=int, default=0)\nparser.add_argument('--init', type=str, default=\"sqrt_fan_in\")\nparser.add_argument('--opt', type=str, default=\"gd\")\nparser.add_argument('--save', type=int, default=0)\nparser.add_argument('--name', type=str, default=\"imagenet_vgg\")\nargs = parser.parse_args()\n\nif args.gpu >= 0:\n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=str(args.gpu)\n\n##############################################\n\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.optimizers import SGD\n\nimport tensorflow as tf\nimport os\nimport math\nimport numpy\nimport numpy as np\nnp.set_printoptions(threshold=1000)\nimport time\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom PIL import Image\nimport scipy.misc\n\nfrom Model import Model\n\nfrom Layer import Layer \nfrom ConvToFullyConnected import ConvToFullyConnected\nfrom FullyConnected import FullyConnected\nfrom Convolution import Convolution\nfrom MaxPool import MaxPool\nfrom Dropout import Dropout\nfrom FeedbackFC import FeedbackFC\nfrom FeedbackConv import FeedbackConv\n\nfrom Activation import Activation\nfrom Activation import Sigmoid\nfrom Activation import Relu\nfrom Activation import Tanh\nfrom Activation import Softmax\nfrom Activation import LeakyRelu\nfrom Activation import Linear\n\n##############################################\n\nbatch_size = args.batch_size\nnum_classes = 1000\nepochs = args.epochs\ndata_augmentation = False\n\nEPOCHS = args.epochs\nBATCH_SIZE = args.batch_size\n\nIMAGENET_MEAN = [123.68, 116.78, 103.94]\n\n##############################################\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n# https://gist.githubusercontent.com/omoindrot/dedc857cdc0e680dfb1be99762990c9c/raw/e560edd240f8b97e1f0483843dc4d64729ce025c/tensorflow_finetune.py\n\n# Preprocessing (for both training and validation):\n# (1) Decode the image from jpg format\n# (2) Resize the image so its smaller side is 256 pixels long\ndef parse_function(filename, label):\n image_string = tf.read_file(filename)\n image_decoded = tf.image.decode_jpeg(image_string, channels=3) # (1)\n image = tf.cast(image_decoded, tf.float32)\n\n smallest_side = 256.0\n height, width = tf.shape(image)[0], tf.shape(image)[1]\n height = tf.to_float(height)\n width = tf.to_float(width)\n\n scale = tf.cond(tf.greater(height, width),\n lambda: smallest_side / width,\n lambda: smallest_side / height)\n new_height = tf.to_int32(height * scale)\n new_width = tf.to_int32(width * scale)\n\n resized_image = tf.image.resize_images(image, [new_height, new_width]) # (2)\n return resized_image, label\n\n# Preprocessing (for training)\n# (3) Take a random 224x224 crop to the scaled image\n# (4) Horizontally flip the image with probability 1/2\n# (5) Substract the per color mean `IMAGENET_MEAN`\n# Note: we don't normalize the data here, as VGG was trained without normalization\ndef train_preprocess(image, label):\n crop_image = tf.random_crop(image, [224, 224, 3]) # (3)\n flip_image = tf.image.random_flip_left_right(crop_image) # (4)\n\n means = tf.reshape(tf.constant(IMAGENET_MEAN), [1, 1, 3])\n centered_image = flip_image - means # (5)\n\n return centered_image, label\n \n\n# Preprocessing (for validation)\n# (3) Take a central 224x224 crop to the scaled image\n# (4) Substract the per color mean `IMAGENET_MEAN`\n# Note: we don't normalize the data here, as VGG was trained without normalization\ndef val_preprocess(image, label):\n crop_image = tf.image.resize_image_with_crop_or_pad(image, 224, 224) # (3)\n\n means = tf.reshape(tf.constant(IMAGENET_MEAN), [1, 1, 3])\n centered_image = crop_image - means # (4)\n\n return centered_image, label\n\n##############################################\n\ndef get_validation_dataset():\n label_counter = 0\n validation_images = []\n validation_labels = []\n\n print (\"building validation dataset\")\n\n for subdir, dirs, files in os.walk('/home/bcrafton3/ILSVRC2012/val/'):\n for file in files:\n validation_images.append(os.path.join('/home/bcrafton3/ILSVRC2012/val/', file))\n validation_images = sorted(validation_images)\n\n validation_labels_file = open('/home/bcrafton3/dfa/imagenet_labels/validation_labels.txt')\n lines = validation_labels_file.readlines()\n for ii in range(len(lines)):\n validation_labels.append(int(lines[ii]))\n\n print (len(validation_images), len(validation_labels))\n remainder = len(validation_labels) % batch_size\n validation_images = validation_images[:(-remainder)]\n validation_labels = validation_labels[:(-remainder)]\n\n print(\"validation data is ready...\")\n\n return validation_images, validation_labels\n \ndef get_train_dataset():\n\n label_counter = 0\n training_images = []\n training_labels = []\n\n print (\"making labels dict\")\n\n f = open('/home/bcrafton3/dfa/imagenet_labels/train_labels.txt', 'r')\n lines = f.readlines()\n\n labels = {}\n for line in lines:\n line = line.split(' ')\n labels[line[0]] = label_counter\n label_counter += 1\n\n f.close()\n\n print (\"building dataset\")\n\n for subdir, dirs, files in os.walk('/home/bcrafton3/ILSVRC2012/train/'):\n for folder in dirs:\n for folder_subdir, folder_dirs, folder_files in os.walk(os.path.join(subdir, folder)):\n for file in folder_files:\n training_images.append(os.path.join(folder_subdir, file))\n training_labels.append(labels[folder])\n\n remainder = len(training_labels) % batch_size\n training_images = training_images[:(-remainder)]\n training_labels = training_labels[:(-remainder)]\n\n print(\"Data is ready...\")\n\n return training_images, training_labels\n\n###############################################################\n\nfilename = tf.placeholder(tf.string, shape=[None])\nlabel = tf.placeholder(tf.int64, shape=[None])\n\n###############################################################\n\nval_imgs, val_labs = get_validation_dataset()\n\nval_dataset = tf.data.Dataset.from_tensor_slices((filename, label))\n# val_dataset = val_dataset.shuffle(len(val_imgs))\nval_dataset = val_dataset.map(parse_function, num_parallel_calls=4)\nval_dataset = val_dataset.map(val_preprocess, num_parallel_calls=4)\nval_dataset = val_dataset.batch(batch_size)\nval_dataset = val_dataset.repeat()\nval_dataset = val_dataset.prefetch(8)\n\n###############################################################\n\ntrain_imgs, train_labs = get_train_dataset()\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((filename, label))\n# train_dataset = train_dataset.shuffle(len(train_imgs))\ntrain_dataset = train_dataset.map(parse_function, num_parallel_calls=4)\ntrain_dataset = train_dataset.map(train_preprocess, num_parallel_calls=4)\ntrain_dataset = train_dataset.batch(batch_size)\ntrain_dataset = train_dataset.repeat()\ntrain_dataset = train_dataset.prefetch(8)\n\n###############################################################\n\nhandle = tf.placeholder(tf.string, shape=[])\niterator = tf.data.Iterator.from_string_handle(handle, train_dataset.output_types, train_dataset.output_shapes)\nfeatures, labels = iterator.get_next()\nfeatures = tf.reshape(features, (-1, 224, 224, 3))\n# labels = tf.one_hot(labels, depth=num_classes)\n\ntrain_iterator = train_dataset.make_initializable_iterator()\nval_iterator = val_dataset.make_initializable_iterator()\n\n###############################################################\n\ntrain_conv=False\nweights_conv='../vgg_weights/vgg_weights.npy'\n\n###############################################################\n\ndropout_rate = tf.placeholder(tf.float32, shape=())\nlearning_rate = tf.placeholder(tf.float32, shape=())\n\nl0 = Convolution(input_sizes=[batch_size, 224, 224, 3], filter_sizes=[3, 3, 3, 64], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv1\", load=weights_conv, train=train_conv)\nl1 = Convolution(input_sizes=[batch_size, 224, 224, 64], filter_sizes=[3, 3, 64, 64], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv2\", load=weights_conv, train=train_conv)\nl2 = MaxPool(size=[batch_size, 224, 224, 64], ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n\nl3 = Convolution(input_sizes=[batch_size, 112, 112, 64], filter_sizes=[3, 3, 64, 128], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv3\", load=weights_conv, train=train_conv)\nl4 = Convolution(input_sizes=[batch_size, 112, 112, 128], filter_sizes=[3, 3, 128, 128], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv4\", load=weights_conv, train=train_conv)\nl5 = MaxPool(size=[batch_size, 112, 112, 128], ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n\nl6 = Convolution(input_sizes=[batch_size, 56, 56, 128], filter_sizes=[3, 3, 128, 256], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv5\", load=weights_conv, train=train_conv)\nl7 = Convolution(input_sizes=[batch_size, 56, 56, 256], filter_sizes=[3, 3, 256, 256], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv6\", load=weights_conv, train=train_conv)\nl8 = Convolution(input_sizes=[batch_size, 56, 56, 256], filter_sizes=[3, 3, 256, 256], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv7\", load=weights_conv, train=train_conv)\nl9 = MaxPool(size=[batch_size, 56, 56, 256], ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n\nl10 = Convolution(input_sizes=[batch_size, 28, 28, 256], filter_sizes=[3, 3, 256, 512], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv8\", load=weights_conv, train=train_conv)\nl11 = Convolution(input_sizes=[batch_size, 28, 28, 512], filter_sizes=[3, 3, 512, 512], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv9\", load=weights_conv, train=train_conv)\nl12 = Convolution(input_sizes=[batch_size, 28, 28, 512], filter_sizes=[3, 3, 512, 512], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv10\", load=weights_conv, train=train_conv)\nl13 = MaxPool(size=[batch_size, 28, 28, 512], ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n\nl14 = Convolution(input_sizes=[batch_size, 14, 14, 512], filter_sizes=[3, 3, 512, 512], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv11\", load=weights_conv, train=train_conv)\nl15 = Convolution(input_sizes=[batch_size, 14, 14, 512], filter_sizes=[3, 3, 512, 512], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv12\", load=weights_conv, train=train_conv)\nl16 = Convolution(input_sizes=[batch_size, 14, 14, 512], filter_sizes=[3, 3, 512, 512], num_classes=num_classes, init_filters=args.init, strides=[1, 1, 1, 1], padding=\"SAME\", alpha=learning_rate, activation=Relu(), bias=0.0, last_layer=False, name=\"conv13\", load=weights_conv, train=train_conv)\nl17 = MaxPool(size=[batch_size, 14, 14, 512], ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n\n###############################################################\n\nmodel = Model(layers=[l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16, l17])\npredict = model.predict(X=features)\n\n###############################################################\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth=True\nsess = tf.InteractiveSession(config=config)\ntf.global_variables_initializer().run()\n\ntrain_handle = sess.run(train_iterator.string_handle())\nval_handle = sess.run(val_iterator.string_handle())\n\n###############################################################\n'''\nsess.run(train_iterator.initializer, feed_dict={filename: train_imgs, label: train_labs})\n\nfor i in range(0, len(train_imgs), batch_size):\n print (i)\n [_predict, _labels] = sess.run([predict, labels], feed_dict={handle: train_handle, dropout_rate: 0.0, learning_rate: 0.0})\n _predict = np.reshape(_predict, (batch_size, 7 * 7 * 512))\n for j in range(batch_size):\n name = './tfrecord/train/%d.tfrecord' % (int(i + j))\n with tf.python_io.TFRecordWriter(name) as writer:\n image_raw = _predict[j].tostring()\n _feature={\n 'label': _int64_feature(int(_labels[j])),\n 'image_raw': _bytes_feature(image_raw)\n }\n _features=tf.train.Features(feature=_feature)\n example = tf.train.Example(features=_features)\n writer.write(example.SerializeToString())\n'''\n##################################################################\n\nsess.run(val_iterator.initializer, feed_dict={filename: val_imgs, label: val_labs})\n\nfor i in range(0, len(val_imgs), batch_size):\n print (i)\n [_predict, _labels] = sess.run([predict, labels], feed_dict={handle: val_handle, dropout_rate: 0.0, learning_rate: 0.0})\n _predict = np.reshape(_predict, (batch_size, 7 * 7 * 512))\n for j in range(batch_size):\n name = './tfrecord/test/%d.tfrecord' % (int(i + j))\n with tf.python_io.TFRecordWriter(name) as writer:\n image_raw = _predict[j].tostring()\n _feature={\n 'label': _int64_feature(int(_labels[j])),\n 'image_raw': _bytes_feature(image_raw)\n }\n _features=tf.train.Features(feature=_feature)\n example = tf.train.Example(features=_features)\n writer.write(example.SerializeToString())\n\n\n\n\n\n","sub_path":"vgg_transfer.py","file_name":"vgg_transfer.py","file_ext":"py","file_size_in_byte":15759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"5243713","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse, reverse_lazy\n\nfrom dashboard.forms import ClassTakenForm\nfrom dashboard.models import (\n Position,\n Classes,\n Brother,\n Grade\n)\nfrom dashboard.utils import verify_position\nfrom dashboard.views._dashboard_generic_views import DashboardDeleteView\n\n\n@login_required\ndef classes(request, department=None, number=None, brother=None):\n if not request.user.is_authenticated: # brother auth check\n messages.error(request, \"Brother not logged in\")\n return HttpResponseRedirect(reverse('dashboard:home'))\n if request.user.brother in Position.objects.get(title=Position.PositionChoices.SCHOLARSHIP_CHAIR).brothers.all():\n view = \"scholarship\"\n else:\n view = \"\"\n classes_taken = Classes.objects.all().order_by('department', 'number')\n if department is not None:\n classes_taken = classes_taken.filter(department=department)\n if brother is not None:\n classes_taken = classes_taken.filter(brothers=brother)\n if isinstance(brother, str):\n brother = int(brother)\n if request.user.brother.pk == brother:\n view = \"brother\"\n if number is not None:\n classes_taken = classes_taken.filter(number=number)\n\n if request.method == 'POST':\n if 'filter' in request.POST:\n form = request.POST\n department = ('department', form.get('department'))\n brother = ('brother', form.get('brother'))\n number = ('number', form.get('class_number'))\n kwargs = dict((arg for arg in [department, number, brother] if arg[1] != \"\"))\n\n return HttpResponseRedirect(reverse('dashboard:classes', kwargs=kwargs))\n elif 'unadd_self' in request.POST:\n form = request.POST\n class_taken = Classes.objects.get(pk=form.get('class'))\n class_taken.brothers.remove(request.user.brother)\n if not class_taken.brothers.exists():\n class_taken.delete()\n\n context = {\n 'classes_taken': classes_taken,\n 'departments': Classes.objects.all().values_list('department', flat=True).distinct,\n 'brothers': Brother.objects.order_by('last_name', 'first_name'),\n 'filter_department': department,\n 'filter_number': number,\n 'filter_brother': brother,\n 'view': view,\n }\n\n return render(request, \"general/classes.html\", context)\n\n\ndef classes_add(request):\n form = ClassTakenForm(request.POST or None)\n\n brother = request.user.brother\n\n if request.method == 'POST':\n if form.is_valid():\n instance = form.save(commit=False)\n instance.department = instance.department.upper()\n class_taken, created = Classes.objects.get_or_create(department=instance.department, number=instance.number)\n class_taken.brothers.add(brother)\n brother_grades = Grade(grade=form.cleaned_data['grade'], class_taken=class_taken, brother=brother)\n brother_grades.save()\n class_taken.save()\n return HttpResponseRedirect(reverse('dashboard:classes'), brother.pk)\n\n context = {\n 'form': form,\n 'brother': brother,\n 'title': 'Add a Class',\n }\n\n return render(request, \"model-add.html\", context)\n\n\nclass ClassesDelete(DashboardDeleteView):\n @verify_position([Position.PositionChoices.SCHOLARSHIP_CHAIR, Position.PositionChoices.PRESIDENT, Position.PositionChoices.ADVISER])\n def get(self, request, *args, **kwargs):\n return super(ClassesDelete, self).get(request, *args, **kwargs)\n\n model = Classes\n template_name = 'generic-forms/base-confirm-delete.html'\n success_url = reverse_lazy('dashboard:classes')\n","sub_path":"dashboard/views/_general/_classes.py","file_name":"_classes.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"539859300","text":"from string import ascii_letters, digits\nfrom random import choices\n\n\ndef make_activation_code():\n \"\"\"\n ascii_letters = 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n digits = '0123456789',\n 'k' is the length for code\n \"\"\"\n code = ''.join(choices(ascii_letters+digits, k=15))\n return code\n\n\nif __name__ == '__main__':\n results = []\n for i in range(200):\n result_code = make_activation_code()\n results.append(result_code)\n print(results)\n","sub_path":"001/001.py","file_name":"001.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"47587929","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Dom Jul 7 16:33:38 2019\n@author: fmozo\n\"\"\"\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\nfrom scipy import ndimage as ndi\n#####################################################################################\n\ndef find_perf(I):\n #############################################################\n # Devuelve imagen con perf encontradas y matriz (cubo) con ##\n # esquinas de las perf orden (II,SI,SD,ID) ##\n #############################################################\n\n ret, J = cv2.threshold(I, 200, 255, cv2.THRESH_TOZERO)\n\n kernel = np.ones((5, 5), np.uint8)\n J = cv2.erode(J, kernel, iterations=2)\n kernel = np.ones((4, 4), np.uint8)\n J = cv2.dilate(J, kernel, iterations=2)\n\n ret, J = cv2.threshold(J, 200, 255, cv2.THRESH_BINARY)\n\n found_perf = np.zeros(J.shape)\n J = cv2.cvtColor(J, cv2.COLOR_BGR2GRAY)\n contours, _ = cv2.findContours(J, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n perf_corners = np.zeros((40, 4, 2)).astype(int)\n index = 0\n for cnt in contours:\n rect = cv2.minAreaRect(cnt)\n # box = vertices del rect sent antihorario arranca\n # esquina superior derecha\n box = np.int0(cv2.boxPoints(rect))\n\n # Calculo datos de interes de los rectangulos\n x_min = np.amin(box, axis=0)[0]\n x_max = np.amax(box, axis=0)[0]\n\n y_min = np.amin(box[:, 1])\n y_max = np.amax(box[:, 1])\n\n # filtro por area y long de los lados\n h, w = y_max - y_min, x_max - x_min\n area = h * w\n area_range_ok = (area > 2500) and (area < 105000)\n dim_proportion_ok = np.abs(h - w) < 30\n if area_range_ok and dim_proportion_ok:\n cv2.drawContours(found_perf, [box], 0, (255), 3)\n\n # reordeno los vertices y los guardo\n x1 = box[0, 0]\n x3 = box[2, 0]\n aux = box.copy() # aux = box ordenado\n if x1 >= x3: # hay que rotar\n aux[0, :], aux[1, :], aux[2, :], aux[3, :], = box[1, :], box[2, :], box[3, :], box[0, :]\n perf_corners[index, :, :] = aux[:, :]\n index += 1\n\n perf_corners[index, :, :] = np.ones((4, 2)).astype(int) * (-1)\n return found_perf, perf_corners\n\n\n#####################################################################################\n\n\ndef orient(I, found_perf):\n\n vert = found_perf[:,1100:] # franja con posibles perforaciones verticales\n horiz = found_perf[650:,:] # franja con posibles perforaciones horizontales\n\n # perforaciones están en la franja horizontal o vertical?\n if len(vert[vert == 255]) > len(horiz[horiz == 255]): # si están en la vertical, rotar 180 grados\n M = cv2.getRotationMatrix2D((I.shape[1]/2, I.shape[0]/2), 180, 1)\n I = cv2.warpAffine(I, M, (I.shape[1], I.shape[0]))\n ang = 180\n\n else: # si están en la horizontal, rotar 90 grados\n M = cv2.getRotationMatrix2D((I.shape[1]/3, I.shape[0]/2), 270, 1)\n I = cv2.warpAffine(I, M, (I.shape[0], I.shape[1]))\n ang = 270\n\n return cv2.cvtColor(I, cv2.COLOR_BGR2RGB), ang\n#####################################################################################\n\n\ndef orient_corners(oriented_frame, perf_corners, ang):\n h ,w = oriented_frame.shape[0], oriented_frame.shape[1]\n oriented_corners = perf_corners.copy()\n index = 0\n\n aux_h = np.ones((4,))*h\n aux_w = np.ones((4,))*w\n if ang == 180:\n while perf_corners[index, 0, 0] != -1:\n oriented_corners[index, :, 0] = aux_w - perf_corners[index, :, 0]\n oriented_corners[index, :, 1] = aux_h - perf_corners[index, :, 1]\n index += 1\n elif ang == 270:\n while perf_corners[index, 0, 0] != -1:\n oriented_corners[index, :, 0] = aux_w - perf_corners[index, :, 1]\n oriented_corners[index, :, 1] = perf_corners[index, :, 0]\n index += 1\n\n return oriented_corners\n#####################################################################################\n\n\ndef angle(x1, y1, x2, y2):\n if x1 == x2:\n return 0\n else:\n return np.arctan((y2 - y1) / (x2 - x1))\n\n\ndef calc_rotation(perf_corners):\n ###############################################################\n # calcula mediante promedio de pendientes, el angulo a rotar ##\n ###############################################################\n angles = np.zeros((1, 40))\n ang_index = 0\n index = 0\n while perf_corners[index, 0, 0] != -1:\n x1, y1 = perf_corners[index, 1, 0], perf_corners[index, 1, 1]\n x2, y2 = perf_corners[index, 2, 0], perf_corners[index, 2, 1]\n angles[0, ang_index] = angle(x1, y1, x2, y2)\n ang_index += 1\n\n x1, y1 = perf_corners[index, 0, 0], perf_corners[index, 0, 1]\n x2, y2 = perf_corners[index, 3, 0], perf_corners[index, 3, 1]\n angles[0, ang_index] = angle(x1, y1, x2, y2)\n ang_index += 1\n index += 1\n angles[0, ang_index] = -1\n\n # promedio todos los angulos calculados\n i = 0\n ang_mean = 0\n while angles[0, i] != -1:\n ang_mean += angles[0, i]\n i += 1\n ang_mean = ang_mean / i\n return ang_mean\n'''\ndef calc_rotation(oriented_corners):\n ###############################################################\n # calcula mediante promedio de pendientes, el angulo a rotar ##\n ###############################################################\n angles = np.zeros((1, 40))\n ang_index = 0\n index = 0\n while oriented_corners[index, 0, 0] != -1:\n x1, y1 = oriented_corners[index, 1, 0], oriented_corners[index, 1, 1]\n x2, y2 = oriented_corners[index, 2, 0], oriented_corners[index, 2, 1]\n angles[0, ang_index] = angle(x1, y1, x2, y2)\n ang_index += 1\n\n x1, y1 = oriented_corners[index, 0, 0], oriented_corners[index, 0, 1]\n x2, y2 = oriented_corners[index, 3, 0], oriented_corners[index, 3, 1]\n angles[0, ang_index] = angle(x1, y1, x2, y2)\n ang_index += 1\n index += 1\n angles[0, ang_index] = -1\n\n # promedio todos los angulos calculados\n i = 0\n ang_mean = 0\n while angles[0, i] != -1:\n ang_mean += angles[0, i]\n i += 1\n ang_mean = ang_mean / i\n return ang_mean\n'''\n\n\ndef rotate_image(image, angle):\n image_center = tuple(np.array(image.shape[1::-1]) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n return result\n\n#######################################################################\n\n\ndef borde(franja):\n\n edges = cv2.Laplacian(franja, -1, ksize = 5)\n\n _, binaria = cv2.threshold(edges,80,255,cv2.THRESH_BINARY)\n binaria = cv2.cvtColor(binaria, cv2.COLOR_RGB2GRAY)\n\n ### Detección de líneas aplicado al Laplaciano\n\n rho = 1 # distance resolution in pixels of the Hough grid\n theta = np.pi / 180 # angular resolution in radians of the Hough grid\n threshold = 10 # minimum number of votes (intersections in Houg, cmap = 'gray'h grid cell)\n min_line_length = 150 # minimum number of pixels making up a line\n max_line_gap = 0 # maximum gap in pixels between connectable line segments\n line_image = np.copy(binaria) * 0 # creating a blank to draw lines on\n\n\n # Run Hough on edge detected image\n # Output \"lines\" is an array containing endpoints of detected line segments\n lines = cv2.HoughLinesP(binaria, rho, theta, threshold, np.array([]),\n min_line_length, max_line_gap)\n\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),1)\n\n return line_image, lines\n\n\ndef det_frame(I, x):\n\n # Asumiendo que la primer perforación que llega es la inferior\n sup = I[int(x[1,2,1]): int(x[1,3,1]), int(x[1,2,0]):, :]\n img1, bordesup = borde(sup)\n\n inf = I[int(x[0,2,1]): int(x[0,3,1]), int(x[0,2,0]):, :]\n img2, bordeinf = borde(inf)\n\n # Tomo un margen de +20 y -20 arriba y abajo para evitar posibles errores\n inter = I[int(x[1,2,1]) + bordesup[0,0,1] + 20: int(x[0,2,1]) + bordeinf[0,0,1] - 20, int(x[1,2,0]): , :]\n img3, bordeder = borde(inter)\n\n cuadro = I[int(x[1,2,1]) + np.max(bordesup[:,0,1]): int(x[0,2,1]) + np.min(bordeinf[0,0,1]), int(x[1,2,0]): int(x[1,2,0]) + np.min(bordeder[:,0,0]) , :]\n\n return cuadro\n\n###################################################################################################\n######################################## AUXILIARES ###############################################\n\ndef corners(I, perf_corners):\n #for i in len(perf_corners):\n\n i = 0\n while perf_corners[i,0,0] != -1:\n for corner in perf_corners[i]:\n x, y = corner.ravel()\n cv2.circle(I, (x,y), 10, 150, -1)\n i += 1\n return I\n\n\n\ndef show_im(I):\n # obtengo las esquinas de las perforaciones detectadas (antes de corregir orientacion)\n found_perf, perf_corners = find_perf(I)\n\n # obtengo el frame orientado y las perforaciones correspondientes al frame orientado\n oriented_frame, ang = orient(I, found_perf)\n oriented_corners = orient_corners(oriented_frame, perf_corners, ang)\n result = corners(oriented_frame, oriented_corners)\n\n # calculo el angulo a rotar, y lo roto\n ang_mean = calc_rotation(perf_corners)\n corrected_frame = rotate_image(oriented_frame, ang_mean)\n corrected_result = corners(corrected_frame, oriented_corners)\n\n plt.figure()\n plt.subplot(1,2,1)\n plt.imshow(oriented_frame)\n plt.title('antes')\n\n plt.subplot(1,2,2)\n plt.imshow(corrected_result)\n plt.title('corregida')\n return\n\n########################################################################################\n# leo la imagen\nfilm_1 = cv2.imread('./imagenes/film_1/000121.jpg', 1)\nfilm_2 = cv2.imread('./imagenes/film_2/000819.jpg', 1)\nfilm_3 = cv2.imread('./imagenes/film_3/000441.jpg', 1)\nfilm_4 = cv2.imread('./imagenes/film_4/000160.jpg', 1)\nfilm_5 = cv2.imread('./imagenes/film_5/000346.jpg', 1)\n\nshow_im(film_1)\nshow_im(film_2)\nshow_im(film_3)\nshow_im(film_4)\nshow_im(film_5)\n\nplt.show()\n\n\n\n\n#####################################################################################################\n'''\nLEGACY################3\ndef orient(I, perf_corners):\n gray = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)\n perf = fill_holes(gray)\n\n vert = perf[:, 1100:] # franja con posibles perforaciones verticales\n horiz = perf[650:, :] # franja con posibles perforaciones horizontales\n\n # perforaciones están en la franja horizontal o vertical?\n # si están en la vertical, rotar 180 grados\n if len(vert[vert == 255]) > len(horiz[horiz == 255]):\n M = cv2.getRotationMatrix2D((I.shape[1] / 2, I.shape[0] / 2), 180, 1)\n I = cv2.warpAffine(I, M, (I.shape[1], I.shape[0]))\n\n ##### ARREGLAR #####\n # cambio indices de x con y en el cubo de valores de vertices\n for index in range(perf_corners.shape[0]):\n aux = perf_corners[index, :, 0].copy()\n perf_corners[index, :, 0] = I.shape(0) - perf_corners[index, :, 0]\n perf_corners[index, :, 1] = aux\n\n else: # si están en la horizontal, rotar 90 grados\n M = cv2.getRotationMatrix2D((I.shape[1] / 2, I.shape[0] / 2), 270, 1)\n I = cv2.warpAffine(I, M, (I.shape[1], I.shape[0]))\n\n ##### ARREGLAR #####\n # cambio indices de x con y en el cubo de valores de vertices\n for index in range(perf_corners.shape[0]):\n aux = perf_corners[index, :, 0].copy()\n perf_corners[index, :, 0] = perf_corners[index, :, 1]\n perf_corners[index, :, 1] = aux\n\n J = cv2.cvtColor(I, cv2.COLOR_BGR2RGB)\n return J, perf_corners\n'''\n","sub_path":"bin/ideas.py","file_name":"ideas.py","file_ext":"py","file_size_in_byte":11797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"136725332","text":"from django.conf.urls import patterns, url\n\nfrom work_orders import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^detail/$', views.detail, name='detail'),\n url(r'^new/$', views.new, name='new'),\n url(r'^get_json/$', views.get_json, name='get_json'),\n url(r'^get_machine/$', views.get_machine, name='get_machine'),\n url(r'^tables/$', views.tables, name='tables'),\n url(r'^part_lookup/$', views.part_lookup, name='part_lookup'),\n url(r'^update/$', views.update, name='update'),\n url(r'^print/$', views.print_wo, name='print_wo'),\n )\n","sub_path":"work_orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"188169519","text":"#!/usr/bin/env python3\nimport hashlib\nimport sys\ndef hash_this():\n pw = sys.argv[1]\n print(pw)\n pw = pw.rstrip()\n pw = bytes(pw, 'utf-8')\n md_hash(pw)\n sha_hash(pw)\n sha3_hash(pw)\n blake(pw)\ndef md_hash(pw):\n pw_md = hashlib.md5(pw)\n pw_md = pw_md.hexdigest()\n print(f'md5: {pw_md}\\n')\n # print(sys.getsizeof(pw_md)) #sys.getsizeof(object[, default]) Return the size of an object in bytes.\ndef sha_hash(pw):\n pw_sha1 = hashlib.sha1(pw)\n pw_sha1 = pw_sha1.hexdigest()\n print(f'sha1: {pw_sha1}\\n')\n # print(sys.getsizeof(pw_sha1))\ndef sha3_hash(pw):\n pw_sha3 = hashlib.sha3_512(pw)\n pw_sha3 = pw_sha3.hexdigest()\n print(f'sha3-512: {pw_sha3}\\n')\n # print(sys.getsizeof(pw_sha3))\ndef blake(pw):\n pw_blake2b = hashlib.blake2b(pw)\n pw_blake2b = pw_blake2b.hexdigest()\n print(f'blake2b: {pw_blake2b}\\n')\n # print(sys.getsizeof(pw_blake2b))\nif __name__ == '__main__':\n #usage hasher.py \n if len(sys.argv) != 2:\n print(\"Usage: hash_this.py \")\n sys.exit(0)\n else:\n hash_this()\n#sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), and blake2s(). md5() (edited) \n","sub_path":"hash-this-2.py","file_name":"hash-this-2.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"159317845","text":"# chapter 15 Eigendecomposition\n\n\nimport numpy as np\nfrom numpy.linalg import eig\n\nA = np.array([\n [1,2,3],\n [4, 5, 6],\n [7, 8, 9],\n\n])\n\nprint(A)\n\nvalues, vectors = eig(A)\n\nprint(values)\nprint(vectors)","sub_path":"ch15/ch15.py","file_name":"ch15.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"538932898","text":"from unittest import TestCase\n\nfrom validator import ZipCodeValidator\n\nclass TestValidatorBetwheenMinAndMax(TestCase):\n\n def setUp(self):\n self.params = {\n 'cep': 100_000,\n 'min_value': 100_000,\n 'max_value': 999_999,\n }\n\n def test_cep_number_equal_min(self):\n \"\"\"Zip code number must be greater than min value\"\"\"\n validator = ZipCodeValidator(**self.params)\n self.assertEqual(False, validator.validate_limits())\n\n def test_cep_number_equal_max(self):\n \"\"\"Zip code number must be less than max value\"\"\"\n self.params['cep'] = 999_999\n validator = ZipCodeValidator(**self.params)\n self.assertEqual(False, validator.validate_limits())\n\n def test_within_allowed_range(self):\n self.params['cep'] = 250_420\n validator = ZipCodeValidator(**self.params)\n self.assertEqual(True, validator.validate_limits())\n\n\nclass TestValidatorAlternate(TestCase):\n\n def test_alternate_repeated_pairs(self):\n validator = ZipCodeValidator(121426)\n self.assertEqual(False, validator.validate_alternate())\n\n def test_not_alternate_repeated_pairs(self):\n validator = ZipCodeValidator(523563)\n self.assertEqual(True, validator.validate_alternate())\n\n\nclass TestValidatorIsValid(TestCase):\n\n def setUp(self):\n self.zip_codes = [\n '100000', '150123', '999999', '121426', '523563', '552523', '112233'\n ]\n self.expected_results = [\n False, True, False, False, True, False, True\n ]\n\n def test_is_valid(self):\n for zip_code, result in zip(self.zip_codes, self.expected_results):\n with self.subTest():\n self.assertEqual(\n ZipCodeValidator(\n zip_code, min_value=100000, max_value=999999\n ).is_valid, result\n )\n\n\nclass TestValidatorValueErrorException(TestCase):\n\n def test_value_error_exception(self):\n raised = False\n try:\n ZipCodeValidator('abcdef')\n except ValueError:\n raised = True\n\n self.assertEqual(raised, True)\n","sub_path":"validator/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"108483363","text":"import discord\n\nfrom discord.ext import commands\n\nclass Misc(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def ping(self, ctx: commands.Context):\n await ctx.message.reply('**Pong!** `{}ms`'.format(round(self.bot.latency * 1000)), mention_author=False)\n\ndef setup(bot):\n bot.add_cog(Misc(bot))","sub_path":"cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"558583025","text":"from datetime import timedelta\nfrom pathlib import Path\n\nimport minio\nfrom django.conf import settings\n\n\nclass Minio:\n def __init__(self):\n endpoint = settings.MINIO_STORAGE_ENDPOINT\n access_key = settings.MINIO_STORAGE_ACCESS_KEY\n secret_key = settings.MINIO_STORAGE_SECRET_KEY\n secure = settings.MINIO_STORAGE_USE_HTTPS\n self.client = minio.Minio(\n endpoint, access_key=access_key, secret_key=secret_key, secure=secure\n )\n self.bucket = settings.MINIO_STORAGE_MEDIA_BUCKET_NAME\n\n def download_url(self, object_name):\n try:\n return self.client.presigned_get_object(\n self.bucket,\n object_name,\n timedelta(minutes=settings.MINIO_PRESIGNED_TTL_MINUTES),\n )\n except minio.error.NoSuchBucket: # pragma: no cover\n if settings.MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET:\n self.client.make_bucket(self.bucket)\n return self.download_url(object_name)\n\n def upload_url(self, object_name):\n try:\n return self.client.presigned_put_object(\n self.bucket,\n object_name,\n timedelta(minutes=settings.MINIO_PRESIGNED_TTL_MINUTES),\n )\n except minio.error.NoSuchBucket: # pragma: no cover\n if settings.MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET:\n self.client.make_bucket(self.bucket)\n return self.upload_url(object_name)\n\n def remove_object(self, object_name):\n self.client.remove_object(self.bucket, object_name)\n\n def get_object(self, object_name):\n data = self.client.get_object(self.bucket, object_name)\n return data\n\n def put_object(self, filepath, object_name):\n filepath = Path(filepath) # make sure we got a Path object\n\n with filepath.open(\"rb\") as file_data:\n file_stat = filepath.stat()\n return self.client.put_object(\n self.bucket, object_name, file_data, file_stat.st_size\n )\n\n\nif settings.MEDIA_STORAGE_SERVICE == \"minio\":\n client = Minio()\nelse: # pragma: no cover\n client = None\n raise NotImplementedError(\n f\"Storage service {settings.MEDIA_STORAGE_SERVICE} is not implemented!\"\n )\n","sub_path":"alexandria/core/storage_clients.py","file_name":"storage_clients.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"521897054","text":"# -*- coding: utf-8 -*-\nfrom flask import current_app, _app_ctx_stack\nfrom sqlservice import SQLClient\n\n\nclass FlaskSQLService(object):\n \"\"\"Flask extension for sqlservice.SQLClient instance.\"\"\"\n def __init__(self,\n app=None,\n model_class=None,\n query_class=None,\n session_class=None,\n session_options=None):\n self.app = app\n self.model_class = model_class\n self.query_class = query_class\n self.session_class = session_class\n\n # Set default scopefunc for SQLAlchemy session as app context stack\n # identifier function. This associates each session with the\n # appropriate Flask app context.\n self.session_options = {'scopefunc': _app_ctx_stack.__ident_func__}\n self.session_options.update(session_options or {})\n\n if app:\n self.init_app(app)\n\n def init_app(self, app):\n options = {}\n\n if self.model_class:\n options['model_class'] = self.model_class\n\n if self.query_class:\n options['query_class'] = self.query_class\n\n if self.session_class:\n options['session_class'] = self.session_class\n\n options['session_options'] = self.session_options\n\n # Store SQLClient instances on app.extensions so it can be accessed\n # through flask.current_app proxy.\n app.extensions['sqlservice'] = SQLClient(app.config, **options)\n\n # Ensure that the session is removed on app context teardown so we\n # don't leave any sessions open after the request ends.\n @app.teardown_appcontext\n def shutdown_session(response_or_exc):\n self.remove()\n return response_or_exc\n\n def __getattr__(self, attr):\n \"\"\"Proxy attribute access to SQLClient instance.\"\"\"\n return getattr(current_app.extensions['sqlservice'], attr)\n","sub_path":"mwgs/server/flask_sqlservice.py","file_name":"flask_sqlservice.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"115609256","text":"import warnings\n\nimport cupy\n\n\ndef correlate(input, weights, output=None, mode='reflect', cval=0.0, origin=0):\n \"\"\"Multi-dimensional correlate.\n\n The array is correlated with the given kernel.\n\n Args:\n input (cupy.ndarray): The input array.\n weights (cupy.ndarray): Array of weights, same number of dimensions as\n input\n output (cupy.ndarray, dtype or None): The array in which to place the\n output.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``constant``. Default is ``0.0``.\n origin (scalar or tuple of scalar): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n\n Returns:\n cupy.ndarray: The result of correlate.\n\n .. seealso:: :func:`scipy.ndimage.correlate`\n \"\"\"\n return _correlate_or_convolve(input, weights, output, mode, cval, origin)\n\n\ndef convolve(input, weights, output=None, mode='reflect', cval=0.0, origin=0):\n \"\"\"Multi-dimensional convolution.\n\n The array is convolved with the given kernel.\n\n Args:\n input (cupy.ndarray): The input array.\n weights (cupy.ndarray): Array of weights, same number of dimensions as\n input\n output (cupy.ndarray, dtype or None): The array in which to place the\n output.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``constant``. Default is ``0.0``.\n origin (scalar or tuple of scalar): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n\n Returns:\n cupy.ndarray: The result of convolution.\n\n .. seealso:: :func:`scipy.ndimage.convolve`\n \"\"\"\n return _correlate_or_convolve(input, weights, output, mode, cval, origin,\n True)\n\n\ndef correlate1d(input, weights, axis=-1, output=None, mode=\"reflect\", cval=0.0,\n origin=0):\n \"\"\"One-dimensional correlate.\n\n The array is correlated with the given kernel.\n\n Args:\n input (cupy.ndarray): The input array.\n weights (cupy.ndarray): One-dimensional array of weights\n axis (int): The axis of input along which to calculate. Default is -1.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int): The origin parameter controls the placement of the\n filter, relative to the center of the current element of the\n input. Default is ``0``.\n Returns:\n cupy.ndarray: The result of the 1D correlation.\n .. seealso:: :func:`scipy.ndimage.correlate1d`\n \"\"\"\n weights, origins = _convert_1d_args(input.ndim, weights, origin, axis)\n return _correlate_or_convolve(input, weights, output, mode, cval, origins)\n\n\ndef convolve1d(input, weights, axis=-1, output=None, mode=\"reflect\", cval=0.0,\n origin=0):\n \"\"\"One-dimensional convolution.\n\n The array is convolved with the given kernel.\n\n Args:\n input (cupy.ndarray): The input array.\n weights (cupy.ndarray): One-dimensional array of weights\n axis (int): The axis of input along which to calculate. Default is -1.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int): The origin parameter controls the placement of the\n filter, relative to the center of the current element of the\n input. Default is ``0``.\n Returns:\n cupy.ndarray: The result of the 1D convolution.\n .. seealso:: :func:`scipy.ndimage.convolve1d`\n \"\"\"\n weights = weights[::-1]\n origin = -origin\n if not len(weights) & 1:\n origin -= 1\n weights, origins = _convert_1d_args(input.ndim, weights, origin, axis)\n return _correlate_or_convolve(input, weights, output, mode, cval, origins)\n\n\ndef _correlate_or_convolve(input, weights, output, mode, cval, origin,\n convolution=False):\n origins, int_type = _check_nd_args(input, weights, mode, origin)\n if weights.size == 0:\n return cupy.zeros_like(input)\n if convolution:\n weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]\n origins = list(origins)\n for i, wsize in enumerate(weights.shape):\n origins[i] = -origins[i]\n if wsize % 2 == 0:\n origins[i] -= 1\n origins = tuple(origins)\n kernel = _get_correlate_kernel(mode, weights.shape, int_type,\n origins, cval)\n return _call_kernel(kernel, input, weights, output)\n\n\n@cupy.util.memoize(for_each_device=True)\ndef _get_correlate_kernel(mode, wshape, int_type, origins, cval):\n return _generate_nd_kernel(\n 'correlate',\n 'W sum = (W)0;',\n 'sum += (W){value} * wval;',\n 'y = (Y)sum;',\n mode, wshape, int_type, origins, cval)\n\n\ndef minimum_filter(input, size=None, footprint=None, output=None,\n mode=\"reflect\", cval=0.0, origin=0):\n \"\"\"Multi-dimensional minimum filter.\n\n Args:\n input (cupy.ndarray): The input array.\n size (int or sequence of int): One of ``size`` or ``footprint`` must be\n provided. If ``footprint`` is given, ``size`` is ignored. Otherwise\n ``footprint = cupy.ones(size)`` with ``size`` automatically made to\n match the number of dimensions in ``input``.\n footprint (cupy.ndarray): a boolean array which specifies which of the\n elements within this shape will get passed to the filter function.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int or sequence of int): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.minimum_filter`\n \"\"\"\n return _min_or_max_filter(input, size, footprint, None, output, mode,\n cval, origin, 'min')\n\n\ndef maximum_filter(input, size=None, footprint=None, output=None,\n mode=\"reflect\", cval=0.0, origin=0):\n \"\"\"Multi-dimensional maximum filter.\n\n Args:\n input (cupy.ndarray): The input array.\n size (int or sequence of int): One of ``size`` or ``footprint`` must be\n provided. If ``footprint`` is given, ``size`` is ignored. Otherwise\n ``footprint = cupy.ones(size)`` with ``size`` automatically made to\n match the number of dimensions in ``input``.\n footprint (cupy.ndarray): a boolean array which specifies which of the\n elements within this shape will get passed to the filter function.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int or sequence of int): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.maximum_filter`\n \"\"\"\n return _min_or_max_filter(input, size, footprint, None, output, mode,\n cval, origin, 'max')\n\n\ndef _min_or_max_filter(input, size, footprint, structure, output, mode, cval,\n origin, func):\n # structure is used by morphology.grey_erosion() and grey_dilation()\n # and not by the regular min/max filters\n\n sizes, footprint, structure = _check_size_footprint_structure(\n input.ndim, size, footprint, structure)\n\n if sizes is not None:\n # Seperable filter, run as a series of 1D filters\n fltr = minimum_filter1d if func == 'min' else maximum_filter1d\n output_orig = output\n output = _get_output(output, input)\n sizes = _fix_sequence_arg(sizes, input.ndim, 'size', int)\n modes = _fix_sequence_arg(mode, input.ndim, 'mode', _check_mode)\n origins = _fix_sequence_arg(origin, input.ndim, 'origin', int)\n n_filters = sum(size > 1 for size in sizes)\n if n_filters == 0:\n output[...] = input[...]\n return output\n # We can't operate in-place efficiently, so use a 2-buffer system\n temp = _get_output(output.dtype, input) if n_filters > 1 else None\n first = True\n iterator = zip(sizes, modes, origins)\n for axis, (size, mode, origin) in enumerate(iterator):\n if size <= 1:\n continue\n fltr(input, size, axis, output, mode, cval, origin)\n input, output = output, temp if first else input\n if isinstance(output_orig, cupy.ndarray) and input is not output_orig:\n output_orig[...] = input\n input = output_orig\n return input\n\n origins, int_type = _check_nd_args(input, footprint, mode, origin,\n 'footprint')\n if structure is not None and structure.ndim != input.ndim:\n raise RuntimeError('structure array has incorrect shape')\n\n if footprint.size == 0:\n return cupy.zeros_like(input)\n center = tuple(x//2 + origin\n for x, origin in zip(footprint.shape, origins))\n kernel = _get_min_or_max_kernel(mode, footprint.shape, func,\n origins, float(cval), int_type,\n has_structure=structure is not None,\n has_central_value=bool(footprint[center]))\n return _call_kernel(kernel, input, footprint, output, structure,\n weights_dtype=bool)\n\n\ndef minimum_filter1d(input, size, axis=-1, output=None, mode=\"reflect\",\n cval=0.0, origin=0):\n \"\"\"Compute the minimum filter along a single axis.\n\n Args:\n input (cupy.ndarray): The input array.\n size (int): Length of the minimum filter.\n axis (int): The axis of input along which to calculate. Default is -1.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int): The origin parameter controls the placement of the\n filter, relative to the center of the current element of the\n input. Default is ``0``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.minimum_filter1d`\n \"\"\"\n return _min_or_max_1d(input, size, axis, output, mode, cval, origin, 'min')\n\n\ndef maximum_filter1d(input, size, axis=-1, output=None, mode=\"reflect\",\n cval=0.0, origin=0):\n \"\"\"Compute the maximum filter along a single axis.\n\n Args:\n input (cupy.ndarray): The input array.\n size (int): Length of the maximum filter.\n axis (int): The axis of input along which to calculate. Default is -1.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int): The origin parameter controls the placement of the\n filter, relative to the center of the current element of the\n input. Default is ``0``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.maximum_filter1d`\n \"\"\"\n return _min_or_max_1d(input, size, axis, output, mode, cval, origin, 'max')\n\n\ndef _min_or_max_1d(input, size, axis=-1, output=None, mode=\"reflect\", cval=0.0,\n origin=0, func='min'):\n ftprnt = cupy.ones(size, dtype=bool)\n ftprnt, origins = _convert_1d_args(input.ndim, ftprnt, origin, axis)\n origins, int_type = _check_nd_args(input, ftprnt, mode, origins,\n 'footprint')\n kernel = _get_min_or_max_kernel(mode, ftprnt.shape, func, origins,\n float(cval), int_type, has_weights=False)\n return _call_kernel(kernel, input, None, output, weights_dtype=bool)\n\n\n@cupy.util.memoize(for_each_device=True)\ndef _get_min_or_max_kernel(mode, wshape, func, origins, cval, int_type,\n has_weights=True, has_structure=False,\n has_central_value=True):\n value = '{value}'\n if has_structure:\n value += ' - (X)sval' if func == 'min' else ' + (X)sval'\n\n if has_central_value:\n pre = 'X value = x[i];'\n found = 'value = {func}({value}, value);'\n else:\n # If the central pixel is not included in the footprint we cannot\n # assume `x[i]` is not below the min or above the max and thus cannot\n # seed with that value. Instead we keep track of having set `value`.\n pre = 'X value; bool set = false;'\n found = 'value = set ? {func}({value}, value) : {value}; set=true;'\n return _generate_nd_kernel(\n func, pre, found.format(func=func, value=value), 'y = (Y)value;',\n mode, wshape, int_type, origins, cval,\n has_weights=has_weights, has_structure=has_structure)\n\n\ndef rank_filter(input, rank, size=None, footprint=None, output=None,\n mode=\"reflect\", cval=0.0, origin=0):\n \"\"\"Multi-dimensional rank filter.\n Args:\n input (cupy.ndarray): The input array.\n rank (int): The rank of the element to get. Can be negative to count\n from the largest value, e.g. ``-1`` indicates the largest value.\n size (int or sequence of int): One of ``size`` or ``footprint`` must be\n provided. If ``footprint`` is given, ``size`` is ignored. Otherwise\n ``footprint = cupy.ones(size)`` with ``size`` automatically made to\n match the number of dimensions in ``input``.\n footprint (cupy.ndarray): a boolean array which specifies which of the\n elements within this shape will get passed to the filter function.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int or sequence of int): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.rank_filter`\n \"\"\"\n rank = int(rank)\n return _rank_filter(input, lambda fs: rank+fs if rank < 0 else rank,\n size, footprint, output, mode, cval, origin)\n\n\ndef median_filter(input, size=None, footprint=None, output=None,\n mode=\"reflect\", cval=0.0, origin=0):\n \"\"\"Multi-dimensional median filter.\n Args:\n input (cupy.ndarray): The input array.\n size (int or sequence of int): One of ``size`` or ``footprint`` must be\n provided. If ``footprint`` is given, ``size`` is ignored. Otherwise\n ``footprint = cupy.ones(size)`` with ``size`` automatically made to\n match the number of dimensions in ``input``.\n footprint (cupy.ndarray): a boolean array which specifies which of the\n elements within this shape will get passed to the filter function.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int or sequence of int): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.median_filter`\n \"\"\"\n return _rank_filter(input, lambda fs: fs//2,\n size, footprint, output, mode, cval, origin)\n\n\ndef percentile_filter(input, percentile, size=None, footprint=None,\n output=None, mode=\"reflect\", cval=0.0, origin=0):\n \"\"\"Multi-dimensional percentile filter.\n Args:\n input (cupy.ndarray): The input array.\n percentile (scalar): The percentile of the element to get (from ``0``\n to ``100``). Can be negative, thus ``-20`` equals ``80``.\n size (int or sequence of int): One of ``size`` or ``footprint`` must be\n provided. If ``footprint`` is given, ``size`` is ignored. Otherwise\n ``footprint = cupy.ones(size)`` with ``size`` automatically made to\n match the number of dimensions in ``input``.\n footprint (cupy.ndarray): a boolean array which specifies which of the\n elements within this shape will get passed to the filter function.\n output (cupy.ndarray, dtype or None): The array in which to place the\n output. Default is is same dtype as the input.\n mode (str): The array borders are handled according to the given mode\n (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,\n ``'wrap'``). Default is ``'reflect'``.\n cval (scalar): Value to fill past edges of input if mode is\n ``'constant'``. Default is ``0.0``.\n origin (int or sequence of int): The origin parameter controls the\n placement of the filter, relative to the center of the current\n element of the input. Default of 0 is equivalent to\n ``(0,)*input.ndim``.\n Returns:\n cupy.ndarray: The result of the filtering.\n .. seealso:: :func:`scipy.ndimage.percentile_filter`\n \"\"\"\n percentile = float(percentile)\n if percentile < 0.0:\n percentile += 100.0\n if percentile < 0.0 or percentile > 100.0:\n raise RuntimeError('invalid percentile')\n if percentile == 100.0:\n def get_rank(fs):\n return fs - 1\n else:\n def get_rank(fs):\n return int(float(fs) * percentile / 100.0)\n return _rank_filter(input, get_rank,\n size, footprint, output, mode, cval, origin)\n\n\ndef _rank_filter(input, get_rank, size=None, footprint=None, output=None,\n mode=\"reflect\", cval=0.0, origin=0):\n _, footprint, _ = _check_size_footprint_structure(\n input.ndim, size, footprint, None, force_footprint=True)\n origins, int_type = _check_nd_args(input, footprint, mode, origin,\n 'footprint')\n if footprint.size == 0:\n return cupy.zeros_like(input)\n filter_size = int(footprint.sum())\n rank = get_rank(filter_size)\n if rank < 0 or rank >= filter_size:\n raise RuntimeError('rank not within filter footprint size')\n if rank == 0:\n return _min_or_max_filter(input, None, footprint, None, output, mode,\n cval, origins, 'min')\n if rank == filter_size - 1:\n return _min_or_max_filter(input, None, footprint, None, output, mode,\n cval, origins, 'max')\n kernel = _get_rank_kernel(filter_size, rank, mode, footprint.shape,\n origins, float(cval), int_type)\n return _call_kernel(kernel, input, footprint, output, None, bool)\n\n\n__SHELL_SORT = '''\n__device__ void sort(X *array, int size) {{\n int gap = {gap};\n while (gap > 1) {{\n gap /= 3;\n for (int i = gap; i < size; ++i) {{\n X value = array[i];\n int j = i - gap;\n while (j >= 0 && value < array[j]) {{\n array[j + gap] = array[j];\n j -= gap;\n }}\n array[j + gap] = value;\n }}\n }}\n}}'''\n\n\n__SELECTION_SORT = '''\n__device__ void sort(X *array, int size) {\n for (int i = 0; i < size-1; ++i) {\n X min_val = array[i];\n int min_idx = i;\n for (int j = i+1; j < size; ++j) {\n X val_j = array[j];\n if (val_j < min_val) {\n min_idx = j;\n min_val = val_j;\n }\n }\n if (i != min_idx) {\n array[min_idx] = array[i];\n array[i] = min_val;\n }\n }\n}'''\n\n\n@cupy.util.memoize()\ndef _get_shell_gap(filter_size):\n gap = 1\n while gap < filter_size:\n gap = 3*gap+1\n return gap\n\n\n@cupy.util.memoize(for_each_device=True)\ndef _get_rank_kernel(filter_size, rank, mode, wshape, origins, cval, int_type):\n # Below 225 (15x15 median filter) selection sort is 1.5-2.5x faster\n # Above, shell sort does progressively better (by 3025 (55x55) it is 9x)\n # Also tried insertion sort, which is always slower than either one\n sorter = __SELECTION_SORT if filter_size <= 255 else \\\n __SHELL_SORT.format(gap=_get_shell_gap(filter_size))\n return _generate_nd_kernel(\n 'rank_{}_{}'.format(filter_size, rank),\n 'int iv = 0;\\nX values[{}];'.format(filter_size),\n 'values[iv++] = {value};',\n 'sort(values, {});\\ny = (Y)values[{}];'.format(filter_size, rank),\n mode, wshape, int_type, origins, cval, preamble=sorter)\n\n\ndef _get_output(output, input, shape=None):\n if shape is None:\n shape = input.shape\n if isinstance(output, cupy.ndarray):\n if output.shape != tuple(shape):\n raise ValueError('output shape is not correct')\n else:\n dtype = output\n if dtype is None:\n dtype = input.dtype\n output = cupy.zeros(shape, dtype)\n return output\n\n\ndef _fix_sequence_arg(arg, ndim, name, conv=lambda x: x):\n if isinstance(arg, str):\n return [conv(arg)] * ndim\n try:\n arg = iter(arg)\n except TypeError:\n return [conv(arg)] * ndim\n lst = [conv(x) for x in arg]\n if len(lst) != ndim:\n msg = \"{} must have length equal to input rank\".format(name)\n raise RuntimeError(msg)\n return lst\n\n\ndef _check_origin(origin, width):\n origin = int(origin)\n if (width // 2 + origin < 0) or (width // 2 + origin >= width):\n raise ValueError('invalid origin')\n return origin\n\n\ndef _check_mode(mode):\n if mode not in ('reflect', 'constant', 'nearest', 'mirror', 'wrap'):\n msg = 'boundary mode not supported (actual: {})'.format(mode)\n raise RuntimeError(msg)\n return mode\n\n\ndef _check_size_footprint_structure(ndim, size, footprint, structure,\n stacklevel=3, force_footprint=False):\n if structure is None and footprint is None:\n if size is None:\n raise RuntimeError(\"no footprint or filter size provided\")\n sizes = _fix_sequence_arg(size, ndim, 'size', int)\n if force_footprint:\n return None, cupy.ones(sizes, bool), None\n return sizes, None, None\n if size is not None:\n warnings.warn(\"ignoring size because {} is set\".format(\n 'structure' if footprint is None else 'footprint'),\n UserWarning, stacklevel=stacklevel+1)\n\n if footprint is not None:\n footprint = cupy.array(footprint, bool, True, 'C')\n if not footprint.any():\n raise ValueError(\"all-zero footprint is not supported\")\n\n if structure is None:\n if not force_footprint and footprint.all():\n return footprint.shape, None, None\n return None, footprint, None\n\n structure = cupy.ascontiguousarray(structure)\n if footprint is None:\n footprint = cupy.ones(structure.shape, bool)\n return None, footprint, structure\n\n\ndef _convert_1d_args(ndim, weights, origin, axis):\n if weights.ndim != 1 or weights.size < 1:\n raise RuntimeError('incorrect filter size')\n axis = cupy.util._normalize_axis_index(axis, ndim)\n wshape = [1]*ndim\n wshape[axis] = weights.size\n weights = weights.reshape(wshape)\n origins = [0]*ndim\n origins[axis] = _check_origin(origin, weights.size)\n return weights, tuple(origins)\n\n\ndef _check_nd_args(input, weights, mode, origins, wghts_name='filter weights'):\n if input.dtype.kind == 'c':\n raise TypeError('Complex type not supported')\n _check_mode(mode)\n # The integer type to use for indices in the input array\n # The indices actually use byte positions and we can't just use\n # input.nbytes since that won't tell us the number of bytes between the\n # first and last elements when the array is non-contiguous\n nbytes = sum((x-1)*abs(stride) for x, stride in\n zip(input.shape, input.strides)) + input.dtype.itemsize\n int_type = 'int' if nbytes < (1 << 31) else 'ptrdiff_t'\n # However, weights must always be 2 GiB or less\n if weights.nbytes > (1 << 31):\n raise RuntimeError('weights must be 2 GiB or less, use FFTs instead')\n weight_dims = [x for x in weights.shape if x != 0]\n if len(weight_dims) != input.ndim:\n raise RuntimeError('{} array has incorrect shape'.format(wghts_name))\n origins = _fix_sequence_arg(origins, len(weight_dims), 'origin', int)\n for origin, width in zip(origins, weight_dims):\n _check_origin(origin, width)\n return tuple(origins), int_type\n\n\ndef _call_kernel(kernel, input, weights, output, structure=None,\n weights_dtype=cupy.float64, structure_dtype=cupy.float64):\n \"\"\"\n Calls a constructed ElementwiseKernel. The kernel must take an input image,\n an optional array of weights, an optional array for the structure, and an\n output array.\n\n weights and structure can be given as None (structure defaults to None) in\n which case they are not passed to the kernel at all. If the output is given\n as None then it will be allocated in this function.\n\n This function deals with making sure that the weights and structure are\n contiguous and float64 (or bool for weights that are footprints)*, that the\n output is allocated and appriopately shaped. This also deals with the\n situation that the input and output arrays overlap in memory.\n\n * weights is always cast to float64 or bool in order to get an output\n compatible with SciPy, though float32 might be sufficient when input dtype\n is low precision. If weights_dtype is passed as weights.dtype then no\n dtype conversion will occur. The input and output are never converted.\n \"\"\"\n args = [input]\n if weights is not None:\n weights = cupy.ascontiguousarray(weights, weights_dtype)\n args.append(weights)\n if structure is not None:\n structure = cupy.ascontiguousarray(structure, structure_dtype)\n args.append(structure)\n output = _get_output(output, input)\n needs_temp = cupy.shares_memory(output, input, 'MAY_SHARE_BOUNDS')\n if needs_temp:\n output, temp = _get_output(output.dtype, input), output\n args.append(output)\n kernel(*args)\n if needs_temp:\n temp[...] = output[...]\n output = temp\n return output\n\n\ndef _generate_boundary_condition_ops(mode, ix, xsize):\n if mode == 'reflect':\n ops = '''\n if ({ix} < 0) {{\n {ix} = - 1 - {ix};\n }}\n {ix} %= {xsize} * 2;\n {ix} = min({ix}, 2 * {xsize} - 1 - {ix});'''.format(ix=ix, xsize=xsize)\n elif mode == 'mirror':\n ops = '''\n if ({ix} < 0) {{\n {ix} = - {ix};\n }}\n if ({xsize} == 1) {{\n {ix} = 0;\n }} else {{\n {ix} = 1 + ({ix} - 1) % (({xsize} - 1) * 2);\n {ix} = min({ix}, 2 * {xsize} - 2 - {ix});\n }}'''.format(ix=ix, xsize=xsize)\n elif mode == 'nearest':\n ops = '''\n {ix} = min(max({ix}, 0), {xsize} - 1);'''.format(ix=ix, xsize=xsize)\n elif mode == 'wrap':\n ops = '''\n if ({ix} < 0) {{\n {ix} += (1 - ({ix} / {xsize})) * {xsize};\n }}\n {ix} %= {xsize};'''.format(ix=ix, xsize=xsize)\n elif mode == 'constant':\n ops = '''\n if ({ix} >= {xsize}) {{\n {ix} = -1;\n }}'''.format(ix=ix, xsize=xsize)\n return ops\n\n\ndef _generate_nd_kernel(name, pre, found, post, mode, wshape, int_type,\n origins, cval, preamble='', options=(),\n has_weights=True, has_structure=False):\n # Currently this code uses CArray for weights but avoids using CArray for\n # the input data and instead does the indexing itself since it is faster.\n # If CArray becomes faster than follow the comments that start with\n # CArray: to switch over to using CArray for the input data as well.\n\n ndim = len(wshape)\n in_params = 'raw X x'\n if has_weights:\n in_params += ', raw W w'\n if has_structure:\n in_params += ', raw S s'\n out_params = 'Y y'\n\n inds = _generate_indices_ops(\n ndim, int_type, 'xsize_{j}',\n [' - {}'.format(wshape[j]//2 + origins[j]) for j in range(ndim)])\n # CArray: remove xstride_{j}=... from string\n sizes = ['{type} xsize_{j}=x.shape()[{j}], xstride_{j}=x.strides()[{j}];'.\n format(j=j, type=int_type) for j in range(ndim)]\n # CArray: remove expr entirely\n expr = ' + '.join(['ix_{0}'.format(j) for j in range(ndim)])\n\n ws_init = ws_pre = ws_post = ''\n if has_weights or has_structure:\n ws_init = 'int iws = 0;'\n if has_structure:\n ws_pre = 'S sval = s[iws];\\n'\n if has_weights:\n ws_pre += 'W wval = w[iws];\\nif (wval)'\n ws_post = 'iws++;'\n\n loops = []\n for j in range(ndim):\n if wshape[j] == 1:\n # CArray: string becomes 'inds[{j}] = ind_{j};', remove (int_)type\n loops.append('{{ {type} ix_{j} = ind_{j} * xstride_{j};'.\n format(j=j, type=int_type))\n else:\n boundary = _generate_boundary_condition_ops(\n mode, 'ix_{}'.format(j), 'xsize_{}'.format(j))\n # CArray: last line of string becomes inds[{j}] = ix_{j};\n loops.append('''\n for (int iw_{j} = 0; iw_{j} < {wsize}; iw_{j}++)\n {{\n {type} ix_{j} = ind_{j} + iw_{j};\n {boundary}\n ix_{j} *= xstride_{j};\n '''.format(j=j, wsize=wshape[j], boundary=boundary, type=int_type))\n\n # CArray: string becomes 'x[inds]', no format call needed\n value = '(*(X*)&data[{expr}])'.format(expr=expr)\n if mode == 'constant':\n cond = ' || '.join(['(ix_{0} < 0)'.format(j) for j in range(ndim)])\n value = '(({cond}) ? (X){cval} : {value})'.format(\n cond=cond, cval=cval, value=value)\n found = found.format(value=value)\n\n # CArray: replace comment and next line in string with\n # {type} inds[{ndim}] = {{0}};\n # and add ndim=ndim, type=int_type to format call\n operation = '''\n {sizes}\n {inds}\n // don't use a CArray for indexing (faster to deal with indexing ourselves)\n const unsigned char* data = (const unsigned char*)&x[0];\n {ws_init}\n {pre}\n {loops}\n // inner-most loop\n {ws_pre} {{\n {found}\n }}\n {ws_post}\n {end_loops}\n {post}\n '''.format(sizes='\\n'.join(sizes), inds=inds, pre=pre, post=post,\n ws_init=ws_init, ws_pre=ws_pre, ws_post=ws_post,\n loops='\\n'.join(loops), found=found, end_loops='}'*ndim)\n\n name = 'cupy_ndimage_{}_{}d_{}_w{}'.format(\n name, ndim, mode, '_'.join(['{}'.format(j) for j in wshape]))\n if int_type == 'ptrdiff_t':\n name += '_i64'\n if has_structure:\n name += '_with_structure'\n return cupy.ElementwiseKernel(in_params, out_params, operation, name,\n reduce_dims=False, preamble=preamble,\n options=options)\n\n\ndef _generate_indices_ops(ndim, int_type, xsize='x.shape()[{j}]', extras=None):\n if extras is None:\n extras = ('',)*ndim\n code = '{type} ind_{j} = _i % ' + xsize + '{extra}; _i /= ' + xsize + ';'\n body = [code.format(type=int_type, j=j, extra=extras[j])\n for j in range(ndim-1, 0, -1)]\n return '{type} _i = i;\\n{body}\\n{type} ind_0 = _i{extra};'.format(\n type=int_type, body='\\n'.join(body), extra=extras[0])\n","sub_path":"cupyx/scipy/ndimage/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":35236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"586608874","text":"r\"\"\"Heat flow in a 1D rod with boundary and initial conditions.\n\nThis problem involves heat conduction in a 1D rod of length :math:`L`.\nThe heat conduction equation for the temperature profile :math:`T(x,t)` is\n\n.. math::\n \\frac{\\partial T}{\\partial t} = \\kappa \\, \\frac{\\partial^2 T}{\\partial x^2}\n \\ ,\n :label: DE\n\nwhere :math:`\\kappa` is the (constant) thermal conductivity of the rod. We place\nthe ends of the rod at :math:`x=0` and :math:`x=L`, and use a linear combination\nof Dirichlet and Neumann and boundary conditions,\n\n.. math::\n \\alpha_1 T(0,t) + \\beta_1 \\partial_x T(0,t) &= 0\n \\\\\n \\alpha_2 T(0,t) + \\beta_2 \\partial_x T(0,t) &= 0\n \\ ,\n :label: BCs\n\nwith :math:`t > 0`. Finally, we must provide a continuous initial temperature\nprofile :math:`T(x,0)` to obtain a solution to the differential equation.\nFor simplicity we shall consider only two cases: :math:`T(x,0)` is a constant\ntemperature :math:`T_0`, or :math:`T(x,0)` varies linearly between :math:`T_0`\nand :math:`T_1` over the length of the rod,\n\n.. math::\n T(x,0) = T_0 + \\frac{T_1 - T_0}{L} \\cdot x\n \\ ,\n :label: IC\n\nfor :math:`x \\in (0,L)`. Note that :math:`T(x=0,0)=T_0` and :math:`T(x=L,0)=T_1`.\n\nIn general, the boundary conditions (BC's) give a transcendental equation, but there\nare four special cases that are particularly simple.\n\nBC1: The first boundary condition choice is\n\n.. math::\n T(0,t) &= 0\n \\\\[5pt]\n T(L,t) &= 0\n \\ ,\n :label: BC1\n\nwhich corresponds to :math:`\\alpha_1 = 1`, :math:`\\beta_1 = 0`, :math:`\\alpha_2 = 1`,\nand :math:`\\beta_2 = 0`. The solution takes the form\n\n.. math::\n T(x,t)\n &=\n \\sum_{n=1}^\\infty\n \\left[\\frac{2 T_0 - 2 T_1 \\, (-1)^n}{n \\pi}\\right]\\,\n \\sin k_n x \\, e^{- \\kappa \\, k_n^2 t}\n \\\\[5pt]\n k_n\n &=\n \\frac{n\\pi}{L}\n \\ .\n :label: BC1sol\n\nBC2: The second boundary condition choice is\n\n.. math::\n \\partial_x T(0,t) &= 0\n \\\\[5pt]\n \\partial_x T(L,t) &= 0\n \\ ,\n :label: BC2\n\nwhich corresponds to :math:`\\alpha_1 = 0`, :math:`\\beta_1 = 1`, :math:`\\alpha_2 = 0`,\nand :math:`\\beta_2 = 1`. The solution takes the form\n\n.. math::\n T(x,t)\n &=\n \\frac{1}{2}(T_0 + T_1) + \\sum_{n=1}^\\infty\n \\left[ 2(T_1 - T_0) \\, \\frac{ 1 - (-1)^n}{n^2 \\pi^2} \\right]\\,\n \\cos k_n x \\, e^{- \\kappa \\, k_n^2 t}\n \\\\[5pt]\n k_n\n &=\n \\frac{n\\pi}{L}\n \\ .\n :label: BC2sol\n\nFor the case of constant initial condition :math:`T(x,0)=T_0`, or equivalently\nfor :math:`T_1 = T_0`, note that the solution reduces to the time independent\nform :math:`T(x,t) = T_0`. This is because the BC's prevent heat from flowing\nacross the boundaries, and the initial temperature profile remains fixed.\n\nBC3: The third boundary condition choice is\n\n.. math::\n T(0,t) &= 0\n \\\\[5pt]\n \\partial_x T(L,t) &= 0\n \\ ,\n :label: BC3\n\nwhich corresponds to :math:`\\alpha_1 = 1`, :math:`\\beta_1 = 0`, :math:`\\alpha_2 = 0`, and\n:math:`\\beta_2 = 1`. The solution takes the form\n\n.. math::\n T(x,t) &= \\sum_{n=0}^\\infty\n \\left[\\frac{4T_1}{(2n + 1)\\pi} - \\frac{8(T_1 - T_0)}{(2n+1)^2 \\pi^2} \\right]\n \\sin k_n x \\, e^{-\\kappa \\, k_n^2 t}\n \\\\[5pt]\n k_n &= \\frac{(2 n + 1) \\pi}{2 L}\n \\ .\n :label: BC3sol\n\nBC4: The fourth boundary condition choice is\n\n.. math::\n \\partial_x T(0,t) &= 0\n \\\\[5pt]\n T(L,t) &= 0\n \\ ,\n :label: BC4\n\nwhich corresponds to :math:`\\alpha_1 = 0`, :math:`\\beta_1 = 1`, :math:`\\alpha_2 = 1`, and\n:math:`\\beta_2 = 0`. On physical grounds, the solution must be identical to the one for BC3,\nexcept that the rod has been inverted. In terms of a series expansion, we have\n\n.. math::\n T(x,t) &= \\sum_{n=0}^\\infty\n \\left[\n \\frac{4T_0\\, (-1)^n}{(2n+1)\\pi}\n -\n \\frac{8(T_1 - T_0)}{(2n+1)^2 \\pi^2} \\Big[1 - (-1)^n\\Big]\n \\right]\n \\cos k_n x \\, e^{-\\kappa \\, k_n^2 t}\n \\\\[5pt]\n k_n &= \\frac{(2 n + 1) \\pi}{2 L}\n \\ .\n :label: BC4sol\n\nThe solutions for BC3 and BC4 appear to be quite different; however, they\nare indeed just a reflection across the midpoint of the rod. Since the\ninfinite sums in ExactPack must be truncated at some order, comparing BC3\nagainst BC4 provides a good metric to determine whether the truncation\nhas been performed to sufficient accuracy. The first 100 terms seems gives\nreasonable results.\n\nGeneral BC: The solution is of the form\n\n.. math::\n T(x,t) = \\sum_n \\Big[A_n \\cos k_n x + B_n \\sin k_n x \\Big]\\,\n e^{-\\kappa \\, k_n^2 t}\n \\ ,\n\nwhere the wave numbers are\n\n.. math::\n k_n = \\frac{\\mu_n}{L}\n \\ ,\n\nwith :math:`\\mu_n` being the solutions to\n\n.. math::\n \\tan \\mu\n &= \\frac{(\\alpha_2 \\bar\\beta_1 - \\alpha_1 \\bar\\beta_2)\\mu}\n {\\alpha_1 \\alpha_2 + \\bar\\beta_1 \\bar\\beta_2 \\mu^2}\n \\,\\,\\,\\, {\\rm for}\\,\\,\\, \\bar\\beta_i = \\beta_i/L\n \\ .\n\nCase I: :math:`\\alpha_1 \\ne 0`. The coefficients :math:`A_n` and\n:math:`B_n` are related by\n\n.. math::\n A_n = - \\frac{\\beta_1 k_n}{\\alpha_1}\\, B_n\n \\ ,\n\nwhich leads us to write\n\n.. math::\n X_n(x)\n &=\n \\sin k_n x - \\frac{\\beta_1 k_n}{\\alpha_1} \\, \\cos k_n x\n \\\\[5pt]\n T(x,t)\n &=\n \\sum_{n=1}^\\infty B_n \\, X_n(x) \\, e^{-\\kappa \\, k_n^2 t}\n \\ .\n\nNote that :math:`n=0` does not contribute since :math:`\\mu_0=0` means\nthat :math:`k_0=0`, and therefore :math:`A_0=0` and :math:`\\sin k_0 x\n= 0` (for :math:`\\alpha_1 \\ne 0`). The modes :math:`X_n` are orthogonal\nfor :math:`n \\ne m`, and calculating the normalization :math:`N_n` is\nstraightforward but tedious:\n\n.. math::\n \\int_0^L dx \\, X_n(x) \\, X_m(x)\n &= N_n \\, \\delta_{nm}\n \\\\[5pt]\n {\\rm where}\\,\\,\\,\n N_n\n &=\n \\frac{1}{4 \\alpha_1 k_n^2}\\, \\Big[ -2 \\alpha_1 \\beta_1 k_n +\n 2 (\\beta_1^2 k_n^2 + \\alpha_1^2) k_n L \\, +\n \\\\\n & 2 \\alpha_1 \\beta_1 k_n \\cos 2 k_n L + (\\beta_1^2 k_n^2 - \\alpha_1^2)\n \\sin 2 k_n L \\Big]\n \\ .\n\nThe coefficients :math:`B_n` can be calculated from\n\n.. math::\n B_n = \\frac{1}{N_n}\\int_0^L dx \\, T(x,0)\\, X_n(x)\n \\ .\n\nSince the expression for :math:`B_n` is rather long for a constant plus\na linear initial condition, :math:`T(x,0) = T_0 + (T_1 - T_0)\\, x / L`,\nwe divide the result into two pieces:\n\n.. math::\n T^{(0)}(x,0) &= T_0:\n \\\\[3pt]\n B_n^{(0)}\n &=\n \\frac{T_0}{N_n}\\Big[ \\frac{1 - \\cos k_n L}{k_n} -\n \\frac{\\beta_1 }{\\alpha_1}\\, \\sin k_n L\n \\Big]\n \\ ,\n\nand\n\n.. math::\n T^{(1)}(x,0) &= \\frac{T_1 - T_0}{L}\\, x:\n \\\\[5pt]\n B_n^{(1)}\n &=\n \\frac{T_1-T_0}{N_n \\, L} \\, \\frac{1}{\\alpha_1 k_n^2}\n \\Big[\n \\beta_1 k_n - (\\alpha_1 k_n L + \\beta_1 k_n) \\cos k_n L \\,+\n \\\\\n & \\hskip3.5cm (\\alpha_1 - \\beta_1 k)n^2 L) \\sin k_n L\n \\Big]\n \\ .\n\nSince the boundary conditions are homogenous, we may add the two\nsolutions the constant plus linear initial condition, :math:`T(x,0)\n= T^{(0)}(x,0) + X^{(1)}(x,0)`, in which case :math:`B_n = B_n^{(0)}\n+ B_n^{(1)}`.\n\nCase II: :math:`\\alpha_1 = 0`. We may assume that :math:`\\beta_2 \\ne 0`,\notherwise this is BC4, which has already been treated. The wave numbers\nare given by :math:`k_n = \\mu_n/L`, where :math:`\\mu_n` are the solutions\nto\n\n.. math::\n \\tan \\mu\n &= \\frac{\\alpha_2}{\\bar\\beta_2}\\,\\frac{1}{\\mu}\n \\ .\n\nThe coefficients of the sin-function vanish,\n\n.. math::\n B_n = 0\n \\ ,\n\nwhich leads us to write\n\n.. math::\n X_n(x)\n &=\n \\cos k_n x\n \\\\[5pt]\n T(x,t)\n &=\n \\sum_{n=1}^\\infty A_n \\, X_n(x) \\, e^{-\\kappa \\, k_n^2 t}\n \\ .\n\nThe orthogonality relation is\n\n.. math::\n \\int_0^L dx \\, X_n(x) \\, X_m(x)\n &= N_n \\, \\delta_{nm}\n \\\\[5pt]\n {\\rm where}\\,\\,\\,\n N_n\n &= \\frac{1}{4 k_n}\\Big[ 2 k_n L + sin 2 k_n L \\Big]\n \\ .\n\nThe coefficients :math:`B_n` can be calculated from\n\n.. math::\n A_n\n &= \\frac{1}{N_n}\\int_0^L dx \\, T(x,0)\\, X_n(x)\n \\\\[5pt]\n &=\n T_0 \\, \\frac{sin k_n L}{k_n} + \\frac{(T_1 - T)}{L k_n^2}\n \\Big[ -1 + \\cos k_n L + k_n L \\, \\sin k_n L \\Big]\n \\ .\n\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import fsolve\n\nfrom ...base import ExactSolver, ExactSolution, Jump, JumpCondition\n\n\nclass Rod1D(ExactSolver):\n\n r\"\"\"Computes the solution to the 1D heat conduction problem om rod for boundary\n conditions given by linear combinations of Neumann and Dirichlet.\n\n The four boundary condition types BC1, BC2, BC3, BC4 have been implements for\n homogeneous and nonhomogeneous cases. BC1 is equivalent to the planar sandwich,\n and BC2 to the hot planar sandwich. Note that BC3 and BC4 are physically equivalent\n correspond to the same physical system, which one might call the planar half sandwich,\n with constant temperature at one end, and constant heat flux at the other. This is\n a new test problem, not mentioned by Dawes et al. The general case for rod1D might\n be called PlanarSandwichTheWorks.\n\n \"\"\"\n\n parameters = {\n 'Nsum': \"Number of terms to include in the sum.\",\n 'kappa': \"Thermal diffusivity\",\n 'TL': \"Value of IC profile for the left end of the rod at x=0\",\n 'TR': \"Value of IC profile for the right end of the rod at x=L\",\n 'L': \"Length of the rod\",\n 'alpha1': \"BC parameter for temperature at x=0\",\n 'beta1': \"BC parameter for flux at x=0\",\n 'gamma1': \"nonhomogeneous BC parameter at x=0\",\n 'alpha2': \"BC parameter for temperature at x=L\",\n 'beta2': \"BC parameter for flux at x=L\",\n 'gamma2': \"nonhomogeneous BC parameter for x=L\",\n }\n\n kappa = 1.0\n TL = 3.0\n TR = 3.0\n L = 2.0\n Nsum = 100\n alpha1 = 1.0\n beta1 = 0.0\n gamma1 = 0.0\n alpha2 = 1.0\n beta2 = 0.0\n gamma2 = 0.0\n\n def modes_BC1(self):\n r\"\"\"Computes coefficients :math:`A_n` and :math:`B_n` and the modes :math:`k_n`\n for the first boundary condition special case:\n\n :math:`\\alpha_1 \\ne 0` , :math:`\\beta_1 = 0` , :math:`\\alpha_2 \\ne 0` , and :math:`\\beta_2 = 0`\n \"\"\"\n\n T1 = self.gamma1 / self.alpha1\n T2 = self.gamma2 / self.alpha2\n Ta = self.TL - T1\n Tb = self.TR - T2\n for n in range(self.Nsum):\n self.kn[n] = n * np.pi / self.L\n if n != 0:\n self.Bn[n] = 2 * Ta * (1 - (-1)**n) / float(n * np.pi) # constant\n self.Bn[n] = self.Bn[n] + 2 * (Ta - Tb) * (-1)**n / (n * np.pi) # linear\n\n def modes_BC2(self):\n r\"\"\"Computes coefficients :math:`A_n` and :math:`B_n` and the modes :math:`k_n`\n for the second boundary condition special case:\n\n :math:`\\alpha_1 = 0` , :math:`\\beta_1 \\ne 0` , :math:`\\alpha_2 = 0` , and :math:`\\beta_2 \\ne 0`\n \"\"\"\n\n F1 = self.gamma1 / self.beta1\n Ta = self.TL\n Tb = self.TR - F1 * self.L\n for n in range(self.Nsum):\n self.kn[n] = n * np.pi / self.L\n if n == 0:\n self.An[n] = float(Ta + Tb) / 2\n else:\n self.An[n] = 2 * (Ta - Tb) * (1 - (-1)**n) / (n * np.pi)**2\n\n def modes_BC3(self):\n r\"\"\"Computes coefficients :math:`A_n` and :math:`B_n` and the modes :math:`k_n`\n for the third boundary condition special case:\n\n :math:`\\alpha_1 \\ne 0` , :math:`\\beta_1 = 0` , :math:`\\alpha_2 = 0` , and :math:`\\beta_2 \\ne 0`\n \"\"\"\n\n T1 = self.gamma1 / self.alpha1\n F2 = self.gamma2 / self.beta2\n Ta = self.TL - T1\n Tb = self.TR - (T1 + F2 * self.L)\n for n in range(self.Nsum):\n self.kn[n] = (2 * n + 1) * np.pi / (2 * self.L)\n self.Bn[n] = 4 * Ta / ((2 * n + 1) * np.pi) # constant\n self.Bn[n] = self.Bn[n] + 8 * (Tb - Ta) * (-1)**n / ((2 * n + 1) * np.pi)**2 # linear\n\n def modes_BC4(self):\n r\"\"\"Computes coefficients :math:`A_n` and :math:`B_n` and the modes :math:`k_n`\n for the fourth boundary condition special case:\n\n :math:`\\alpha_1 = 0` , :math:`\\beta_1 \\ne 0` , :math:`\\alpha_2 \\ne 0` , and :math:`\\beta_2 = 0`\n \"\"\"\n\n F1 = self.gamma1 / self.beta1\n T2 = self.gamma2 / self.alpha2\n Ta = self.TL - (T2 - F1 * self.L)\n Tb = self.TR - T2\n for n in range(self.Nsum):\n self.kn[n] = (2 * n + 1) * np.pi / (2 * self.L)\n self.An[n] = 4 * Ta * (-1)**n / ((2 * n + 1) * np.pi) # constant\n self.An[n] = self.An[n] - 8 * (Tb - Ta) / ((2 * n + 1) * np.pi)**2 + \\\n 4 * (Tb - Ta) * (-1)**n / ((2 * n + 1) * np.pi) # linear\n\n # otherwise\n def modes_BCgen(self):\n r\"\"\"Computes coefficients :math:`A_n` and :math:`B_n` and the modes :math:`k_n`\n for the general boundary condition:\n\n :math:`\\alpha_1 \\ne 0` , :math:`\\beta_1 \\ne 0` , :math:`\\alpha_2 \\ne 0` , and :math:`\\beta_2 \\ne 0`\n \"\"\"\n a1 = float(self.alpha1)\n b1 = float(self.beta1) / self.L\n a2 = float(self.alpha2)\n b2 = float(self.beta2) / self.L\n if (a1 != 0.0):\n func = lambda mu: np.tan(mu) - (a2 * b1 - a1 * b2) * mu / (a1 * a2 + b1 * b2 * mu**2)\n for n in range(self.Nsum):\n if n != 0:\n muinit = n * np.pi # initial guess for wave number\n mu = fsolve(func, muinit)[0]\n self.kn[n] = mu / self.L # wave number\n Nn = (-2 * a1 * b1 * mu + 2 * (b1**2 * mu**2 + a1**2) * mu +\n 2 * a1 * b1 * mu * np.cos(2 * mu) + (b1**2 * mu**2 - a1**2) *\n np.sin(2 * mu)) / (4 * a1**2 * self.kn[n]) # normalization\n tmp = self.TL * (1 - np.cos(mu)) / self.kn[n] - (b1 * self.L / a1) * np.sin(mu) # const\n tmp = tmp + ((self.TR - self.TL) / (self.L * a1 * self.kn[n]**2)) * \\\n (b1 * mu - (a1*mu + b1 * mu) * np.cos(mu) + (a1 - b1**2 * mu**2) * np.sin(mu))\n self.Bn[n] = tmp / Nn\n self.An[n] = -(b1 * mu / a1) * self.Bn[n]\n else:\n a = a2 / b2 # b2 =/= 0, as a1 = 0 and b2 = 0 is case B4 above\n func = lambda mu: np.tan(mu) - a / mu\n for n in range(self.Nsum):\n if (n == 0):\n muinit = 0.1\n muasym = 0\n else:\n muinit = n * np.pi\n muasym = n * np.pi + a / ((1 + a) * n * np.pi) # mu_n for n >> 1\n mu = fsolve(func, muinit)[0]\n self.kn[n] = mu / self.L # wave number\n Nn = (2 * mu + np.sin(2 * mu)) / (4 * self.kn[n])\n tmp = self.TL * np.sin(mu) / self.kn[n]\n tmp = tmp + ((self.TR - self.TL) / (self.L * self.kn[n]**2)) * \\\n (-1 + np.cos(mu) + mu * np.sin(mu))\n self.An[n] = tmp / Nn\n\n def __init__(self, **kwargs):\n super(Rod1D, self).__init__(**kwargs)\n\n self.kn = np.zeros(shape=self.Nsum)\n self.An = np.zeros(shape=self.Nsum)\n self.Bn = np.zeros(shape=self.Nsum)\n\n if self.alpha1 != 0 and self.beta1 == 0 and self.alpha2 != 0 and self.beta2 == 0:\n self.modes_BC1()\n elif self.alpha1 == 0 and self.beta1 != 0 and self.alpha2 == 0 and self.beta2 != 0:\n self.modes_BC2()\n elif self.alpha1 != 0 and self.beta1 == 0 and self.alpha2 == 0 and self.beta2 != 0:\n self.modes_BC3()\n elif self.alpha1 == 0 and self.beta1 != 0 and self.alpha2 != 0 and self.beta2 == 0:\n self.modes_BC4()\n else:\n self.modes_BCgen()\n\n def _run(self, x, t):\n temperature = np.zeros(shape=x.shape)\n tempnonhom = np.zeros(shape=x.shape)\n\n if self.alpha1 != 0 and self.beta1 == 0 and self.alpha2 != 0 and self.beta2 == 0:\n # BC1\n N = self.Nsum\n T1 = self.gamma1 / self.alpha1\n T2 = self.gamma2 / self.alpha2\n tempnonhom = T1 + (T2 - T1) * x / self.L\n elif self.alpha1 == 0 and self.beta1 != 0 and self.alpha2 == 0 and self.beta2 != 0:\n # BC2\n N = self.Nsum\n F1 = self.gamma1 / self.beta1\n F2 = self.gamma2 / self.beta2\n if F1 != F2:\n raise ValueError(\"The flux at either end of rod must be equal\")\n tempnonhom = F1 * x\n elif self.alpha1 != 0 and self.beta1 == 0 and self.alpha2 == 0 and self.beta2 != 0:\n # BC3\n N = self.Nsum\n T1 = self.gamma1 / self.alpha1\n F2 = self.gamma2 / self.beta2\n tempnonhom = T1 + F2 * x # = Ta + (Tb - Ta) * x / L\n elif self.alpha1 == 0 and self.beta1 != 0 and self.alpha2 != 0 and self.beta2 == 0:\n # BC4\n N = self.Nsum\n F1 = self.gamma1 / self.beta1\n T2 = self.gamma2 / self.alpha2\n tempnonhom = (T2 - self.L * F1) + F1 * x # = Ta + (Tb - Ta) * x / L\n else:\n N = self.Nsum\n a1 = float(self.alpha1)\n b1 = float(self.beta1) / self.L\n a2 = float(self.alpha2)\n b2 = float(self.beta2) / self.L\n c1 = float(self.gamma1)\n c2 = float(self.gamma2)\n T1 = (b2 * c1 - b1 * c2 + self.L * a2 * c1) / (a1 * b2 - a2 * b1 + self.L * a1 * a2)\n T2 = (b2 * c1 - b1 * c2 + self.L * a1 * c2) / (a1 * b2 - a2 * b1 + self.L * a1 * a2)\n tempnonhom = T1 + (T2 - T1) * x / self.L\n\n # construct time dependent solution\n for n in range(self.Nsum):\n temperature += (self.An[n] * np.cos(self.kn[n] * x) + self.Bn[n] * np.sin(self.kn[n] * x)) * \\\n np.exp(-self.kappa * self.kn[n]**2 * t)\n\n # add homogeneous and nonhomogeneous\n temperature = temperature + tempnonhom\n\n return ExactSolution([x, temperature],\n names=['position',\n 'temperature',\n ])\n","sub_path":"exactpack/solvers/heat/rod1d.py","file_name":"rod1d.py","file_ext":"py","file_size_in_byte":17379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"205299721","text":"# -*- coding:utf-8 -*-\n\n## =====================================================================\n## Copyright (C) 2007-2011 Jean-Philippe GOLAY\n##\n## This program is free software; you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation; either version 2 of the License, or\n## (at your option) any later version.\n##\n## This program is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n## GNU General Public License for more details.\n##\n## You should have received a copy of the GNU General Public License\n## along with this program; if not, write to the Free Software\n## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n## =====================================================================\n\n\nfrom Tkinter import *\nimport Pmw\nimport time\nfrom tkMessageBox import *\n\nfrom Persistance import *\nfrom iCalendar import CalendarGUI\nfrom iNotes import NotesGUI\nfrom iStaff import StaffListGUI\nfrom iProduct import ProductListGUI\nfrom iTime import TimePopupGUI\n\n\nclass TechnicalGUI(Toplevel):\n\tdef __init__(self, parent=None, balloon=None, path=None, log=None):\n\t\tToplevel.__init__(self, parent)\n\t\tself.parent=parent\n\t\tself.grab_set()\n\t\tself.transient(self.master)\n\t\tself.resizable(width=False, height=False)\n\t\tself.title(u\"Planning Technique de la résidence\")\n\t\tself.balloon=balloon\n\t\tself.imgSearch=PhotoImage(file=\"img/search_icon.gif\")\n\t\tself.imgNotes=PhotoImage(file=\"img/edit.gif\")\n\t\tself.imgSave=PhotoImage(file=\"img/save_icon.gif\")\n\t\tself.imgDelete=PhotoImage(file=\"img/delete_icon.gif\")\n\t\tself.imgCalendar=PhotoImage(file=\"img/calendar.gif\")\n\t\tself.imgTime=PhotoImage(file=\"img/time_icon.gif\")\n\t\tself.hoursListCB = Glob.HOURS_LIST\n\t\tself.minutesListCB = Glob.MINUTES_LIST\r\n\t\tself.path=path\r\n\t\tself.log=log\r\n\t\t# Afficher un icon personnalisé\r\n\t\ttry:\r\n\t\t\tif os.name ==\"posix\":\r\n\t\t\t\timg = PhotoImage(file=self.path+\"/icons/Technical-icon.gif\")\r\n\t\t\t\tself.tk.call(\"wm\", \"iconphoto\", self._w, img)\r\n\t\t\telse:\r\n\t\t\t\tself.iconbitmap(default=self.path+\"/icons/Technical-icon.gif\")\r\n\t\texcept TclError:\r\n\t\t\tself.log.warning(\"Le window manager ne supporte pas l'icône que je veux lui mettre...\")\r\n\t\tself.log.info(\"\\tTechnicalGUI\\tStart\")\n\t\tself.makeTechnical()\n\n\t# DEBUT de la gestion du module Technical ------------------------------------------------------------------------------------------------------\r\n\tdef clearFieldTechnical(self):\n\t\t# Mise a zéro des champs\r\n\t\tself.technicalValues[0].set(\"\")\r\n\t\tself.technicalValues[1].set(\"\")\r\n\t\tself.technicalValues[2].set(u\"EA\")\r\n\t\tself.technicalValues[3].set(\"\")\r\n\t\tself.technicalValues[4].set(time.strftime(\"%d/%m/%Y\" ,time.localtime()))\r\n\t\tself.technicalValues[5].set(\"\")\r\n\t\tself.technicalValues[6].set(\"\")\r\n\t\tself.technicalValues[7].set(\"\")\r\n\t\tself.technicalValues[8].set(\"\")\r\n\t\tself.technicalValues[9].set(\"\")\r\n\t\tself.technicalValues[10].set(\"\")\r\n\t\tself.technicalValues[11].set(\"\")\r\n\t\tself.technicalValues[12].set(\"\")\r\n\t\t# Remise à zéro des ComboBox\r\n\t\tself.technicalStatusCB.selectitem(0)\r\n\t\tself.hourRequestTechnicalCB.selectitem(0)\r\n\t\tself.minRequestTechnicalCB.selectitem(0)\r\n\t\tself.hourFinishTechnicalCB.selectitem(0)\r\n\t\tself.minFinishTechnicalCB.selectitem(0)\r\n\t\tself.hourCheckedTechnicalCB.selectitem(0)\r\n\t\tself.minCheckedTechnicalCB.selectitem(0)\r\n\t\tself.technicalHourRequest=StringVar()\r\n\t\tself.technicalMinuteRequest=StringVar()\r\n\t\tself.technicalHourFinish=StringVar()\r\n\t\tself.technicalMinuteFinish=StringVar()\r\n\t\tself.technicalHourChecked=StringVar()\r\n\t\tself.technicalMinuteChecked=StringVar()\r\n\t\tself.listObject=[Product, Stay, Stay, Stay]\r\n\t\thour = time.strftime(\"%H\" ,time.localtime())\r\n\t\tminute = time.strftime(\"%M\" ,time.localtime())\r\n\t\t# Affichage de l'heure dans la ComboBox \r\n\t\tcount = 0\r\n\t\tfor h in self.hoursListCB:\r\n\t\t\tif h == hour: self.hourRequestTechnicalCB.selectitem(count)\r\n\t\t\tcount+=1\r\n\t\t# Affichage des minutes dans la ComboBox\r\n\t\tcount = 0\r\n\t\tfor m in self.minutesListCB:\r\n\t\t\tif m == minute: self.minRequestTechnicalCB.selectitem(count)\r\n\t\t\tcount+=1\r\n\t\t# Mise à jour des variables heure et minutes\r\n\t\tself.technicalHourRequest.set(hour)\r\n\t\tself.technicalMinuteRequest.set(minute)\r\n\r\n\tdef selectTechnical(self, event):\r\n\t\tself.clearFieldTechnical()\r\n\t\tif self.listTechnical.get(0)!=\"\":\r\n\t\t\tresult = Technical.select(Technical.q.id==self.idListTechnical[int(self.listTechnical.curselection()[0])])\r\n\t\t\tfor row in result:\r\n\t\t\t\tself.selectedTechnical = row\r\n\t\t\tself.listObject[0]=self.selectedTechnical.product\r\n\t\t\tself.listObject[1]=self.selectedTechnical.requestByTech\r\n\t\t\tself.listObject[2]=self.selectedTechnical.answerBy\r\n\t\t\tself.listObject[3]=self.selectedTechnical.solvingBy\r\n\t\t\tif self.selectedTechnical.product != None:self.technicalValues[0].set(self.listObject[0].number+\" - \"+self.listObject[0].designation)\r\n\t\t\tif self.selectedTechnical.requestByTech != None:self.technicalValues[3].set(self.listObject[1].fname+\" - \"+self.listObject[1].lname)\r\n\t\t\tif self.selectedTechnical.answerBy != None:self.technicalValues[6].set(self.listObject[2].fname+\" - \"+self.listObject[2].lname)\r\n\t\t\tif self.selectedTechnical.solvingBy != None:self.technicalValues[9].set(self.listObject[3].fname+\" - \"+self.listObject[3].lname)\r\n\t\t\tif self.selectedTechnical.notes != None:self.technicalValues[12].set(self.selectedTechnical.notes)\r\n\t\t\tif self.selectedTechnical.designation != None:self.technicalValues[1].set(self.selectedTechnical.designation)\r\n\t\t\tif self.selectedTechnical.status != None:self.technicalValues[2].set(self.selectedTechnical.status)\r\n\t\t\t# Affichage du status dans la ComboBox\r\n\t\t\tstatus = ((u\"EA\", 0),(u\"TR\", 1),(u\"EC\", 2),(u\"AV\", 3),(u\"VU\", 4),(u\"LI\", 5),)\r\n\t\t\tfor n in status:\r\n\t\t\t\tif n[0] == self.selectedTechnical.status: self.technicalStatusCB.selectitem(n[1])\r\n\t\t\tif self.selectedTechnical.request != None:\r\n\t\t\t\t# Affichage de la date de Demande\r\n\t\t\t\tself.technicalValues[4].set(self.selectedTechnical.request.strftime(\"%d/%m/%Y\"))\r\n\t\t\t\t# Affichage de l'heure dans la ComboBox \r\n\t\t\t\tcount = 0\r\n\t\t\t\tfor h in self.hoursListCB:\r\n\t\t\t\t\tif h == self.selectedTechnical.request.strftime(\"%H\"): self.hourRequestTechnicalCB.selectitem(count)\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\t# Affichage des minutes dans la ComboBox\r\n\t\t\t\tcount = 0\r\n\t\t\t\tfor m in self.minutesListCB:\r\n\t\t\t\t\tif m == self.selectedTechnical.request.strftime(\"%M\"): self.minRequestTechnicalCB.selectitem(count)\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\t# Mise à jour des variables heure et minutes\r\n\t\t\t\tself.technicalHourRequest.set(self.selectedTechnical.request.strftime(\"%H\"))\r\n\t\t\t\tself.technicalMinuteRequest.set(self.selectedTechnical.request.strftime(\"%M\"))\r\n\t\t\tif self.selectedTechnical.answer != None:\r\n\t\t\t\t# Affichage de la date de Effectué\r\n\t\t\t\tself.technicalValues[7].set(self.selectedTechnical.answer.strftime(\"%d/%m/%Y\"))\r\n\t\t\t\t# Affichage de l'heure dans la ComboBox \r\n\t\t\t\tcount = 0\r\n\t\t\t\tfor h in self.hoursListCB:\r\n\t\t\t\t\tif h == self.selectedTechnical.answer.strftime(\"%H\"): self.hourFinishTechnicalCB.selectitem(count)\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\t# Affichage des minutes dans la ComboBox\r\n\t\t\t\tcount = 0\r\n\t\t\t\tfor m in self.minutesListCB:\r\n\t\t\t\t\tif m == self.selectedTechnical.answer.strftime(\"%M\"): self.minFinishTechnicalCB.selectitem(count)\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\t# Mise à jour des variables heure et minutes\r\n\t\t\t\tself.technicalHourFinish.set(self.selectedTechnical.answer.strftime(\"%H\"))\r\n\t\t\t\tself.technicalMinuteFinish.set(self.selectedTechnical.answer.strftime(\"%M\"))\r\n\t\t\tif self.selectedTechnical.solving != None:\r\n\t\t\t\t# Affichage de la date de Verifié\r\n\t\t\t\tself.technicalValues[10].set(self.selectedTechnical.solving.strftime(\"%d/%m/%Y\"))\r\n\t\t\t\t# Affichage de l'heure dans la ComboBox \r\n\t\t\t\tcount = 0\r\n\t\t\t\tfor h in self.hoursListCB:\r\n\t\t\t\t\tif h == self.selectedTechnical.solving.strftime(\"%H\"): self.hourCheckedTechnicalCB.selectitem(count)\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\t# Affichage des minutes dans la ComboBox\r\n\t\t\t\tcount = 0\r\n\t\t\t\tfor m in self.minutesListCB:\r\n\t\t\t\t\tif m == self.selectedTechnical.solving.strftime(\"%M\"): self.minCheckedTechnicalCB.selectitem(count)\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\t# Mise à jour des variables heure et minutes\r\n\t\t\t\tself.technicalHourChecked.set(self.selectedTechnical.solving.strftime(\"%H\"))\r\n\t\t\t\tself.technicalMinuteChecked.set(self.selectedTechnical.solving.strftime(\"%M\"))\r\n\t\t\t# activation du bouton supprimer\r\n\t\t\tself.deleteTechnicalBt.config(state=NORMAL)\r\n\n\tdef setTechnical(self, e):\n\t\t\tresult = Technical.select(Technical.q.id==int(e.technicalID))\n\t\t\tfor row in result:\n\t\t\t\tself.selectedTechnical = row\n\t\t\tself.listObject[0]=self.selectedTechnical.product\n\t\t\tself.listObject[1]=self.selectedTechnical.requestByTech\n\t\t\tself.listObject[2]=self.selectedTechnical.answerBy\n\t\t\tself.listObject[3]=self.selectedTechnical.solvingBy\n\t\t\tif self.selectedTechnical.product != None:self.technicalValues[0].set(self.listObject[0].number+\" - \"+self.listObject[0].designation)\n\t\t\tif self.selectedTechnical.requestByTech != None:self.technicalValues[3].set(self.listObject[1].fname+\" - \"+self.listObject[1].lname)\n\t\t\tif self.selectedTechnical.answerBy != None:self.technicalValues[6].set(self.listObject[2].fname+\" - \"+self.listObject[2].lname)\n\t\t\tif self.selectedTechnical.solvingBy != None:self.technicalValues[9].set(self.listObject[3].fname+\" - \"+self.listObject[3].lname)\n\t\t\tif self.selectedTechnical.notes != None:self.technicalValues[12].set(self.selectedTechnical.notes)\n\t\t\tif self.selectedTechnical.designation != None:self.technicalValues[1].set(self.selectedTechnical.designation)\n\t\t\tif self.selectedTechnical.status != None:self.technicalValues[2].set(self.selectedTechnical.status)\n\t\t\t# Affichage du status dans la ComboBox\n\t\t\tstatus = ((u\"EA\", 0),(u\"TR\", 1),(u\"EC\", 2),(u\"AV\", 3),(u\"VU\", 4),(u\"LI\", 5),)\n\t\t\tfor n in status:\n\t\t\t\tif n[0] == self.selectedTechnical.status: self.technicalStatusCB.selectitem(n[1])\n\t\t\tif self.selectedTechnical.request != None:\n\t\t\t\t# Affichage de la date de Demande\n\t\t\t\tself.technicalValues[4].set(self.selectedTechnical.request.strftime(\"%d/%m/%Y\"))\n\t\t\t\t# Affichage de l'heure dans la ComboBox \n\t\t\t\tcount = 0\n\t\t\t\tfor h in self.hoursListCB:\n\t\t\t\t\tif h == self.selectedTechnical.request.strftime(\"%H\"): self.hourRequestTechnicalCB.selectitem(count)\n\t\t\t\t\tcount+=1\n\t\t\t\t# Affichage des minutes dans la ComboBox\n\t\t\t\tcount = 0\n\t\t\t\tfor m in self.minutesListCB:\n\t\t\t\t\tif m == self.selectedTechnical.request.strftime(\"%M\"): self.minRequestTechnicalCB.selectitem(count)\n\t\t\t\t\tcount+=1\n\t\t\t\t# Mise à jour des variables heure et minutes\n\t\t\t\tself.technicalHourRequest.set(self.selectedTechnical.request.strftime(\"%H\"))\n\t\t\t\tself.technicalMinuteRequest.set(self.selectedTechnical.request.strftime(\"%M\"))\n\t\t\tif self.selectedTechnical.answer != None:\n\t\t\t\t# Affichage de la date de Effectué\n\t\t\t\tself.technicalValues[7].set(self.selectedTechnical.answer.strftime(\"%d/%m/%Y\"))\n\t\t\t\t# Affichage de l'heure dans la ComboBox \n\t\t\t\tcount = 0\n\t\t\t\tfor h in self.hoursListCB:\n\t\t\t\t\tif h == self.selectedTechnical.answer.strftime(\"%H\"): self.hourFinishTechnicalCB.selectitem(count)\n\t\t\t\t\tcount+=1\n\t\t\t\t# Affichage des minutes dans la ComboBox\n\t\t\t\tcount = 0\n\t\t\t\tfor m in self.minutesListCB:\n\t\t\t\t\tif m == self.selectedTechnical.answer.strftime(\"%M\"): self.minFinishTechnicalCB.selectitem(count)\n\t\t\t\t\tcount+=1\n\t\t\t\t# Mise à jour des variables heure et minutes\n\t\t\t\tself.technicalHourFinish.set(self.selectedTechnical.answer.strftime(\"%H\"))\n\t\t\t\tself.technicalMinuteFinish.set(self.selectedTechnical.answer.strftime(\"%M\"))\n\t\t\tif self.selectedTechnical.solving != None:\n\t\t\t\t# Affichage de la date de Verifié\n\t\t\t\tself.technicalValues[10].set(self.selectedTechnical.solving.strftime(\"%d/%m/%Y\"))\n\t\t\t\t# Affichage de l'heure dans la ComboBox \n\t\t\t\tcount = 0\n\t\t\t\tfor h in self.hoursListCB:\n\t\t\t\t\tif h == self.selectedTechnical.solving.strftime(\"%H\"): self.hourCheckedTechnicalCB.selectitem(count)\n\t\t\t\t\tcount+=1\n\t\t\t\t# Affichage des minutes dans la ComboBox\n\t\t\t\tcount = 0\n\t\t\t\tfor m in self.minutesListCB:\n\t\t\t\t\tif m == self.selectedTechnical.solving.strftime(\"%M\"): self.minCheckedTechnicalCB.selectitem(count)\n\t\t\t\t\tcount+=1\n\t\t\t\t# Mise à jour des variables heure et minutes\n\t\t\t\tself.technicalHourChecked.set(self.selectedTechnical.solving.strftime(\"%H\"))\n\t\t\t\tself.technicalMinuteChecked.set(self.selectedTechnical.solving.strftime(\"%M\"))\n\t\t\t# activation du bouton supprimer\n\t\t\tself.deleteTechnicalBt.config(state=NORMAL)\n\n\tdef setDateTime(self, e):\n\t\tself.technicalValues[4].set(e.date)\n\t\tresult=Product.select(Product.q.id==int(e.productID))\r\n\t\tfor row in result:\r\n\t\t\tself.listObject[0]=row\r\n\t\t\tself.technicalValues[0].set(self.listObject[0].number+\" - \"+self.listObject[0].designation)\n\r\n\tdef searchTechnical(self, event=None):\r\n\t\tif self.searchTechnicalValue.get() != \"\":\r\n\t\t\tself.listTechnical.delete(0,END)\r\n\t\t\tself.idListTechnical = []\r\n\t\t\tresult = Technical.select(Technical.q.designation.startswith(self.searchTechnicalValue.get().encode(\"utf-8\")), orderBy=Technical.q.request)\r\n\t\t\tfor row in result:\r\n\t\t\t\tself.listTechnical.insert(END, str(row.id)+\" - \"+row.product.place.company+\" - \"+row.product.number+\" - \"+row.product.designation+\" - \"+row.designation+\" - Demande : \"+row.request.strftime(\"%d/%m/%Y %H:%M\")+\" Etat : \"+row.status)\r\n\t\t\t\tself.idListTechnical.append(row.id)\r\n\t\telse:\r\n\t\t\tself.listTechnical.delete(0,END)\r\n\t\t\tself.idListTechnical = []\r\n\t\t\tresult = Technical.select(orderBy=Technical.q.request)\r\n\t\t\tfor row in result:\r\n\t\t\t\tself.listTechnical.insert(END, str(row.id)+\" - \"+row.product.place.company+\" - \"+row.product.number+\" - \"+row.product.designation+\" - \"+row.designation+\" - Demande : \"+row.request.strftime(\"%d/%m/%Y %H:%M\")+\" Etat : \"+row.status)\r\n\t\t\t\tself.idListTechnical.append(row.id)\n\r\n\tdef makeTechnical(self):\r\n\t\tleftFrame = Frame(self)\r\n\t\t# Fiche Ménage (présentation colonne de gauche)\r\n\t\tLabel(leftFrame, text=u\"Intervention Technique\").pack(side=TOP, fill=X)\r\n\t\t# Création des champs a renseigner pour un object Technical\r\n\t\ttechnicalStatusListCB = (u\"En attente\", u\"Transmis\", u\"En cours\", u\"A vérifié\", u\"Verifié ok\", u\"Litige\") \r\n\t\ttechnicalLabels = (u\"Produit\", u\"Tâche\", u\"Avancement\", u\"Demandé par\", u\"Date\", u\"Heure\", u\"Pris en charge par\", u\"Date\", u\"Heure\", u\"Résolu par\", u\"Date\", u\"Heure\",u\"Notes\")\r\n\t\tself.technicalValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]\r\n\t\tcount = 0\r\n\t\tfor name in technicalLabels:\r\n\t\t\tf = Frame(leftFrame)\r\n\t\t\tLabel(f, width=16, text=name, anchor=W).pack(side=LEFT)\r\n\t\t\tif count == 0: # Produit (product)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21, state=DISABLED, bd=0, disabledforeground=\"black\").pack(side=LEFT, fill=X)\r\n\t\t\t\tmyProduct=Button(f, image=self.imgSearch, command=lambda x=self.technicalValues[count]:self.ctrlListProduct(x), padx=4, pady=1)\r\n\t\t\t\tmyProduct.pack(side=RIGHT)\r\n\t\t\t\tself.balloon.bind(myProduct, u\"Séléctionner un Produit\")\r\n\t\t\telif count == 2: # Avancement (status - CB)\r\n\t\t\t\tself.technicalStatusCB=Pmw.ComboBox(f, selectioncommand=self.technicalStatus, scrolledlist_items=technicalStatusListCB, listheight=140)\r\n\t\t\t\tself.technicalStatusCB._entryfield._entryFieldEntry.config( width=21)\r\n\t\t\t\tself.technicalStatusCB.pack(side=LEFT, fill=X)\r\n\t\t\t\tself.technicalStatusCB.selectitem(0)\r\n\t\t\t\tself.technicalValues[count].set(u\"EA\")\r\n\t\t\telif count == 3: # Demandé par (Staff - requestByClean)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21, state=DISABLED, bd=0, disabledforeground=\"black\").pack(side=LEFT, fill=X)\r\n\t\t\t\tmyRequestBy=Button(f, image=self.imgSearch, command=lambda x=self.technicalValues[count]:self.ctrlListStaff(x,1), padx=4, pady=1)\r\n\t\t\t\tmyRequestBy.pack(side=RIGHT)\r\n\t\t\t\tself.balloon.bind(myRequestBy, u\"Séléctionner un employé\")\r\n\t\t\telif count == 4: # Demande date (request)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21).pack(side=LEFT, fill=X)\r\n\t\t\t\tmyCal1=Button(f, image=self.imgCalendar, command=lambda x=self.technicalValues[count]:self.ctrlCalendar(x), padx=4, pady=1)\r\n\t\t\t\tmyCal1.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(myCal1, u\"Calendrier\")\r\n\t\t\telif count == 5: # Demande hour (request)\r\n\t\t\t\thStartLb1=Label(f, width=2, text=\"H\", anchor=W)\r\n\t\t\t\thStartLb1.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(hStartLb1, u\"Heure\")\r\n\t\t\t\tself.hourRequestTechnicalCB=Pmw.ComboBox(f, selectioncommand=self.technicalHourRequest, scrolledlist_items=self.hoursListCB, listheight=100)\r\n\t\t\t\tself.hourRequestTechnicalCB._entryfield._entryFieldEntry.config( width = 3)\r\n\t\t\t\tself.hourRequestTechnicalCB.pack(side=LEFT)\r\n\t\t\t\tmStartLb1=Label(f, width=3, text=\"mn\", anchor=W)\r\n\t\t\t\tmStartLb1.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(mStartLb1, u\"minutes\")\r\n\t\t\t\tself.minRequestTechnicalCB=Pmw.ComboBox(f, selectioncommand=self.technicalMinuteRequest, scrolledlist_items=self.minutesListCB, listheight=100)\r\n\t\t\t\tself.minRequestTechnicalCB._entryfield._entryFieldEntry.config( width = 3)\r\n\t\t\t\tself.minRequestTechnicalCB.pack(side=LEFT)\r\n\t\t\t\t# Menu Time\r\n\t\t\t\tmyTime1=Button(f, image=self.imgTime, padx=1, pady=1)\r\n\t\t\t\tmyTime1.pack(side=RIGHT)\r\n\t\t\t\tmyTime1.bind(\"\",self.ctrlTimeNow1)\r\n\t\t\t\tself.balloon.bind(myTime1, u\"Séléctionner une heure\")\r\n\t\t\telif count == 6: # Effectué par (Staff - answerBy)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21, state=DISABLED, bd=0, disabledforeground=\"black\").pack(side=LEFT, fill=X)\r\n\t\t\t\tmyFinishBy=Button(f, image=self.imgSearch, command=lambda x=self.technicalValues[count]:self.ctrlListStaff(x,2), padx=4, pady=1)\r\n\t\t\t\tmyFinishBy.pack(side=RIGHT)\r\n\t\t\t\tself.balloon.bind(myFinishBy, u\"Séléctionner un employé\")\r\n\t\t\telif count == 7: # Effectué date (answer)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21).pack(side=LEFT, fill=X)\r\n\t\t\t\tmyCal2=Button(f, image=self.imgCalendar, command=lambda x=self.technicalValues[count]:self.ctrlCalendar(x), padx=4, pady=1)\r\n\t\t\t\tmyCal2.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(myCal2, u\"Calendrier\")\r\n\t\t\telif count == 8: # Effectué hour (answer)\r\n\t\t\t\thStartLb2=Label(f, width=2, text=\"H\", anchor=W)\r\n\t\t\t\thStartLb2.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(hStartLb2, u\"Heure\")\r\n\t\t\t\tself.hourFinishTechnicalCB=Pmw.ComboBox(f, selectioncommand=self.technicalHourFinish, scrolledlist_items=self.hoursListCB, listheight=100)\r\n\t\t\t\tself.hourFinishTechnicalCB._entryfield._entryFieldEntry.config( width = 3)\r\n\t\t\t\tself.hourFinishTechnicalCB.pack(side=LEFT)\r\n\t\t\t\tmStartLb2=Label(f, width=3, text=\"mn\", anchor=W)\r\n\t\t\t\tmStartLb2.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(mStartLb2, u\"minutes\")\r\n\t\t\t\tself.minFinishTechnicalCB=Pmw.ComboBox(f, selectioncommand=self.technicalMinuteFinish, scrolledlist_items=self.minutesListCB, listheight=100)\r\n\t\t\t\tself.minFinishTechnicalCB._entryfield._entryFieldEntry.config( width = 3)\r\n\t\t\t\tself.minFinishTechnicalCB.pack(side=LEFT)\r\n\t\t\t\t# Menu Time\r\n\t\t\t\tmyTime2=Button(f, image=self.imgTime, padx=1, pady=1)\r\n\t\t\t\tmyTime2.pack(side=RIGHT)\r\n\t\t\t\tmyTime2.bind(\"\",self.ctrlTimeNow2)\r\n\t\t\t\tself.balloon.bind(myTime2, u\"Séléctionner une heure\")\r\n\t\t\telif count == 9: # Vérifié par (Staff - solvingBy)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21, state=DISABLED, bd=0, disabledforeground=\"black\").pack(side=LEFT, fill=X)\r\n\t\t\t\tmyCheckBy=Button(f, image=self.imgSearch, command=lambda x=self.technicalValues[count]:self.ctrlListStaff(x,3), padx=4, pady=1)\r\n\t\t\t\tmyCheckBy.pack(side=RIGHT)\r\n\t\t\t\tself.balloon.bind(myCheckBy, u\"Séléctionner un employé\")\r\n\t\t\telif count == 10: # Vérifié date (solving)\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21).pack(side=LEFT, fill=X)\r\n\t\t\t\tmyCal3=Button(f, image=self.imgCalendar, command=lambda x=self.technicalValues[count]:self.ctrlCalendar(x), padx=4, pady=1)\r\n\t\t\t\tmyCal3.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(myCal3, u\"Calendrier\")\r\n\t\t\telif count == 11: # Vérifié hour (solving)\r\n\t\t\t\thStartLb3=Label(f, width=2, text=\"H\", anchor=W)\r\n\t\t\t\thStartLb3.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(hStartLb3, u\"Heure\")\r\n\t\t\t\tself.hourCheckedTechnicalCB=Pmw.ComboBox(f, selectioncommand=self.technicalHourChecked, scrolledlist_items=self.hoursListCB, listheight=100)\r\n\t\t\t\tself.hourCheckedTechnicalCB._entryfield._entryFieldEntry.config( width = 3)\r\n\t\t\t\tself.hourCheckedTechnicalCB.pack(side=LEFT)\r\n\t\t\t\tmStartLb3=Label(f, width=3, text=\"mn\", anchor=W)\r\n\t\t\t\tmStartLb3.pack(side=LEFT)\r\n\t\t\t\tself.balloon.bind(mStartLb3, u\"minutes\")\r\n\t\t\t\tself.minCheckedTechnicalCB=Pmw.ComboBox(f, selectioncommand=self.technicalMinuteChecked, scrolledlist_items=self.minutesListCB, listheight=100)\r\n\t\t\t\tself.minCheckedTechnicalCB._entryfield._entryFieldEntry.config( width = 3)\r\n\t\t\t\tself.minCheckedTechnicalCB.pack(side=LEFT) \r\n\t\t\t\t# Menu Time\r\n\t\t\t\tmyTime3=Button(f, image=self.imgTime, padx=1, pady=1)\r\n\t\t\t\tmyTime3.pack(side=RIGHT)\r\n\t\t\t\tmyTime3.bind(\"\",self.ctrlTimeNow3)\r\n\t\t\t\tself.balloon.bind(myTime3, u\"Séléctionner une heure\")\r\n\t\t\telif count == 12: # Notes\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=21).pack(side=LEFT, fill=X)\r\n\t\t\t\tmyNotes=Button(f, image=self.imgNotes, command=lambda x=self.technicalValues[count]:self.ctrlNotes(x,u\"Notes intervention technique\"), padx=4, pady=1)\r\n\t\t\t\tmyNotes.pack(side=RIGHT)\r\n\t\t\t\tself.balloon.bind(myNotes, u\"Détails de la note\")\r\n\t\t\telse:\r\n\t\t\t\tEntry(f, textvariable=self.technicalValues[count], width=24).pack(side=LEFT, fill=X)\r\n\t\t\tf.pack(side=TOP, fill=X)\r\n\t\t\tcount += 1\r\n\t\t# Boutons enregistrement (new ou modify) et suppression\r\n\t\ts = Frame(leftFrame) \r\n\t\tself.saveTechnicalBt=Button(s, image=self.imgSave, command=self.createTechnical)\r\n\t\tself.saveTechnicalBt.bind(\"\", self.createTechnical)\r\n\t\tself.saveTechnicalBt.pack(side=LEFT)\r\n\t\tself.balloon.bind(self.saveTechnicalBt, u\"Enregistrer\")\r\n\t\tself.deleteTechnicalBt=Button(s, image=self.imgDelete, command=self.deleteTechnical, state=DISABLED)\r\n\t\tself.deleteTechnicalBt.bind(\"\", self.deleteTechnical)\r\n\t\tself.deleteTechnicalBt.pack(side=LEFT)\r\n\t\tself.balloon.bind(self.deleteTechnicalBt, u\"Supprimer\")\r\n\t\ts.pack(side=TOP, fill=X)\r\n\t\tleftFrame.pack(side=LEFT, fill=X)\r\n\t\t# Liste des Occupation existants (présentation colonne de droite)\r\n\t\trightFrame = Frame(self) \r\n\t\tLabel(rightFrame, text=u\"Liste des Interventions plannifiées\").pack(side=TOP, fill=X)\r\n\t\tself.searchTechnicalValue = StringVar()\r\n\t\tself.searchTechnicalEt = Entry(rightFrame, width=93, textvariable=self.searchTechnicalValue, relief=GROOVE)\r\n\t\tself.searchTechnicalEt.bind(\"\", self.searchTechnical)\r\n\t\tself.searchTechnicalEt.pack(side=TOP, fill=X)\r\n\t\tself.balloon.bind(self.searchTechnicalEt, u\"Saisir les premières lettres d'une Intervention\\npour une recherche plus précise,\\nla liste est classée par date de demande.\")\r\n\t\ts = Frame(rightFrame) \r\n\t\tscrollbar = Scrollbar(s)\r\n\t\tscrollbar.pack(side=RIGHT, fill=Y)\r\n\t\tself.listTechnical = Listbox(s)\r\n\t\tself.listTechnical.config(yscrollcommand=scrollbar.set, width=90, selectmode=SINGLE, height=17)\r\n\t\tself.listTechnical.bind(\"\",self.selectTechnical)\r\n\t\tscrollbar.config(command=self.listTechnical.yview)\r\n\t\tself.listTechnical.pack()\r\n\t\tself.balloon.bind(self.listTechnical, u\"S��léctionner une Intervention\\npour la visualiser ou la modifier.\")\r\n\t\ts.pack(side=TOP, fill=X)\r\n\t\trightFrame.pack(side=RIGHT, fill=BOTH)\r\n\t\t# Initialisation\r\n\t\tself.clearFieldTechnical()\r\n\t\tself.searchTechnical()\r\n\r\n\tdef ctrlTimeNow1(self,event):\r\n\t\tvarHour=[self.technicalHourRequest, self.technicalMinuteRequest, self.hourRequestTechnicalCB, self.minRequestTechnicalCB] \r\n\t\tTimePopupGUI(self, event=event, field=self.technicalValues[5], varHour=varHour, log=self.log, path=self.path)\r\n\r\n\tdef ctrlTimeNow2(self,event):\r\n\t\tvarHour=[self.technicalHourFinish, self.technicalMinuteFinish, self.hourFinishTechnicalCB, self.minFinishTechnicalCB]\r\n\t\tTimePopupGUI(self, event=event, field=self.technicalValues[8], varHour=varHour, log=self.log, path=self.path)\r\n\r\n\tdef ctrlTimeNow3(self,event):\r\n\t\tvarHour=[self.technicalHourChecked, self.technicalMinuteChecked, self.hourCheckedTechnicalCB, self.minCheckedTechnicalCB]\r\n\t\tTimePopupGUI(self, event=event, field=self.technicalValues[11], varHour=varHour, log=self.log, path=self.path)\r\n\n\tdef ctrlCalendar(self,field):\n\t\tCalendarGUI(field=field, log=self.log, path=self.path)\n\n\tdef ctrlNotes(self,field,title):\n\t\tNotesGUI(field=field,title=title, log=self.log, path=self.path)\n\n\tdef ctrlListProduct(self,field):\n\t\tProductListGUI(balloon=self.balloon, field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)\n\n\tdef ctrlListStaff(self,field,index):\n\t\tStaffListGUI(balloon=self.balloon, field=field, index=index, listObject=self.listObject, log=self.log, path=self.path)\n\r\n\tdef technicalStatus(self, value):\r\n\t\tstatus = ((u\"EA\", u\"En attente\"),(u\"TR\", u\"Transmis\"),(u\"EC\", u\"En cours\"),(u\"AV\", u\"A vérifié\"),(u\"VU\", u\"Verifié ok\"),(u\"LI\", u\"Litige\"),)\r\n\t\tfor n in status:\r\n\t\t\tif n[1] == value: self.technicalValues[2].set(n[0])\r\n\r\n\tdef technicalHourRequest(self, value):\r\n\t\tself.technicalHourRequest.set(value)\r\n\t\tself.minRequestTechnicalCB.selectitem(0)\r\n\t\tself.minRequestTechnicalCB.invoke()\r\n\r\n\tdef technicalMinuteRequest(self, value):\r\n\t\tself.technicalMinuteRequest.set(value)\r\n\r\n\tdef technicalHourFinish(self, value):\r\n\t\tself.technicalHourFinish.set(value)\r\n\t\tself.minFinishTechnicalCB.selectitem(0)\r\n\t\tself.minFinishTechnicalCB.invoke()\r\n\r\n\tdef technicalMinuteFinish(self, value):\r\n\t\tself.technicalMinuteFinish.set(value)\r\n\r\n\tdef technicalHourChecked(self, value):\r\n\t\tself.technicalHourChecked.set(value)\r\n\t\tself.minCheckedTechnicalCB.selectitem(0)\r\n\t\tself.minCheckedTechnicalCB.invoke()\r\n\r\n\tdef technicalMinuteChecked(self, value):\r\n\t\tself.technicalMinuteChecked.set(value)\r\n\r\n\tdef getDateTimeRequestTechnical(self):\r\n\t\tif self.technicalValues[4].get() != \"\":\r\n\t\t\tdate=self.technicalValues[4].get().split(\"/\")\r\n\t\t\td = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.technicalHourRequest.get()), int(self.technicalMinuteRequest.get()), 0)\r\n\t\t\treturn d\r\n\t\telse:\r\n\t\t\treturn None\r\n\r\n\tdef getDateTimeFinishTechnical(self):\r\n\t\tif self.technicalValues[7].get() != \"\":\r\n\t\t\tdate=self.technicalValues[7].get().split(\"/\")\r\n\t\t\td = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.technicalHourFinish.get()), int(self.technicalMinuteFinish.get()), 0)\r\n\t\t\treturn d\r\n\t\telse:\r\n\t\t\treturn None\r\n\r\n\tdef getDateTimeCheckedTechnical(self):\r\n\t\tif self.technicalValues[10].get() != \"\":\r\n\t\t\tdate=self.technicalValues[10].get().split(\"/\")\r\n\t\t\td = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.technicalHourChecked.get()), int(self.technicalMinuteChecked.get()), 0)\r\n\t\t\treturn d\r\n\t\telse:\r\n\t\t\treturn None\r\n\r\n\tdef verifyTechnical(self):\r\n\t\tif self.technicalValues[0].get() == \"\":\r\n\t\t\tshowerror(u\"Erreur de saisie\", u\"Le champ Produit est obligatoire !\\nMerci de le compléter.\")\r\n\t\t\treturn False\r\n\t\telif self.technicalValues[1].get() == \"\":\r\n\t\t\tshowerror(u\"Erreur de saisie\", u\"Le champ Tâche est obligatoire !\\nMerci de le compléter.\")\r\n\t\t\treturn False\r\n\t\telif self.technicalValues[3].get() == \"\": \r\n\t\t\tshowerror(u\"Erreur de saisie\", u\"Le champ Demandé par est obligatoire !\\nMerci de le compléter.\")\r\n\t\t\treturn False\r\n\t\telif self.technicalValues[4].get() == \"\": \r\n\t\t\tshowerror(u\"Erreur de saisie\", u\"Le champ Demande Date est obligatoire !\\nMerci de le compléter.\")\r\n\t\t\treturn False\r\n\t\telif self.technicalHourRequest.get() == \"\" or self.technicalMinuteRequest.get() == \"\": \r\n\t\t\tshowerror(u\"Erreur de saisie\", u\"Les champs Heures et Minutes de la Demande sont obligatoire !\\nMerci de les compléter.\")\r\n\t\t\treturn False\r\n\t\telse:\r\n\t\t\treturn True\r\n\r\n\tdef createTechnical(self, event=None):\r\n\t\tif self.verifyTechnical():\r\n\t\t\tif self.deleteTechnicalBt.config()[\"state\"][4] == \"normal\":\r\n\t\t\t\tself.modifyTechnical()\r\n\t\t\telse:\r\n\t\t\t\tif askyesno(u\"Enregistrement\", u\"Souhaitez-vous enregistrer %s comme une nouvelle interventione ?\\n\" % self.technicalValues[1].get()):\r\n\t\t\t\t\tTechnical(product=self.listObject[0],\r\n\t\t\t\t\t\tdesignation=self.technicalValues[1].get().encode(\"utf-8\"),\r\n\t\t\t\t\t\trequest=self.getDateTimeRequestTechnical(),\r\n\t\t\t\t\t\tanswer=self.getDateTimeFinishTechnical(),\r\n\t\t\t\t\t\tsolving=self.getDateTimeCheckedTechnical(),\r\n\t\t\t\t\t\tstatus=self.technicalValues[2].get().encode(\"utf-8\"),\r\n\t\t\t\t\t\trequestByTech=self.listObject[1],\r\n\t\t\t\t\t\tanswerBy=self.listObject[2],\r\n\t\t\t\t\t\tsolvingBy=self.listObject[3],\r\n\t\t\t\t\t\tnotes=self.technicalValues[12].get().encode(\"utf-8\"),\r\n\t\t\t\t\t\tcreateDate=datetime.datetime.now()\r\n\t\t\t\t\t)\r\n\t\t\t\t\tself.searchTechnical()\r\n\t\t\t\tself.clearFieldTechnical()\r\n\r\n\tdef modifyTechnical(self, event=None): \r\n\t\tif askyesno(u\"Modifier\", u\"Souhaitez-vous modifier l'intervention %s ?\" % str(self.selectedTechnical.id)):\r\n\t\t\tself.selectedTechnical.product=self.listObject[0]\r\n\t\t\tself.selectedTechnical.designation=self.technicalValues[1].get().encode(\"utf-8\")\r\n\t\t\tself.selectedTechnical.request=self.getDateTimeRequestTechnical()\r\n\t\t\tself.selectedTechnical.answer=self.getDateTimeFinishTechnical()\r\n\t\t\tself.selectedTechnical.solving=self.getDateTimeCheckedTechnical()\r\n\t\t\tself.selectedTechnical.status=self.technicalValues[2].get().encode(\"utf-8\")\r\n\t\t\tself.selectedTechnical.requestByTech=self.listObject[1]\r\n\t\t\tself.selectedTechnical.answerBy=self.listObject[2]\r\n\t\t\tself.selectedTechnical.solvingBy=self.listObject[3]\r\n\t\t\tself.selectedTechnical.notes=self.technicalValues[12].get().encode(\"utf-8\")\r\n\t\t\tself.searchTechnical()\r\n\t\tself.deleteTechnicalBt.config(state=DISABLED)\r\n\t\tself.clearFieldTechnical()\r\n\r\n\tdef deleteTechnical(self, event=None): \r\n\t\tif askyesno(u\"Suppression\", u\"Souhaitez-vous supprimer l'intervention %s ?\\nCette opération est irréversible !\" % str(self.selectedTechnical.id)):\r\n\t\t\tTechnical.delete(self.selectedTechnical.id)\r\n\t\t\tself.searchTechnical() \r\n\t\tself.deleteTechnicalBt.config(state=DISABLED)\r\n\t\tself.clearFieldTechnical()\r\n\t# FIN de la gestion du module Technical --------------------------------------------------------------------------------------------------------\r\n\n#~ class TechnicalListGUI(Toplevel):\n #~ def __init__(self, parent=None, balloon=None, field=None, index=None):\n #~ Toplevel.__init__(self, parent)\n #~ self.parent=parent\n #~ self.grab_set()\n #~ self.transient(self.master)\n #~ self.resizable(width=False, height=False)\n #~ self.title(u\"Liste des Articles\")\n #~ self.balloon=balloon\n #~ self.field=field\n #~ self.index=index\n #~ self.makeListItem()","sub_path":"iTechnical.py","file_name":"iTechnical.py","file_ext":"py","file_size_in_byte":30442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"606587929","text":"__author__ = 'zhangyin'\n\nimport re\nimport string\nimport timeit\nfrom nltk.stem.porter import *\nfrom nltk.corpus import stopwords\nfrom nltk import FreqDist\nimport json\nimport os\nimport nltk\nimport numpy as np\nstemmer = PorterStemmer()\n\n###### data loading and parsing functions#########\n\n\ndef parse_to_sentence(content, stopwords):\n sent_word = []\n sentences = nltk.sent_tokenize(content) # Sentence tokenization\n for sent in sentences:\n words = nltk.word_tokenize(sent) # Word tokenization\n temp = [stemmer.stem(w.lower()) # word to lower letters -> stemming (if not punctuation)\n for w in words if w not in string.punctuation]\n temp2 = [v for v in temp if v not in stopwords] # removing stop words\n if len(temp2) > 0: # if not [], adding word to sent_word\n sent_word.append(temp2)\n return sent_word\n\n\ndef load_a_json_file(filename):\n with open(filename, encoding=\"ISO-8859-1\") as data_file:\n data = json.load(data_file)\n return data\n\n\ndef load_all_json_files(jsonfolder, suffix):\n data = []\n\n def load_a_json_folder(folder, suffix):\n if not folder[-1] == \"/\":\n folder = folder+\"/\"\n # list all the files and sub folders under the Path\n # Get all the files and folders from the directory\n fs = os.listdir(folder)\n for f in fs:\n if not f.startswith(\".\"): # ignore files or folders start with period\n fpath = folder+f\n # if this is not a folder, that is, this is a file\n if not os.path.isdir(fpath):\n # add data loading code\n if fpath.split(\".\")[-1] == suffix:\n with open(fpath, encoding=\"ISO-8859-1\") as data_file:\n data.append(json.load(data_file))\n else:\n subfolder = fpath+\"/\"\n # else this is a folder\n load_a_json_folder(subfolder, suffix)\n load_a_json_folder(jsonfolder, suffix)\n return data\n\n\nclass CreateVocab:\n def __init__(self, is_dev_mode):\n self.is_dev_mode = is_dev_mode\n print(\"is_dev_mode: {}\".format(is_dev_mode))\n\n def create_stopwords(self):\n init_stopwords = [stemmer.stem(v) for v in stopwords.words('english')]\n additional_stopwords = [\"'s\", \"...\", \"'ve\",\n \"``\", \"''\", \"'m\", '--', \"'ll\", \"'d\"]\n self.stopwords = additional_stopwords + init_stopwords\n\n def read_data(self, folder, suffix):\n # suffix=\"json\"\n # folder=\"/Users/zhangyin/python projects/IR project/data/yelp mp1 data/\"\n self.corpus = load_all_json_files(folder, suffix)\n\n def create_vocab(self):\n All_Contents = []\n i = 0\n for hotel in self.corpus:\n print(\"loading file No.\"+str(i+1))\n for review in hotel.get(\"Reviews\"):\n s = [] # s : temporary list for one hotel (one file)\n for v in parse_to_sentence(review.get('Content'), self.stopwords):\n s = v + s\n All_Contents = All_Contents + s\n i = i+1\n # nltk package provides a function that calculates frequencies of words\n term_freq = FreqDist(All_Contents)\n Vocab = []\n Count = []\n VocabDict = {}\n\n # term_freq is a dictionary\n for k, v in term_freq.items():\n if self.is_dev_mode or v > 5: # only if term frequency is over 5, added to Vocab\n Vocab.append(k) # appending key (word)\n Count.append(v) # appending value (counts)\n\n # vocab sorting and re-saving\n self.Vocab = np.array(Vocab)[np.argsort(Vocab)].tolist()\n self.Count = np.array(Count)[np.argsort(Vocab)].tolist()\n # making a Vocab list to a dict (Vocab and index)\n self.VocabDict = dict(zip(self.Vocab, range(len(self.Vocab))))\n\n def save_to_file(self, savefilepath):\n # Saving corpus, Vocab, Count, VocabDict\n np.save(savefilepath, (self.corpus, self.Vocab,\n self.Count, self.VocabDict))\n print(\"succeed saving to file \"+savefilepath)\n\n def load_Vocab(self, loadfilepath):\n print(\"loading data from\" + loadfilepath)\n return np.load(loadfilepath)\n\n# savefilepath = \"./output/yelp_mp1_corpus\"\n# loadfilepath = \"./output/yelp_mp1_corpus.npy\"\n\n\ndef get_top_p_tf(dict, p):\n temp = dict.copy()\n res = []\n for i in range(p):\n key = temp.max()\n v = temp.get(key)\n temp.pop(key)\n # res.append((key,v))\n res.append(key)\n return res\n","sub_path":"LARA_LDA_Python/src/CreateVocab.py","file_name":"CreateVocab.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"505947244","text":"import os\nimport csv\n\n\nclass CarBase:\n def __init__(self, brand, photo_file_name, carrying):\n self.brand = brand\n self.photo_file_name = photo_file_name\n self.carrying = float(carrying)\n \n car_type = None\n\n def get_photo_file_ext(self):\n return os.path.splitext(self.photo_file_name)[1]\n\n\nclass Car(CarBase):\n def __init__(self, brand, photo_file_name, carrying, passenger_seats_count):\n super().__init__(brand, photo_file_name, carrying)\n self.passenger_seats_count = int(passenger_seats_count)\n self.car_type = 'car'\n\n\nclass Truck(CarBase):\n def __init__(self, brand, photo_file_name, carrying, body_whl):\n super().__init__(brand, photo_file_name, carrying)\n try:\n b_length, b_width, b_height = body_whl.split('x')\n self.body_width = float(b_width)\n self.body_height = float(b_height)\n self.body_length = float(b_length)\n except ValueError:\n self.body_width = 0.0\n self.body_height = 0.0\n self.body_length = 0.0\n self.car_type = 'truck'\n \n def get_body_volume(self):\n return self.body_width * self.body_height * self.body_length\n\n\nclass SpecMachine(CarBase):\n def __init__(self, brand, photo_file_name, carrying, extra):\n super().__init__(brand, photo_file_name, carrying)\n self.extra = extra\n self.car_type = 'spec_machine'\n\n\ndef get_car_list(csv_filename):\n car_list = []\n with open(csv_filename) as csv_fd:\n reader = csv.reader(csv_fd, delimiter=';')\n next(reader)\n for row in reader:\n if row[0] not in ['car', 'truck', 'spec_machine'] \\\n or row[1] == '' \\\n or os.path.splitext(row[3])[1] == '' \\\n or '.' in os.path.splitext(row[3])[0] \\\n or row[5] == '':\n continue\n elif row[0] == 'car':\n if row[2] == '':\n continue\n else:\n car_list.append(Car(row[1], row[3], row[5], \\\n row[2]))\n elif row[0] == 'truck':\n car_list.append(Truck(row[1], row[3], row[5], \\\n row[4]))\n elif row[0] == 'spec_machine':\n if row[6] == '':\n continue\n else: \n car_list.append(SpecMachine(row[1], row[3], row[5], \\\n row[6]))\n return car_list\n","sub_path":"week_3/цуул03_02.py","file_name":"цуул03_02.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"480901047","text":"import FWCore.ParameterSet.Config as cms\nfrom RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi import electronMVAVariableHelper\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\nfrom Configuration.AlCa.GlobalTag import GlobalTag\n\nprocess = cms.Process(\"ElectronMVANtuplizer\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc', '')\n\n# File with the ID variables to include in the Ntuplizer\nmvaVariablesFile = \"RecoEgamma/ElectronIdentification/data/ElectronIDVariables.txt\"\n\noutputFile = \"electron_ntuple.root\"\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n '/store/mc/RunIIFall17MiniAOD/DYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8/MINIAODSIM/RECOSIMstep_94X_mc2017_realistic_v10-v1/00000/0293A280-B5F3-E711-8303-3417EBE33927.root'\n )\n)\n\nuseAOD = False\n\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\n# turn on VID producer, indicate data format to be\n# DataFormat.AOD or DataFormat.MiniAOD, as appropriate\nif useAOD == True :\n dataFormat = DataFormat.AOD\nelse :\n dataFormat = DataFormat.MiniAOD\n\nswitchOnVIDElectronIdProducer(process, dataFormat)\n\n# define which IDs we want to produce\nmy_id_modules = [\n 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_noIso_V2_cff',\n 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_iso_V2_cff',\n 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_noIso_V1_cff',\n 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_iso_V1_cff',\n ]\n\n#add them to the VID producer\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)\n\nprocess.ntuplizer = cms.EDAnalyzer('ElectronMVANtuplizer',\n # AOD case\n src = cms.InputTag('gedGsfElectrons'),\n vertices = cms.InputTag('offlinePrimaryVertices'),\n pileup = cms.InputTag('addPileupInfo'),\n genParticles = cms.InputTag('genParticles'),\n # miniAOD case\n srcMiniAOD = cms.InputTag('slimmedElectrons'),\n verticesMiniAOD = cms.InputTag('offlineSlimmedPrimaryVertices'),\n pileupMiniAOD = cms.InputTag('slimmedAddPileupInfo'),\n genParticlesMiniAOD = cms.InputTag('prunedGenParticles'),\n #\n eleMVAs = cms.untracked.vstring(\n \"egmGsfElectronIDs:mvaEleID-Fall17-noIso-V2-wp80\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-noIso-V2-wpLoose\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-noIso-V2-wp90\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V2-wpHZZ\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V2-wp80\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V2-wpLoose\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V2-wp90\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-noIso-V1-wp90\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-noIso-V1-wp80\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-noIso-V1-wpLoose\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V1-wp90\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V1-wp80\",\n \"egmGsfElectronIDs:mvaEleID-Fall17-iso-V1-wpLoose\",\n ),\n eleMVALabels = cms.untracked.vstring(\n \"Fall17noIsoV2wp80\",\n \"Fall17noIsoV2wpLoose\",\n \"Fall17noIsoV2wp90\",\n \"Fall17isoV2wpHZZ\",\n \"Fall17isoV2wp80\",\n \"Fall17isoV2wpLoose\",\n \"Fall17isoV2wp90\",\n \"Fall17noIsoV1wp90\",\n \"Fall17noIsoV1wp80\",\n \"Fall17noIsoV1wpLoose\",\n \"Fall17isoV1wp90\",\n \"Fall17isoV1wp80\",\n \"Fall17isoV1wpLoose\",\n ),\n eleMVAValMaps = cms.untracked.vstring(\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17NoIsoV2Values\",\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17NoIsoV2RawValues\",\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17IsoV2Values\",\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17IsoV2RawValues\",\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17IsoV1Values\",\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17NoIsoV1Values\",\n ),\n eleMVAValMapLabels = cms.untracked.vstring(\n \"Fall17NoIsoV2Vals\",\n \"Fall17NoIsoV2RawVals\",\n \"Fall17IsoV2Vals\",\n \"Fall17IsoV2RawVals\",\n \"Fall17IsoV1Vals\",\n \"Fall17NoIsoV1Vals\",\n ),\n eleMVACats = cms.untracked.vstring(\n \"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17NoIsoV1Categories\",\n ),\n eleMVACatLabels = cms.untracked.vstring(\n \"EleMVACats\",\n ),\n #\n variableDefinition = cms.string(mvaVariablesFile),\n isMC = cms.bool(True),\n deltaR = cms.double(0.1),\n )\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string( outputFile )\n )\n\nprocess.p = cms.Path(process.egmGsfElectronIDSequence * process.ntuplizer)\n","sub_path":"RecoEgamma/ElectronIdentification/python/Training/ElectronMVANtuplizer_cfg.py","file_name":"ElectronMVANtuplizer_cfg.py","file_ext":"py","file_size_in_byte":6904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"47226270","text":"import argparse\nimport os\nimport os.path as osp\n\nimport numpy as np\nfrom PIL import Image\nimport pathlib\nimport json\n\nimport utils\n\nfolder_classes = []\n\nlabel_ids = {}\n\n\ndef cvt_annotations(img_name_paths, out_file, has_labels):\n label_ids = {name: i for i, name in enumerate(folder_classes)}\n\n annotations = []\n\n file_client_args = dict(backend='disk')\n color_type = 'color'\n\n for i, [img_name, img_path, height, width] in enumerate(img_name_paths):\n if i % 1000 == 0:\n print(i)\n # if i > 10000:\n # break\n # print(i, img_path)\n\n wnid = pathlib.PurePath(img_path).parent.name\n\n if has_labels:\n bboxes = [[1, 1, width, height]]\n labels = [label_ids[wnid]]\n\n bboxes = np.array(bboxes, ndmin=2) - 1\n labels = np.array(labels)\n else:\n bboxes = np.zeros((0, 4), dtype=np.float32),\n labels = np.zeros((0, ), dtype=np.int64),\n\n annotation = {\n 'filename': os.path.join(wnid, img_name),\n 'width': width,\n 'height': height,\n 'ann': {\n 'bboxes': bboxes.astype(np.float32),\n 'labels': labels.astype(np.int64),\n 'bboxes_ignore': np.zeros((0, 4), dtype=np.float32),\n 'labels_ignore': np.zeros((0, ), dtype=np.int64),\n }\n }\n\n annotations.append(annotation)\n annotations = cvt_to_coco_json(annotations)\n\n with open(out_file, 'w') as f:\n json.dump(annotations, f)\n\n return annotations\n\n\ndef cvt_to_coco_json(annotations):\n image_id = 0\n annotation_id = 0\n coco = dict()\n coco['images'] = []\n coco['type'] = 'instance'\n coco['categories'] = []\n coco['annotations'] = []\n image_set = set()\n\n def addAnnItem(annotation_id, image_id, category_id, bbox, difficult_flag):\n annotation_item = dict()\n annotation_item['segmentation'] = []\n\n seg = []\n # bbox[] is x1,y1,x2,y2\n # left_top\n seg.append(int(bbox[0]))\n seg.append(int(bbox[1]))\n # left_bottom\n seg.append(int(bbox[0]))\n seg.append(int(bbox[3]))\n # right_bottom\n seg.append(int(bbox[2]))\n seg.append(int(bbox[3]))\n # right_top\n seg.append(int(bbox[2]))\n seg.append(int(bbox[1]))\n\n annotation_item['segmentation'].append(seg)\n\n xywh = np.array(\n [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]])\n annotation_item['area'] = int(xywh[2] * xywh[3])\n if difficult_flag == 1:\n annotation_item['ignore'] = 0\n annotation_item['iscrowd'] = 1\n else:\n annotation_item['ignore'] = 0\n annotation_item['iscrowd'] = 0\n annotation_item['image_id'] = int(image_id)\n annotation_item['bbox'] = xywh.astype(int).tolist()\n annotation_item['category_id'] = int(category_id)\n annotation_item['id'] = int(annotation_id)\n coco['annotations'].append(annotation_item)\n return annotation_id + 1\n\n for category_id, name in enumerate(folder_classes):\n category_item = dict()\n category_item['supercategory'] = str('none')\n category_item['id'] = int(category_id)\n category_item['name'] = str(name)\n coco['categories'].append(category_item)\n\n for ann_dict in annotations:\n file_name = ann_dict['filename']\n ann = ann_dict['ann']\n assert file_name not in image_set\n image_item = dict()\n image_item['id'] = int(image_id)\n image_item['file_name'] = str(file_name)\n image_item['height'] = int(ann_dict['height'])\n image_item['width'] = int(ann_dict['width'])\n coco['images'].append(image_item)\n image_set.add(file_name)\n\n bboxes = ann['bboxes'][:, :4]\n labels = ann['labels']\n for bbox_id in range(len(bboxes)):\n bbox = bboxes[bbox_id]\n label = labels[bbox_id]\n annotation_id = addAnnItem(\n annotation_id, image_id, label, bbox, difficult_flag=0)\n\n bboxes_ignore = ann['bboxes_ignore'][:, :4]\n labels_ignore = ann['labels_ignore']\n for bbox_id in range(len(bboxes_ignore)):\n bbox = bboxes_ignore[bbox_id]\n label = labels_ignore[bbox_id]\n annotation_id = addAnnItem(\n annotation_id, image_id, label, bbox, difficult_flag=1)\n\n image_id += 1\n\n return coco\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Convert image list to coco format')\n parser.add_argument('--img-root', help='img root')\n parser.add_argument('--out-file', help='output path')\n parser.add_argument('--max-per-cat', help='max per cat')\n parser.add_argument('--num-labels', help='number of labels')\n parser.add_argument('--category-file', help='category json file path')\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n out_file = args.out_file\n img_root = args.img_root\n max_per_cat = int(args.max_per_cat)\n has_labels = True\n num_labels = int(args.num_labels)\n\n category_file = args.category_file\n\n global folder_classes\n\n fns = []\n cnt = 0\n wnid = ''\n for root, dirs, files in os.walk(img_root):\n cnt_per_dir = 0\n for name in files:\n if cnt % 1000 == 0:\n print(cnt)\n\n # if cnt >= 10:\n # break\n\n if max_per_cat > 0 and cnt_per_dir >= max_per_cat:\n break\n\n if name.endswith('.jpg') or name.endswith('.JPG'):\n pass\n elif name.endswith('.png') or name.endswith('.PNG'):\n pass\n elif name.endswith('.jpeg') or name.endswith('.JPEG'):\n pass\n else:\n print(\"skipping: \", name)\n continue\n\n path = os.path.join(root, name)\n\n wnid = pathlib.PurePath(path).parent.name\n\n if wnid not in folder_classes:\n folder_classes.append(wnid)\n\n try:\n img = utils.read_image(path, format='BGR')\n height, width, _ = img.shape\n except Exception as e:\n print('*' * 60)\n print(\"fail to open image: \", e)\n print('*' * 60)\n\n # if width < 224 or height < 224:\n # continue\n\n # if width > 1000 or height > 1000:\n # continue\n\n fns.append([name, path, height, width])\n\n # print(name, path, pathlib.PurePath(path).parent.name)\n cnt_per_dir += 1\n cnt += 1\n\n print(\"folder: \", wnid, \" number: \", cnt_per_dir)\n\n # for dirname in dirs:\n # folder_classes.append(dirname)\n\n folder_classes.sort()\n for i in range(len(folder_classes), num_labels):\n folder_classes.append('unknown_' + str(i))\n\n print('categories', len(folder_classes), ':', folder_classes)\n print('image number: ', cnt)\n\n annotations = cvt_annotations(fns, out_file, has_labels)\n print('Done!')\n\n if category_file:\n with open(category_file, 'r') as f:\n json_data = json.load(f)\n categories = json_data['categories']\n\n all_id = [c['id'] for c in categories]\n min_id = min(all_id)\n for category in categories:\n category[\"id\"] -= min_id\n annotations[\"categories\"] = categories\n with open(out_file, 'w') as f:\n json.dump(annotations, f)\n\nif __name__ == '__main__':\n main()\n","sub_path":"image2coco/image_folder.py","file_name":"image_folder.py","file_ext":"py","file_size_in_byte":7601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"317319558","text":"import numpy as np\nfrom keras.models import Model\nimport warnings\nwarnings.filterwarnings('ignore', '.*output shape of zoom.*')\nimport data_augmentation as da\nimport test_phase_utils as tpu\nimport train_utils as tu\nimport sys\nimport get_filenames as gf\nimport get_data as gd\n\n# Read the file we are going to do test on\ntrain_file_name = sys.argv[1]\nrepeats = 5\n\n# Training parameters and test results are stored with the \"_Test\" extension\nresult_filename = train_file_name + \"_Test\"\nresult_file = open(\"test_results/\" + result_filename + \".txt\",'a')\nparam_dict = tpu.training_file_parameters(train_file_name)\n\n# Some earlier training files were named differently, so we check for that\nif 'network_type' not in param_dict:\n param_dict = tpu.rename_param_dict(param_dict)\n\n# Change initial weights to be the result of training instead of\n# the initial weights in the training\nparam_dict['initial_weights'] = train_file_name\nparam_dict['scale_weights_on_input'] = \"False\"\n\n# Write all parameters to terminal and result file\nfor key in param_dict:\n print(key + \":\", param_dict[key])\n result_file.write(key + \": \" + param_dict[key] + '\\n')\n\n#param_dict['dataset_name'] = \"d:/b3sd\"\n\n\n# Get parameters from training parameters\nnetwork_type = param_dict['network_type']\ndataset_name = param_dict['dataset_name']\ndata_specifier = param_dict['data_specifier']\n#channels = [int(c) for c in param_dict['channels'].split(\",\")]\nsec1_frame = tpu.str2bool(param_dict['sec1_frame'])\n\n\n# Read filenames for dataset to use\nX,Y = gf.get_filenames(dataset_name, data_specifier, \"test\")\nprint(X.shape)\nprint(Y.shape)\n\n# Prepare input and output name of model,\n# then make model and load weights from training\n# Weights are saved before and efter to validate succesful load\ninput_names, output_name, stream = tu.prepare_stream(network_type) \nmodel = tu.make_network_model(param_dict,stream,None)\n\nweights_pre = model.get_weights()\nmodel = tu.load_weights(model, param_dict, stream, False, \"test\")\nweights_after = model.get_weights()\nweight_names = [weight.name for layer in model.layers for weight in layer.weights]\ntu.check_weights(weights_pre, weights_after, weight_names)\n\n\n# If the frame at second 1 is used (time of shot in B3SD dataset), then\n# we only get that particular frame for each video.\n\nif sec1_frame:\n print(\"1sec_frame set, so choosing that frame for each video\")\n result_file.write(\"1sec_frame set, so choosing that frame for each video\\n\")\n X = gd.get_batch(X, param_dict)\n augmented_X = da.augment_data(X, param_dict, \"test\")\n\n\n fit_input = tu.make_model_input_dict(input_names, augmented_X)\n predictions_categorical = model.predict(fit_input, verbose=1)\n \n print(predictions_categorical.shape)\n predictions = np.asarray([np.argmax(pred) for pred in predictions_categorical])\n print(predictions.shape)\n\n acc, correct_predictions = tpu.calculate_accuracy(predictions, Y, len(predictions))\n\n# If sec1_frame is false, then we select x frames from each video for a \n# more averaged guess for each video.\nelse:\n print(\"Augmenting each input \"+str(repeats)+\" times\")\n result_file.write(\"Augmenting each input \"+str(repeats)+\" times\\n\")\n result_file.close()\n \n # Prepare variables for testing\n predictions=[]\n for idx, x in enumerate(X):\n if (idx%10) == 0:\n print(\"Now working on test input number\", idx)\n \n # Get x frames from the same video\n #x_frames = gd.get_X_frames(x, param_dict, 10)\n x_frames = gd.get_batch(x, param_dict, phase=\"test\", repeats=repeats)\n x_frames = da.augment_data(x_frames, param_dict, \"test\")\n\n # Predict on each of the frames\n fit_input = tu.make_model_input_dict(input_names, x_frames)\n x_predictions_on_same_input = model.predict(fit_input, verbose=1)\n\n print(\"\\nInput\", idx, \"- Truth:\", x, int(Y[idx][0]))\n # Returns the top n predicted classes over an average prediction\n top_preds = tpu.top_n_predictions(x_predictions_on_same_input, 2)\n\n # Add prediction to list of predictions\n predictions.append(top_preds[0])\n\n # Calculate test accuracy\n acc, correct_predictions = tpu.calculate_accuracy(predictions, Y, idx+1)\n\n\n# Plot confusion matrix\ntpu.plot_confusion_matrix(param_dict, Y, np.asarray(predictions)-1, result_filename)\n\n# Save test results to file\nend = tpu.save_results(result_filename, correct_predictions, acc, len(X), len(predictions))","sub_path":"modules/test_phase.py","file_name":"test_phase.py","file_ext":"py","file_size_in_byte":4460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"183696857","text":"from pymongo import MongoClient\n\nimport xml.etree.ElementTree as ET\nclass NDFRTXML:\n 'Parse NDFRT XML'\n\n ndfrtxml_obj_list = []\n ndfrtxml_pid_list = []\n dict={}\n\n mongo_clinet= MongoClient(\"50.84.62.186\",27017)\n db=mongo_clinet.annt\n db.authenticate(\"annt\",\"5r4ShV7Z\")\n Ndf = db[\"NDFRT_Public_2014.07.07_TDE\"]\n\n def __init__(self, name, code, id, kind):\n self.name = name\n self.code = code\n self.id = id\n self.kind = kind\n\n def display(self):\n print(self.name + '\\t' + self.code + '\\t' + self.id + '\\t' + self.kind)\n\n def insertDb(self,d):\n self.Ndf.insert(d)\n\n def print_obj(ndfrtxml_obj_list ):\n mycount=0\n for obj in ndfrtxml_obj_list:\n obj.display()\n mycount = mycount + 1\n if mycount > 3:\n mycount = 0\n break\n\n def generate_conceptDef_mongodbobj(self):\n mongodb_dict = {\n \"name\":self.name,\n \"code\":self.code,\n \"id\":self.id ,\n \"kind\":self.kind,\n }\n\n if self.name == '1':\n mongodb_dict[\"name\"] = self.name\n\n if self.code == '1':\n mongodb_dict[\"code\"] = self.code\n\n if self.id == '1':\n mongodb_dict[\"id\"] = self.id\n\n if self.code == '1':\n mongodb_dict[\"kind\"] = self.kind\n\n return mongodb_dict\n\n @staticmethod\n def del_none(d):\n dup=d.copy()\n for key, value in d.items():\n if(value is None)or(value is '')or(value is \"\"):\n del dup[key]\n return (dup)\n\n\ntree = ET.parse(\"NDFRT_Public_2014.07.07_TDE.xml\")\nroot = tree.getroot()\nfor conceptdef in root.findall('conceptDef'):\n name = conceptdef.find('name').text\n code = conceptdef.find('code').text\n id = conceptdef.find('id').text\n kind = conceptdef.find('kind').text\n obj = NDFRTXML(name, code, id, kind)\n dict=obj.generate_conceptDef_mongodbobj()\n purifieddict=obj.del_none(dict)\n obj.Ndf.insert(purifieddict)\n print(\"Finished Inserting new record\")\nobj.db.logout\next=input(\"Completed Parsering xml file, Press enter to exit the program:\")\n","sub_path":"XmlInsert.py","file_name":"XmlInsert.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"649821017","text":"import tensorflow as tf\nimport numpy as np\n\nimport config\n\ndef fc(input, shape_, act=None):\n w = tf.Variable(tf.truncated_normal(shape_, stddev=0.1))\n b = tf.Variable(tf.constant(0.0, shape=[shape_[1]]))\n if act is not None:\n return act(tf.matmul(input, w) + b)\n else:\n return tf.matmul(input, w) + b\n\nclass Model():\n def __init__(self):\n self.input_userid = tf.placeholder(tf.int32, [None])\n self.input_movieid = tf.placeholder(tf.int32, [None])\n self.input_rating = tf.placeholder(tf.float32, [None])\n self.input_category = tf.placeholder(tf.float32, [None, config.N_CATEGORY])\n self.input_userattr = tf.placeholder(tf.float32, [None, 3])\n\n self.keep_prob = tf.placeholder(tf.float32)\n\n movie_embedding = tf.Variable(tf.truncated_normal([config.N_MOVIE+1, config.EMBED_DIM], stddev=0.1))\n user_embedding = tf.Variable(tf.truncated_normal([config.N_USER+1, config.EMBED_DIM], stddev=0.1))\n\n user_input = tf.nn.embedding_lookup(user_embedding, self.input_userid)\n movie_input = tf.nn.embedding_lookup(movie_embedding, self.input_movieid)\n\n user_input = tf.concat([user_input, self.input_category, self.input_userattr], axis=-1)\n movie_input = tf.concat([movie_input, self.input_category, self.input_userattr], axis=-1)\n\n user_input = fc(user_input, [config.EMBED_DIM+config.N_CATEGORY+3, 64], tf.nn.relu)\n movie_input = fc(movie_input, [config.EMBED_DIM+config.N_CATEGORY+3, 64], tf.nn.relu)\n\n user_input = tf.nn.dropout(user_input, keep_prob=self.keep_prob)\n movie_input = tf.nn.dropout(movie_input, keep_prob=self.keep_prob)\n\n user_input = fc(user_input, [64, 16])\n movie_input = fc(movie_input, [64, 16])\n print(user_input)\n print(movie_input)\n\n user_bias_embed = tf.Variable(tf.constant(0.0, shape=[config.N_USER+1, 1]))\n movie_bias_embed = tf.Variable(tf.constant(0.0, shape=[config.N_MOVIE+1, 1]))\n\n user_bias = tf.nn.embedding_lookup(user_bias_embed, self.input_userid)\n movie_bias = tf.nn.embedding_lookup(movie_bias_embed, self.input_movieid)\n print(user_bias)\n print(movie_bias)\n \n score = tf.reduce_sum(user_input*movie_input, axis=1, keep_dims=True) + user_bias + movie_bias\n score = tf.reshape(score, [-1])\n print(score)\n\n self.pred = score\n\n self.loss = tf.reduce_mean(tf.square(self.pred-self.input_rating))\n trainer = tf.train.AdamOptimizer(config.LEARNING_RATE)\n self.train_step = trainer.minimize(self.loss)\n\n self.saver = tf.train.Saver()\n \n def train(self, sess, userid, movieid, category, userattr, rating):\n loss, _ = sess.run([self.loss, self.train_step], feed_dict={self.input_userid:userid, self.input_movieid:movieid, self.input_category:category, self.input_userattr:userattr, self.input_rating:rating, self.keep_prob:config.KEEP_PROB})\n return np.sqrt(loss)\n\n def valid(self, sess, userid, movieid, category, userattr, rating):\n loss = sess.run(self.loss, feed_dict={self.input_userid:userid, self.input_movieid:movieid, self.input_category:category, self.input_userattr:userattr, self.input_rating:rating, self.keep_prob:1.0})\n return np.sqrt(loss)\n\n def predict(self, sess, userid, movieid, category, userattr):\n pred = sess.run(self.pred, feed_dict={self.input_userid:userid, self.input_movieid:movieid, self.input_category:category, self.input_userattr:userattr, self.keep_prob:1.0})\n return pred\n\n def load(self, sess):\n ckpt = tf.train.get_checkpoint_state('.')\n self.saver.restore(sess, ckpt.model_checkpoint_path)\n print('Model loaded from', ckpt.model_checkpoint_path, '.')\n \n def save(self, sess):\n self.saver.save(sess, './model.ckpt')\n print('Model saved.')\n \n def init(self, sess):\n sess.run(tf.global_variables_initializer())\n print('Variables initialized.')","sub_path":"hw5/model_dnn/model_dnn.py","file_name":"model_dnn.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"392694764","text":"import datetime\nimport glob\nimport re\nimport sys\nimport os\nfrom urllib.parse import quote\nfrom hashlib import md5\n\nimport lxml.html\n\nos.environ[\"SCRAPERWIKI_DATABASE_NAME\"] = \"sqlite:///data.sqlite\"\n\nimport scraperwiki\n\n# simple enviroment\ndebug = len(sys.argv) > 1\n\n# 11.02.2005\ndef extract_data_format_1(source, sep_source):\n source_date_string = source[sep_source + 1 :].strip()\n source_date = datetime.datetime.strptime(source_date_string, \"%d.%m.%Y\")\n source_name = source[:sep_source]\n return source_name, source_date\n\n\n# 11.02.05\ndef extract_data_format_2(source, sep_source):\n source_date_string = source[sep_source + 1 :].strip()\n source_date = datetime.datetime.strptime(source_date_string, \"%d.%m.%y\")\n source_name = source[:sep_source]\n return source_name, source_date\n\n\ndef extract_sources(source_list):\n # sometimes they concat sources with ; so try to get them\n source_list_fixed = []\n for s in source_list:\n source_list_fixed += s.split(\";\")\n source_list = source_list_fixed\n\n sources = []\n for source in source_list:\n source_name = source\n source_date = None\n if \",\" in source:\n sep_source = source.rindex(\",\")\n done = False\n # parse\n try:\n source_name, source_date = extract_data_format_1(source, sep_source)\n done = True\n except BaseException as e:\n if debug:\n print(source)\n print(str(e))\n if not done:\n try:\n source_name, source_date = extract_data_format_2(source, sep_source)\n except BaseException as e:\n if debug:\n print(source)\n print(str(e))\n sources.append({\"name\": source_name, \"date\": source_date})\n\n return sources\n\n\ndef extract_location(location):\n # print(raw_location)\n county = re.findall(r\"\\(.*\\)\", location)\n if len(county) > 0:\n county = county[0]\n county = county.replace(\"(\", \"\").replace(\")\", \"\")\n\n # special case for Halle Saale\n if county == \"Saale\":\n county = []\n else:\n # remove landkreis from location\n location = re.sub(r\"\\(.*|\\/.*\", \"\", location)\n\n # sometimes new white spaces need to be stripped again\n location = location.strip()\n if len(county) == 0:\n location_final = \", \".join([location, \"Sachsen-Anhalt\", \"Deutschland\"])\n else:\n location_final = \", \".join([location, county, \"Sachsen-Anhalt\", \"Deutschland\"])\n return location_final\n\n\ndef process_one(entry, url):\n source_list = entry.xpath(\"./text()\")\n sources = extract_sources(source_list)\n\n head = entry.xpath(\"./following-sibling::h1[1]/text()\")[0]\n\n # add all parts to one large string\n raw_text = \"\"\n for part in entry.xpath(\"./following-sibling::div[1]/p/text()\"):\n raw_text += \" \" + part\n text = re.sub(r\"\", \"\", raw_text).strip()\n\n head_split = head.split()\n raw_date = head_split[0]\n date = datetime.datetime.strptime(raw_date, \"%d.%m.%Y\")\n # just location\n raw_location = \" \".join(head_split[1:])\n location = extract_location(raw_location)\n\n identifier = md5((url + date.isoformat() + location + text).encode()).hexdigest()\n\n scraperwiki.sqlite.save(\n unique_keys=[\"identifier\"],\n data={\"description\": text, \"date\": date, \"iso3166_2\": \"DE-ST\", \"url\": url, \"identifier\": identifier, \"aggregator\": \"Mobile Opferberatung (Sachsen-Anhalt)\"},\n table_name=\"incidents\",\n )\n\n scraperwiki.sqlite.save(\n unique_keys=[\"identifier\"],\n data={\"subdivisions\": location, \"identifier\": identifier},\n table_name=\"locations\",\n )\n\n for s in sources:\n scraperwiki.sqlite.save(\n unique_keys=[\"identifier\"],\n data={\"date\": s[\"date\"], \"name\": s[\"name\"], \"identifier\": identifier},\n table_name=\"sources\",\n )\n\n\nbase_url = \"http://www.mobile-opferberatung.de/monitoring/chronik%s/\"\n\nindices = range(2003, datetime.datetime.now().year + 1)\n\nfor i in indices:\n\n url = base_url % i\n\n # special case for 2019\n if i == 2019:\n url = url.replace(\"chronik2019\", \"chronik-2019\")\n\n print(\"Sending Requests:\")\n print(url)\n\n try:\n html = scraperwiki.scrape(url)\n except Exception as e:\n print('some error,', e)\n\n doc = lxml.html.fromstring(html)\n\n for entry in doc.xpath(\"//h5\"):\n process_one(entry, url)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"255094124","text":"import pandas as pd\n\nclass Precaution():\n def __init__(self, disease):\n self.disease = disease\n\n def display(self):\n \n df = pd.read_csv('dataset/symptom_precaution.csv')\n idx = df[df['Disease'] == f'{self.disease}'].index[0]\n precautions = list(df.iloc[idx])[1:] \n \n return(precautions)\n\nif __name__ == \"__main__\":\n dis = Precaution('Migraine')\n print(dis.display())\n","sub_path":"precaution_detection.py","file_name":"precaution_detection.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"300619707","text":"import torch\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\nimport numpy as np\r\nfrom sklearn.base import BaseEstimator, RegressorMixin\r\nfrom Optim import Optim\r\nimport argparse\r\nimport pandas as pd\r\nfrom sklearn.metrics import mean_absolute_error, explained_variance_score, mean_squared_error, median_absolute_error, \\\r\n r2_score\r\nfrom utils import DataS, DataM, mean_absolute_percentage_error\r\nfrom models.LSTNet import LSTNet\r\nfrom models.LSTM import LSTM\r\nfrom models.GRU import GRU\r\nfrom utils import mkdir\r\nimport os.path as osp\r\n\r\n\r\nclass LSTNetModel(BaseEstimator, RegressorMixin):\r\n\r\n def __init__(self, args):\r\n\r\n super(LSTNetModel, self).__init__()\r\n\r\n torch.manual_seed(args.seed)\r\n\r\n self.epoch = 1\r\n self.epochs = args.epochs\r\n self.batchSize = args.batchSize\r\n self.lr = args.lr\r\n\r\n if args.taskName == 'S':\r\n\r\n self.trainSet = DataS(args, mode='Train')\r\n self.validSet = DataS(args, mode='Val', scaler=self.trainSet.scaler)\r\n self.dimI = self.trainSet.data.shape[1] - 1\r\n self.dimO = 1\r\n\r\n else:\r\n\r\n self.trainSet = DataM(args, mode='Train')\r\n self.validSet = DataM(args, mode='Val', scaler=self.trainSet.scaler)\r\n self.dimI = self.trainSet.data.shape[1]\r\n self.dimO = self.dimI\r\n\r\n self.criterion = nn.MSELoss()\r\n\r\n if args.modelName == 'LSTNet':\r\n self.model = LSTNet(args, self.dimI, self.dimO).to(torch.device('cuda:{}'.format(args.device)))\r\n if args.modelName == 'GRU':\r\n self.model = GRU(args, self.dimI, self.dimO).to(torch.device('cuda:{}'.format(args.device)))\r\n if args.modelName == 'LSTM':\r\n self.model = LSTM(args, self.dimI, self.dimO).to(torch.device('cuda:{}'.format(args.device)))\r\n\r\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=args.lr)\r\n # self.scheduler = optim.lr_scheduler.StepLR(self.optimizer, step_size, gamma)\r\n\r\n self.trainDict = dict()\r\n self.evalDict = dict()\r\n self.trainDict['loss'] = np.array([])\r\n self.evalDict['medianAbsoluteError'] = np.array([])\r\n self.evalDict['explainedVarianceScore'] = np.array([])\r\n self.evalDict['meanAbsoluteError'] = np.array([])\r\n self.evalDict['meanAbsolutePercentageError'] = np.array([])\r\n self.evalDict['rootMeanSquaredError'] = np.array([])\r\n self.evalDict['r2'] = np.array([])\r\n self.evalDict['r2Best'] = 0\r\n self.savePath = osp.join('./works', args.dataName, args.modelName + args.taskName + str(args.horizon),\r\n str(args.seed))\r\n mkdir(self.savePath)\r\n\r\n def fit(self):\r\n\r\n trainLoader = DataLoader(dataset=self.trainSet, batch_size=self.batchSize, shuffle=True)\r\n\r\n for i in range(1, self.epochs + 1):\r\n\r\n self.model.train()\r\n self.epoch = i\r\n\r\n for batchX, batchY in trainLoader:\r\n self.model.zero_grad()\r\n output = self.model(batchX)\r\n output = output.reshape(batchY.shape)\r\n loss = self.criterion(output, batchY) # shape\r\n loss.backward()\r\n self.optimizer.step()\r\n self.trainDict['loss'] = np.append(self.trainDict['loss'], loss.data.cpu().numpy())\r\n\r\n # self.scheduler.step()\r\n\r\n print('Epoch: {}, Loss: {}'.format(self.epoch, loss.data.cpu().numpy()))\r\n\r\n self.valid()\r\n if self.epoch % 20 == 0:\r\n torch.save(model, osp.join(self.savePath, 'epoch{}.pth'.format(self.epoch)))\r\n\r\n if self.evalDict['r2'][-1].mean() > self.evalDict['r2Best']:\r\n self.evalDict['r2Best'] = self.evalDict['r2'][-1].mean()\r\n\r\n if self.epoch > 10:\r\n torch.save(model, osp.join(self.savePath, 'best.pth'.format(self.epoch)))\r\n\r\n pd.DataFrame(self.trainDict).to_csv(self.savePath + '/trainLog.txt', header=0, index=0)\r\n pd.DataFrame(self.evalDict).to_csv(self.savePath + '/validLog.txt', header=0, index=0)\r\n\r\n def valid(self):\r\n\r\n with torch.no_grad():\r\n self.model.eval()\r\n validLoader = DataLoader(dataset=self.validSet, batch_size=self.batchSize, shuffle=True)\r\n results = {'output': np.array([]), 'label': np.array([])}\r\n\r\n for batchX, batchY in validLoader:\r\n output = self.model(batchX)\r\n output = output.reshape(batchY.shape).data.cpu().numpy()\r\n batchY = batchY.data.cpu().numpy()\r\n results['label'] = np.append(results['label'], batchY)\r\n results['output'] = np.append(results['output'], output)\r\n\r\n r2 = r2_score(results['label'], results['output'])\r\n explainedVarianceScore = explained_variance_score(results['label'], results['output'])\r\n rootMeanSquaredError = np.sqrt(mean_squared_error(results['label'], results['output']))\r\n meanAbsoluteError = mean_absolute_error(results['label'], results['output'])\r\n medianAbsoluteError = median_absolute_error(results['label'], results['output'])\r\n meanAbsolutePercentageError = mean_absolute_percentage_error(results['label'], results['output'])\r\n\r\n self.evalDict['r2'] = np.append(self.evalDict['r2'], r2)\r\n self.evalDict['explainedVarianceScore'] = np.append(self.evalDict['explainedVarianceScore'],\r\n explainedVarianceScore)\r\n self.evalDict['rootMeanSquaredError'] = np.append(self.evalDict['rootMeanSquaredError'],\r\n rootMeanSquaredError)\r\n self.evalDict['meanAbsoluteError'] = np.append(self.evalDict['meanAbsoluteError'], meanAbsoluteError)\r\n self.evalDict['medianAbsoluteError'] = np.append(self.evalDict['medianAbsoluteError'], medianAbsoluteError)\r\n self.evalDict['meanAbsolutePercentageError'] = np.append(self.evalDict['meanAbsolutePercentageError'],\r\n meanAbsolutePercentageError)\r\n\r\n print('Epoch: {}, Valid Loss: {}, R2: {}'.format(self.epoch, rootMeanSquaredError, r2))\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='PyTorch Time series forecasting')\r\n parser.add_argument('--dataName', type=str, default='traffic')\r\n parser.add_argument('--taskName', type=str, default='S')\r\n parser.add_argument('--modelName', type=str, default='LSTNet')\r\n parser.add_argument('--dimFC', type=int, default=64, help='number of RNN hidden units')\r\n\r\n parser.add_argument('--hidC', type=int, default=100, help='number of CNN hidden units')\r\n parser.add_argument('--hidR', type=int, default=100, help='number of RNN hidden units')\r\n\r\n parser.add_argument('--layerRNN', type=int, default=1, help='number of RNN hidden units')\r\n parser.add_argument('--bidirection', type=bool, default=False, help='number of RNN hidden units')\r\n parser.add_argument('--window', type=int, default=24 * 7, help='window size')\r\n parser.add_argument('--kernelCNN', type=int, default=6, )\r\n parser.add_argument('--highway_window', type=int, default=24, help='The window size of the highway component')\r\n parser.add_argument('--clip', type=float, default=10., help='gradient clipping')\r\n parser.add_argument('--epochs', type=int, default=200)\r\n parser.add_argument('--batchSize', type=int, default=32, metavar='N')\r\n parser.add_argument('--dropout', type=float, default=0.1, help='(0 = no dropout)')\r\n parser.add_argument('--device', default=0)\r\n parser.add_argument('--lr', type=float, default=0.001)\r\n parser.add_argument('--horizon', type=int, default=1)\r\n parser.add_argument('--skip', type=float, default=24)\r\n parser.add_argument('--hidSkip', type=int, default=5)\r\n parser.add_argument('--normalize', type=int, default=2)\r\n parser.add_argument('--seed', type=int, default=1024)\r\n args = parser.parse_args()\r\n\r\n model = LSTNetModel(args)\r\n model.fit()\r\n model.valid()\r\n","sub_path":"LSTNet.py","file_name":"LSTNet.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"299455121","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"aioflask\",\n version=\"0.2.0\",\n author=\"Miguel Grinberg\",\n author_email=\"miguel.grinberg@gmail.com\",\n description=\"Flask running on asyncio.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/miguelgrinberg/aioflask\",\n packages=setuptools.find_packages(),\n install_requires=[\n 'greenletio',\n 'flask>=2',\n 'uvicorn',\n ],\n entry_points={\n 'flask.commands': [\n 'run=aioflask.cli:run'\n ],\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.7',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"460220085","text":"#Amber Freeman\n#Python\n#April 17, 2017\n#Employee Payroll maintenance\n#Lab 4\n\ndata = []\nemployees = []\nfinal = []\nfile=input(\"Please type your file name, including type of file: \")\nwith open(file, 'r') as employee_file:\n first_line = employee_file.readline()\n\n for line in employee_file:\n if line != '\\n':\n data = line.rstrip(\"\\r\\n\")\n employees=data.split()\n print(data)\n name = str(employees[0])\n hours = float(employees[1])\n rate = float(employees[2])\n emp_input = input(\"Enter your 4 digit employee number: \")\n wages = (rate) * (hours)\n emp_list=(name, emp_input, hours, wages)\n final.extend(emp_list)\n print(\"NAME\", \" EMP #\", \"HOURS\", \" WAGES\")\n count=0\n for x in range(3):\n print(final[count], final[count+1], final[count+2], '${:3,.2f}'.format(final[count+3]))\n count=count+4\n\nemployee_file.close()\n","sub_path":"SSNToPayroll.py","file_name":"SSNToPayroll.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"97411897","text":"import pygame\nfrom shelf import Shelf\n\n\n\nclass Field:\n\n def __init__(self, screen, x, y, center_x, center_y, is_shelf, is_occupied_by_agent, cost_of_travel):\n # Jakieś podstawowe rzeczy\n self.screen = screen\n self.x = x\n self.y = y\n self.center_x = center_x\n self.center_y = center_y\n self.is_shelf = is_shelf\n self.is_occupied_by_agent = is_occupied_by_agent\n self.cost_of_travel = cost_of_travel\n self.neighbors = []\n self.shelves = []\n\n # Te parametry są potrzebne do algorytmu A*\n self.g = 0\n self.h = 0\n self.f = 0\n self.previous = None\n\n # Przedmiot, który podnosi agent\n self.item = []\n self.is_empty = True\n\n # Te rzeczy są potrzebne do wyświetlenia pola\n self.image = pygame.image.load('img/Field.png')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n self.rect.center = (center_x, center_y)\n\n # Metoda do wyświetlania pola na ekranie\n def blitme(self):\n self.screen.blit(self.image, self.rect)\n\n def add_neighbors(self, board):\n if self.x > 0 and board[self.y][self.x - 1].is_shelf == False:\n self.neighbors.append(board[self.y][self.x - 1])\n if self.x < 9 and board[self.y][self.x + 1].is_shelf == False:\n self.neighbors.append(board[self.y][self.x + 1])\n if self.y > 0 and board[self.y - 1][self.x].is_shelf == False:\n self.neighbors.append(board[self.y - 1][self.x])\n if self.y < 9 and board[self.y + 1][self.x].is_shelf == False:\n self.neighbors.append(board[self.y + 1][self.x])\n\n def addShelf(self):\n shelf = Shelf(len(self.shelves) + 1)\n self.shelves.append(shelf)\n\n def isShelf(self):\n return self.is_shelf","sub_path":"field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"327358018","text":"from django import forms\n\nfrom .models import Subscribe\n\nclass SubscribeForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Subscribe\n\t\tfields = ['email'] \n\t\twidgets = {\n 'email': forms.TextInput(attrs={'class': 'form-control', 'onFocus': \"this.value=''\", 'required': 'true', 'placeholder': 'Your Email', 'id':'email'}), \n }\n","sub_path":"home/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"322241409","text":"#!/usr/bin/env python\n\nimport rospy\nimport tf\nimport numpy as np\nimport cv2\nfrom cv_bridge import CvBridge\nfrom sensor_msgs.msg import NavSatFix, Image\nfrom geometry_msgs.msg import PoseStamped, TwistStamped\nfrom mavros_msgs.msg import State, ExtendedState, PositionTarget, ParamValue\nfrom mavros_msgs.srv import CommandBool, CommandBoolRequest, SetMode, SetModeRequest, CommandTOL, CommandTOLRequest, \\\n ParamSet, ParamGet\n\nEPSILON = 0.01\nCMD = None\n\n\nclass DroneWrapper:\n def state_cb(self, msg):\n self.state = msg\n rospy.logdebug('State updated')\n\n def extended_state_cb(self, msg):\n self.extended_state = msg\n rospy.logdebug('Extended State updated')\n\n self.rqt_extended_state_publisher.publish(self.extended_state)\n\n def pose_stamped_cb(self, msg):\n self.pose_stamped = msg\n rospy.logdebug('Pose updated')\n\n self.rqt_pose_publisher.publish(self.pose_stamped)\n\n def vel_body_stamped_cb(self, msg):\n self.vel_body_stamped = msg\n rospy.logdebug('Velocity (body) updated')\n\n self.rqt_velocity_body_publisher.publish(self.vel_body_stamped)\n\n def global_position_cb(self, msg):\n self.global_position = msg\n rospy.logdebug('Global position updated')\n\n def cam_frontal_cb(self, msg):\n self.frontal_image = msg\n rospy.logdebug('Frontal image updated')\n\n self.rqt_cam_frontal_publisher.publish(self.frontal_image)\n\n def cam_ventral_cb(self, msg):\n self.ventral_image = msg\n rospy.logdebug('Ventral image updated')\n\n self.rqt_cam_ventral_publisher.publish(self.ventral_image)\n\n def stay_armed_stay_offboard_cb(self, event):\n if self.state.mode != 'OFFBOARD':\n if self.request_mode('OFFBOARD'):\n rospy.loginfo(\"OFFBOARD requested\")\n elif not self.state.armed:\n if self.arm(True):\n rospy.loginfo(\"Vehicle Armed\")\n\n def get_frontal_image(self):\n return self.bridge.imgmsg_to_cv2(self.frontal_image)\n\n def get_ventral_image(self):\n return self.bridge.imgmsg_to_cv2(self.ventral_image)\n\n def get_position(self):\n return np.array([self.pose_stamped.pose.position.x,\n self.pose_stamped.pose.position.y,\n self.pose_stamped.pose.position.z])\n\n def get_velocity(self):\n return np.array([self.vel_body_stamped.twist.linear.x,\n self.vel_body_stamped.twist.linear.y,\n self.vel_body_stamped.twist.linear.z])\n\n def get_yaw_rate(self):\n return self.vel_body_stamped.twist.angular.z\n\n def get_orientation(self):\n return np.array(tf.transformations.euler_from_quaternion([self.pose_stamped.pose.orientation.x,\n self.pose_stamped.pose.orientation.y,\n self.pose_stamped.pose.orientation.z,\n self.pose_stamped.pose.orientation.w]))\n\n def get_roll(self):\n return self.get_orientation()[0]\n\n def get_pitch(self):\n return self.get_orientation()[1]\n\n def get_yaw(self):\n return self.get_orientation()[2]\n\n def get_landed_state(self):\n return self.extended_state.landed_state\n\n def param_set(self, param, value):\n if isinstance(value, float):\n val = ParamValue(integer=0, real=value)\n else:\n val = ParamValue(integer=value, real=0.0)\n\n rospy.wait_for_service(self.ns + '/mavros/param/set')\n try:\n set_param = rospy.ServiceProxy(self.ns + '/mavros/param/set', ParamSet)\n resp = set_param(param_id=param, value=val)\n print(\"setmode send ok\", resp.success)\n except rospy.ServiceException as e:\n print(\"Failed SetMode:\", e)\n\n def param_get(self, param):\n try:\n get_param = rospy.ServiceProxy(self.ns + 'mavros/param/get', ParamGet)\n resp = get_param(param_id=param)\n print(\"setmode send ok\", resp.success)\n except rospy.ServiceException as e:\n print(\"Failed SetMode:\", e)\n return None\n\n if resp.value.integer != 0:\n return resp.value.integer\n elif resp.value.real != 0.0:\n return resp.value.real\n else:\n return 0\n\n def arm(self, value=True):\n req = CommandBoolRequest()\n req.value = value\n if self.arm_client(req).success:\n rospy.loginfo('Arming/Disarming successful')\n return True\n else:\n rospy.logwarn('Arming/Disarming unsuccessful')\n return False\n\n def request_mode(self, mode='OFFBOARD'):\n rospy.sleep(2)\n rospy.loginfo('Current mode: %s', self.state.mode)\n req = SetModeRequest()\n req.custom_mode = mode\n if self.mode_client(req).mode_sent:\n rospy.loginfo('Mode change request successful')\n return True\n else:\n rospy.logwarn('Mode change request unsuccessful')\n return False\n\n def set_cmd_pos(self, x=0, y=0, z=0, az=0):\n self.setpoint_raw.coordinate_frame = 8\n self.setpoint_raw.yaw = az\n\n self.posx = x\n self.posy = y\n self.height = z\n self.vx = 0\n self.vy = 0\n self.vz = 0\n\n self.setpoint_raw.position.x = x\n self.setpoint_raw.position.y = y\n self.setpoint_raw.position.z = z\n\n global CMD\n CMD = 0 # POS\n self.setpoint_raw.type_mask = 3064 # xyz yaw\n\n self.setpoint_raw_publisher.publish(self.setpoint_raw)\n\n def set_cmd_vel(self, vx=0, vy=0, vz=0, az=0):\n self.setpoint_raw.coordinate_frame = 8\n self.setpoint_raw.yaw_rate = az\n\n self.posx = self.pose_stamped.pose.position.x\n self.posy = self.pose_stamped.pose.position.y\n self.height = self.pose_stamped.pose.position.z\n self.vx = -vy\n self.vy = vx\n self.vz = vz\n\n global CMD\n CMD = 1 # VEL\n\n if abs(vx) <= EPSILON and abs(vy) <= EPSILON:\n self.is_xy = True\n else:\n self.setpoint_raw.velocity.x = -vy\n self.setpoint_raw.velocity.y = vx\n\n self.is_xy = False\n\n if abs(vz) <= EPSILON:\n self.is_z = True\n else:\n self.setpoint_raw.velocity.z = vz\n self.is_z = False\n\n if self.is_xy:\n if self.is_z:\n self.setpoint_raw.type_mask = 2040 # xyz yaw_rate\n # self.setpoint_raw.type_mask = 3064 # xyz yaw\n else:\n self.setpoint_raw.type_mask = 1991 # vx vy vy yaw_rate\n # self.setpoint_raw.type_mask = 3015 # vx vy vz yaw\n # self.setpoint_raw.type_mask = 3036 # x y vz yaw -> NOT SUPPORTED \n else:\n if self.is_z:\n self.setpoint_raw.type_mask = 1987 # vx vy vz z yaw_rate\n # self.setpoint_raw.type_mask = 2019 # vx vy z yaw_rate -> NOT SUPPORTED\n # self.setpoint_raw.type_mask = 3011 # vx vy vz z yaw\n # self.setpoint_raw.type_mask = 3043 # vx vy z yaw -> NOT SUPPORTED\n else:\n self.setpoint_raw.type_mask = 1991 # vx vy vy yaw_rate\n # self.setpoint_raw.type_mask = 3015 # vx vy vz yaw\n\n self.setpoint_raw_publisher.publish(self.setpoint_raw)\n\n def set_cmd_mix(self, vx=0, vy=0, z=0, az=0):\n self.setpoint_raw.coordinate_frame = 8\n self.setpoint_raw.yaw_rate = az\n\n self.posx = self.pose_stamped.pose.position.x\n self.posy = self.pose_stamped.pose.position.y\n self.height = z\n self.vx = -vy\n self.vy = vx\n self.vz = 0\n\n self.setpoint_raw.position.z = z\n self.setpoint_raw.velocity.x = -vy\n self.setpoint_raw.velocity.y = vx\n\n global CMD\n CMD = 2 # MIX\n self.setpoint_raw.type_mask = 1987 # vx vy vz z yaw_rate\n\n self.setpoint_raw_publisher.publish(self.setpoint_raw)\n\n def repeat_setpoint_raw(self, event):\n self.setpoint_raw.coordinate_frame = 8\n\n self.setpoint_raw.position.x = self.posx\n self.setpoint_raw.position.y = self.posy\n self.setpoint_raw.position.z = self.height\n self.setpoint_raw.velocity.x = self.vx\n self.setpoint_raw.velocity.y = self.vy\n self.setpoint_raw.velocity.z = self.vz\n\n if CMD == 0: # POS\n self.setpoint_raw.type_mask = 3064 # xyz yaw\n elif CMD == 1: # VEL\n if self.is_xy:\n if self.is_z:\n self.setpoint_raw.type_mask = 2040 # xyz yaw_rate\n else:\n self.setpoint_raw.type_mask = 1991 # vx vy vy yaw_rate\n else:\n if self.is_z:\n self.setpoint_raw.type_mask = 1987 # vx vy vz z yaw_rate\n else:\n self.setpoint_raw.type_mask = 1991 # vx vy vy yaw_rate\n elif CMD == 2: # MIX\n self.setpoint_raw.type_mask = 1987 # vx vy vz z yaw_rate\n else:\n self.setpoint_raw.type_mask = 3064 # xyz yaw\n print(\"[CMD error]: Mask set to position control\")\n\n self.setpoint_raw_publisher.publish(self.setpoint_raw)\n\n def hold_setpoint_raw(self):\n if not self.setpoint_raw_flag:\n self.setpoint_raw_timer = rospy.Timer(rospy.Duration(nsecs=50000000), self.repeat_setpoint_raw)\n\n def takeoff(self, h=3):\n self.set_cmd_pos(0, 0, 0, 0)\n self.hold_setpoint_raw()\n self.arm(True)\n self.stay_armed_stay_offboard_timer = rospy.Timer(rospy.Duration(3), self.stay_armed_stay_offboard_cb)\n while True:\n while not (self.state.armed and self.state.mode == 'OFFBOARD'):\n self.rate.sleep()\n rospy.loginfo('Sleeping 1 secs to confirm change')\n rospy.sleep(1)\n if self.state.mode == 'OFFBOARD':\n break\n self.set_cmd_mix(z=h)\n rospy.loginfo('Taking off!!!')\n while True:\n if round(self.pose_stamped.pose.position.z, 1) == h:\n break\n self.set_cmd_vel()\n\n def take_control(self):\n self.set_cmd_pos(0, 0, 0, 0)\n self.hold_setpoint_raw()\n self.arm(True)\n self.stay_armed_stay_offboard_timer = rospy.Timer(rospy.Duration(3), self.stay_armed_stay_offboard_cb)\n\n def land(self):\n self.setpoint_raw_timer.shutdown()\n self.stay_armed_stay_offboard_timer.shutdown()\n req = CommandTOLRequest()\n req.latitude = self.global_position.latitude\n req.longitude = self.global_position.longitude\n self.land_client(req)\n\n def __init__(self, name='drone', ns='', verbose=False):\n if name != 'rqt':\n if verbose:\n rospy.init_node(name, anonymous=True, log_level=rospy.DEBUG)\n else:\n rospy.init_node(name)\n self.ns = ns\n\n self.state = State()\n self.extended_state = ExtendedState()\n self.pose_stamped = PoseStamped()\n self.vel_body_stamped = TwistStamped()\n self.rate = rospy.Rate(20)\n self.setpoint_raw = PositionTarget()\n self.setpoint_raw_flag = False\n self.vz_factor = 0.4\n self.bridge = CvBridge()\n\n self.is_z = False\n self.is_xy = False\n\n self.posx = 0\n self.posy = 0\n self.height = 0\n self.vx = 0\n self.vy = 0\n self.vz = 0\n\n self.setpoint_raw_timer = rospy.Timer(rospy.Duration(nsecs=50000000), self.repeat_setpoint_raw)\n self.setpoint_raw_timer.shutdown()\n self.stay_armed_stay_offboard_timer = rospy.Timer(rospy.Duration(5), self.stay_armed_stay_offboard_cb)\n self.stay_armed_stay_offboard_timer.shutdown()\n\n rospy.wait_for_service(self.ns + 'mavros/cmd/arming')\n self.arm_client = rospy.ServiceProxy(ns + 'mavros/cmd/arming', CommandBool)\n rospy.wait_for_service(self.ns + 'mavros/set_mode')\n self.mode_client = rospy.ServiceProxy(ns + 'mavros/set_mode', SetMode)\n rospy.wait_for_service(self.ns + 'mavros/cmd/land')\n self.land_client = rospy.ServiceProxy(ns + 'mavros/cmd/land', CommandTOL)\n\n self.rqt_extended_state_publisher = rospy.Publisher(self.ns + 'drone_wrapper/extended_state', ExtendedState,\n queue_size=1)\n self.rqt_pose_publisher = rospy.Publisher(self.ns + 'drone_wrapper/local_position/pose', PoseStamped,\n queue_size=1)\n self.rqt_velocity_body_publisher = rospy.Publisher(self.ns + 'drone_wrapper/local_position/velocity_body',\n TwistStamped, queue_size=1)\n self.rqt_cam_frontal_publisher = rospy.Publisher(self.ns + 'drone_wrapper/cam_frontal/image_raw', Image,\n queue_size=1)\n self.rqt_cam_ventral_publisher = rospy.Publisher(self.ns + 'drone_wrapper/cam_ventral/image_raw', Image,\n queue_size=1)\n\n rospy.Subscriber(self.ns + 'mavros/state', State, self.state_cb)\n rospy.Subscriber(self.ns + 'mavros/extended_state', ExtendedState, self.extended_state_cb)\n rospy.Subscriber(self.ns + 'mavros/local_position/pose', PoseStamped, self.pose_stamped_cb)\n rospy.Subscriber(self.ns + 'mavros/local_position/velocity_body', TwistStamped, self.vel_body_stamped_cb)\n rospy.Subscriber(self.ns + 'mavros/global_position/global', NavSatFix, self.global_position_cb)\n cam_frontal_topic = rospy.get_param('cam_frontal_topic', '/iris/cam_frontal/image_raw')\n cam_ventral_topic = rospy.get_param('cam_ventral_topic', '/iris/cam_ventral/image_raw')\n rospy.Subscriber(cam_frontal_topic, Image, self.cam_frontal_cb)\n rospy.Subscriber(cam_ventral_topic, Image, self.cam_ventral_cb)\n\n self.setpoint_raw_publisher = rospy.Publisher(self.ns + 'mavros/setpoint_raw/local', PositionTarget,\n queue_size=1)\n","sub_path":"drone_wrapper/src/drone_wrapper/drone_wrapper_class.py","file_name":"drone_wrapper_class.py","file_ext":"py","file_size_in_byte":14280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"411808249","text":"t = int(input())\nfor x in range(t):\n x1, y1, x2, y2 = [int(i) for i in input().split()]\n x3, y3, x4, y4 = [int(i) for i in input().split()]\n if not (min(x1,x2) <= max(x3,x4) and min(y3,y4) <= max(y1,y2) and min(x3,x4) <= max(x1,x2) and min(y1,y2) <= max(y3,y4)):\n print(0)\n break\n else:\n fc = (y3-y1) * (x2-x1) - (x3-x1) *(y2-y1)\n fd = (y4-y1) * (x2-x1) - (x4-x1) *(y2-y1)\n if(fc * fd > 0):\n print(0)\n break\n print(1)\n","sub_path":"Code/CodeRecords/2544/39200/307089.py","file_name":"307089.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"358175305","text":"import pygame\nfrom pygame.locals import *\nimport sys\n \nSCREEN_SIZE = (640, 480)\n \npygame.init()\nscreen = pygame.display.set_mode(SCREEN_SIZE)\npygame.display.set_caption(\"move pikachu\")\n \nimg = pygame.image.load(\"../images/pikachu.png\").convert_alpha()\nimg_rect = img.get_rect()\nimg_rect.center = (320, 240)\n \nvx = vy = 10\n \nwhile True:\n pressed_keys = pygame.key.get_pressed()\n if pressed_keys[K_LEFT]:\n img_rect.move_ip(-vx, 0)\n if pressed_keys[K_RIGHT]:\n img_rect.move_ip(vx, 0)\n if pressed_keys[K_UP]:\n img_rect.move_ip(0, -vy)\n if pressed_keys[K_DOWN]:\n img_rect.move_ip(0, vy)\n \n screen.fill((0,0,255))\n screen.blit(img, img_rect)\n pygame.display.update()\n \n for event in pygame.event.get():\n if event.type == QUIT: sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n sys.exit()\n","sub_path":"samples/sample_keyevent2.py","file_name":"sample_keyevent2.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"625807611","text":"# Copyright 2012 OpenStack Foundation\n# Copyright 2013 IBM Corp.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport subprocess\n\nfrom oslo_log import log\nfrom oslo_serialization import jsonutils as json\n\nfrom tempest.common import compute\nfrom tempest.common import image as common_image\nfrom tempest.common.utils.linux import remote_client\nfrom tempest.common.utils import net_utils\nfrom tempest.common import waiters\nfrom tempest import config\nfrom tempest import exceptions\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib.common.utils import test_utils\nfrom tempest.lib import exceptions as lib_exc\nimport tempest.test\n\nCONF = config.CONF\n\nLOG = log.getLogger(__name__)\n\n\nclass ScenarioTest(tempest.test.BaseTestCase):\n \"\"\"Base class for scenario tests. Uses tempest own clients. \"\"\"\n\n credentials = ['primary']\n\n @classmethod\n def setup_clients(cls):\n super(ScenarioTest, cls).setup_clients()\n # Clients (in alphabetical order)\n cls.flavors_client = cls.os_primary.flavors_client\n cls.compute_floating_ips_client = (\n cls.os_primary.compute_floating_ips_client)\n if CONF.service_available.glance:\n # Check if glance v1 is available to determine which client to use.\n if CONF.image_feature_enabled.api_v1:\n cls.image_client = cls.os_primary.image_client\n elif CONF.image_feature_enabled.api_v2:\n cls.image_client = cls.os_primary.image_client_v2\n else:\n raise lib_exc.InvalidConfiguration(\n 'Either api_v1 or api_v2 must be True in '\n '[image-feature-enabled].')\n # Compute image client\n cls.compute_images_client = cls.os_primary.compute_images_client\n cls.keypairs_client = cls.os_primary.keypairs_client\n # Nova security groups client\n cls.compute_security_groups_client = (\n cls.os_primary.compute_security_groups_client)\n cls.compute_security_group_rules_client = (\n cls.os_primary.compute_security_group_rules_client)\n cls.servers_client = cls.os_primary.servers_client\n cls.interface_client = cls.os_primary.interfaces_client\n # Neutron network client\n cls.networks_client = cls.os_primary.networks_client\n cls.ports_client = cls.os_primary.ports_client\n cls.routers_client = cls.os_primary.routers_client\n cls.subnets_client = cls.os_primary.subnets_client\n cls.floating_ips_client = cls.os_primary.floating_ips_client\n cls.security_groups_client = cls.os_primary.security_groups_client\n cls.security_group_rules_client = (\n cls.os_primary.security_group_rules_client)\n\n cls.volumes_client = cls.os_primary.volumes_client_latest\n cls.snapshots_client = cls.os_primary.snapshots_client_latest\n\n # ## Test functions library\n #\n # The create_[resource] functions only return body and discard the\n # resp part which is not used in scenario tests\n\n def _create_port(self, network_id, client=None, namestart='port-quotatest',\n **kwargs):\n if not client:\n client = self.ports_client\n name = data_utils.rand_name(namestart)\n result = client.create_port(\n name=name,\n network_id=network_id,\n **kwargs)\n self.assertIsNotNone(result, 'Unable to allocate port')\n port = result['port']\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n client.delete_port, port['id'])\n return port\n\n def create_keypair(self, client=None):\n if not client:\n client = self.keypairs_client\n name = data_utils.rand_name(self.__class__.__name__)\n # We don't need to create a keypair by pubkey in scenario\n body = client.create_keypair(name=name)\n self.addCleanup(client.delete_keypair, name)\n return body['keypair']\n\n def create_server(self, name=None, image_id=None, flavor=None,\n validatable=False, wait_until='ACTIVE',\n clients=None, **kwargs):\n \"\"\"Wrapper utility that returns a test server.\n\n This wrapper utility calls the common create test server and\n returns a test server. The purpose of this wrapper is to minimize\n the impact on the code of the tests already using this\n function.\n \"\"\"\n\n # NOTE(jlanoux): As a first step, ssh checks in the scenario\n # tests need to be run regardless of the run_validation and\n # validatable parameters and thus until the ssh validation job\n # becomes voting in CI. The test resources management and IP\n # association are taken care of in the scenario tests.\n # Therefore, the validatable parameter is set to false in all\n # those tests. In this way create_server just return a standard\n # server and the scenario tests always perform ssh checks.\n\n # Needed for the cross_tenant_traffic test:\n if clients is None:\n clients = self.os_primary\n\n if name is None:\n name = data_utils.rand_name(self.__class__.__name__ + \"-server\")\n\n vnic_type = CONF.network.port_vnic_type\n\n # If vnic_type is configured create port for\n # every network\n if vnic_type:\n ports = []\n\n create_port_body = {'binding:vnic_type': vnic_type,\n 'namestart': 'port-smoke'}\n if kwargs:\n # Convert security group names to security group ids\n # to pass to create_port\n if 'security_groups' in kwargs:\n security_groups = \\\n clients.security_groups_client.list_security_groups(\n ).get('security_groups')\n sec_dict = dict([(s['name'], s['id'])\n for s in security_groups])\n\n sec_groups_names = [s['name'] for s in kwargs.pop(\n 'security_groups')]\n security_groups_ids = [sec_dict[s]\n for s in sec_groups_names]\n\n if security_groups_ids:\n create_port_body[\n 'security_groups'] = security_groups_ids\n networks = kwargs.pop('networks', [])\n else:\n networks = []\n\n # If there are no networks passed to us we look up\n # for the project's private networks and create a port.\n # The same behaviour as we would expect when passing\n # the call to the clients with no networks\n if not networks:\n networks = clients.networks_client.list_networks(\n **{'router:external': False, 'fields': 'id'})['networks']\n\n # It's net['uuid'] if networks come from kwargs\n # and net['id'] if they come from\n # clients.networks_client.list_networks\n for net in networks:\n net_id = net.get('uuid', net.get('id'))\n if 'port' not in net:\n port = self._create_port(network_id=net_id,\n client=clients.ports_client,\n **create_port_body)\n ports.append({'port': port['id']})\n else:\n ports.append({'port': net['port']})\n if ports:\n kwargs['networks'] = ports\n self.ports = ports\n\n tenant_network = self.get_tenant_network()\n\n body, servers = compute.create_test_server(\n clients,\n tenant_network=tenant_network,\n wait_until=wait_until,\n name=name, flavor=flavor,\n image_id=image_id, **kwargs)\n\n self.addCleanup(waiters.wait_for_server_termination,\n clients.servers_client, body['id'])\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n clients.servers_client.delete_server, body['id'])\n server = clients.servers_client.show_server(body['id'])['server']\n return server\n\n def create_volume(self, size=None, name=None, snapshot_id=None,\n imageRef=None, volume_type=None):\n if size is None:\n size = CONF.volume.volume_size\n if imageRef:\n image = self.compute_images_client.show_image(imageRef)['image']\n min_disk = image.get('minDisk')\n size = max(size, min_disk)\n if name is None:\n name = data_utils.rand_name(self.__class__.__name__ + \"-volume\")\n kwargs = {'display_name': name,\n 'snapshot_id': snapshot_id,\n 'imageRef': imageRef,\n 'volume_type': volume_type,\n 'size': size}\n volume = self.volumes_client.create_volume(**kwargs)['volume']\n\n self.addCleanup(self.volumes_client.wait_for_resource_deletion,\n volume['id'])\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n self.volumes_client.delete_volume, volume['id'])\n\n # NOTE(e0ne): Cinder API v2 uses name instead of display_name\n if 'display_name' in volume:\n self.assertEqual(name, volume['display_name'])\n else:\n self.assertEqual(name, volume['name'])\n waiters.wait_for_volume_resource_status(self.volumes_client,\n volume['id'], 'available')\n # The volume retrieved on creation has a non-up-to-date status.\n # Retrieval after it becomes active ensures correct details.\n volume = self.volumes_client.show_volume(volume['id'])['volume']\n return volume\n\n def create_volume_type(self, client=None, name=None, backend_name=None):\n if not client:\n client = self.admin_volume_types_client\n if not name:\n class_name = self.__class__.__name__\n name = data_utils.rand_name(class_name + '-volume-type')\n randomized_name = data_utils.rand_name('scenario-type-' + name)\n\n LOG.debug(\"Creating a volume type: %s on backend %s\",\n randomized_name, backend_name)\n extra_specs = {}\n if backend_name:\n extra_specs = {\"volume_backend_name\": backend_name}\n\n body = client.create_volume_type(name=randomized_name,\n extra_specs=extra_specs)\n volume_type = body['volume_type']\n self.assertIn('id', volume_type)\n self.addCleanup(client.delete_volume_type, volume_type['id'])\n return volume_type\n\n def _create_loginable_secgroup_rule(self, secgroup_id=None):\n _client = self.compute_security_groups_client\n _client_rules = self.compute_security_group_rules_client\n if secgroup_id is None:\n sgs = _client.list_security_groups()['security_groups']\n for sg in sgs:\n if sg['name'] == 'default':\n secgroup_id = sg['id']\n\n # These rules are intended to permit inbound ssh and icmp\n # traffic from all sources, so no group_id is provided.\n # Setting a group_id would only permit traffic from ports\n # belonging to the same security group.\n rulesets = [\n {\n # ssh\n 'ip_protocol': 'tcp',\n 'from_port': 22,\n 'to_port': 22,\n 'cidr': '0.0.0.0/0',\n },\n {\n # ping\n 'ip_protocol': 'icmp',\n 'from_port': -1,\n 'to_port': -1,\n 'cidr': '0.0.0.0/0',\n }\n ]\n rules = list()\n for ruleset in rulesets:\n sg_rule = _client_rules.create_security_group_rule(\n parent_group_id=secgroup_id, **ruleset)['security_group_rule']\n rules.append(sg_rule)\n return rules\n\n def _create_security_group(self):\n # Create security group\n sg_name = data_utils.rand_name(self.__class__.__name__)\n sg_desc = sg_name + \" description\"\n secgroup = self.compute_security_groups_client.create_security_group(\n name=sg_name, description=sg_desc)['security_group']\n self.assertEqual(secgroup['name'], sg_name)\n self.assertEqual(secgroup['description'], sg_desc)\n self.addCleanup(\n test_utils.call_and_ignore_notfound_exc,\n self.compute_security_groups_client.delete_security_group,\n secgroup['id'])\n\n # Add rules to the security group\n self._create_loginable_secgroup_rule(secgroup['id'])\n\n return secgroup\n\n def get_remote_client(self, ip_address, username=None, private_key=None):\n \"\"\"Get a SSH client to a remote server\n\n @param ip_address the server floating or fixed IP address to use\n for ssh validation\n @param username name of the Linux account on the remote server\n @param private_key the SSH private key to use\n @return a RemoteClient object\n \"\"\"\n\n if username is None:\n username = CONF.validation.image_ssh_user\n # Set this with 'keypair' or others to log in with keypair or\n # username/password.\n if CONF.validation.auth_method == 'keypair':\n password = None\n if private_key is None:\n private_key = self.keypair['private_key']\n else:\n password = CONF.validation.image_ssh_password\n private_key = None\n linux_client = remote_client.RemoteClient(ip_address, username,\n pkey=private_key,\n password=password)\n try:\n linux_client.validate_authentication()\n except Exception as e:\n message = ('Initializing SSH connection to %(ip)s failed. '\n 'Error: %(error)s' % {'ip': ip_address,\n 'error': e})\n caller = test_utils.find_test_caller()\n if caller:\n message = '(%s) %s' % (caller, message)\n LOG.exception(message)\n self._log_console_output()\n raise\n\n return linux_client\n\n def _image_create(self, name, fmt, path,\n disk_format=None, properties=None):\n if properties is None:\n properties = {}\n name = data_utils.rand_name('%s-' % name)\n params = {\n 'name': name,\n 'container_format': fmt,\n 'disk_format': disk_format or fmt,\n }\n if CONF.image_feature_enabled.api_v1:\n params['is_public'] = 'False'\n params['properties'] = properties\n params = {'headers': common_image.image_meta_to_headers(**params)}\n else:\n params['visibility'] = 'private'\n # Additional properties are flattened out in the v2 API.\n params.update(properties)\n body = self.image_client.create_image(**params)\n image = body['image'] if 'image' in body else body\n self.addCleanup(self.image_client.delete_image, image['id'])\n self.assertEqual(\"queued\", image['status'])\n with open(path, 'rb') as image_file:\n if CONF.image_feature_enabled.api_v1:\n self.image_client.update_image(image['id'], data=image_file)\n else:\n self.image_client.store_image_file(image['id'], image_file)\n return image['id']\n\n def glance_image_create(self):\n img_path = CONF.scenario.img_file\n img_container_format = CONF.scenario.img_container_format\n img_disk_format = CONF.scenario.img_disk_format\n img_properties = CONF.scenario.img_properties\n LOG.debug(\"paths: img: %s, container_format: %s, disk_format: %s, \"\n \"properties: %s\", img_path, img_container_format,\n img_disk_format, img_properties)\n image = self._image_create('scenario-img',\n img_container_format,\n img_path,\n disk_format=img_disk_format,\n properties=img_properties)\n LOG.debug(\"image:%s\", image)\n\n return image\n\n def _log_console_output(self, servers=None):\n if not CONF.compute_feature_enabled.console_output:\n LOG.debug('Console output not supported, cannot log')\n return\n if not servers:\n servers = self.servers_client.list_servers()\n servers = servers['servers']\n for server in servers:\n try:\n console_output = self.servers_client.get_console_output(\n server['id'])['output']\n LOG.debug('Console output for %s\\nbody=\\n%s',\n server['id'], console_output)\n except lib_exc.NotFound:\n LOG.debug(\"Server %s disappeared(deleted) while looking \"\n \"for the console log\", server['id'])\n\n def _log_net_info(self, exc):\n # network debug is called as part of ssh init\n if not isinstance(exc, lib_exc.SSHTimeout):\n LOG.debug('Network information on a devstack host')\n\n def create_server_snapshot(self, server, name=None):\n # Glance client\n _image_client = self.image_client\n # Compute client\n _images_client = self.compute_images_client\n if name is None:\n name = data_utils.rand_name(self.__class__.__name__ + 'snapshot')\n LOG.debug(\"Creating a snapshot image for server: %s\", server['name'])\n image = _images_client.create_image(server['id'], name=name)\n image_id = image.response['location'].split('images/')[1]\n waiters.wait_for_image_status(_image_client, image_id, 'active')\n\n self.addCleanup(_image_client.wait_for_resource_deletion,\n image_id)\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n _image_client.delete_image, image_id)\n\n if CONF.image_feature_enabled.api_v1:\n # In glance v1 the additional properties are stored in the headers.\n resp = _image_client.check_image(image_id)\n snapshot_image = common_image.get_image_meta_from_headers(resp)\n image_props = snapshot_image.get('properties', {})\n else:\n # In glance v2 the additional properties are flattened.\n snapshot_image = _image_client.show_image(image_id)\n image_props = snapshot_image\n\n bdm = image_props.get('block_device_mapping')\n if bdm:\n bdm = json.loads(bdm)\n if bdm and 'snapshot_id' in bdm[0]:\n snapshot_id = bdm[0]['snapshot_id']\n self.addCleanup(\n self.snapshots_client.wait_for_resource_deletion,\n snapshot_id)\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n self.snapshots_client.delete_snapshot,\n snapshot_id)\n waiters.wait_for_volume_resource_status(self.snapshots_client,\n snapshot_id,\n 'available')\n image_name = snapshot_image['name']\n self.assertEqual(name, image_name)\n LOG.debug(\"Created snapshot image %s for server %s\",\n image_name, server['name'])\n return snapshot_image\n\n def nova_volume_attach(self, server, volume_to_attach):\n volume = self.servers_client.attach_volume(\n server['id'], volumeId=volume_to_attach['id'], device='/dev/%s'\n % CONF.compute.volume_device_name)['volumeAttachment']\n self.assertEqual(volume_to_attach['id'], volume['id'])\n waiters.wait_for_volume_resource_status(self.volumes_client,\n volume['id'], 'in-use')\n\n # Return the updated volume after the attachment\n return self.volumes_client.show_volume(volume['id'])['volume']\n\n def nova_volume_detach(self, server, volume):\n self.servers_client.detach_volume(server['id'], volume['id'])\n waiters.wait_for_volume_resource_status(self.volumes_client,\n volume['id'], 'available')\n\n volume = self.volumes_client.show_volume(volume['id'])['volume']\n self.assertEqual('available', volume['status'])\n\n def rebuild_server(self, server_id, image=None,\n preserve_ephemeral=False, wait=True,\n rebuild_kwargs=None):\n if image is None:\n image = CONF.compute.image_ref\n\n rebuild_kwargs = rebuild_kwargs or {}\n\n LOG.debug(\"Rebuilding server (id: %s, image: %s, preserve eph: %s)\",\n server_id, image, preserve_ephemeral)\n self.servers_client.rebuild_server(\n server_id=server_id, image_ref=image,\n preserve_ephemeral=preserve_ephemeral,\n **rebuild_kwargs)\n if wait:\n waiters.wait_for_server_status(self.servers_client,\n server_id, 'ACTIVE')\n\n def ping_ip_address(self, ip_address, should_succeed=True,\n ping_timeout=None, mtu=None):\n timeout = ping_timeout or CONF.validation.ping_timeout\n cmd = ['ping', '-c1', '-w1']\n\n if mtu:\n cmd += [\n # don't fragment\n '-M', 'do',\n # ping receives just the size of ICMP payload\n '-s', str(net_utils.get_ping_payload_size(mtu, 4))\n ]\n cmd.append(ip_address)\n\n def ping():\n proc = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n proc.communicate()\n\n return (proc.returncode == 0) == should_succeed\n\n caller = test_utils.find_test_caller()\n LOG.debug('%(caller)s begins to ping %(ip)s in %(timeout)s sec and the'\n ' expected result is %(should_succeed)s', {\n 'caller': caller, 'ip': ip_address, 'timeout': timeout,\n 'should_succeed':\n 'reachable' if should_succeed else 'unreachable'\n })\n result = test_utils.call_until_true(ping, timeout, 1)\n LOG.debug('%(caller)s finishes ping %(ip)s in %(timeout)s sec and the '\n 'ping result is %(result)s', {\n 'caller': caller, 'ip': ip_address, 'timeout': timeout,\n 'result': 'expected' if result else 'unexpected'\n })\n return result\n\n def check_vm_connectivity(self, ip_address,\n username=None,\n private_key=None,\n should_connect=True,\n mtu=None):\n \"\"\"Check server connectivity\n\n :param ip_address: server to test against\n :param username: server's ssh username\n :param private_key: server's ssh private key to be used\n :param should_connect: True/False indicates positive/negative test\n positive - attempt ping and ssh\n negative - attempt ping and fail if succeed\n :param mtu: network MTU to use for connectivity validation\n\n :raises: AssertError if the result of the connectivity check does\n not match the value of the should_connect param\n \"\"\"\n if should_connect:\n msg = \"Timed out waiting for %s to become reachable\" % ip_address\n else:\n msg = \"ip address %s is reachable\" % ip_address\n self.assertTrue(self.ping_ip_address(ip_address,\n should_succeed=should_connect,\n mtu=mtu),\n msg=msg)\n if should_connect:\n # no need to check ssh for negative connectivity\n self.get_remote_client(ip_address, username, private_key)\n\n def check_public_network_connectivity(self, ip_address, username,\n private_key, should_connect=True,\n msg=None, servers=None, mtu=None):\n # The target login is assumed to have been configured for\n # key-based authentication by cloud-init.\n LOG.debug('checking network connections to IP %s with user: %s',\n ip_address, username)\n try:\n self.check_vm_connectivity(ip_address,\n username,\n private_key,\n should_connect=should_connect,\n mtu=mtu)\n except Exception:\n ex_msg = 'Public network connectivity check failed'\n if msg:\n ex_msg += \": \" + msg\n LOG.exception(ex_msg)\n self._log_console_output(servers)\n raise\n\n def create_floating_ip(self, thing, pool_name=None):\n \"\"\"Create a floating IP and associates to a server on Nova\"\"\"\n\n if not pool_name:\n pool_name = CONF.network.floating_network_name\n floating_ip = (self.compute_floating_ips_client.\n create_floating_ip(pool=pool_name)['floating_ip'])\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n self.compute_floating_ips_client.delete_floating_ip,\n floating_ip['id'])\n self.compute_floating_ips_client.associate_floating_ip_to_server(\n floating_ip['ip'], thing['id'])\n return floating_ip\n\n def create_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',\n private_key=None):\n ssh_client = self.get_remote_client(ip_address,\n private_key=private_key)\n if dev_name is not None:\n ssh_client.make_fs(dev_name)\n ssh_client.mount(dev_name, mount_path)\n cmd_timestamp = 'sudo sh -c \"date > %s/timestamp; sync\"' % mount_path\n ssh_client.exec_command(cmd_timestamp)\n timestamp = ssh_client.exec_command('sudo cat %s/timestamp'\n % mount_path)\n if dev_name is not None:\n ssh_client.umount(mount_path)\n return timestamp\n\n def get_timestamp(self, ip_address, dev_name=None, mount_path='/mnt',\n private_key=None):\n ssh_client = self.get_remote_client(ip_address,\n private_key=private_key)\n if dev_name is not None:\n ssh_client.mount(dev_name, mount_path)\n timestamp = ssh_client.exec_command('sudo cat %s/timestamp'\n % mount_path)\n if dev_name is not None:\n ssh_client.umount(mount_path)\n return timestamp\n\n def get_server_ip(self, server):\n \"\"\"Get the server fixed or floating IP.\n\n Based on the configuration we're in, return a correct ip\n address for validating that a guest is up.\n \"\"\"\n if CONF.validation.connect_method == 'floating':\n # The tests calling this method don't have a floating IP\n # and can't make use of the validation resources. So the\n # method is creating the floating IP there.\n return self.create_floating_ip(server)['ip']\n elif CONF.validation.connect_method == 'fixed':\n # Determine the network name to look for based on config or creds\n # provider network resources.\n if CONF.validation.network_for_ssh:\n addresses = server['addresses'][\n CONF.validation.network_for_ssh]\n else:\n creds_provider = self._get_credentials_provider()\n net_creds = creds_provider.get_primary_creds()\n network = getattr(net_creds, 'network', None)\n addresses = (server['addresses'][network['name']]\n if network else [])\n for address in addresses:\n if ((address['version'] ==\n CONF.validation.ip_version_for_ssh) and\n address['OS-EXT-IPS:type'] == 'fixed'):\n return address['addr']\n raise exceptions.ServerUnreachable(server_id=server['id'])\n else:\n raise lib_exc.InvalidConfiguration()\n","sub_path":"blazar_tempest_plugin/tests/scenario/manager_freeze.py","file_name":"manager_freeze.py","file_ext":"py","file_size_in_byte":29446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"468811945","text":"import pandas as pd \nfrom collections import defaultdict\nimport math\nimport copy\nimport json\nimport ast\ndata= pd.read_csv('input.csv')\n\noutput=[]\ncosts_list=[]\nfor instance in range(640):\n\tprint(instance+1)\n\tcosts=ast.literal_eval(data['Costs'].iloc[instance])\n\tdemand=ast.literal_eval(data['Demand'].iloc[instance])\n\tsupply=ast.literal_eval(data['Supply'].iloc[instance])\n\tcols = sorted(demand.keys())\n\tcosts1=copy.deepcopy(costs)\n\t# print(supply['S1'])\n\t# break\n\t# costs1=copy.deepcopy(costs)\n# \n\tcosts2=copy.deepcopy(costs)\n\tcosts3=copy.deepcopy(costs)\n\tfor i in supply:\n\t mi=min(costs[i].values())\n\t # print(costs[i])\n\t # print(mi)\n\t for j in costs2[i]:\n\t costs2[i][j]-=mi\n\t# print(costs2)\n\tfor i in demand :\n\t mi=10000\n\t for j in supply:\n\t if costs[j][i]=ma:\n\t\t\t\tsup=x \n\t\t# print(costs[sup][g[sup][0]], len(supply))\n\t\tif costs[sup][g[sup][0]]!=0 or len(supply)==1:\n\t\t\t# print(\"here\")\n\t\t\tv=min(supply[sup],demand[g[sup][0]])\n\t\t\t# print(sup,demand,v)\n\t\t\tdemand[g[sup][0]]-=v\n\t\t\tsupply[sup]-=v \n\t\t\tres[sup][g[sup][0]]+=v \n\t\t\tdem = g[sup][0]\n\t\t\t# print(sup,dem,v)\n\t\t\tif demand[dem]==0:\n\t\t\t\tfor k, n in supply.items():\n\t\t\t\t if n != 0:\n\t\t\t\t g[k].remove(dem)\n\t\t\t\tdel g[dem]\n\t\t\t\tdel demand[dem]\n\t\t\tif supply[sup]==0:\n\t\t\t\tfor k, n in demand.items():\n\t\t\t\t if n != 0:\n\t\t\t\t g[k].remove(sup)\n\t\t\t\tdel g[sup]\n\t\t\t\tdel supply[sup]\n\n\t\telse :\n\t\t\tmind=\"S\"\n\t\t\tma=-1\n\t\t\t# print(sup)\n\t\t\tfor x in supply :\n\t\t\t\tif s[x]>ma and x!=sup :\n\t\t\t\t\tma=s[x]\n\t\t\t\t\tmind=x\n\t\t\tgv1=0\n\t\t\t# print(mind,\"this\")\n\t\t\tfor y in demand:\n\t\t\t\tif costs[sup][y] > costs[mind][y]:\n\t\t\t\t\tgv1+=1 \n\t\t\t\telse:\n\t\t\t\t\tgv1-=1\n\t\t\tif gv1>=0 :\n\t\t\t\tv=min(supply[sup],demand[g[sup][0]])\n\t\t\t\t# print(sup,demand,v)\n\t\t\t\tdemand[g[sup][0]]-=v\n\t\t\t\tsupply[sup]-=v \n\t\t\t\tres[sup][g[sup][0]]+=v \n\t\t\t\tdem=g[sup][0]\n\t\t\t\t# print(sup,dem,v)\n\t\t\t\tif demand[dem]==0:\n\t\t\t\t\tfor k, n in supply.items():\n\t\t\t\t\t if n != 0:\n\t\t\t\t\t g[k].remove(dem)\n\t\t\t\t\tdel g[dem]\n\t\t\t\t\tdel demand[dem]\n\t\t\t\tif supply[sup]==0:\n\t\t\t\t\tfor k, n in demand.items():\n\t\t\t\t\t if n != 0:\n\t\t\t\t\t g[k].remove(sup)\n\t\t\t\t\tdel g[sup]\n\t\t\t\t\tdel supply[sup]\n\t\t\telse :\n\t\t\t\tsup=mind \n\t\t\t\tv=min(supply[sup],demand[g[sup][0]])\n\t\t\t\t\n\t\t\t\tdemand[g[sup][0]]-=v\n\t\t\t\tsupply[sup]-=v \n\t\t\t\tres[sup][g[sup][0]]+=v \n\t\t\t\tdem=g[sup][0]\n\t\t\t\t# print(sup,dem,v)\n\t\t\t\tif demand[dem]==0:\n\t\t\t\t\tfor k, n in supply.items():\n\t\t\t\t\t if n != 0:\n\t\t\t\t\t g[k].remove(dem)\n\t\t\t\t\tdel g[dem]\n\t\t\t\t\tdel demand[dem]\n\t\t\t\tif supply[sup]==0:\n\t\t\t\t\tfor k, n in demand.items():\n\t\t\t\t\t if n != 0:\n\t\t\t\t\t g[k].remove(sup)\n\t\t\t\t\tdel g[sup]\n\t\t\t\t\tdel supply[sup]\n\t\t# break\n\n\n\tprint(demand,supply)\t\n\t \n\t# print(costs1)\n\tcost = 0\n\tfor g in sorted(costs1):\n\t\t# print (g, \" \",)\n\t\tfor n in cols:\n\t\t\ty = res[g][n]\n\t\t\tif y != 0:\n\t\t\t\tpass\n\t\t\t\t# print (y,)\n\t\t\tcost += y * costs1[g][n]\n\t\t\t# print (\" \",)\n\t\t# print(\" \")\n\t# print (\"Total Cost = \", cost)\n\t\n\tcosts_list.append(cost)\n\t\n # 921541\nimport csv\nfrom itertools import zip_longest\ninstance_number=range(1,641)\nd = [instance_number,costs_list]\nexport_data = zip_longest(*d, fillvalue = '')\nwith open('TOCM_modified-MT.csv', 'w', encoding=\"ISO-8859-1\", newline='') as myfile:\n wr = csv.writer(myfile)\n wr.writerow((\"Instance\",\"Costs\"))\n wr.writerows(export_data)\nmyfile.close()\n","sub_path":"TOCM-MT/TOCM-MT.py","file_name":"TOCM-MT.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"293413073","text":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import GridSearchCV\n\nfrom repository import Repository\nfrom configuration import config\nimport math\n\nrepository = Repository(config)\ndataset, labels = repository.get_dataset_and_labels()\n\ndataset = dataset.fillna(-85)\nsize = dataset.size\n\ndataset = dataset.truncate(after=299)\nlabels= labels[:300]\n\n\n# Split the dataset into training (90 \\%) and testing (10 \\%)\nX_train, X_test, y_train, y_test = train_test_split(dataset, labels, test_size = 0.1)\n\ncv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)\n\n# Define the classifier to use\n#estimator = SVC(kernel=\"linear\",cache_size=310)\nestimator = SVC(kernel=\"linear\")\n\n# Define parameter space.\ngammas = np.logspace(-6, -1, 10)\n\n# Use Test dataset and use cross validation to find best hyper-parameters.\nCV_classifier = GridSearchCV(estimator=estimator, cv=cv ,param_grid=dict(gamma=gammas))\nCV_classifier.fit(X_train, [repository.locations.keys().index(tuple(l)) for l in y_train])\n\n# Test final results with the testing dataset\n\ndef find_accurancy(classifier):\n acc = classifier.score(X_test, [repository.locations.keys().index(tuple(i)) for i in y_test])\n print (\"accurancy = \", acc)\n\n\ndef find_error(classifier):\n predictY = [repository.locations.keys()[i] for i in classifier.predict(X_test)]\n #print (\"predictY: \", predictY)\n for lat, long in predictY:\n predictLat = lat\n predictLong = long\n # print y_test\n for lat, long in y_test:\n RealLat = lat\n RealLong = long\n DiffLat = predictLat - RealLat\n DiffLong = predictLong - RealLong\n Cst = math.pi / 180\n R = 6378.1\n\n Em = R * Cst * math.sqrt(math.pow(DiffLat, 2) + math.pow(DiffLong, 2))\n print (\"error = \", Em)\n\nfind_accurancy(CV_classifier)\nfind_error(CV_classifier)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"291956622","text":"with open(\"hada.txt\",\"r\") as file:\r\n lines = file.read().split(\"\\n\")\r\n\r\ndef pocet_hier(data):\r\n return len(data)\r\n\r\ndef najdljsia_hra(data):\r\n max_len = 0\r\n for i in data:\r\n if len(i)>max_len:\r\n max_len = len(i)\r\n return max_len\r\n\r\ndef kopiruj_subor(data):\r\n with open(\"hada_kopia.txt\",\"w\") as hada:\r\n for i in data:\r\n last_char = i[0]\r\n char_count = 0\r\n for char in i:\r\n if char != last_char:\r\n hada.write(last_char + str(char_count))\r\n last_char = char\r\n char_count = 1\r\n else:\r\n char_count += 1\r\n hada.write(f\"{last_char}{str(char_count)}\\n\")\r\n\r\nprint(pocet_hier(lines))\r\nprint(najdljsia_hra(lines))\r\nkopiruj_subor(lines)","sub_path":"inf_2022/Maturitne zadania/Zadanie 7/zadanie7.py","file_name":"zadanie7.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"156386959","text":"import col as col\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nimport statsmodels.api as sm\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.metrics import r2_score\r\n\r\ndf = pd.read_csv(\r\n 'C:\\\\Users\\\\vidya\\OneDrive\\\\Desktop\\\\Python_coding_practice_Datasets\\\\PythonDataSets\\\\Logistic_Regression\\\\archive\\\\wineQualityReds.csv', )\r\n\r\ncol = df.columns\r\ncol = [i.replace('.', '_') for i in col]\r\ndf.columns = col\r\nx = df[df.columns[1: -1]]\r\nprint(x.shape)\r\ny = df[df.columns[-1]]\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.75, random_state=44)\r\nprint()\r\n\r\nx_train_new = sm.add_constant(x_train)\r\nx_test_new = sm.add_constant(x_test)\r\n\r\nfull_mod = sm.OLS(y_train, x_train_new)\r\nfull_res = full_mod.fit()\r\n\r\nprint(full_res.summary())\r\n\r\nprint('Test r2', r2_score(y_test, full_res.predict(x_test_new)))\r\n\r\nprint('Variable Infaltion Factor')\r\n\r\ncol = list(x.columns)\r\nprint(col)\r\n\"\"\"\r\nfor i in (col):\r\n x_var = col\r\n y_var = x.pop(i)\r\n \r\n print(y_var)\r\n print(x_var)\r\n \r\n mod = sm.OLS(x_train[y_var], sm.add_constant(x_train[x_var]))\r\n mod = mod.fit()\r\n \r\n vif = 1/(1-mod.rsquared)\r\n print(y_var, round(vif, 3))\r\n\"\"\"\r\nprint(x.shape)\r\nx.drop(labels=['density', 'residual_sugar', 'fixed_acidity', 'citric_acid' ], inplace = True, axis=1)\r\nprint(x.shape)\r\n\r\ny = df['quality']\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.75, random_state=44)\r\nprint()\r\n\r\nx_train_new = sm.add_constant(x_train)\r\nx_test_new = sm.add_constant(x_test)\r\n\r\nfull_mod = sm.OLS(y_train, x_train_new)\r\nfull_res = full_mod.fit()\r\n\r\nprint(full_res.summary())\r\n\r\nprint('Variable Infaltion Factor')\r\ncol = list(x.columns)\r\nprint(col)","sub_path":"Linear_Regression/Multilinear_regrtession_Using_statsmodel_Library.py","file_name":"Multilinear_regrtession_Using_statsmodel_Library.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"568814665","text":"import torch\nfrom torch import nn\nimport numpy as np\nfrom .utils import *\nfrom itertools import product\nimport math\nimport matplotlib\nimport json\nfrom pandas.io.json import json_normalize\n\nclass Flow(nn.Module):\n\n def __init__(self, world):\n super(Flow, self).__init__()\n self.world = world\n\n def camera_center_wall_reference_dimension(self, camera_proximity_dimension, camera_wall_dimension):\n\t return (camera_proximity_dimension + camera_wall_dimension) / 2\n\n def estimate_dimension(self, measured_length, measured_height, hfov, vfov):\n\t return (measured_length/hfov + measured_height/vfov) / (1/hfov + 1/vfov)\n\n def estimate_distance(self, camera_known_proximity, camera_known_distant, \n\testimated_dimension, wall_reference_center_dimension, reference_dimensions,\n\talpha=1e-5):\n coefficient = 0.0;\n if(estimated_dimension < wall_reference_center_dimension):\n coefficient = (wall_reference_center_dimension - estimated_dimension) / (wall_reference_center_dimension - reference_dimensions[1]);\n\n return (np.exp(alpha * -coefficient) * camera_known_proximity + np.exp(alpha * coefficient) * camera_known_distant) / (np.exp(alpha * coefficient)+np.exp(alpha * -coefficient));\n elif(estimated_dimension > wall_reference_center_dimension):\n coefficient = (estimated_dimension - wall_reference_center_dimension) / (reference_dimensions[0] - wall_reference_center_dimension);\n\n return (np.exp(alpha * coefficient) * camera_known_proximity + np.exp(alpha * -coefficient) * camera_known_distant) / (np.exp(alpha * coefficient)+np.exp(alpha * -coefficient));\n else:\n return (camera_known_proximity + camera_known_distant) / 2\n\n # def view_from_detection(self):\n # view = json.load(open(\"plugin_config/camera.json\", \"r\"))\n # view_df = json_normalize(view)\n # return view_df.values\n\n def view_from_detection(self, detection, alpha=2.5):\n reference_dimensions = [144,117]\n z_values = []\n view = json.load(open(\"plugin_config/camera.json\", \"r\"))\n for det in detection[0][0].numpy():\n measured_length, measured_height = det[5] - det[3], det[6] - det[4]\n wall_reference_center_dimension = self.camera_center_wall_reference_dimension(144, 90)\n estimated_dimension = self.estimate_dimension(measured_length, measured_height, 60, 40)\n z_values.append(self.estimate_distance(0.75, 5, estimated_dimension, wall_reference_center_dimension, reference_dimensions, alpha=alpha))\n view['shutter_open']['camera']['x'] = 2.0\n view['shutter_open']['camera']['y'] = 2.0\n view['shutter_open']['camera']['z'] = 2.0\n view['shutter_open']['lookat']['x'] = 2.0\n view['shutter_open']['lookat']['y'] = 2.0\n view['shutter_open']['lookat']['z'] = np.mean(z_values)\n view['shutter_close']['camera']['x'] = 2.1\n view['shutter_close']['camera']['y'] = 2.1\n view['shutter_close']['camera']['z'] = 2.1\n view['shutter_close']['lookat']['x'] = 2.1\n view['shutter_close']['lookat']['y'] = 2.1\n view['shutter_close']['lookat']['z'] = np.mean(z_values) + 0.4\n return json_normalize(view).iloc[0,:]\n\n def optical_flow(self, points, shutter_open, shutter_close, alpha=0.5, shutter_time=(1.0/60),\n hfov=60, pixel_width=320, vfov=45, pixel_height=240):\n # Alpha is the linear interpolation coefficient, 0.5 takes the derivative in the midpoint\n # which is where the ground truth renders are taken. The photo render integrates via sampling\n # over the whole shutter open-close trajectory\n view_pose = self.world.pose.interpolate_poses(shutter_open,shutter_close,alpha)\n wTc = self.world.world_to_camera_with_pose(view_pose)\n camera_pose = self.world.pose.position_to_tensor({'x': view_pose[\"camera\"][\"x\"], 'y': view_pose[\"camera\"][\"y\"], 'z': view_pose[\"camera\"][\"z\"]})\n lookat_pose = self.world.pose.position_to_tensor({'x': view_pose[\"lookat\"][\"x\"], 'y': view_pose[\"lookat\"][\"y\"], 'z': view_pose[\"lookat\"][\"z\"]})\n\n # Get camera pixel scale constants\n uk = (pixel_width/2.0) * ((1.0/math.tan(math.radians(hfov/2.0))))\n vk = (pixel_height/2.0) * ((1.0/math.tan(math.radians(vfov/2.0))))\n\n # Get basis vectors\n ub1 = lookat_pose - camera_pose\n b1 = normalize_norm_np(ub1)\n ub2 = np.cross(b1,np.array([0,1,0]))\n b2 = normalize_norm_np(ub2)\n ub3 = np.cross(b2,b1)\n b3 = -normalize_norm_np(ub3)\n\n # Get camera pose alpha derivative\n camera_end = self.world.pose.position_to_tensor(shutter_close['camera'])\n camera_start = self.world.pose.position_to_tensor(shutter_open['camera'])\n lookat_end = self.world.pose.position_to_tensor(shutter_close['lookat'])\n lookat_start= self.world.pose.position_to_tensor(shutter_open['lookat'])\n dc_dalpha = camera_end - camera_start\n\n # Get basis vector derivatives\n # dub1 means d unnormalised b1\n db1_dub1 = (np.eye(3) - np.outer(b1,b1))/np.linalg.norm(ub1)\n dub1_dalpha = lookat_end - lookat_start - camera_end + camera_start\n db1_dalpha = db1_dub1.dot(dub1_dalpha)\n db2_dub2 = (np.eye(3) - np.outer(b2,b2))/np.linalg.norm(ub2)\n dub2_dalpha = np.array([-db1_dalpha[2],0,db1_dalpha[0]])\n db2_dalpha = db2_dub2.dot(dub2_dalpha)\n db3_dub3 = (np.eye(3) - np.outer(b3,b3))/np.linalg.norm(ub3)\n dub3_dalpha = np.array([\n -(db2_dalpha[2]*b1[1]+db1_dalpha[1]*b2[2]),\n -(db2_dalpha[0]*b1[2] + db1_dalpha[2]*b2[0])+(db2_dalpha[2]*b1[0]+db1_dalpha[0]*b2[2]),\n (db1_dalpha[1]*b2[0]+db2_dalpha[0]*b1[1])\n ])\n db3_dalpha = -db3_dub3.dot(dub3_dalpha)\n\n # derivative of the rotated translation offset\n dt3_dalpha = np.array([\n -db2_dalpha.dot(camera_pose)-dc_dalpha.dot(b2),\n -db3_dalpha.dot(camera_pose)-dc_dalpha.dot(b3),\n -db1_dalpha.dot(camera_pose)-dc_dalpha.dot(b1),\n ])\n\n # camera transform derivative\n dT_dalpha = np.empty((4,4))\n dT_dalpha[0,:3] = db2_dalpha\n dT_dalpha[1,:3] = db3_dalpha\n dT_dalpha[2,:3] = db1_dalpha\n dT_dalpha[:3,3] = dt3_dalpha\n\n # Calculate 3D point derivative alpha derivative\n \n # error in matmul operation\n dpoint_dalpha = torch.matmul(points.t().double(), torch.from_numpy(dT_dalpha).double()).t()\n point_in_camera_coords = torch.matmul(points.t().double(), torch.from_numpy(wTc).double()).t()\n\n # Calculate pixel location alpha derivative\n du_dalpha = uk * (dpoint_dalpha[0] * point_in_camera_coords[2] - dpoint_dalpha[2] * point_in_camera_coords[0])\n dv_dalpha = vk * (dpoint_dalpha[1] * point_in_camera_coords[2] - dpoint_dalpha[2] * point_in_camera_coords[1])\n du_dalpha = du_dalpha/(point_in_camera_coords[2]*point_in_camera_coords[2])\n dv_dalpha = dv_dalpha/(point_in_camera_coords[2]*point_in_camera_coords[2])\n\n # Calculate pixel location time derivative\n du_dt = du_dalpha / shutter_time\n dv_dt = dv_dalpha / shutter_time\n return torch.cat((du_dt.view(-1,1),dv_dt.view(-1,1)),dim=1)\n\n @staticmethod\n def flow_to_hsv_image(self, flow, magnitude_scale=1.0/100.0):\n\n height = self.world.pose.height\n width = self.world.pose.width\n pixel = np.meshgrid(np.arange(0,height), np.arange(0,width))\n hsv = np.zeros((height,width,3))\n v = np.linalg.norm(flow.detach().numpy().astype(np.float64), axis=2)\n idxs = np.where(v < 1e-8)\n hsv[idxs[0],idxs[1],0:3] = 0.0\n idxs = np.where(v >= 1e-8)\n direction = flow[idxs[0],idxs[1],:] / np.expand_dims(v[idxs],1)\n theta = np.arctan2(direction[:,1].detach().numpy().astype(np.float64),direction[:,0].detach().numpy().astype(np.float64))\n theta[theta<=0] = theta[theta<=0] + 2*np.pi\n if np.sum((theta < 0) | (theta > 2*np.pi)) > 0:\n raise Exception(\"Invalid value for theta\")\n\n values = v[idxs].flatten() * magnitude_scale\n values[values > 1] = 1.0\n hsv[idxs[0],idxs[1],0] = theta / (2*np.pi)\n hsv[idxs[0],idxs[1],1] = 1.0\n hsv[idxs[0],idxs[1],2] = values\n return torch.from_numpy(hsv)\n\n @staticmethod\n def hsv_to_rgb(hsv):\n \"\"\"\n Convert hsv values to rgb.\n\n Parameters\n ----------\n hsv : (..., 3) array-like\n All values assumed to be in range [0, 1]\n\n Returns\n -------\n rgb : (..., 3) ndarray\n Colors converted to RGB values in range [0, 1]\n \"\"\"\n\n # check length of the last dimension, should be _some_ sort of rgb\n if hsv.shape[-1] != 3:\n raise ValueError(\"Last dimension of input array must be 3; \"\n \"shape {shp} was found.\".format(shp=hsv.shape))\n\n in_shape = hsv.shape\n\n h = hsv[:,:, 0]\n s = hsv[:,:, 1]\n v = hsv[:,:, 2]\n\n r = torch.empty(h.shape).double()\n g = torch.empty(h.shape).double()\n b = torch.empty(h.shape).double()\n\n i = (h * 6.0).int()\n f = (h * 6.0) - i\n p = v * (1.0 - s)\n q = v * (1.0 - s * f)\n t = v * (1.0 - s * (1.0 - f))\n\n idx = i % 6 == 0\n r[idx] = v[idx]\n g[idx] = t[idx]\n b[idx] = p[idx]\n\n idx = i == 1\n r[idx] = q[idx]\n g[idx] = v[idx]\n b[idx] = p[idx]\n\n idx = i == 2\n r[idx] = p[idx]\n g[idx] = v[idx]\n b[idx] = t[idx]\n\n idx = i == 3\n r[idx] = p[idx]\n g[idx] = q[idx]\n b[idx] = v[idx]\n\n idx = i == 4\n r[idx] = t[idx]\n g[idx] = p[idx]\n b[idx] = v[idx]\n\n idx = i == 5\n r[idx] = v[idx]\n g[idx] = p[idx]\n b[idx] = q[idx]\n\n idx = s == 0\n r[idx] = v[idx]\n g[idx] = v[idx]\n b[idx] = v[idx]\n\n rgb = torch.cat([r.unsqueeze(2), g.unsqueeze(2), b.unsqueeze(2)],dim=2)\n # rgb = np.concatenate([np.expand_dims(r,2), np.expand_dims(g,2), np.expand_dims(b,2)],axis=2)\n\n return rgb.reshape(in_shape)\n \n def compute_flow(self, depth_map, view):\n\n cached_pixel_to_ray_array = self.world.pose.normalised_pixel_to_ray_array()\n\n # This is a 320x240x3 array, with each 'pixel' containing the 3D point in camera coords\n points_in_camera = self.world.points_in_camera_coords(depth_map, cached_pixel_to_ray_array)\n\n # Transform point from camera coordinates into world coordinates\n ground_truth_pose = self.world.pose.interpolate_poses(build_shutter_open_view(view),build_shutter_close_view(view),0.5)\n camera_to_world_matrix = self.world.camera_to_world_with_pose(ground_truth_pose)\n\n # error in matmul\n points_in_world = (torch.matmul(points_in_camera.view(-1,4).double(), camera_to_world_matrix.double())).t()\n\n optical_flow_derivatives = self.optical_flow(points_in_world,build_shutter_open_view(view),build_shutter_close_view(view))\n optical_flow_derivatives = optical_flow_derivatives.view(self.world.pose.height,self.world.pose.width,2)\n\n # Write out hsv optical flow image. We use the matplotlib hsv colour wheel\n # hsv = self.flow_to_hsv_image(optical_flow_derivatives)\n # rgb = self.hsv_to_rgb(hsv)\n\n return optical_flow_derivatives\n\n def forward(self, depth_map, detection):\n\n view = self.view_from_detection(detection)\n view = convert_view_to_df(view)\n return self.compute_flow(depth_map, view)\n\n","sub_path":"student-repositories/motion-tracking/network/Flow.py","file_name":"Flow.py","file_ext":"py","file_size_in_byte":11690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"495444003","text":"'''\n\"Base-level\" objects which represent Pages and Elements.\n\nNone of these are intended to be instantiated directly.\n'''\n\nimport logging\nimport time\n\nfrom utils.exceptions import Timeout\n\n# This variable is for the WebDriver object. It must be set before any Page\n# Objects can be instantiated. It will effectively be a global variable, but\n# should cause no problems assuming no test requires multiple browser\n# instances.\ndriver = None\n\nclass Loading(object):\n '''\n Defines a wait_for_load() method.\n\n All Page classes and many Element classes will need time to load before they\n can be acted upon. Such classes can inherit from this one. Such classes\n must also define their own is_loaded() methods, since, obviously, the\n definition of an Page or Element being \"loaded\" will differ.\n '''\n\n def wait_for_load(self, time_limit=5.0):\n '''\n Waits for the page or element to finish loading.\n\n Parameters\n ----------\n time_limit : int or float, optional\n\n Returns\n -------\n None\n\n Raises\n ------\n Timeout\n If time limit is exceeded.\n '''\n end_time = time.time() + time_limit\n while time.time() < end_time:\n time.sleep(0.5)\n if self.is_loaded():\n logging.info('Object loaded.')\n return\n logging.debug('Object not loaded yet.')\n log_str = 'Object did not load.'\n logging.error(log_str)\n raise Timeout(log_str)\n\nclass Clickable(Loading):\n '''\n Defines a click() method.\n\n Because executing a WebElement's click() method often includes adding a\n short wait, plus logging statements, it would be handy to define our own\n click() method.\n '''\n\n def click(self):\n logging.info('Clicking element.')\n self.webelement.click()\n time.sleep(0.5)\n return\n\nclass BasePage(Loading):\n '''\n Class which represents a webpage.\n '''\n\n def __init__(self):\n if driver == None:\n raise Exception('page_objects.base.driver variable must be set to the WebDriver before any Page or Element Objects can be instantiated.')\n self.driver = driver\n\nclass BaseElement(object):\n '''\n Class which represents an element on a webpage.\n\n While handling everything on a page can be coded within a Page object,\n that will result in the object becoming \"bigger than your head.\" Use an\n Element object to make the Page object smaller and easier to read.\n\n Init\n ----\n webelement : WebElement\n Element objects will reference a single specific element on the page.\n That WebElement must first be found before using it to initialize this\n object. It should be found using a Page object, since that contains\n the relevant locators and the WebDriver itself, which contains the\n relevant find_element(s) methods.\n '''\n\n def __init__(self, webelement):\n if driver == None:\n raise Exception('page_objects.base.driver variable must be set to the WebDriver before any Page or Element Objects can be instantiated.')\n self.webelement = webelement\n\nclass LoadingElement(BaseElement, Loading):\n pass\n","sub_path":"page_objects/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"272167560","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog\nfrom EDEui import Ui_MainWindow as EDEui\nimport Codec\nfrom random import randint\nfrom pathlib import Path\n\n\ndef show_error(e: str):\n ###\n # Show error message\n\n msg = QtWidgets.QMessageBox()\n msg.setIcon(QtWidgets.QMessageBox.Critical)\n msg.setWindowTitle('Error')\n msg.setText(e)\n msg.exec_()\n\n\nclass EDECore(EDEui):\n key = 0\n\n def setup_callbacks(self):\n # connect callbacks with buttons\n\n self.input.textChanged.connect(self.cypher_callback)\n #self.decrypt_mode.clicked.connect(self.switch_mode_callback)\n self.decrypt_mode.toggled['bool'].connect(self.switch_mode_callback)\n # self.encrypt_mode.clicked.connect(self.switch_mode_callback)\n self.encrypt_mode.toggled['bool'].connect(self.switch_mode_callback)\n self.enable_encrypting_cb.clicked.connect(self.cypher_callback)\n\n self.code_rb.clicked.connect(self.cypher_callback)\n self.char_rb.clicked.connect(self.cypher_callback)\n\n self.rand_b.clicked.connect(self.rand_b_callback)\n self.key_input.textChanged.connect(self.set_key_callback)\n self.key_input.setValidator(QtGui.QIntValidator())\n\n # Connect with file menu\n self.actionOpen.triggered.connect(self.open_file)\n self.actionSave.triggered.connect(self.save_file)\n\n def switch_mode_callback(self, enabled: bool):\n\n if not enabled:\n return\n\n in_ = self.input.toPlainText()\n out_ = self.output.toPlainText()\n\n self.input.setPlainText(out_)\n self.output.setPlainText(in_)\n\n if self.encrypt_mode.isChecked():\n self.output_box.setTitle('Encrypted')\n elif self.decrypt_mode.isChecked():\n self.output_box.setTitle('Decrypted')\n\n def cypher_callback(self):\n # cypher here\n if not self.enable_encrypting_cb.isChecked():\n return\n\n try:\n str_in = self.input.toPlainText()\n\n if self.encrypt_mode.isChecked():\n str_in = Codec.encrypt(str_in, self.key)\n str_in = Codec.str_to_codes(str_in)\n elif self.decrypt_mode.isChecked():\n str_in = Codec.codes_to_str(str_in)\n str_in = Codec.decrypt(str_in, self.key)\n\n self.output.setPlainText(str_in)\n except:\n pass\n\n def set_key_callback(self):\n new_key = self.key_input.text()\n\n try:\n self.key = int(new_key, base=10) if new_key is not '' else 0\n self.cypher_callback()\n except Exception as e:\n self.key = 0\n\n def rand_b_callback(self):\n # random value in settings\n\n if self.encrypt_mode.isChecked():\n self.key = randint(0, 4095)\n elif self.decrypt_mode.isChecked():\n self.key = randint(-4096, 0)\n\n self.key_input.setText(str(self.key))\n self.cypher_callback()\n\n # Fileo added\n def __check_path(self, path: str):\n return True if path not in ('', None) and \\\n Path(path).exists() and \\\n Path(path).resolve().suffix == '.txt' else False\n \n def open_file(self):\n path = QFileDialog.getOpenFileName()\n \n if self.__check_path(path[0]):\n try:\n with open(path[0], 'rb') as f:\n txt = f.read()\n self.input.setPlainText(txt.decode('utf-8', 'ignore'))\n except Exception as e:\n show_error(str(e))\n\n elif path[0] not in ('', None):\n show_error('Select *.txt file please')\n\n def save_file(self):\n path = QFileDialog.getSaveFileName(filter='.txt', initialFilter='.txt')\n\n if path[0] not in ('', None):\n\n with open(path[0] + path[1], 'wb') as f:\n ws = self.output.toPlainText()\n try:\n f.write(ws.encode('utf-8', 'ignore'))\n except Exception as e:\n print(e)\n","sub_path":"ISL1/EDECore.py","file_name":"EDECore.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"154274158","text":"import unittest\nfrom problem_14 import calculateTotalStep,calculateTotalStepTo\n\nclass problem14Test(unittest.TestCase):\n\n\tdef test_calculateTotalStep_shouldReturn2_WhenInputIs2(self):\n\t\tself.assertEquals(2,calculateTotalStep(2))\n\t\tself.assertEquals(9,calculateTotalStep(6))\n\n\n\t\n\nif __name__ == '__main__':\n\tunittest.main()\n\t\t","sub_path":"euler/test_problem_14.py","file_name":"test_problem_14.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"571591937","text":"# coding=utf8\n\n__author__ = 'Alexander.Li'\n\nimport redis\nimport threading\nimport logging\n\nclass SingletonMixin(object):\n __singleton_lock = threading.Lock()\n __singleton_instance = None\n\n @classmethod\n def instance(cls):\n if not cls.__singleton_instance:\n with cls.__singleton_lock:\n if not cls.__singleton_instance:\n cls.__singleton_instance = cls()\n\n return cls.__singleton_instance\n\n\nclass RedisConnection(SingletonMixin):\n def __init__(self):\n self.redis = None\n self.connected = False\n self.configure = None\n\n def initConnection(self, configure):\n self.configure = configure\n\n def reconnect(self):\n if not self.connected:\n self.redis = redis.StrictRedis(host=self.configure.redis_host, port=self.configure.redis_port)\n self.connected = True\n\n def waitfor(self):\n self.reconnect()\n logging.info('redis watch key: %s', self.configure.watch_key)\n resp = self.redis.brpop(self.configure.watch_key, timeout=60)\n logging.info('redis returned:%s', resp)\n if resp:\n _, message = resp\n return message\n\n def push_queue(self, value):\n self.reconnect()\n self.redis.rpush(self.configure.watch_key, value)\n\n","sub_path":"filebeat_delegate/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"197761815","text":"import payload\nimport sys\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n#the following variables setup the system\nFc = 1000 #simulate a carrier frequency of 1kHz\nFbit = 50 #simulated bitrate of data\nFdev = 500 #frequency deviation, make higher than bitrate\nN = 64 #how many bits to send\nA = 1 #transmitted signal amplitude\nFs = 10000 #sampling frequency for the simulator, must be higher than twice the carrier frequency\nA_n = 0.1 #noise peak amplitude\nN_prntbits = 10 #number of bits to print in plots\n\namp = 1\nf0 = 17000\nf1 = 18000\nf2 = 19000\nf3 = 20000\nx_t = np.linspace(0, 3, 1024)\n\n\n\ndef FSK_modulator(bit0, bit1, f0, f1, f2, f3, amp, x_t, phase=0, T_RES=1024):\n \"\"\" FSk modulator for 2 bit, with f0, f1, f2, f3 and it's time \n \n \"\"\"\n freq0 = f0 if bit0==0 else f1\n freq1 = f2 if bit1==0 else f3\n signal = amp * np.cos(2 * np.pi * freq0 * x_t + phase) + \\\n amp * np.cos(2 * np.pi * freq1 * x_t + phase)\n return np.hanning(T_RES)*signal\ndef FSK_bin_fix(string):\n while(len(string)<8):\n string = '0' + string\n return string\ndef FSK_string_fix(string):\n my_string_len = str (len(string))\n if(len(string)>255):\n print(\"sorry i can't sent thest str\")\n return -1\n elif(len(string)>=0 and len(string)<10):\n my_string_len = \"00\"+my_string_len\n elif(len(string)>=10 and len(string)<100):\n my_string_len = \"0\"+my_string_len\n else:\n my_string_len = my_string_len\n return my_string_len\n\ndef FSK_num_fix(num):\n my_string_len = str(num)\n if(num>255):\n print(\"sorry i can't sent thest str\")\n return -1\n elif(num>=0 and num<10):\n my_string_len = \"00\"+my_string_len\n elif(num>=10 and num<100):\n my_string_len = \"0\"+my_string_len\n else:\n my_string_len = my_string_len\n return my_string_len\n\ndef FSK_string_to_binStr(string):\n ''' transmit len of string is limit to 253'''\n my_fix_top = \"UW\" # top 0x55 0x57\n my_string_len = FSK_string_fix(string)\n print(my_string_len)\n my_encode_string = my_fix_top + my_string_len + string\n string_sum_num = 0\n my_binStr =\"\"\n for i in my_encode_string:\n string_sum_num = string_sum_num + ord(i)\n string_crc = string_sum_num%255\n string_crc = FSK_num_fix(string_crc)\n my_encode_string = my_encode_string + string_crc#generate full data\n for j in my_encode_string:\n print(FSK_bin_fix(bin(ord(j)).replace('0b','')))\n my_binStr = my_binStr + FSK_bin_fix(bin(ord(j)).replace('0b',''))\n return my_binStr\n\n# ttt = FSK_string_to_binStr(\"he\")\n# print(ttt)\n#plt.figure(1) # 创建图表1\n#plt.plot(x_t, FSK_modulator(0, 0, f0, f1, f2, f3, amp, x_t))\n#plt.show()\n\n#print(FSK_crc(255))","sub_path":"fsk.py","file_name":"fsk.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"265008644","text":"import os\nimport redis\nimport datetime\nimport time\nfrom urllib.parse import urlparse\nfrom werkzeug.wrappers import Request, Response\nfrom werkzeug.routing import Map, Rule\nfrom werkzeug.exceptions import HTTPException, NotFound\nfrom werkzeug.wsgi import SharedDataMiddleware\nfrom werkzeug.utils import redirect\nfrom jinja2 import Environment, FileSystemLoader\n\n\ndef get_hostname(url):\n return urlparse(url).netloc\n\n\nclass AdBoard(object):\n def __init__(self, config):\n self.redis = redis.Redis(config['redis_host'], config['redis_port'])\n template_path = os.path.join(os.path.dirname(__file__), 'templates')\n self.jinja_env = Environment(loader=FileSystemLoader(template_path),\n autoescape=True)\n\n self.jinja_env.filters['hostname'] = get_hostname\n\n self.url_map = Map([\n Rule('/', endpoint='board_list'),\n Rule('/add_new_board', endpoint='add_new_board'),\n Rule('/', endpoint='single_board'),\n Rule('//add_new_comment', endpoint='add_new_comment'),\n ])\n\n def on_board_list(self, request):\n boards = self.redis.keys('board:*')\n ads = []\n if boards is None:\n return self.render_template('add_new_board.html')\n else:\n for board_key in boards:\n board_name = self.redis.get(board_key).decode(\"utf-8\")\n board_author = self.redis.get('author:' + board_key.decode(\"utf-8\")).decode(\"utf-8\")\n board_date = datetime.datetime.fromtimestamp(\n int(self.redis.get('date_created:' + board_key.decode(\"utf-8\")).decode(\"utf-8\"))\n ).strftime('%Y-%m-%d %H:%M:%S')\n ad = {'name': board_name, 'author': board_author, 'date': board_date, 'id':board_key.decode('utf-8').split(':')[1]}\n ads.append(ad)\n return self.render_template('home.html', boards=ads)\n\n def on_add_new_board(self, request):\n if request.method == 'POST':\n # adds new board to redis with the folowing fields:\n name = request.form['title']\n author = request.form['author']\n self.insert_new_board(name, author)\n return redirect('/')\n return self.render_template('add_new_board.html')\n\n def on_single_board(self, request, board_id):\n # outputs single board with the comments\n board_name = self.redis.get('board:' + board_id)\n if board_name is None:\n raise NotFound()\n board_author = self.redis.get('author:board:' + board_id).decode('utf-8')\n board_date = datetime.datetime.fromtimestamp(int(self.redis.get('date_created:' + 'board:' + board_id).decode(\"utf-8\"))\n ).strftime('%Y-%m-%d %H:%M:%S')\n comments = self.get_comments(board_id)\n return self.render_template('single_board.html', id=board_id, name=board_name, author=board_author, date=board_date, comments=comments)\n\n def on_add_new_comment(self, request, board_id):\n if request.method == 'POST':\n body = request.form['body']\n author = request.form['author']\n self.insert_new_comment(board_id, author, body)\n return redirect('/%s' % board_id)\n\n def insert_new_board(self, name, author):\n boards = self.redis.keys('board:*')\n if len(boards) == 0:\n board_key = 'board:1'\n else:\n boards.sort()\n max_key = boards[-1].decode('utf-8') if len(boards) > 1 else boards[0].decode('utf-8')\n prefix,num = max_key.split(':')\n board_key = 'board:'+str(int(num)+1)\n self.redis.set(board_key, name)\n self.redis.set('author:'+board_key, author)\n self.redis.set('date_created:'+board_key, int(time.time()))\n\n def insert_new_comment(self, board_id, author, comment):\n comments = self.redis.keys('commentboard'+board_id+\":*\")\n if len(comments) == 0:\n comments_key = 'commentboard'+board_id+':1'\n else:\n comments.sort()\n max_key = comments[-1].decode('utf-8') if len(comments) > 1 else comments[0].decode('utf-8')\n prefix,num = max_key.split(':')\n comments_key = 'commentboard'+board_id+':'+str(int(num)+1)\n self.redis.set('author:'+comments_key, author)\n self.redis.set(comments_key, comment)\n\n def get_comments(self, board_id):\n comment_keys = self.redis.keys('commentboard' + board_id+\":*\")\n comments = []\n for comment_key in comment_keys:\n comment = self.redis.get(comment_key).decode(\"utf-8\")\n comment_author = self.redis.get('author:' + comment_key.decode(\"utf-8\")).decode(\"utf-8\")\n comments.append({'author': comment_author, 'body': comment})\n return comments\n\n def render_template(self, template_name, **context):\n t = self.jinja_env.get_template(template_name)\n return Response(t.render(context), mimetype='text/html')\n\n def dispatch_request(self, request):\n adapter = self.url_map.bind_to_environ(request.environ)\n try:\n endpoint, values = adapter.match()\n return getattr(self, 'on_' + endpoint)(request, **values)\n except HTTPException as e:\n return e\n\n def wsgi_app(self, environ, start_response):\n request = Request(environ)\n response = self.dispatch_request(request)\n return response(environ, start_response)\n\n def __call__(self, environ, start_response):\n return self.wsgi_app(environ, start_response)\n\n\ndef create_app(redis_host='localhost', redis_port=6379, with_static=True):\n app = AdBoard({\n 'redis_host': redis_host,\n 'redis_port': redis_port\n })\n if with_static:\n app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {\n '/static': os.path.join(os.path.dirname(__file__), 'static')\n })\n return app\n\n\nif __name__ == '__main__':\n from werkzeug.serving import run_simple\n\n app = create_app()\n run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True)\n","sub_path":"adboard.py","file_name":"adboard.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"650521655","text":"import csv\nimport sys\nimport pandas as pd\nimport requests\nimport io\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nall_link='https://www.bag.admin.ch/dam/bag/de/dokumente/mt/k-und-i/aktuelle-ausbrueche-pandemien/2019-nCoV/covid-19-basisdaten-fallzahlen.xlsx.download.xlsx/Dashboards_1&2_COVID19_swiss_data_pv.xlsx'\n\npopulation_link='https://www.bag.admin.ch/dam/bag/de/dokumente/mt/k-und-i/aktuelle-ausbrueche-pandemien/2019-nCoV/covid-19-basisdaten-bevoelkerungszahlen.xlsx.download.xlsx/Population_Size_BFS.xlsx'\n\ncantons_DE={\n 'AG': 'Aargau', \n 'AR': 'Appelzell Ausserrhoden',\n 'AI': 'Appenzell Innerrhoden',\n 'BL': 'Basel-Landschaft',\n 'BS': 'Basel-Stadt',\n 'BE': 'Bern',\n 'FR': 'Freiburg',\n 'GE': 'Genf',\n 'GL': 'Glarus',\n 'GR': 'Graubünden',\n 'JU': 'Jura',\n 'LU': 'Luzern',\n 'NE': 'Neuenburg',\n 'NW': 'Nidwalden',\n 'OW': 'Obwalden',\n 'SH': 'Schaffhausen',\n 'SZ': 'Schwyz',\n 'SO': 'Solothurn',\n 'SG': 'St. Gallen',\n 'TI': 'Tessin',\n 'TG': 'Thurgau',\n 'UR': 'Uri',\n 'VD': 'Waadt',\n 'VS': 'Wallis',\n 'ZG': 'Zug',\n 'ZH': 'Zürich'}\nregions_DE={\n 'Genferseeregion' : ['GE', 'VD', 'VS'],\n 'Espace Mittelland' : ['BE', 'JU', 'FR', 'NE', 'SO'],\n 'Nordwestschweiz' : ['BS', 'BL', 'AG'],\n 'Zürich' : ['ZH'],\n 'Ostschweiz' : ['SG', 'TG', 'AI', 'AR', 'GL', 'SH', 'GR'],\n 'Zentralschweiz' : ['UR', 'SZ', 'OW', 'NW', 'LU', 'ZG'],\n 'Tessin' : ['TI']\n }\n\n\nexcel_all=requests.get(all_link).content\nexcel_population=requests.get(population_link).content\ncases_df=pd.ExcelFile(excel_all).parse().set_index(\"fall_dt\")\ndeaths_df=pd.ExcelFile(excel_all).parse().set_index(\"pttoddat\")\npopulation_df=pd.ExcelFile(excel_population).parse()\n\ncases_df=cases_df[cases_df.index.notnull()]\ndeaths_df=deaths_df[deaths_df.index.notnull()]\n\ncases_df.reset_index(inplace=True)\ndeaths_df.reset_index(inplace=True)\n\ncases_df.rename(columns={'fall_dt': 'date', 'ktn': 'canton', 'akl': 'age', 'fallklasse_3':'cases'}, inplace=True) \ndeaths_df.rename(columns={'pttoddat': 'date', 'ktn': 'canton', 'akl': 'age', 'pttod_1':'deaths'}, inplace=True) \npopulation_df.rename(columns={'ktn':'canton', 'Geschlecht':'sex', 'akl':'age', 'pop_size':'population'}, inplace=True)\n\ncases_df['sex'].replace(to_replace={1:'male', 2:'female', 9:'unknown'}, inplace=True)\ndeaths_df['sex'].replace(to_replace={1:'male', 2:'female', 9:'unknown'}, inplace=True)\npopulation_df['sex'].replace(to_replace={'Männlich':'male', 'Weiblich':'female'}, inplace=True)\n\ncases_index=pd.MultiIndex.from_frame(cases_df[['date', 'canton', 'age', 'sex']])\ndeaths_index=pd.MultiIndex.from_frame(deaths_df[['date', 'canton', 'age', 'sex']])\npopulation_index=pd.MultiIndex.from_frame(population_df[['canton','age','sex']])\n\ncases_df.set_index(cases_index, inplace=True)\ndeaths_df.set_index(deaths_index, inplace=True)\n\npopulation_df.set_index(population_index, inplace=True)\n\ncases_df=cases_df[['cases']]\ndeaths_df=deaths_df[['deaths']]\npopulation_df=population_df[['population']]\ndf=cases_df.join(deaths_df, how='outer')\npopulation_df = population_df.groupby(['canton','age','sex']).sum()\nprint(population_df)\n\n#df=cases_df[['cases']].merge(deaths_df[['deaths']], left_index=True, right_on=['date', 'canton','age', 'sex'])\n\ndf.fillna(value=0, inplace=True)\ndf=df.join(population_df, how='outer')\nprint(df.groupby(['date','age']).sum())\n\ndf_prevalence=df.groupby(['date', 'age']).sum()\ndf_prevalence['prevalence per 100 000']=df_prevalence['cases']/df_prevalence['population']*100000\nprint(df_prevalence)\nprint(df.groupby(['age']).sum())\nprint(df.query('canton in [\"BE\",\"ZH\"]').groupby('canton').sum())\nprint(df.xs('BE', level='canton', drop_level=False))\nprint(df.xs('BE', level='canton', drop_level=False).groupby(['age']).sum())\nprint(df.sum())\n#df.xs('BE', level='canton', drop_level=False).groupby(['date']).sum().plot()\n#df.xs('BE', level='canton', drop_level=False).groupby(['date']).sum().rolling(window=7).mean().plot()\n#plt.show()\n\ndf_all=df\n\n\ndf_ch_cantons = df[['cases']].groupby(['date', 'canton']).sum().unstack(level='canton')\ndf_ch_cantons.columns = df_ch_cantons.columns.droplevel(0)\ndf_ch_cantons.columns.names=[None]\n\ndf_ch_cantons_prevalence = df.groupby(['date', 'canton']).sum()\ndf_ch_cantons_prevalence['prevalence per 100 000'] = df_ch_cantons_prevalence['cases']/df_ch_cantons_prevalence['population']*100000\ndf_ch_cantons_prevalence = df_ch_cantons_prevalence[['prevalence per 100 000']].unstack(level='canton')\ndf_ch_cantons_prevalence.columns = df_ch_cantons_prevalence.columns.droplevel(0)\ndf_ch_cantons_prevalence.columns.names=[None]\n\nPath(r'out/ch_cantons/').mkdir(parents=True, exist_ok=True)\ndf_ch_cantons.to_csv(r'out/ch_cantons/cases.csv')\ndf_ch_cantons_prevalence.to_csv(r'out/ch_cantons/prevalence.csv')\n\ndef generate_age_csv(df, path):\n df_age_men = df[['cases']].xs('male', level='sex').groupby(['date', 'age']).sum().unstack(level='age')\n df_age_men.columns = df_age_men.columns.droplevel(0)\n df_age_men.columns.names=[None]\n df_age_men.to_csv(path + 'men.csv')\n\n df_age_men_prevalence = df.xs('male', level='sex').groupby(['date', 'age']).sum()\n df_age_men_prevalence['prevalence per 100 000'] = df_age_men_prevalence['cases']/df_age_men_prevalence['population']*100000\n df_age_men_prevalence = df_age_men_prevalence[['prevalence per 100 000']].unstack(level='age')\n df_age_men_prevalence.columns = df_age_men_prevalence.columns.droplevel(0)\n df_age_men_prevalence.columns.names=[None]\n df_age_men_prevalence.to_csv(path + 'men_prevalence.csv')\n\n df_age_women = df[['cases']].xs('female', level='sex').groupby(['date', 'age']).sum().unstack(level='age')\n df_age_women.columns = df_age_women.columns.droplevel(0)\n df_age_women.columns.names=[None]\n df_age_women.to_csv(path + 'women.csv')\n\n df_age_women_prevalence = df.xs('female', level='sex').groupby(['date', 'age']).sum()\n df_age_women_prevalence['prevalence per 100 000'] = df_age_women_prevalence['cases']/df_age_women_prevalence['population']*100000\n df_age_women_prevalence = df_age_women_prevalence[['prevalence per 100 000']].unstack(level='age')\n df_age_women_prevalence.columns = df_age_women_prevalence.columns.droplevel(0)\n df_age_women_prevalence.columns.names=[None]\n df_age_women_prevalence.to_csv(path + 'women_prevalence.csv')\n \n df_age_all = df[['cases']].groupby(['date', 'age']).sum().unstack(level='age')\n df_age_all.columns = df_age_all.columns.droplevel(0)\n df_age_all.columns.names=[None]\n df_age_all.to_csv(path + 'all.csv')\n \n df_age_all_prevalence = df.groupby(['date', 'age']).sum()\n df_age_all_prevalence['prevalence per 100 000'] = df_age_all_prevalence['cases']/df_age_all_prevalence['population']*100000\n df_age_all_prevalence = df_age_all_prevalence[['prevalence per 100 000']].unstack(level='age')\n df_age_all_prevalence.columns = df_age_all_prevalence.columns.droplevel(0)\n df_age_all_prevalence.columns.names=[None]\n df_age_all_prevalence.to_csv(path + 'all_prevalence.csv')\n\nPath(r'out/ch_age/').mkdir(parents=True, exist_ok=True)\ngenerate_age_csv(df, r'out/ch_age/')\n\nfor key, cantons in regions_DE.items():\n df=df_all.query('canton in @cantons')\n Path(r'out/region_age/{}/'.format(key)).mkdir(parents=True, exist_ok=True)\n generate_age_csv(df, r'out/region_age/{}/'.format(key))\n\nfor key, canton in cantons_DE.items():\n print(key + '>' + canton)\n df= df_all.xs(key, level='canton', drop_level=False)\n Path(r'out/canton_age/{}/'.format(key)).mkdir(parents=True, exist_ok=True)\n generate_age_csv(df, r'out/canton_age/{}/'.format(key))\n\n\n","sub_path":"bag_cases_csv.py","file_name":"bag_cases_csv.py","file_ext":"py","file_size_in_byte":7799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"45123166","text":"from machine import Pin\nimport utime\nimport ustruct\nimport time\nimport usocket\n\nimport gc\nfrom urequests import get\nfrom machine import I2C\ni2c = I2C(sda=Pin(23), scl=Pin(22), freq=400000)\n\nfrom vl53l0x import VL53L0X\n\nprint('Hello world! I can count to 10:')\nfor i in range(1,11):\n print(i)\n\n# create an output pin on pin #0\nprint('Setup the pin...')\npin = Pin(12, Pin.OUT)\n\ndef do_connect():\n import network\n wlan = network.WLAN(network.STA_IF)\n wlan.active(True)\n if not wlan.isconnected():\n print('connecting to network...')\n wlan.connect('ACME', 'roadrunner')\n while not wlan.isconnected():\n pass\n print('network config:', wlan.ifconfig())\n\ndef select_channel(channel):\n i2c.writeto(0x74, ustruct.pack('>B', 1 << channel ))\n print (\"Selected: \", channel, ustruct.pack('>B', 1 << channel ))\n\ndef retrieve_url(url):\n #gc.collect()\n resp = None\n try:\n resp = get(url)\n value = resp.text\n except Exception as e: # Here it catches any error.\n if isinstance(e, OSError) and resp: # If the error is an OSError the socket has to be closed.\n resp.close()\n value = {\"error\": e}\n #gc.collect()\n return value\n\ndo_connect()\nprint('Network is setup.')\n\nfor i in range(4,7):\n select_channel(i);\n dist = VL53L0X(i2c);\n dist.measurement_timing_budget = 20000;\n #dist.io_timeout_s = 3000;\n\n print(\"Identifying.\");\n print(\"Range: \", dist.range)\n#addr = usocket.getaddrinfo(\"192.168.2.204\", 5005)[0][-1];\naddr = usocket.getaddrinfo(\"192.168.2.38\", 3001)[0][-1];\n\nwhile True:\n for i in range(4, 7):\n select_channel(i + 4);\n dist.start_range();\n\n for i in range(4, 7):\n select_channel(i + 4);\n r = dist.range\n print (\"Range\");\n print (r);\n\n #s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)\n #s.sendto(ustruct.pack('>H',r), addr);\n #s.close()\n #res = retrieve_url('http://192.168.2.38:3000/add?source=throwy1&stat=vl6180&type=sample&value=' + str(dist.range() - 15));\n","sub_path":"throwy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"501257048","text":"import turtle\nturtle.speed(0)\nl=150\nang=15\nturtle.color(\"black\",\"yellow\")\nfor i in range(100):\n turtle.begin_fill()\n for i in range(3):\n turtle.forward(l)\n turtle.left(120)\n turtle.end_fill()\n l+=2\n turtle.left(ang)\n","sub_path":"school_life_projects/graphics/triangle - Copy.py","file_name":"triangle - Copy.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"395830168","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass MeterDetailsResponse(Model):\n \"\"\"The properties of the meter detail.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar meter_name: The name of the meter, within the given meter category\n :vartype meter_name: str\n :ivar meter_category: The category of the meter, for example, 'Cloud\n services', 'Networking', etc..\n :vartype meter_category: str\n :ivar meter_sub_category: The subcategory of the meter, for example, 'A6\n Cloud services', 'ExpressRoute (IXP)', etc..\n :vartype meter_sub_category: str\n :ivar unit_of_measure: The unit in which the meter consumption is charged,\n for example, 'Hours', 'GB', etc.\n :vartype unit_of_measure: str\n :ivar service_family: The service family.\n :vartype service_family: str\n \"\"\"\n\n _validation = {\n 'meter_name': {'readonly': True},\n 'meter_category': {'readonly': True},\n 'meter_sub_category': {'readonly': True},\n 'unit_of_measure': {'readonly': True},\n 'service_family': {'readonly': True},\n }\n\n _attribute_map = {\n 'meter_name': {'key': 'meterName', 'type': 'str'},\n 'meter_category': {'key': 'meterCategory', 'type': 'str'},\n 'meter_sub_category': {'key': 'meterSubCategory', 'type': 'str'},\n 'unit_of_measure': {'key': 'unitOfMeasure', 'type': 'str'},\n 'service_family': {'key': 'serviceFamily', 'type': 'str'},\n }\n\n def __init__(self, **kwargs) -> None:\n super(MeterDetailsResponse, self).__init__(**kwargs)\n self.meter_name = None\n self.meter_category = None\n self.meter_sub_category = None\n self.unit_of_measure = None\n self.service_family = None\n","sub_path":"sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/meter_details_response_py3.py","file_name":"meter_details_response_py3.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"391532308","text":"from player import Player\r\nfrom level import Level\r\nfrom gameio import Control\r\nfrom gameui import MainUI\r\nfrom gameui import LevelsUI\r\nfrom gameui import StartUI\r\nfrom gameui import StoryUI\r\nfrom gameui import LevelCompleteUI\r\nfrom config import level_config\r\n\r\n\r\nclass Game(object):\r\n \"\"\"Game class that contains all the game mechanics.\"\"\"\r\n\r\n def __init__(self):\r\n self.control = Control(self)\r\n self.level = Level(self)\r\n self.player = Player(self)\r\n self.gameui = StartUI(self)\r\n self.setup()\r\n\r\n def setup_level(self, level_number):\r\n \"\"\"Setup the game level.\"\"\"\r\n\r\n level = Level(self)\r\n level.build(level_number)\r\n self.level = level\r\n\r\n def setup_player(self):\r\n \"\"\"Setup the player based on the game level\"\"\"\r\n\r\n map_config = level_config['levels'][self.level.number]['map']\r\n enter_coords = map_config['coord_enter']\r\n enter_orientation = map_config['orientation_enter']\r\n\r\n self.player.move_to(*enter_coords)\r\n self.player.orientation = enter_orientation\r\n self.player.inventory.clear_items()\r\n\r\n def setup(self, level_number=0):\r\n \"\"\"Setup game elements.\"\"\"\r\n\r\n # setup level before player\r\n self.setup_level(level_number)\r\n self.setup_player()\r\n\r\n def mainloop(self):\r\n \"\"\"The main game loop.\"\"\"\r\n\r\n while True:\r\n if isinstance(self.gameui, MainUI):\r\n if self.player.cell.has_story_text() and not self.player.cell.story_seen:\r\n self.gameui = StoryUI(self)\r\n if self.level.is_complete():\r\n if self.level.number == 0:\r\n self.gameui = LevelsUI(self)\r\n else:\r\n self.gameui = LevelCompleteUI(self)\r\n self.gameui.process_input(self.gameui.prompt())\r\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"284728761","text":"from ryu.lib import hub\nfrom ryu.lib.packet import packet, ether_types, in_proto, igmp\n\nimport networkx as nx\nfrom networkx.algorithms.approximation.steinertree import steiner_tree\n\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Process\nimport itertools\n\nfrom . import domain, group, topology, graph, events\n\n#########################################################\n# the real controller !\n#########################################################\n\nclass SDNNetwork(Process):\n\n def __init__(self, log):\n\n super(SDNNetwork, self).__init__()\n\n self.ip_2_mac = {}\n self.logger = log\n self.log = self.logger.info\n\n self.topology_manager = topology.SDNTopologyManager(self)\n self.group_manager = group.SDNGroupManager(self)\n self.domain_manager = domain.SDNDomainManager(self)\n self.monitor_thread = hub.spawn(self.monitor)\n self.interval = 10\n\n self.maximum_bandwidth = 10000 # packets per second\n self.link_repair_type = \"domain\" # or \"full\"\n\n self.plt = plt\n self.plt.ion()\n\n print(\"Network is ON\")\n\n def get_topology(self):\n return self.topology_manager.network_graph\n\n def switches(self):\n return self.topology_manager.switches\n\n def links(self):\n return self.topology_manager.links\n\n def hosts(self):\n return self.topology_manager.hosts\n\n def ports(self):\n return self.topology_manager.ports\n\n # check multicast address :‌ true or false\n def is_multicast(self, dst):\n\n multicast = dst[0:2] == '01' or dst[0:5] == '33:33' or dst == 'ff:ff:ff:ff:ff:ff'\n self.log(str(dst) + \"is Multicast? \" + str(multicast))\n return multicast\n\n def monitor(self):\n\n hub.sleep(self.interval * 3)\n\n #self.domain_manager.calculate_domains()\n\n while True:\n\n hub.sleep(self.interval)\n\n network_switches = self.switches()\n\n for sw in network_switches.values():\n\n self.port_stats_request(sw)\n\n def port_stats_request(self, sw):\n\n datapath = sw.dp\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n request = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)\n datapath.send_msg(request)\n\n self.log(\"Asking for port stats of Switch \" + str(sw.dp.id))\n\n def port_stats_reply(self, ev):\n\n msg = ev.msg\n dpid = msg.datapath.id\n network_graph = self.get_topology()\n\n for stat in ev.msg.body:\n\n for link in self.topology_manager.links[dpid].values():\n\n if link.src.port_no == stat.port_no:\n\n weight = (stat.rx_packets + stat.tx_packets) - network_graph[dpid][link.dst.dpid]['weight']\n network_graph[dpid][link.dst.dpid]['weight'] = weight\n\n self.log('Weight of link from ' + str(dpid) + ' to ' + str(link.dst.dpid) + ' : ' + str(weight))\n\n if link.dst in self.topology_manager.hosts.keys():\n network_graph.nodes[link.dst]['price'] = weight\n\n if weight > (self.maximum_bandwidth * self.interval):\n\n self.log(\" Link repair is called because of overflow\")\n self.link_repair(link.src, link.dst.dpid)\n\n def state_change(self, ev):\n\n datapath = ev.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n self.log('Deleting all existing flows')\n del_flows = parser.OFPFlowMod(datapath=datapath,\n table_id=ofproto.OFPTT_ALL,\n out_port=ofproto.OFPP_ANY,\n out_group=ofproto.OFPG_ANY,\n command=ofproto.OFPFC_DELETE)\n datapath.send_msg(del_flows)\n\n self.log('Deleting all exising groups')\n del_groups = parser.OFPGroupMod(datapath=datapath,\n command=ofproto.OFPGC_DELETE,\n group_id=ofproto.OFPG_ALL)\n datapath.send_msg(del_groups)\n\n barrier_req = parser.OFPBarrierRequest(datapath)\n datapath.send_msg(barrier_req)\n\n def switch_features(self, ev):\n\n datapath = ev.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n match = parser.OFPMatch()\n actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)]\n instr = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]\n\n cmd = parser.OFPFlowMod(datapath=datapath,\n priority=0,\n match=match,\n instructions=instr)\n datapath.send_msg(cmd)\n self.log('Default flow is added to dpid : ' + str(datapath.id))\n\n def send_packet_2_host(self, host, msg):\n\n network_graph = self.get_topology()\n\n if host not in network_graph:\n self.log(\"Host \" + str(host.mac) + \"is not connected to network\")\n return\n\n switch_id = list(network_graph.predecessors(host))[0]\n\n datapath = network_graph.nodes[switch_id]['switch'].dp\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n port = network_graph[switch_id][host]['src_port']\n actions = [parser.OFPActionOutput(port)]\n\n cmd = parser.OFPPacketOut(datapath=datapath,\n buffer_id=ofproto.OFP_NO_BUFFER,\n in_port=ofproto.OFPP_CONTROLLER,\n actions=actions,\n data=msg.data)\n\n datapath.send_msg(cmd)\n self.log(\"Sending msg from controller to host \" + str(host.mac))\n\n def get_key(self, multicast, dst_address, src_address, tag):\n\n if multicast:\n return dst_address, src_address, tag\n else:\n return dst_address\n\n def get_priority(self, tag):\n\n ret = 2 if tag is None else 3\n return ret\n\n def get_ports(self, dpid, dsts):\n\n network_graph = self.get_topology()\n\n ports_s = set()\n ports_h = set()\n\n for dst in dsts:\n\n port = network_graph[dpid][dst]['src_port']\n\n if network_graph.nodes[dst]['host']:\n\n ports_h.add(port)\n\n else:\n\n ports_s.add(port)\n\n return ports_s, ports_h\n\n def get_match(self, parser, dst_address, src_address, multicast, tag):\n\n if multicast:\n\n match = parser.OFPMatch(eth_dst=self.ip_2_mac[dst_address], eth_src=self.ip_2_mac[src_address])\n\n else:\n\n match = parser.OFPMatch(eth_dst=dst_address)\n\n if tag is not None:\n\n match = parser.OFPMatch(vlan_vid=(0x1000 | tag), **dict(match.items()))\n\n return match\n\n def get_actions(self, parser, tag, ports_s, ports_h):\n\n actions = []\n\n actions_outputs = list()\n actions_remove_tag = list()\n actions_remove_tag.append(parser.OFPActionPopVlan())\n\n for port in ports_s:\n actions_outputs.append(parser.OFPActionOutput(port))\n\n for port in ports_h:\n\n if tag is None:\n actions_outputs.append(parser.OFPActionOutput(port))\n else:\n actions_remove_tag.append(parser.OFPActionOutput(port))\n\n if len(actions_outputs) > 0:\n actions.append(actions_outputs)\n\n if len(actions_remove_tag) > 1:\n actions.append(actions_remove_tag)\n\n return actions\n\n def install_actions(self, datapath, parser, ofproto, prio, current_tables, match, actions):\n\n for i in range(0, len(actions)):\n\n instructions = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions[i])]\n\n if len(actions) - 1 > i:\n\n instructions.append(parser.OFPInstructionGotoTable(i + 1))\n\n if i < current_tables:\n\n command = ofproto.OFPFC_MODIFY_STRICT\n\n else:\n\n command = ofproto.OFPFC_ADD\n\n cmd = parser.OFPFlowMod(datapath=datapath,\n table_id=i,\n command=command,\n priority=prio,\n match=match,\n instructions=instructions,\n out_port=ofproto.OFPP_ANY,\n out_group=ofproto.OFPG_ANY)\n datapath.send_msg(cmd)\n\n for i in range(len(actions), current_tables):\n\n cmd = parser.OFPFlowMod(datapath=datapath,\n table_id=i,\n out_port=ofproto.OFPP_ANY,\n out_group=ofproto.OFPG_ANY,\n command=ofproto.OFPFC_DELETE_STRICT,\n match=match,\n priority=prio)\n\n datapath.send_msg(cmd)\n\n def add_flow(self, dpid, dst_address, dsts, multicast=False, src_address=None, tag=None):\n\n network_graph = self.get_topology()\n\n datapath = network_graph.nodes[dpid]['switch'].dp\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n key = self.get_key(multicast, dst_address, src_address, tag)\n ports_s, ports_h = self.get_ports(dpid, dsts)\n\n install = False\n current_tables = 0\n\n flows = network_graph.nodes[dpid]['flows']\n\n if key in flows and (len(flows[key][0]) > 0 or len(flows[key][1]) > 0):\n\n current_s, current_h, current_tables = flows[key]\n\n for port in ports_s:\n if port not in current_s:\n\n ports_s.update(current_s)\n ports_h.update(current_h)\n install = True\n\n break\n\n if not install:\n for port in ports_h:\n if port not in current_h:\n\n ports_s.update(current_s)\n ports_h.update(current_h)\n install = True\n\n break\n\n else:\n\n install = True\n\n if install:\n\n match = self.get_match(parser=parser,\n dst_address=dst_address,\n src_address=src_address,\n multicast=multicast,\n tag=tag)\n\n priority = self.get_priority(tag=tag)\n\n actions = self.get_actions(parser=parser,\n tag=tag,\n ports_s=ports_s,\n ports_h=ports_h)\n\n self.install_actions(datapath=datapath,\n parser=parser,\n ofproto=ofproto,\n prio=priority,\n current_tables=current_tables,\n match=match,\n actions=actions)\n\n flows[key] = (ports_s, ports_h, len(actions))\n\n self.log('Added/Modified flows from switch '\n + str(dpid)\n + ' to ports '\n + str(ports_s)\n + ' and '\n + str(ports_h))\n\n self.log('destination = ' + str(dst_address))\n\n if tag is not None:\n self.log('tag = ' + str(tag))\n\n def remove_flow(self, dpid, dst_address, dsts, multicast=False, src_address=None, tag=None):\n\n network_graph = self.get_topology()\n\n gp_key = (dst_address, src_address)\n if gp_key in self.group_manager.groups.key():\n\n tree = self.group_manager.groups[gp_key]\n\n if dsts == 'all':\n\n destinations = list(tree.successors(dpid))\n\n for destination in destinations:\n\n subs = self.group_manager.get_subscribers(tree, destination)\n price = []\n\n for sub in subs:\n price.append(tree.nodes[sub]['price'])\n\n price_avg = max[price]\n\n network_graph[dpid][destination] = network_graph[dpid][destination] - price_avg\n else:\n\n for destination in dsts:\n\n subs = self.group_manager.get_subscribers(tree, destination)\n price = 0\n\n for sub in subs:\n price = price + network_graph[sub]['price']\n\n network_graph[dpid][destination] = network_graph[dpid][destination] - price\n\n datapath = network_graph.nodes[dpid]['switch'].dp\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n key = self.get_key(multicast, dst_address, src_address, tag)\n flows = network_graph.node[dpid]['flows']\n\n if key not in flows:\n\n self.log('Tried to remove flows from '\n + str(dpid)\n + ' to '\n + str(dsts) +\n ' , but they do not exist')\n\n if tag is not None:\n\n self.log('Tag = ' + str(tag))\n\n return\n\n current_s, current_h, current_tables = flows[key]\n\n priority = self.get_priority(tag)\n\n if dsts == 'all':\n\n other_s = []\n other_h = []\n\n else:\n\n ports_s, ports_h = self.get_ports(dpid, dsts)\n other_s = [port for port in current_s if port not in ports_s]\n other_h = [port for port in current_h if port not in ports_h]\n\n match = self.get_match(parser=parser,\n dst_address=dst_address,\n src_address=src_address,\n multicast=multicast,\n tag=tag)\n\n if len(other_s) == 0 and len(other_h) == 0:\n\n for i in range(0, current_tables):\n\n cmd = parser.OFPFlowMod(datapath=datapath,\n out_port=ofproto.OFPP_ANY,\n out_group=ofproto.OFPG_ANY,\n command=ofproto.OFPFC_DELETE_STRICT,\n match=match,\n priority=priority)\n\n datapath.send_msg(cmd)\n\n else:\n\n actions = self.get_actions(parser=parser,\n tag=tag,\n ports_s=other_s,\n ports_h=other_h)\n\n self.install_actions(datapath=datapath,\n parser=parser,\n ofproto=ofproto,\n prio=priority,\n current_tables=current_tables,\n match=match,\n actions=actions)\n\n if other_s or other_h:\n flows[key] = (other_s, other_h, len(actions))\n else:\n del flows[key]\n\n self.log('Removed flows from switch '\n + str(dpid)\n + ' to ports '\n + str(ports_s)\n + ' and '\n + str(ports_h))\n\n self.log('destination = ' + str(dst_address))\n\n if tag is not None:\n self.log('tag = ' + str(tag))\n\n def packet_in_handler(self, ev):\n\n msg = ev.msg\n datapath = msg.datapath\n in_port = msg.match['in_port']\n\n pkt = packet.Packet(msg.data)\n eth = pkt[0]\n\n if eth.protocol_name != 'ethernet':\n\n self.log('Ignoring non ethernet packet: ')\n return\n\n if eth.ethertype == ether_types.ETH_TYPE_LLDP:\n return\n\n src = eth.src\n dst = eth.dst\n\n self.log('Received ethernet packet from ' + src + ' to ' + dst)\n\n network_graph = self.get_topology()\n\n if src not in network_graph:\n\n port = events.Port(datapath.id, in_port)\n host = events.Host(src, port)\n ev = events.EventHostBase(host)\n\n self.topology_manager.add_host(ev)\n\n if self.is_multicast(dst):\n self.process_multicast(datapath, msg, pkt)\n else:\n self.process_unicast(pkt)\n\n def process_unicast(self, pkt):\n\n eth = pkt[0]\n\n if eth.ethertype == ether_types.ETH_TYPE_IP and eth.dst != 'ff:ff:ff:ff:ff:ff':\n\n self.log('IP Unicast Message')\n ip = pkt[1]\n\n if ip.protocol_name != 'ipv4':\n\n self.log('Expected ipv4, but got ' + ip.protocol_name)\n return\n\n self.ip_2_mac[ip.dst] = eth.dst\n self.ip_2_mac[ip.src] = eth.src\n\n path = nx.dijkstra_path(self.get_topology(), eth.src, eth.dst, weight='weight')\n\n if len(path) == 0:\n\n self.log('No path from ' + str(eth.src) + ' to ' + str(eth.dst))\n return\n\n for i in range(len(path) - 1, 0, -1):\n\n pre = path[i - 1]\n cur = path[i]\n\n self.add_flow(pre, eth.dst, [cur], False, eth.src, None)\n\n self.log('Unicast flow from '\n + str(eth.src)\n + ' to '\n + str(eth.dst)\n + ' is loaded to network.')\n\n def process_multicast(self, datapath, msg, pkt):\n\n eth = pkt[0]\n dst = eth.dst\n src = eth.src\n\n network_graph = self.get_topology()\n\n if eth.ethertype == ether_types.ETH_TYPE_IP and dst != 'ff:ff:ff:ff:ff:ff':\n\n self.log('IPV4 Multicast Message')\n ip = pkt[1]\n\n if ip.protocol_name != 'ipv4':\n\n self.log('Expected ipv4, but got ' + ip.protocol_name)\n return\n\n if ip.proto == in_proto.IPPROTO_IGMP:\n\n igmp_msg = pkt[2]\n\n self.process_IGMP(eth.src, ip.src, igmp_msg)\n return\n\n if ip.dst not in self.group_manager.group_2_sources:\n\n self.group_manager.group_2_sources[ip.dst] = set()\n self.ip_2_mac[ip.dst] = eth.dst\n\n if ip.src not in self.group_manager.group_2_sources[ip.dst]:\n\n self.group_manager.create_group(ip.dst, ip.src, datapath.id)\n self.group_manager.group_2_sources[ip.dst].add(ip.src)\n self.ip_2_mac[ip.src] = eth.src\n\n ofp = datapath.ofproto\n parser = datapath.ofproto_parser\n actions = []\n\n match = parser.OFPMatch(eth_dst=eth.dst,\n eth_src=eth.src)\n\n instruction = [parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)]\n\n cmd = parser.OFPFlowMod(\n datapath=datapath,\n priority=1,\n match=match,\n instructions=instruction)\n\n datapath.send_msg(cmd)\n\n subscribers = self.group_manager.subscribers.get(ip.dst, {})\n add_subscriber = list()\n\n for subscriber in itertools.filter(lambda eth_src: eth_src != eth.src, subscribers):\n\n sub_info = subscribers[subscriber]\n\n if sub_info[0]:\n add = ip.src in sub_info[1]\n else:\n add = ip.src not in sub_info[1]\n\n if add:\n\n add_subscriber.append(subscriber)\n\n for subscriber in add_subscriber:\n\n self.group_manager.add_subscriber(ip.dst, ip.src, subscriber)\n self.send_packet_2_host(subscriber, msg)\n\n def process_IGMP(self, eth_src, ip_src, igmp_msg):\n\n if igmp_msg.protocol_name == 'igmpv3_report':\n\n records = igmp_msg.records\n\n for record in records:\n address = record.address\n\n if record.type_ == igmp.CHANGE_TO_INCLUDE_MODE or record.type_ == igmp.CHANGE_TO_EXCLUDE_MODE:\n\n mode = record.type_ == igmp.CHANGE_TO_INCLUDE_MODE\n\n self.log('Record change for group ' + address)\n\n if address not in self.group_manager.subscribers:\n\n self.group_manager.subscribers[address] = {}\n\n subscribers = self.group_manager.subscribers[address]\n subscribers[eth_src] = [mode, record.srcs]\n\n if address in self.group_manager.group_2_sources.keys():\n\n group = self.group_manager.group_2_sources[address]\n\n if mode:\n\n for src_ip in itertools.filter(lambda ip: ip != ip_src, group):\n\n if src_ip in record.srcs:\n\n self.group_manager.add_subscriber(address, src_ip, eth_src)\n\n else:\n\n self.group_manager.remove_subscriber(address, src_ip, eth_src)\n else:\n\n for src_ip in itertools.filter(lambda ip: ip != ip_src, group):\n\n if src_ip in record.srcs:\n\n self.group_manager.remove_subscriber(address, src_ip, eth_src)\n\n else:\n\n self.group_manager.add_subscriber(address, src_ip, eth_src)\n\n def move_host(self, ev):\n\n host = ev.host\n mac = host.mac\n\n host_dst_port = ev.dst\n host_dst_dpid = host_dst_port.dpid\n\n host_src_port = ev.src\n host_src_dpid = host_src_port.dpid\n\n self.log(\"moving host \" + mac + ' from' + host_src_dpid + ' to ' + host_dst_dpid)\n\n add_subscriber = list()\n add_source = list()\n\n network_graph = self.get_topology()\n\n for host_ip in host.ip:\n for address in self.group_manager.group_2_sources.keys():\n\n source_list = self.group_manager.group_2_sources[address]\n\n for src_ip in itertools.filter(lambda ip: ip != host_ip, source_list):\n\n key = (address, src_ip)\n\n if key in self.group_manager.groups.key():\n tree = self.group_manager.groups[key]\n\n if mac in tree:\n\n self.log('host ' + mac + 'is subscriber of group ' + str((address, src_ip)))\n self.group_manager.remove_subscriber(address, src_ip, mac)\n\n add_subscriber.append((address, src_ip))\n\n for host_ip in host.ip:\n for address in self.group_manager.group_2_sources.keys():\n\n key = (address, host_ip)\n if key in self.group_manager.groups.key():\n\n self.log('host ' + mac + ' is the source of group ' + str(key))\n\n tree = self.group_manager.groups[key]\n\n path = graph.calculate_path(network=network_graph,\n tree=tree,\n node=host_src_dpid,\n links_to_exclude=[],\n root=tree.graph['root'],\n price=0)\n\n nodes = [n for n in path.nodes]\n\n did = self.domain_manager.most_similiar_domain(nodes)\n virtual_hosts = self.domain_manager.calculate_virtual_hosts(did, tree)\n\n tag = tree.graph['tag']\n\n for node in self.domain_manager.domain[did]:\n\n if node in tree:\n\n dsts = list(tree.successors(node))\n\n if len(dsts) > 0:\n self.remove_flow(node, address, 'all', True, host_ip, tag)\n\n add_source.append({'ip_group': address,\n 'ip_source': host_ip,\n 'virtual_hosts': virtual_hosts})\n\n self.topology_manager.move_host(ev)\n\n for src in add_source:\n\n virtual_hosts = src['virtual_hosts']\n ip_group = src['ip_group']\n ip_source = src['ip_source']\n\n key = (ip_group, ip_source)\n if key not in self.group_manager.groups:\n self.log('Group ' + str(key) + ' does not exist')\n return\n\n tree = self.group_manager.groups[key]\n tree.graph['root'] = host_dst_dpid\n\n for v in virtual_hosts:\n\n subs_list = self.group_manager.get_subscribers(tree, v)\n price = 0\n for sub in subs_list:\n price = price + network_graph[sub]['price']\n\n domain_tree = nx.DiGraph(root=host_dst_dpid)\n domain_tree.add_node(host_dst_dpid)\n\n path = graph.calculate_path(network=network_graph,\n tree=domain_tree,\n node=v,\n links_to_exclude=[],\n root=domain_tree.graph['root'],\n price=price)\n\n self.group_manager.add_path(ip_group, ip_source, domain_tree, path, flow=False)\n self.group_manager.add_path(ip_group, ip_source, tree, path)\n\n for addr, ip in add_subscriber:\n\n self.group_manager.add_subscriber(addr, ip, mac)\n \n def link_repair(self, src, dst):\n\n network_graph = self.get_topology()\n exclude_list = list()\n\n self.log(\"Link (\" + str(src) + \", \" + str(dst) + \") is going to be repaired:\")\n\n for key in self.group_manager.groups.keys():\n\n tree = self.group_manager.groups[key]\n if tree.has_edge(src, dst):\n\n if dst['host'] is False:\n\n ip_group = key[0]\n ip_source = key[1]\n\n if self.link_repair_type == \"domain\":\n\n virtual_hosts = list(tree.successors(dst))\n\n self.remove_flow(src, ip_group, [dst], True, ip_source, tree.graph['tag'])\n self.log(\" Link (\" + str(src) + \", \" + str(dst) + \") removed\")\n exclude_list.append((src, dst))\n\n for v in virtual_hosts:\n self.remove_flow(dst, ip_group, [v], True, ip_source, tree.graph['tag'])\n self.log(\" Link (\" + str(dst) + \", \" + str(v) + \") removed\")\n exclude_list.append((dst, v))\n\n tree.remove_node(dst)\n\n domain_tree = nx.DiGraph(root=src)\n domain_tree.add_node(src)\n\n for v in virtual_hosts:\n\n subs_list = self.group_manager.get_subscribers(tree, v)\n price = 0\n for sub in subs_list:\n price = price + network_graph[sub]['price']\n\n path = graph.calculate_path(network=network_graph,\n tree=domain_tree,\n node=v,\n links_to_exclude=exclude_list,\n root=domain_tree.graph['root'],\n price=price)\n\n self.log(\" Path \" + str(path) + \" added\")\n\n self.group_manager.add_path(ip_group, ip_source, domain_tree, path, flow=False)\n self.group_manager.add_path(ip_group, ip_source, tree, path)\n\n elif self.link_repair_type == \"full\":\n\n affected_subscribers = self.group_manager.get_subscribers(tree, src)\n\n for subscriber in affected_subscribers:\n self.group_manager.remove_subscriber(ip_group, ip_source, subscriber)\n\n for subscriber in affected_subscribers:\n price = network_graph[subscriber]['price']\n self.group_manager.add_subscriber(ip_group, ip_source, subscriber, price)\n\n\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":28862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"353935871","text":"import json\nimport logging\nimport os\nimport requests\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom .models import Message\nfrom .models import Users\n\nfrom .forms import MessageForm\n\nlogger = logging.getLogger(__name__)\nsend_message_url = 'https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s'\n\ndef index(request):\n return render(request, 'index.html')\n\ndef send_message(request):\n user_id = request.COOKIES['Telegram']\n form = MessageForm()\n if request.method == 'POST':\n form = MessageForm(request.POST)\n if form.is_valid():\n message = form.cleaned_data['message']\n full_url = send_message_url % (os.environ.get('TELEGRAM_KEY'), user_id, message)\n r = requests.get(full_url)\n print(r.text)\n return HttpResponseRedirect('')\n else:\n print('Invalid form')\n return render(request, 'send_message.html', {'form': form})\n\ndef login(request):\n user_id = request.GET['id']\n response = HttpResponse('ok')\n if exists(user_id):\n response.set_cookie('Telegram', str(user_id))\n else:\n user = Users(user=user_id)\n user.save()\n response.set_cookie('Telegram', str(user_id))\n return response\n\ndef logout(request):\n pass\n\n# receiving messages from telegram here\ndef message(request):\n message_raw = request.body\n d = json.loads(message_raw)\n logger.error(message_raw.decode(\"utf-8\"))\n if 'text' in d['message']:\n message_text = d['message']['text']\n message_from = d['message']['from']['id']\n message_chat_id = d['message']['chat']['id']\n db_message = Message(user=message_from,\n message=message_text,\n raw_message=message_raw,\n chat_id=message_chat_id)\n db_message.save()\n logger.error(d['message']['text'])\n return HttpResponse('
' + message_raw.decode(\"utf-8\") + '
')\n\n## non-public stuff\n\ndef exists(user_id):\n return Users.objects.filter(user=user_id).count()\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"625497231","text":"\n\nfrom xai.brain.wordbase.nouns._hint import _HINT\n\n#calss header\nclass _HINTED(_HINT, ):\n\tdef __init__(self,): \n\t\t_HINT.__init__(self)\n\t\tself.name = \"HINTED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"hint\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_hinted.py","file_name":"_hinted.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"117522615","text":"# ステージ選択画面\n\n#ユーザ定義#\nimport DrawDisplay\nimport CommandManager\nimport PlayScene\nimport CreateMaze\n\n\ndef run():\n DrawDisplay.clear() # 画面削除\n\n # 描画\n DrawDisplay.initialDiplay([\n \"######### ステージ選択 #########\",\n \"\"\n ])\n\n command_number = 0\n command_line = [\n \"\"\"草原\"\"\",\n \"\"\"洞窟\"\"\",\n\n ]+[\"\"\"もどる\"\"\"]\n\n DrawDisplay.commandDisplay(command_line, command_number=command_number,\n cursol=\"▶ \", line_end=\"\\n\", end=\"\\n\")\n\n key = \"\"\n while True:\n key = CommandManager.CommandManager().pressKey() # 入力キー取得\n DrawDisplay.clear() # 画面を消す\n\n #コマンド操作#\n if key in CommandManager.ENTER:\n print(command_number)\n if command_line[command_number] == \"草原\":\n maze = CreateMaze.CreateMaze(12, 12) # 行列\n maze.make_maze() # 迷路生成\n # maze.print_maze() # 迷路出力\n maze.set_enemy(2, number=10, path_index=0) # 敵番号2で10体配置\n maze.set_enemy(3, number=30, path_index=0) # 草30配置\n maze.map_index = {0: \"床\", 1: \"壁\", 2: \"敵\", 3: \"草\"} # MAPインデクス定義\n PlayScene.run(maze=maze) # 迷路作成オブジェクトを引数に\n elif command_line[command_number] == \"洞窟\":\n maze = CreateMaze.CreateMaze(12, 40) # 行列\n maze.make_maze() # 迷路生成\n # maze.print_maze() # 迷路出力\n maze.set_enemy(2, number=40, path_index=0) # 敵番号2で10体配置\n maze.set_enemy(3, number=80, path_index=0) #\n maze.map_index = {0: \"床\", 1: \"壁\", 2: \"敵\", 3: \"石\"} # MAPインデクス定義\n PlayScene.run(maze=maze) # 迷路作成オブジェクトを引数に\n # elif command_line[command_number] == \"Hot Pepper 大海原\":\n # maze = CreateMaze.CreateMaze(60, 60) # 行列\n # maze.make_maze() # 迷路生成\n # maze.print_maze() # 迷路出力\n # maze.set_enemy(2, number=100, path_index=0) # 敵番号2で10体配置\n # maze.set_enemy(3, number=100, path_index=0) #\n # maze.map_index = {0: \"海上\", 1: \"壁\",\n # 2: \"敵\", 3: \"中ボス\"} # MAPインデクス定義\n # PlayScene.run(maze=maze) # 迷路作成オブジェクトを引数に\n elif command_line[command_number] == \"もどる\":\n return 0\n\n # 描画\n DrawDisplay.initialDiplay([\n \"######### ステージ選択 #########\",\n \"\"\n ])\n\n if key in CommandManager.UP: # 上キー\n command_number -= 1\n if key in CommandManager.DOWN: # 下キー\n command_number += 1\n elif key in CommandManager.ESC:\n print(\"Info: ESC終了!(MenuScene, run())\")\n return 0\n\n #コマンド#\n if command_number < 0: # 一番上ならば一番下に\n command_number = len(command_line)-1\n elif len(command_line)-1 < command_number: # 一番下ならば一番上に\n command_number = 0\n\n DrawDisplay.commandDisplay(command_line, command_number=command_number,\n cursol=\"▶ \", line_end=\"\\n\", end=\"\\n\")\n\n return 1 # 異常終了\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"StageSelectScene.py","file_name":"StageSelectScene.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"47335215","text":"import nest\nimport numpy as np\nimport pylab\n\nnest.SetKernelStatus({\"local_num_threads\": 8})\n\nneuron_population = 1000\nsimulation_time = 100.0\n\nI_e = 0.0\n\nmean_rate_Je = []\nmean_rate_list = []\n\ndict_parameters_exc = {\"E_L\": -70.0, \"C_m\": 250.0, \"tau_m\": 20.0, \"t_ref\": 2.0, \"V_th\": -55.0, \"V_reset\": -70.0, \"tau_syn\": 2.0, \"I_e\": I_e}\n\nepop = nest.Create(\"iaf_neuron\", neuron_population)\n\nnest.SetStatus(epop, params=dict_parameters_exc)\n\nKe_list = []\nI_e_list = []\n\nmultimeter_times = []\nmultimeter_V_m = []\n\nfor neuron in epop:\n nest.SetStatus([neuron], {\"V_m\": dict_parameters_exc[\"E_L\"]+(dict_parameters_exc[\"V_th\"]-dict_parameters_exc[\"E_L\"])*np.random.rand()})\n\nJe_parameters = np.arange(0,10,0.2)\n\nKe = 20\nd = 1.0\nJe = 10.0\n\nconn_dict_ex = {\"rule\": \"fixed_indegree\", \"indegree\": Ke}\nsyn_dict_ex = {\"delay\": d, \"weight\": Je}\n\nnest.Connect(epop, epop, conn_dict_ex, syn_dict_ex)\n\nspikedetector_exc = nest.Create(\"spike_detector\", params={\"withgid\": True, \"withtime\": True})\n\nmultimeter = nest.Create(\"multimeter\")\n\nnest.SetStatus(multimeter, {\"withtime\":True, \"record_from\":[\"V_m\"]})\n\nnest.Connect(multimeter, [epop[0]])\n\nfor neuron_exc in epop:\n nest.Connect([neuron_exc], spikedetector_exc)\n\nmultimeter_values = []\n\nfor i in range(500,0,-10):\n\n VM_values = []\n TS_values = []\n\n I_e = float(i)\n\n nest.SetStatus(epop, params={\"I_e\": I_e})\n\n nest.Simulate(simulation_time)\n\n nest.ResumeSimulation()\n\ndmm = nest.GetStatus(multimeter)[0]\nVms = dmm[\"events\"][\"V_m\"]\nts = dmm[\"events\"][\"times\"]\n\nprint(Vms)\nprint(ts)\n\nmultimeter_values.append(Vms)\nmultimeter_values.append(ts)\n\na = np.asarray(multimeter_values)\nprint(a)\nnp.savetxt(\"I_e_Je_multimeter.csv\", a, delimiter=\",\")\npylab.figure()\npylab.plot(ts, Vms)\npylab.show()\n","sub_path":"epopulation_V_m_decreasing.py","file_name":"epopulation_V_m_decreasing.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"92360468","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2017, QIIME 2 development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport q2_cutadapt\n\nfrom qiime2.plugin import Plugin\n\n\nplugin = Plugin(\n name='cutadapt',\n version=q2_cutadapt.__version__,\n website='https://github.com/qiime2/q2-cutadapt',\n package='q2_cutadapt',\n description='This QIIME 2 plugin supports removing adapters, primers, '\n 'and other unwanted sequences from sequence data.',\n short_description='Plugin for removing unwanted sequences from sequence '\n 'data.',\n)\n","sub_path":"q2_cutadapt/plugin_setup.py","file_name":"plugin_setup.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"521838452","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom os.path import join as pjoin\nimport contextlib\nimport io\nimport time\nimport threading\nfrom baselayer.log import colorize\n\n@contextlib.contextmanager\ndef nostdout():\n save_stdout = sys.stdout\n sys.stdout = io.StringIO()\n yield\n sys.stdout = save_stdout\n\n\ndef logs_from_config(supervisor_conf):\n watched = []\n\n with open(supervisor_conf) as f:\n for line in f:\n if '_logfile=' in line:\n _, logfile = line.strip().split('=')\n watched.append(logfile)\n\n return watched\n\n\nbasedir = pjoin(os.path.dirname(__file__), '..')\nlogdir = '../log'\nwatched = logs_from_config(pjoin(basedir, 'conf/supervisor/supervisor.conf.template'))\n\nsys.path.insert(0, basedir)\n\nwatched.append('log/error.log')\nwatched.append('log/nginx-bad-access.log')\nwatched.append('log/nginx-error.log')\nwatched.append('log/fake_oauth2.log')\n\n\ndef tail_f(filename, interval=1.0):\n f = None\n\n while not f:\n try:\n f = open(filename, 'r')\n break\n except IOError:\n time.sleep(1)\n\n # Find the size of the file and move to the end\n st_results = os.stat(filename)\n st_size = st_results[6]\n f.seek(st_size)\n\n while True:\n where = f.tell()\n line = f.readline()\n if not line:\n time.sleep(interval)\n f.seek(where)\n else:\n yield line.rstrip('\\n')\n\n\ndef print_log(filename, color):\n def print_col(line):\n print(colorize(line, fg=color))\n\n print_col('-> ' + filename)\n\n for line in tail_f(filename):\n print_col(line)\n\n\ncolors = ['default', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'red']\nthreads = [\n threading.Thread(target=print_log, args=(logfile, colors[n % len(colors)]))\n for (n, logfile) in enumerate(watched)\n]\n\nfor t in threads:\n t.start()\nfor t in threads:\n t.join()\n","sub_path":"tools/watch_logs.py","file_name":"watch_logs.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"361788165","text":"import qiskit\nfrom qiskit.transpiler import CouplingMap, PassManager, Layout\nfrom qiskit.transpiler.passes import BasicSwap, SetLayout, ApplyLayout\n\nimport csv\nfrom _private_benchmark.CONNECTION import INDEX_CONNECTION_LIST as connection_list\nfrom ast import literal_eval\n\nfrom k7m_core import K7MCompiler, K7MInitialMapping\n\nimport time\n\nfrom qiskit.converters import circuit_to_dag\nimport networkx as nx\n\ngdv_name = \"TFL\"\ndepth_range = {\n \"TFL\" : [5 * x for x in range(1, 10)],\n \"QSE\" : [100 * x for x in range(1, 10)]\n}\n# gdv_name = \"QSE\"\n\nqubits = {\n 16 : \"Aspen-4\",\n 20 : \"Tokyo\",\n 53 : \"Rochester\",\n 54 : \"Sycamore\"\n}\n\nnr_qubits = 16\n\nfirst_run = True\n\ndef convert_to_weighted_graph(multigraph):\n G = nx.Graph()\n for u,v in multigraph.edges(data=False):\n w = 1\n if G.has_edge(u,v):\n G[u][v]['weight'] += w\n else:\n G.add_edge(u, v, weight=w)\n\n return G\n\n\ndef dfs(i, visited, goesTo):\n # If it is already visited\n if (visited[i] == 1):\n return 0\n\n visited[i] = 1\n x = dfs(goesTo[i], visited, goesTo)\n\n return (x + 1)\n\n\ndef noOfTranspositions(P1, P, n):\n visited = [0] * n\n\n # This array stores which element goes to which position\n goesTo = [0] * n\n # building the goesTo[] array\n for i in range(n):\n goesTo[P[i]] = P1[i]\n\n # Initializing visited[] array\n for i in range(0, n):\n visited[i] = 0\n\n transpositions = 0\n\n for i in range(0, n):\n if (visited[i] == 0):\n ans = dfs(i, visited, goesTo)\n transpositions += ans - 1\n\n return transpositions\n\ndef circuit_analysis(depth, trail):\n if gdv_name == \"TFL\":\n folder = \"BNTF\"\n depth_string = \"{:02}\".format(depth)\n name_end = \"TFL\"\n if nr_qubits == 54:\n name_end = \"QSE\"\n\n elif gdv_name == \"QSE\":\n folder = \"BSS\"\n depth_string = \"{:03}\".format(depth)\n name_end = \"QSE\"\n\n # if nr_qubits==54:\n # gdv_name = \"QSE\"\n\n qasm_file_name = \"_private_benchmark/{}/{}QBT_{}CYC_{}_{}.qasm\".format(\n folder, nr_qubits, depth_string, name_end, trail)\n\n # print(\"qiskit\", depth)\n # input qasm file as circuit\n test_circuit = qiskit.QuantumCircuit.from_qasm_file(qasm_file_name)\n\n \"\"\"\n NetworkX analysis data\n\n \"\"\"\n dag_circ = circuit_to_dag(test_circuit)\n\n undirect = dag_circ._multi_graph.to_undirected(as_view=True)\n weighted = convert_to_weighted_graph(dag_circ._multi_graph)\n\n # import matplotlib.pyplot as plt\n # # nx.draw_networkx(undirect, with_labels=False, node_size=10)\n # nx.draw_networkx(dag_circ._multi_graph, with_labels=False, node_size=10)\n # plt.show()\n\n return max(nx.pagerank(weighted).values()),\\\n nx.number_connected_components(undirect),\\\n undirect.number_of_edges(),\\\n undirect.number_of_nodes(), \\\n nx.global_efficiency(weighted), \\\n nx.s_metric(dag_circ._multi_graph, False)\n\n\ndef benchmark(depth, trail, parameters):\n\n if gdv_name == \"TFL\":\n folder = \"BNTF\"\n depth_string = \"{:02}\".format(depth)\n name_end = \"TFL\"\n if nr_qubits == 54:\n name_end = \"QSE\"\n\n elif gdv_name == \"QSE\":\n folder = \"BSS\"\n depth_string = \"{:03}\".format(depth)\n name_end = \"QSE\"\n\n # if nr_qubits==54:\n # gdv_name = \"QSE\"\n\n qasm_file_name = \"_private_benchmark/{}/{}QBT_{}CYC_{}_{}.qasm\".format(\n folder, nr_qubits, depth_string, name_end, trail)\n\n solution_file_name = \"_private_benchmark/meta/{}QBT_{}CYC_{}_{}_solution.csv\".format(\n nr_qubits, depth_string, name_end, trail)\n\n # print(\"qiskit\", depth)\n # input qasm file as circuit\n test_circuit = qiskit.QuantumCircuit.from_qasm_file(qasm_file_name)\n\n\n \"\"\"\n Construct the optimal initial mapping\n \"\"\"\n qiskit_layout_dict = dict()\n original_nodes = list()\n with open(solution_file_name, 'r') as csvfile:\n for original_node in csv.reader(csvfile, delimiter=','):\n original_nodes.append(literal_eval(original_node[0]))\n csvfile.close()\n # print(original_nodes)\n\n for i in range(len(original_nodes)):\n qiskit_layout_dict[test_circuit.qregs[0][i]] = original_nodes[i]\n # construct passes that use the optimal initial mapping and BasicSwap\n # however, no swapping gates should be ever necessary\n original_pm = PassManager()\n # print(original_nodes)\n qiskit_coupling_map = CouplingMap(couplinglist=connection_list[qubits[nr_qubits]])\n optimal_layout = Layout()\n optimal_layout.from_dict(qiskit_layout_dict)\n original_pm.append([SetLayout(optimal_layout),\n ApplyLayout(),\n BasicSwap(qiskit_coupling_map)])\n map_original_circuit = original_pm.run(test_circuit)\n optimal_depth = map_original_circuit.depth()\n # print(\"optimal mapping: the circuit has\", optimal_depth, \"cycles\")\n # print(map_original_circuit.draw(style=\"text\"))\n # construct passes that use the DenseLayout+StochasticSwap without initial mapping\n\n\n \"\"\"\n K7M \n \"\"\"\n gate_costs = {'id': 0, 'u1': 0, 'measure': 0,\n 'reset': 0, 'barrier': 0,\n 'u2': 1, 'u3': 1, 'U': 1,\n\n \"ok\": 0,\n # update the costs\n \"rev_cnot\": 4 * 1 + 10, # 4 u2/hadamard + 1 cnot\n \"swap\": 3 * 10 + 4, # 4 u2/hadamard + 3 cnot\n\n 'seed': 19} # pass the seed through gate costs\n\n\n # parameters_string = str(parameters)\n\n # the number of qubits in the device\n parameters[\"nisq_qubits\"] = qiskit_coupling_map.size()\n # Add the gate costs\n parameters[\"gate_costs\"] = gate_costs\n # Should the initial mapping be chosen random?\n parameters[\"initial_map\"] = K7MInitialMapping.HEURISTIC\n parameters[\"unidirectional_coupling\"]=False\n parameters[\"dry_run\"] = False\n\n k7mcomp = K7MCompiler(connection_list[qubits[nr_qubits]], parameters)\n\n execution_time = time.time()\n map_test_circuit, init_time, init_map = k7mcomp.run(test_circuit)\n execution_time = time.time() - execution_time\n\n # print(map_test_circuit.draw(output=\"text\", fold=-1))\n # tmp_circuit = map_test_circuit.decompose()\n tmp_circuit = map_test_circuit\n # print(tmp_circuit.draw(output=\"text\", fold=-1))\n # tmp_circuit = qiskit_to_tk(map_test_circuit)\n # Transform.RebaseToQiskit().DecomposeSWAPtoCX().apply(tmp_circuit)\n depth_result = tmp_circuit.depth()\n\n # print(\"k7m mapping: the circuit has\", depth_result, \"cycles\")\n # print(map_test_circuit.draw(style=\"text\"))\n # accumulate result\n # print(\"----\")\n\n nr_t1 = noOfTranspositions( list(range(nr_qubits)), original_nodes, nr_qubits)\n nr_t2 = noOfTranspositions(original_nodes, init_map, nr_qubits)\n\n\n return optimal_depth, depth_result, execution_time, init_time, nr_t1, nr_t2\n\n\nfile_op_type = \"a\"\nif first_run:\n file_op_type = \"w\"\nfirst_run = False\n\nheader = [\"max_page_ranke\", \"nr_conn_comp\", \"edges\", \"nodes\",\n \"efficiency\", \"smetric\",\n \"optimal_depth\", \"res_depth\",\n \"total_time\", \"init_time\",\n \"nr_t1\", \"nr_t2\"]\n\nwith open(\"circuits_analysis.csv\", \"w\", buffering=1) as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(header)\n print(*header)\n\n for trail in range(10):\n for depth in depth_range[gdv_name]:\n analysis = (depth, trail) + circuit_analysis(depth, trail)\n print(analysis)\n writer.writerow(analysis)\n csvFile.flush()\n\n\nwith open(\"_private_data/training_no_analysis.csv\", \"w\", buffering=1) as csvFile:\n writer = csv.writer(csvFile)\n\n writer.writerow(header)\n print(*header)\n\n for m_depth_p in range(1, nr_qubits + 2, 4):\n for m_c_p in range(1, nr_qubits + 2, 4):\n for b_p in range(0, 21, 2):\n for c_p in range(0, 21, 5):\n for div_p in range(2, 11, 4):\n for cx_p in range(2, 11, 4):\n\n for trail in range(10):\n for depth in depth_range[gdv_name]:\n\n parameters = {\n \"max_depth\": m_depth_p,\n \"max_children\": m_c_p,\n\n \"att_b\": b_p,\n \"att_c\": c_p / 20,\n\n \"div_dist\": div_p / 10,\n \"cx\": cx_p,\n\n # UNUSED\n \"opt_att\": True,\n \"opt_max_t_min\": False,\n \"qubit_increase_factor\": 3,\n \"option_skip_cx\": False,\n \"penalty_skip_cx\": 20,\n \"opt_div_by_act\": False,\n }\n\n analysis = (\"n/a\", \"|\")\n res = benchmark(depth, trail, parameters)\n params = (\"|\", m_depth_p, m_c_p, b_p, c_p, div_p, cx_p, depth, trail)\n line = analysis + res + params\n\n print(line)\n writer.writerow(line)\n\n csvFile.flush()\n\n","sub_path":"papers/arxiv:new/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":9487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"184030507","text":"import argparse\nimport os\nimport time\nimport random\nimport torch\nimport torch.utils.data\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport network\nimport torch.optim as optim\nimport pre_process as prep\nfrom data_list import ImageList\nimport lr_schedule\nfrom logger import Logger\nimport numpy as np\nfrom tensorboardX import SummaryWriter\nimport warnings\nfrom tqdm import tqdm\n\nwarnings.filterwarnings('ignore')\n\n\ndef val(data_set_loader, base_net, f1_net, f2_net, test_10crop, config, num_iter):\n start_test = True\n with torch.no_grad():\n if test_10crop:\n iter_test = [iter(data_set_loader['test'][i]) for i in range(10)]\n for i in range(len(data_set_loader['test'][0])):\n data = [iter_test[j].next() for j in range(10)]\n inputs = [data[j][0] for j in range(10)]\n labels = data[0][1]\n for j in range(10):\n inputs[j] = inputs[j].cuda()\n\n outputs = []\n for j in range(10):\n feature = base_net(inputs[j])\n predict_out1 = f1_net(x=feature, alpha=0)\n predict_out2 = f2_net(x=feature, alpha=0)\n predict_out = predict_out1 + predict_out2\n outputs.append(nn.Softmax(dim=1)(predict_out))\n outputs = sum(outputs)\n\n if start_test:\n all_output = outputs.float().cpu()\n all_label = labels.float()\n start_test = False\n else:\n all_output = torch.cat((all_output, outputs.float().cpu()), dim=0)\n all_label = torch.cat((all_label, labels.float()), dim=0)\n else:\n iter_test = iter(data_set_loader['test'])\n for i in range(len(data_set_loader['test'])):\n data = iter_test.next()\n inputs = data[0]\n labels = data[1]\n inputs = inputs.cuda()\n\n feature = base_net(inputs)\n predict_out1 = f1_net(feature, 0)\n predict_out2 = f2_net(feature, 0)\n outputs = predict_out1 + predict_out2\n\n if start_test:\n all_output = outputs.float().cpu()\n all_label = labels.float()\n start_test = False\n else:\n all_output = torch.cat((all_output, outputs.float().cpu()), 0)\n all_label = torch.cat((all_label, labels.float()), 0)\n\n _, predict = torch.max(all_output, 1)\n accuracy = torch.sum(torch.squeeze(predict).float() == all_label).item() / float(all_label.size()[0])\n if config['is_writer']:\n config['writer'].add_scalars('test', {'test error': 1.0 - accuracy,\n 'acc': accuracy * 100.0},\n num_iter)\n return accuracy * 100.0\n\n\ndef train(config):\n # set pre-process\n prep_dict = {'source': prep.image_train(**config['prep']['params']),\n 'target': prep.image_train(**config['prep']['params'])}\n if config['prep']['test_10crop']:\n prep_dict['test'] = prep.image_test_10crop(**config['prep']['params'])\n else:\n prep_dict['test'] = prep.image_test(**config['prep']['params'])\n\n # prepare data\n data_set = {}\n data_set_loader = {}\n data_config = config['data']\n data_set['source'] = ImageList(open(data_config['source']['list_path']).readlines(),\n transform=prep_dict['source'])\n data_set_loader['source'] = torch.utils.data.DataLoader(data_set['source'],\n batch_size=data_config['source']['batch_size'],\n shuffle=True, num_workers=4, drop_last=True)\n data_set['target'] = ImageList(open(data_config['target']['list_path']).readlines(),\n transform=prep_dict['target'])\n data_set_loader['target'] = torch.utils.data.DataLoader(data_set['target'],\n batch_size=data_config['target']['batch_size'],\n shuffle=True, num_workers=4, drop_last=True)\n if config['prep']['test_10crop']:\n data_set['test'] = [ImageList(open(data_config['test']['list_path']).readlines(),\n transform=prep_dict['test'][i])\n for i in range(10)]\n data_set_loader['test'] = [torch.utils.data.DataLoader(dset, batch_size=data_config['test']['batch_size'],\n shuffle=False, num_workers=4)\n for dset in data_set['test']]\n else:\n data_set['test'] = ImageList(open(data_config['test']['list_path']).readlines(),\n transform=prep_dict['test'])\n data_set_loader['test'] = torch.utils.data.DataLoader(data_set['test'],\n batch_size=data_config['test']['batch_size'],\n shuffle=False, num_workers=4)\n\n # set base network\n net_config = config['network']\n base_net = net_config['name']() # res50\n base_net = base_net.cuda()\n # add domain, classifier network\n class_num = config['network']['params']['class_num']\n ad_net = network.Domain(in_features=base_net.output_num(), hidden_size=1024)\n f1_net = network.Classifier(in_features=base_net.output_num(), hidden_size=128, class_num=class_num)\n f2_net = network.Classifier(in_features=base_net.output_num(), hidden_size=128, class_num=class_num)\n ad_net = ad_net.cuda()\n f1_net = f1_net.cuda()\n f2_net = f2_net.cuda()\n parameter_list = base_net.get_parameters() + ad_net.get_parameters() \\\n + f1_net.get_parameters() + f2_net.get_parameters()\n\n # multi gpus\n gpus = config['gpu'].split(',')\n if len(gpus) > 1:\n base_net = nn.DataParallel(base_net, device_ids=[int(i) for i in gpus])\n f1_net = nn.DataParallel(f1_net, device_ids=[int(i) for i in gpus])\n f2_net = nn.DataParallel(f2_net, device_ids=[int(i) for i in gpus])\n ad_net = nn.DataParallel(ad_net, device_ids=[int(i) for i in gpus])\n\n # set optimizer\n optimizer_config = config['optimizer']\n optimizer = optimizer_config['type'](parameter_list, **(optimizer_config['optim_params']))\n schedule_param = optimizer_config['lr_param']\n lr_scheduler = lr_schedule.schedule_dict[optimizer_config['lr_type']]\n\n # set loss\n class_criterion = nn.CrossEntropyLoss()\n transfer_criterion = nn.BCELoss()\n loss_params = config['loss']\n\n # train\n len_train_source = len(data_set_loader['source'])\n len_train_taget = len(data_set_loader['target'])\n best_acc = 0.0\n since = time.time()\n for num_iter in tqdm(range(config['max_iter'])):\n if num_iter % config['val_iter'] == 0:\n base_net.train(False)\n f1_net.train(False)\n f2_net.train(False)\n temp_acc = val(data_set_loader, base_net, f1_net, f2_net,\n test_10crop=config['prep']['test_10crop'],\n config=config, num_iter=num_iter)\n if temp_acc > best_acc:\n best_acc = temp_acc\n log_str = 'iter: {:d}, accu: {:.4f}\\ntime: {:.4f}'.format(num_iter, temp_acc, time.time() - since)\n config['logger'].logger.debug(log_str)\n config['results'][num_iter].append(temp_acc)\n if num_iter % config['snapshot_iter'] == 0:\n # TODO\n pass\n\n base_net.train(True)\n f1_net.train(True)\n f2_net.train(True)\n ad_net.train(True)\n\n optimizer = lr_scheduler(optimizer, num_iter, **schedule_param)\n optimizer.zero_grad()\n\n if num_iter % len_train_source == 0:\n iter_source = iter(data_set_loader['source'])\n if num_iter % len_train_taget == 0:\n iter_target = iter(data_set_loader['target'])\n input_source, label_source = iter_source.next()\n input_target, _ = iter_target.next()\n input_source, label_source, input_target = input_source.cuda(), label_source.cuda(), input_target.cuda()\n inputs = torch.cat((input_source, input_target), 0)\n batch_size = len(label_source)\n\n # class-wise adaptation\n features = base_net(inputs)\n alpha = 2. / (1. + np.exp(-10 * float(num_iter / config['max_iter']))) - 1\n output1 = f1_net(features, alpha)\n output2 = f2_net(features, alpha)\n output_s1 = output1[:batch_size, :]\n output_s2 = output2[:batch_size, :]\n output_t1 = output1[batch_size:, :]\n output_t2 = output2[batch_size:, :]\n output_t1 = F.softmax(output_t1)\n output_t2 = F.softmax(output_t2)\n\n inconsistency_loss = torch.mean(torch.abs(output_t1 - output_t2))\n classifier_loss1 = class_criterion(output_s1, label_source)\n classifier_loss2 = class_criterion(output_s2, label_source)\n classifier_loss = classifier_loss1 + classifier_loss2\n\n # domain-wise adaptation\n domain_labels = torch.from_numpy(np.array([[1]] * batch_size + [[0]] * batch_size)).float().cuda()\n domain_output = ad_net(features, alpha)\n transfer_loss = transfer_criterion(domain_output, domain_labels)\n\n total_loss = classifier_loss + loss_params['domain_off'] * transfer_loss \\\n - loss_params['dis_off'] * inconsistency_loss\n total_loss.backward()\n optimizer.step()\n\n if num_iter % config['val_iter'] == 0:\n print('class:', classifier_loss.item(),\n 'domain:', transfer_loss.item() * loss_params['domain_off'],\n 'inconsistency:', inconsistency_loss.item() * loss_params['dis_off'],\n 'total:', total_loss.item())\n if config['is_writer']:\n config['writer'].add_scalars('train', {'total': total_loss.item(), 'class': classifier_loss.item(),\n 'domain': transfer_loss.item() * loss_params['domain_off'],\n 'inconsistency': inconsistency_loss.item() * loss_params[\n 'dis_off']},\n num_iter)\n if config['is_writer']:\n config['writer'].close()\n\n return best_acc\n\n\ndef empty_dict(config):\n config['results'] = {}\n for i in range(config['max_iter'] // config['val_iter'] + 1):\n key = config['val_iter'] * i\n config['results'][key] = []\n config['results']['best'] = []\n\n\ndef print_dict(config):\n for i in range(config['max_iter'] // config['val_iter'] + 1):\n key = config['val_iter'] * i\n log_str = 'iter: {:d}, average: {:.4f}'.format(key, np.average(config['results'][key]))\n config['logger'].logger.debug(log_str)\n log_str = 'best, average: {:.4f}'.format(np.average(config['results']['best']))\n config['logger'].logger.debug(log_str)\n config['logger'].logger.debug('-' * 100)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Joint Adversarial Domain Adaptation')\n parser.add_argument('--seed', type=int, default=1, help='manual seed')\n parser.add_argument('--gpu', type=str, nargs='?', default='0', help='device id to run')\n parser.add_argument('--resnet', type=str, default='ResNet50', help='Options: 50')\n parser.add_argument('--data_set', type=str, default='office', help='Options: office,clef')\n parser.add_argument('--source_path', type=str, default='../data/office/amazon_list.txt', help='The source list')\n parser.add_argument('--target_path', type=str, default='../data/office/webcam_list.txt', help='The target list')\n parser.add_argument('--max_iter', type=int, default=20001, help='max iterations')\n parser.add_argument('--val_iter', type=int, default=1000, help='interval of two continuous test phase')\n parser.add_argument('--lr', type=float, default=0.0003, help='learning rate')\n parser.add_argument('--batch_size', type=int, default=36, help='mini batch size')\n parser.add_argument('--output_path', type=str, default='checkpoint/', help='save log/scalar/model file path')\n parser.add_argument('--log_file', type=str, default='log', help='log file name')\n parser.add_argument('--is_writer', type=bool, default=True, help='whether record for tensorboard')\n parser.add_argument('--snapshot_iter', type=int, default=5000, help='interval of two continuous output model')\n args = parser.parse_args()\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n config = {'seed': args.seed, 'gpu': args.gpu, 'max_iter': args.max_iter, 'val_iter': args.val_iter,\n 'is_writer': args.is_writer, 'snapshot_iter': args.snapshot_iter,\n 'output_path': args.output_path,\n 'loss': {'domain_off': 1.0, 'dis_off': 1.0},\n 'prep': {'test_10crop': True, 'params': {'resize_size': 256, 'crop_size': 224}},\n 'network': {'name': network.ResBase, 'params': {'resnet_name': args.resnet, 'class_num': 31}},\n 'optimizer': {'type': optim.SGD,\n 'optim_params': {'lr': args.lr, 'momentum': 0.9, 'weight_decay': 0.0005, 'nesterov': True},\n 'lr_type': 'inv',\n 'lr_param': {'lr': args.lr, 'gamma': 0.0003, 'power': 0.75}}, 'data_set': args.data_set,\n 'data': {\n 'source': {'name': args.source_path.split('/')[-1].split('_')[0], 'list_path': args.source_path,\n 'batch_size': args.batch_size},\n 'target': {'name': args.target_path.split('/')[-1].split('_')[0], 'list_path': args.target_path,\n 'batch_size': args.batch_size},\n 'test': {'list_path': args.target_path, 'batch_size': args.batch_size}}}\n\n if not os.path.exists(config['output_path']):\n os.makedirs(config['output_path'])\n if config['is_writer']:\n config['writer'] = SummaryWriter(log_dir=config['output_path'] + '/scalar/', )\n config['logger'] = Logger(logroot=config['output_path'], filename=args.log_file, level='debug')\n config['logger'].logger.debug(str(config))\n\n empty_dict(config)\n config['results']['best'].append(train(config))\n print_dict(config)\n","sub_path":"Office31/train_office.py","file_name":"train_office.py","file_ext":"py","file_size_in_byte":14726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"530781541","text":"#!/usr/bin/env python3\n\nimport os\n\ndef conv(color):\n if color == 'R':\n return 'red'\n if color == 'G':\n return 'green'\n if color == 'B':\n return 'black'\n if color == 'W':\n return 'white'\n if color == 'U':\n return 'blue'\n\nCOLORS = ['R', 'G', 'B', 'W', 'U']\nfor col in COLORS:\n for i in range(34):\n os.rename(col + str(i) + '.csv', conv(col) + '/' + col + str(i) + '.csv')\n","sub_path":"move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"140409713","text":"#!/usr/local/bin/python\n\nfrom __future__ import print_function\n#from sklearn.model_selection import RepeatedStratifiedKFold\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_selection import SelectFromModel\nimport numpy as np\nimport pandas as pd\nfrom pprint import pprint\nfrom os import listdir\nfrom os.path import isfile, join\nfrom sklearn.model_selection import StratifiedKFold\nfrom scipy import stats\nimport numpy as np\nfrom sklearn import linear_model, svm\nimport re\nfrom sklearn.pipeline import Pipeline\n#s = \"../braindata/data_1_mor_select_100.csv\"\nimport os\nfrom sklearn import linear_model, svm\nfrom sklearn.ensemble import ExtraTreesClassifier\n\n\nimport pickle\nimport os\nimport scipy.io\nfrom scipy import stats\n\nimport pandas as pd\nfrom numpy import *\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\nimport pandas as pd\nimport argparse\nfrom sklearn.model_selection import GridSearchCV, cross_val_score,cross_val_predict,StratifiedKFold\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.metrics import accuracy_score,roc_curve, auc,f1_score,confusion_matrix,roc_auc_score\n\nos.getcwd()\nos.chdir('../braindata')\n\n###########################################################################################################\ndatafile=\"data_2_conn\"######################################################################################\ndatafile_csv=datafile + '.csv'\ndata_name=datafile\n###########################################################################################################\n\ndd =pd.read_csv(datafile_csv,header=0)\nimport csv\n\nwith open(datafile_csv, 'r') as f:\n d_reader = csv.DictReader(f)\n\n #get fieldnames from DictReader object and store in list\n headers = d_reader.fieldnames\ndata=np.array(dd)\n\n#print(data.shape)\nidx_IN_columns = np.append(np.array([3,4]),np.array(range(11,data.shape[1])))\nX=data[:,idx_IN_columns]\nX = stats.zscore(X)\n\n###########################################################################################################\ny=data[:,6]######################################################################################################\n#5: ad-smi / 6:mci-smi / 7:ADONLYvsSMI / 8:ad-mci / 9:adonly-mci / 10:adonly - adwithsmallvv\nname='TEST_MCIvsSMC_newgrid2'##################################################################################\n###########################################################################################################\n\n\n# In[ ]:\n\nind_num=np.isnan(y)\n# print(ind_num.shape)\n\n\ny_no_nan = y[~ind_num]\n\nX_no_nan = X[~ind_num,:]\n\n # print(y.shape)\n\ny=y_no_nan\nX=X_no_nan\nfeature_num_all=[]\nlr_all_feature=[]\nsvm_all_feature=[]\nlr_fls_feature=[]\nsvm_fls_feature=[]\nbase_labels= []\n\n#X=X.reshape(X.size,1)\n#X=X.astype(np.float64,copy=False)\nnp.isnan(X).any()\n#feature_num=features.shape[1]\nX[np.isnan(X)] = np.median(X[~np.isnan(X)])\n\nn_fold = 3\n\nall_TP = []\nall_TN = []\nall_FP = []\nall_FN = []\n\nall_acc = []\nall_sen = []\nall_spec = []\nall_auc = []\n\nall_roc_label = []\nall_roc_pred = []\nall_roc_prob = []\n\nrs_list=[33994,31358,27381,8642,7012,42023,44642,44002,30706,12571]\nrs_list3=[33994,31358,27381]\nfor rs in rs_list3:\n print('********random seed:{}'.format(rs))\n\n inner_cv = StratifiedKFold(n_splits=n_fold, shuffle=True, random_state=rs)\n outer_cv = StratifiedKFold(n_splits=n_fold, shuffle=True, random_state=rs)\n\n scaler = StandardScaler()\n #scaler = RobustScaler()\n scaler.fit(X)\n X = scaler.transform(X)\n\n avg_acc = []\n avg_TP = []\n avg_TN = []\n avg_FP = []\n avg_FN = []\n avg_sen = []\n avg_spec = []\n avg_auc = []\n\n\n roc_label = []\n roc_pred = []\n roc_prob = []\n\n for train_index, test_index in outer_cv.split(X, y):\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n # 'featureExtract__n_estimators': np.arange(10, 100, 10),\n\n\n\n ######### oth grid\n #params = {'randomforest__min_samples_leaf': np.arange(1, 51, 5),\n # 'randomforest__n_estimators': np.arange(10, 100, 10)}\n\n\n\n ######### 1st grid\n #params = {'randomforest__min_samples_leaf': np.arange(1, 51, 1),\n # 'randomforest__n_estimators': np.arange(10, 500, 10)}\n\n\n ######### 2nd grid\n params = {'randomforest__min_samples_leaf': np.arange(1, 51, 2),\n 'randomforest__n_estimators': np.arange(10, 500, 20),\n 'randomforest__min_samples_split' : [2, 4]}\n\n params_svm = [\n {'randomforest__min_samples_leaf': np.arange(1, 51, 5),\n 'randomforest__n_estimators': np.arange(10, 100, 10)},\n {'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],'C': [1, 10, 100, 1000]},\n {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}\n ]\n\n #pipe = Pipeline([\n # ('featureExtract', SelectFromModel(ExtraTreesClassifier())),\n # ('randomforest', RandomForestClassifier())\n #])\n\n pipe_rf = Pipeline([\n ('featureExtract', SelectFromModel(ExtraTreesClassifier())),\n ('randomforest', RandomForestClassifier())\n ])\n\n\n\n #clf = GridSearchCV(estimator=pipe, param_grid=params, cv=inner_cv, scoring='accuracy',n_jobs=8)\n clf = GridSearchCV(estimator=pipe_rf, param_grid=params, cv=inner_cv,scoring='accuracy', n_jobs=96)\n clf.fit(X_train, y_train)\n\n fs = clf.best_estimator_.named_steps['featureExtract']\n mask = fs.get_support()\n y_pred = clf.predict(X_test)\n y_prob = clf.predict_proba(X_test)\n # roc_pred = clf.predict_proba(X_test)\n\n acc = accuracy_score(y_test, y_pred)\n auc = roc_auc_score(y_test, y_prob[:, 1])\n\n roc_label = np.append(roc_label, y_test)\n roc_pred = np.append(roc_pred, y_pred)\n roc_prob = np.append(roc_prob, y_prob[:, 1])\n\n #confusion mat\n\n conf_mat = confusion_matrix(y_test, y_pred)\n\n TP = conf_mat[0][0]\n FP = conf_mat[0][1]\n FN = conf_mat[1][0]\n TN = conf_mat[1][1]\n\n print(TP, FP, FN, TN)\n sen = TP / (TP + FN)\n spec = TN / (TN + FP)\n\n # avg meausres\n avg_TP = np.append(avg_TP, TP)\n avg_TN = np.append(avg_TN, TN)\n avg_FP = np.append(avg_FP, FP)\n avg_FN = np.append(avg_FN, FN)\n\n avg_acc = np.append(avg_acc, acc)\n avg_sen = np.append(avg_sen, sen)\n avg_spec = np.append(avg_spec, spec)\n avg_auc = np.append(avg_auc, auc)\n\n print('Accuracy:{},AUC:{}'.format(acc, auc))\n print('Sensitivity:{},Specificity:{}'.format(sen, spec))\n\n # all measures\n all_TP = np.append(all_TP, avg_TP)\n all_TN = np.append(all_TN, avg_TN)\n all_FP = np.append(all_FP, avg_FP)\n all_FN = np.append(all_FN, avg_FN)\n\n all_acc = np.append(all_acc, avg_acc)\n all_sen = np.append(all_sen, avg_sen)\n all_spec = np.append(all_spec, avg_spec)\n all_auc = np.append(all_auc, avg_auc)\n\n all_roc_label = np.append(all_roc_label, roc_label)\n all_roc_pred = np.append(all_roc_pred, roc_pred)\n all_roc_prob = np.append(all_roc_prob, roc_prob)\n\n\n# print(all_sen)\nimport numpy as np, scipy.stats as st\n\n#all_acc\n#all_sen\n#all_spec\n\n\n\nacc_CI=st.t.interval(0.95, len(all_acc)-1, loc=np.nanmean(all_acc), scale=st.sem(all_acc))\nsen_CI=st.t.interval(0.95, len(all_sen)-1, loc=np.nanmean(all_sen), scale=st.sem(all_sen))\nspec_CI=st.t.interval(0.95, len(all_spec)-1, loc=np.nanmean(all_spec), scale=st.sem(all_spec))\nauc_CI=st.t.interval(0.95, len(all_auc)-1, loc=np.nanmean(all_auc), scale=st.sem(all_auc))\nimport os\n\ntxt_name=path_to_save+'/'+name + '.txt'\nprint(\"ACC={a}, 95%CI={l}-{u}, sd={sd}\".format(a=np.nanmean(all_acc),l=acc_CI[0], u=acc_CI[1], sd=np.nanstd(all_acc)),file=open(txt_name, \"a\"))\nprint(\"AUC={a}, 95%CI={l}-{u},sd={sd}\".format(a=np.nanmean(all_auc), l=auc_CI[0], u=auc_CI[1], sd=np.nanstd(all_auc)),file=open(txt_name, \"a\"))\nprint(\"SENSITIVITY={a}, 95%CI={l}-{u},sd={sd}\".format(a=np.nanmean(all_sen), l=sen_CI[0],u=sen_CI[1], sd=np.nanstd(all_sen)),file=open(txt_name, \"a\"))\nprint(\"SPECIFICITY={a}, 95%CI={l}-{u},sd={sd}\".format(a=np.nanmean(all_spec), l=spec_CI[0],u=spec_CI[1], sd=np.nanstd(all_spec)),file=open(txt_name, \"a\"))\n\n#print(\"Total score for {n} is {s}\".format(n=name, s=score))\n\n\n#print(\"RF_SENSITIVITY={}\".format(np.mean(all_sen)),file=open(txt_name, \"a\"))\n#print(\"RF_SENSITIVITY95%CI={}\".format(sen_CI),file=open(txt_name, \"a\"))\n\n#print(\"RF_SPECIFICITY={}\".format(np.mean(all_spec)),file=open(txt_name, \"a\"))\n#print(\"RF_SPECIFICITY95%CI={}\".format(spec_CI),file=open(txt_name, \"a\"))\n\n\n # ROC curve\nfpr = dict()\ntpr = dict()\nroc_auc = dict()\n\nfpr, tpr, _ = roc_curve(all_roc_label, all_roc_prob)\n#auc = roc_auc_score(all_roc_label, all_roc_prob)\n\nplt.figure()\n\nplt.plot(fpr, tpr, lw=2, label='random forest (AUC = %0.2f)' % np.mean(all_auc))\nplt.plot([0, 1], [0, 1], color='gray', lw=1, linestyle='--')\nplt.xlim([-0.01, 1.01])\nplt.ylim([-0.01, 1.01])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('roc')\nplt.legend(loc=\"lower right\")\n#plt.savefig('10x_Combined_ROC.eps')\nroc_name='../imgs2/' + name + '_' + data_name + '.pdf'\nplt.savefig(roc_name)\n#plt.show()\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n","sub_path":"src_update_idp/0ML_combined_nestedCV_JC.py","file_name":"0ML_combined_nestedCV_JC.py","file_ext":"py","file_size_in_byte":9824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"604778663","text":"# -*- coding: utf-8 -*-\n__author__ = 'Administrator'\nfrom django.shortcuts import HttpResponse\nfrom django.shortcuts import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nimport admininfo\nimport account\nfrom app.common import validator\nfrom app.facade import factory\nfrom app.common import func\n\n\n\n@account.checkLogin\ndef Index(request):\n currentType = func.get_int_param_from_get(request,'type')\n jobTypeFacade = factory.CreateJobTypeFacade()\n jobFacade = factory.CreateJobFacade()\n\n jobTypes = jobTypeFacade.Search(count=100)\n jobs = jobFacade.Search(type=currentType,count=100)\n print(jobs)\n\n if not currentType:\n currentType = jobTypes['list'][0]['id']\n\n return render_to_response('admin/option_job_list.html',locals())\n\n@account.checkLogin\ndef Detail(request):\n jobFacade = factory.CreateJobFacade()\n job = {}\n id = func.get_int_param_from_get(request,'id')\n if request.method == 'POST':\n post = True\n messages=list()\n title = func.get_str_param_from_post(request,'title')\n type = func.get_int_param_from_post(request,'type')\n referrer = func.get_str_param_from_post(request,'referrer')\n if id:\n job = jobFacade.Load(id)\n job['title'] = title\n job['type'] = type\n if not type:\n messages.append(u'请填写学历类型')\n if not title:\n messages.append(u'请填写学历名称')\n if not messages:\n if not id:\n autoIdFacade = factory.CreateAutoIdFacade()\n job['id'] = autoIdFacade.GetNewId('job')\n jobFacade.Update(job)\n return HttpResponseRedirect(referrer)\n\n referrer = func.get_referer(request,default_url='/admin/option/job/')\n jobTypeFacade =factory.CreateJobTypeFacade()\n jobTypes = jobTypeFacade.Search(count=100)\n currentType = func.get_int_param_from_get(request,'type')\n\n if id:\n job = jobFacade.Load(id)\n return render_to_response('admin/option_job_detail.html',locals())\n\n@account.checkLogin\ndef Remove(request):\n id = func.get_int_param_from_get(request,'id')\n jobFacade = factory.CreateJobFacade()\n jobFacade.Remove(id)\n referrer = func.get_referer(request,default_url='/admin/option/Job/')\n return HttpResponseRedirect(referrer)","sub_path":"app/views/admin/dict_bak/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"490691800","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pickle\nfrom collections import namedtuple\nimport get_quote as quote\nimport sys\n\ntransactions_file_path = 'data/transactions.csv'\nwatchlist_file_path = 'data/watchlist.csv'\nportfolio_file_path = 'data/stock_portfolio.csv'\nsnapshot_file_path = 'data/snapshot.csv'\n\ndef avg_price(old_price, old_quantity, new_price, new_quantity):\n return float(c((old_quantity*old_price + new_quantity*new_price)/(old_quantity + new_quantity)))\n\n\ndef round_to_2(num):\n return float(\"{0:.2f}\".format(num))\n\ndef get_ids_from_file(file_path):\n return [line.strip().upper() for line in open(file_path, 'r').readlines()]\n\n\ndef save_portfolio_to_file(portfolio):\n p_file = open(portfolio_file_path, 'w')\n curr_price = quote.get_quotes(sorted(stocks.keys()), False)\n for i in range(len(curr_price)):\n change_from_buy_price = float(curr_price[i][1].replace(\",\", \"\")) - portfolio[curr_price[i][0]][\"avg_price\"]\n percent_change = round_to_2(change_from_buy_price*100/portfolio[curr_price[i][0]][\"avg_price\"])\n print(percent_change)\n if change_from_buy_price > 0:\n curr_price[i] = curr_price[i]._replace(Change_pts = \"+\" + str(change_from_buy_price))\n curr_price[i] = curr_price[i]._replace(Change_percent = quote.Color.green(str(percent_change)))\n else:\n curr_price[i] = curr_price[i]._replace(Change_pts = str(change_from_buy_price))\n curr_price[i] = curr_price[i]._replace(Change_percent = quote.Color.red(str(percent_change)[1:]))\n # stock, volume, avg_price, curr_price, changefromavgprice, change_percent\n p_file.write(curr_price[i][0] + ',' + str(portfolio[curr_price[i][0]][\"total_quantity\"]) + ',' + str(portfolio[curr_price[i][0]][\"avg_price\"]) + ',' + curr_price[i][1] + ',' + curr_price[i][2] + ',' + str(percent_change) + '\\n')\n p_file.close()\n quote.preety_print_stock(curr_price)\n\n\ndef load_portfolio():\n stocks = {}\n t_file = open(transactions_file_path, 'r')\n for line in t_file.readlines():\n name, quantity, date, price = line.strip().split(',')\n price = float(price)\n quantity = int(quantity)\n name = name.upper()\n if name in stocks.keys():\n stocks[name][\"quantity\"].append(quantity)\n stocks[name][\"price\"].append(price)\n # avg_price(stocks[name][\"price\"], stocks[name][\"quantity\"], price, quantity)\n else:\n stocks[name] = {\"quantity\": [quantity], \"price\": [price]}\n for stock in stocks.keys():\n stocks[stock][\"total_quantity\"] = sum(stocks[stock][\"quantity\"])\n stocks[stock][\"avg_price\"] = round_to_2(sum(stocks[stock][\"price\"][i] * stocks[stock][\"quantity\"][i] for i in range(len(stocks[stock][\"price\"])))/stocks[stock][\"total_quantity\"])\n return stocks\n\n\ndef snapshot():\n quote.get_quotes(get_ids_from_file(snapshot_file_path))\n\n\ndef get_watchlist_prices():\n quote.get_quotes(sorted(get_ids_from_file(watchlist_file_path)))\n\n\ndef show_all(portfolio):\n print(\"My portfolio >>>>>>>>>>\")\n quote.get_quotes(sorted(stocks.keys()))\n print(\"Market snapshot >>>>>>>\")\n snapshot()\n print(\"Watchlist >>>>>>>\")\n get_watchlist_prices()\n\ndef watchlist_change_from_date(period):\n pass\n\nif __name__ == '__main__':\n stocks = load_portfolio()\n if len(sys.argv) > 1:\n for item in sys.argv[1].split(\",\"):\n if item == 's':\n print(\"Market snapshot >>>>>>>\")\n snapshot()\n if item == 'p':\n print(\"My portfolio >>>>>>>>>>\")\n quote.get_quotes(sorted(stocks.keys()))\n if item == 'w':\n print(\"Watchlist >>>>>>>\")\n get_watchlist_prices()\n if item == 'savep':\n save_portfolio_to_file(stocks)\n else:\n show_all(stocks)\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"433975379","text":"from django import forms\nfrom django.forms import fields\nfrom .models import Post , Comment\n\nclass PostForm(forms.ModelForm):\n body = forms.CharField(\n label='',\n widget=forms.Textarea(attrs={\n 'rows':'3',\n 'palceholder': 'Post Something...',\n }))\n\n class Meta:\n model = Post \n fields = ['body']\n\nclass CommentForm(forms.ModelForm):\n comment = forms.CharField(\n label='',\n widget=forms.Textarea(attrs={\n 'rows':'3',\n 'palceholder': 'Post Something...'\n }))\n\n class Meta:\n model = Comment\n fields = ['comment']","sub_path":"social/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"126543503","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 07 01:25:07 2017\r\n\r\n@author: z81022868\r\n\"\"\"\r\nimport win32com\r\nfrom win32com.client import Dispatch\r\ndef Cut(sigin):\r\n if sigin:\r\n ind1,ind2=sigin.find(u\"…\"),sigin.find('...')\r\n if ind1>0 and ind2>0:# constant.historyRootShellP[i]):\n shellF = exp(-((tmpP/rootB) ** rootC))\n constant.historyRootShellP[i] = tmpP\n constant.historyRootShellK[i] = shellF\n shellK = rootKmax * 200.0 * constant.historyRootShellK[i]\n if(shellK < 1E-12):\n shellK = 1E-12\n dp += flow / shellK\n tmpP = rizoP + dp\n return dp\n\n# get stem dp with and without history\ndef GetStemDP(rootP, stemKmax, stemB, stemC, flow, history):\n tmpP = rootP\n dp = 0.0\n if(history == 0):\n for i in range(200):\n shellF = exp(-((tmpP/stemB) ** stemC))\n shellK = stemKmax * 200.0 * shellF\n if(shellK < 1E-12):\n shellK = 1E-12\n dp += flow / shellK\n tmpP = rootP + dp\n else:\n for i in range(200):\n if(tmpP > constant.historyStemShellP[i]):\n shellF = exp(-((tmpP/stemB) ** stemC))\n constant.historyStemShellP[i] = tmpP\n constant.historyStemShellK[i] = shellF\n shellK = stemKmax * 200.0 * constant.historyStemShellK[i]\n if(shellK < 1E-12):\n shellK = 1E-12\n dp += flow / shellK\n tmpP = rootP + dp\n return dp\n\n# get leaf dp with and without history\ndef GetLeafDP(stemP, leafKmax, leafB, leafC, flow, history):\n tmpP = stemP\n dp = 0\n if(history == 0):\n for i in range(200):\n shellF = exp(-((tmpP/leafB) ** leafC))\n shellK = leafKmax * 200.0 * shellF\n if(shellK < 1E-12):\n shellK = 1E-12\n dp += flow / shellK\n tmpP = stemP + dp\n else:\n for i in range(200):\n if(tmpP > constant.historyLeafShellP[i]):\n shellF = exp(-((tmpP/leafB) ** leafC))\n constant.historyLeafShellP[i] = tmpP\n constant.historyLeafShellK[i] = shellF\n shellK = leafKmax * 200.0 * constant.historyLeafShellK[i]\n if(shellK < 1E-12):\n shellK = 1E-12\n dp += flow / shellK\n tmpP = stemP + dp\n return dp\n","sub_path":"python/spac/supply_etop.py","file_name":"supply_etop.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"12408542","text":"# Unit Parser Module\n#\n# Quick & dirty python script to parse si-units\n\n# Main Program\n#############################################\nimport re\n\n\n# Control\nFLAG_DERIVED=True\nFLAG_FULL_NAMES=False\n\n\n# Unit System\n\n# LEXER\n\nMUL='[⋅*]'\nPOW='(?:\\^|\\*\\*|)'\n#EXP='[eE]'\nSIGN='[-+]'\n\nNUM='{SIGN}?\\d+(?:\\.\\d+)?'.format(**locals())\n\n\nMANT=NUM\nEXP='(?:[eE]| ?\\* ?10{POW}(\\(?{NUM}\\)))'.format(**locals())\nFLOAT='(({MANT})(?:{EXP})?)'.format(**locals())\n\n# num part\n# -----------------------------------\nreFloatNum = '([-+]?\\d+\\.\\d+)'\nreFloatExp = '(?:[eE]([-+]?\\d\\d?)| ?\\* ?10\\^(\\(?[-+]?\\d\\d?\\)?))?'\nreFloat = '(' + reFloatNum + reFloatExp + ')'\n\n\nprint(reFloat)\nprint(FLOAT)\n\n# dimesnion part\n# -----------------------------------\nrePrefix = '[zafpnumkMGTPEZ]'\nreBaseUnit = 'm|g|s|A|K|deg'\nreDerivedUnit = 'Hz|N|Pa|J|W|V|C|Ω|F|H|Wb|T'\nreUnit = reBaseUnit\n\nrePrefixFull = 'zepto|atto|femto|pico|nano|micro|milli|kilo|mega|giga|tera|peta|exa|zetta'\nreBaseUnitFull = 'meter|gram|second|ampere|kelvin|degree'\nreDerivedUnitFull= 'hertz|newton|pascal|joule|watt|volt|coulomb|ohm|farad|henry|weber|tesla'\n\nif(FLAG_FULL_NAMES):\n\trePrefix = rePrefixFull\n\tif(FLAG_DERIVED):\n\t\treUnit = '{reBaseUnitFull}|{reDerivedUnitFull}'.format(**locals())\n\telse:\n\t\treUnit = reBaseUnitFull\nelse:\n\tif(FLAG_DERIVED):\n\t\treUnit = '{reBaseUnit}|{reDerivedUnit}'.format(**locals())\n\telse:\n\t\treUnit = reBaseUnit\n\nreExp = '{POW}({NUM})'.format(**locals())\nreExp2 = '([⁺⁻]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)'\n\n# dimesnion part\n# -----------------------------------\n\n# expansion: \"{name} is a {adjective} {noun} that {verb}\".format(**locals())\n# hanning%(num)s.pdf' % locals()\nreDim = '({rePrefix})?({reUnit})(?:{reExp}|{reExp2})?'.format(**locals())\n\nreDims = '('+reDim+'(?: ?[*⋅] ?'+reDim+')*)' # + '(?:/' + reDimMul + ')?'\n\nreQuantity = FLOAT + ' ' + reDims + '(?=[ .,;)]|$)'\n\n\nclass Unit_Type:\n\tval = 0.0\n\texp = 0\n\tm = 0\n\tkg = 0\n\ts = 0\n\tA = 0\n\tK = 0\n\tdeg = 0\n\n\ndef printQuantity(quantity):\n\tprint(\"Value: \" + repr(quantity.val) + \", exp: \" + repr(quantity.exp) )\n\tprint(\"Units (m,kg,s,A,K,deg): (\" + repr(quantity.m) + \", \" + repr(quantity.kg) + \", \" + repr(quantity.s) + \", \" + repr(quantity.A) + \", \" + repr(quantity.K) + \", \" + repr(quantity.deg) + \")\")\n\tprint(\"\")\n\n\ndef parseQuantity(text):\n\tmatches = re.findall(reQuantity, text, re.DOTALL)\n\tfor match in matches:\n\t\tprint(match)\n\t\tmyQuantity = Unit_Type()\n\t\tmyQuantity.val = parseValue(match[0])\n\t\tparseDimension(myQuantity, match[3])\n\t\tprintQuantity(myQuantity)\n\ndef parseValue(text):\n\tmatch = re.search(FLOAT, text)\n\tvalstr = match.group(2)\n\tif (match.group(3) != None):\n\t\tvalstr += 'e'+match.group(3)\n\treturn float(valstr)\n\n\ndef parseDimension(quantity, text):\n\tmatches = re.findall(reDim, text, re.DOTALL)\n\tfor match in matches:\n\t\tquantity = setExponent(quantity, match[0], match[1])\n\t\tquantity = setDimension(quantity, match[1], match[2]+match[3])\n\treturn quantity\n\n\ndef setExponent(quantity, prefixstr, dimstr):\n\n\tif (prefixstr == 'p'):\n\t\tquantity.exp += -12\n\t\tquantity.val *= 10.0**-12\n\telif (prefixstr == 'n'):\n\t\tquantity.exp += -9\n\t\tquantity.val *= 10.0**-9\n\telif (prefixstr == 'u'):\n\t\tquantity.exp += -6\n\t\tquantity.val *= 10.0**-6\n\telif (prefixstr == 'm'):\n\t\tquantity.exp += -3\n\t\tquantity.val *= 10.0**-3\n\telif (prefixstr == 'k'):\n\t\tquantity.exp += 3\n\t\tquantity.val *= 10.0**3\n\telif (prefixstr == 'M'):\n\t\tquantity.exp += 6\n\t\tquantity.val *= 10.0**6\n\telif (prefixstr == 'G'):\n\t\tquantity.exp += 9\n\t\tquantity.val *= 10.0**9\n\n\tif (dimstr == 'g'):\n\t\tquantity.exp += -3\n\t\tquantity.val *= 10.0**-3\n\n\t#quantity.val = quantity.val * 10.0**quantity.exp\n\treturn quantity\n\n\ndef setDimension(quantity, dimstr, expstr):\n\tif (expstr == ''):\n\t\texpstr = '1'\n\telif (re.search('[⁰¹²³⁴⁵⁶⁷⁸⁹]', expstr, re.UNICODE)):\n\t\texpstr = parseSupValue(expstr)\n\n\texp = int(expstr)\n\n\tif(FLAG_FULL_NAMES):\n\t\tif (dimstr == 'meter'):\n\t\t\tquantity.m += exp\n\t\telif (dimstr == 'gram'):\n\t\t\tquantity.kg += exp\n\t\telif (dimstr == 'second'):\n\t\t\tquantity.s += exp\n\t\telif (dimstr == 'ampere'):\n\t\t\tquantity.A += exp\n\t\telif (dimstr == 'kelvin'):\n\t\t\tquantity.K += exp\n\t\telif (dimstr == 'degree'):\n\t\t\tquantity.deg += exp\n\n\t\t# derived\n\t\tif (FLAG_DERIVED):\n\t\t\tif (dimstr == 'hertz'):\n\t\t\t\tquantity.s += -1 * exp\n\t\t\telif (dimstr == 'newton'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'pascal'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += -1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'joule'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'watt'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.s += -3 * exp\n\t\t\telif (dimstr == 'volt'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -1 * exp\n\t\t\t\tquantity.s += -3 * exp\n\t\t\telif (dimstr == 'coulomb'):\n\t\t\t\tquantity.A += 1 * exp\n\t\t\t\tquantity.s += 1 * exp\n\t\t\telif (dimstr == 'ohm'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -2 * exp\n\t\t\t\tquantity.s += -3 * exp\n\t\t\telif (dimstr == 'farad'):\n\t\t\t\tquantity.kg += -1 * exp\n\t\t\t\tquantity.m += -2 * exp\n\t\t\t\tquantity.A += 2 * exp\n\t\t\t\tquantity.s += 4 * exp\n\t\t\telif (dimstr == 'henry'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -2 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'weber'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'tesla'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.A += -1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\n\n\telse:\n\t\tif (dimstr == 'm'):\n\t\t\tquantity.m += exp\n\t\telif (dimstr == 'g'):\n\t\t\tquantity.kg += exp\n\t\telif (dimstr == 's'):\n\t\t\tquantity.s += exp\n\t\telif (dimstr == 'A'):\n\t\t\tquantity.A += exp\n\t\telif (dimstr == 'K'):\n\t\t\tquantity.K += exp\n\t\telif (dimstr == 'deg'):\n\t\t\tquantity.deg += exp\n\n\t\t# derived\n\t\tif (FLAG_DERIVED):\n\t\t\tif (dimstr == 'Hz'):\n\t\t\t\tquantity.s += -1 * exp\n\t\t\telif (dimstr == 'N'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'Pa'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += -1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'J'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'W'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.s += -3 * exp\n\t\t\telif (dimstr == 'V'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -1 * exp\n\t\t\t\tquantity.s += -3 * exp\n\t\t\telif (dimstr == 'C'):\n\t\t\t\tquantity.A += 1 * exp\n\t\t\t\tquantity.s += 1 * exp\n\t\t\telif (dimstr == 'Ω'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -2 * exp\n\t\t\t\tquantity.s += -3 * exp\n\t\t\telif (dimstr == 'F'):\n\t\t\t\tquantity.kg += -1 * exp\n\t\t\t\tquantity.m += -2 * exp\n\t\t\t\tquantity.A += 2 * exp\n\t\t\t\tquantity.s += 4 * exp\n\t\t\telif (dimstr == 'H'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -2 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'Wb'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.m += 2 * exp\n\t\t\t\tquantity.A += -1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\t\t\telif (dimstr == 'T'):\n\t\t\t\tquantity.kg += 1 * exp\n\t\t\t\tquantity.A += -1 * exp\n\t\t\t\tquantity.s += -2 * exp\n\n\treturn quantity\n\n\ndef parseSupValue(utfExpStr):\n\tSUP = str.maketrans(\"⁺⁻⁰¹²³⁴⁵⁶⁷⁸⁹\", \"+-0123456789\")\n\tSUB = str.maketrans(\"₀₁₂₃₄₅₆₇₈₉\", \"0123456789\")\n\treturn utfExpStr.translate(SUP)\n\n\n\n\n\n\n","sub_path":"tools/requirement parser/UnitParser.py","file_name":"UnitParser.py","file_ext":"py","file_size_in_byte":7396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"41515559","text":"#! /usr/bin/python3\n\nimport functions as f\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\n#from sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import NuSVC\n#from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\ndata=pd.read_csv('final_usa.csv')\ndata1=data\ndata.pop('Unnamed: 0')\n\nnames=f.get_names(data)\nprint(names)\nhome=data.loc[data['home']=='Los Angeles Galaxy'][-1:]\nhome=home.drop(['vfatigue','vavg_diff50','vavg_diff5','vavg_points15','vavg_points5'],1)\n\naway=(data.loc[data['visitor']=='Toronto FC'][-1:])\naway=away.drop(['hfatigue','havg_diff50','havg_diff5','havg_points15','havg_points5'],1)\n\ndata=data.dropna()\n\ndata=data.drop(['Date','hgoal','vgoal','goaldiff','home','visitor'],1)\n\ny=data.pop('result')\nx=data\nx=x.drop(['vfatigue', 'vavg_diff50', 'vavg_diff5','vavg_points15', 'vavg_points5'],1)\nprint(data.columns)\n\naway=away.drop(['result','Date','hgoal','vgoal','goaldiff','home','visitor'],1)\nprint(away)#['vfatigue','vavg_diff50','vavg_diff5','vavg_points15','vavg_points5'])\nhome=home.drop(['result','Date','hgoal','vgoal','goaldiff','home','visitor'],1)\nhome=home.reset_index(drop=True)\naway=away.reset_index(drop=True)\nprint(home)#['vfatigue','vavg_diff50','vavg_diff5','vavg_points15','vavg_points5'])\n\npred = pd.concat([home,away],axis =1,join = 'inner', sort=False)\ntrain_features, test_features, train_labels, test_labels = train_test_split(x, y, test_size = 0.2, random_state = 2)\n\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = {\n 'random_state':[10,20]\n #'max_depth': [20,40],\n #'n_estimators': [100,200,300]\n}\n#clf= MLPClassifier(activation='relu',solver='adam',batch_size=16)\nclf= NuSVC()\ngrid_search = GridSearchCV(estimator = clf, param_grid = param_grid, \n cv = 3, n_jobs=-1, verbose = 2)\ntrain_features=preprocessing.scale(train_features)\ntrain_features=preprocessing.normalize(train_features)\n\ngrid_search.fit(train_features, train_labels)\nprint(grid_search.best_params_)\ngrid_search=grid_search.best_estimator_\n#clf.fit(train_features,train_labels)\n\nprint(pred.columns)\npred=preprocessing.normalize(pred)\npred=preprocessing.scale(pred)\n\n# test model\npredictions = grid_search.predict(test_features)\n#predictions = clf.predict(pred)\ncc=accuracy_score(test_labels,predictions)\nprint('accuracy: ',cc)\n\nhome,draw,away=0,0,0\nfor x in predictions:\n if x==1:\n home+=1\n elif x==0:\n draw+=1\n else:\n away+=1\n\nprint('home: ',home/len(predictions),', ',home)\nprint('draw: ',draw/len(predictions),', ',draw)\nprint('away: ',away/len(predictions),', ',away)\n\nprint('real:')\nf.winrates(data1)\n\n\n","sub_path":"usa_test/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"77719007","text":"'''\nImplement an autocomplete system. That is, given a query string s and a set \nof all possible query strings, return all strings in the set that have s as \na prefix.\n\nFor example, given the query string de and the set of strings \n[dog, deer, deal], return [deer, deal].\n\nHint: Try preprocessing the dictionary into a more efficient data structure \nto speed up queries.\n'''\n\n# Spend hours tweaking a tree to prove to yourself that you can\n# implement over-complicated algorithms for academic reasons, or maybe\n# to impress a human-resources person who over-values technique and \n# undervalues the creative humans who want to get the job done and move on.\n# This node-tree could be better if instead of storing an entire suffix per\n# first letter or just the first letter, it stored partial strings; ie:\n# with ['doge', 'do', 'done'] it stored like:\n# Node('do', dict(ge=Node('ge'), ne=Node('ne'))) where currently its more like:\n# Node('d', dict('o'=Node('o', dict(ge=Node('ge'), ne=Node('ne'))).\n# But hey, consider getting away from your workstation, taking a walk down\n# to the customer service department, watching the tedious tasks those poor\n# slaves do all day long, pick a brutal task, then come back to your station\n# and spend the next two weeks eliminating it for dozens/hundreds of those cs \n# agents; your boss and them too deserve to spend more of their energy making\n# happy customers. Im really serious, stop what you're working on, go now, \n# do some useful magic!\nclass Node:\n def __repr__(self): \n return 'Node(%s, suffixes=%s)' % (repr(self.value), repr(self.suffixes))\n\n def __init__(self, aString, suffixes): \n self.value = aString.lower()\n self.suffixes = suffixes\n\n def add(self, aString):\n aString = aString.lower()\n if len(aString):\n if aString[0] in [x[0] for x in self.suffixes if len(x)]:\n for key, suffix in self.suffixes.items():\n if key and key[0] == aString[0]:\n if len(key) > 1:\n suffix = Node(key[0], suffixes={})\n suffix.add(key[1:])\n del self.suffixes[key]\n self.suffixes[key[0]] = suffix\n suffix.add(aString[1:])\n break\n else: \n self.suffixes[aString] = Node(aString, {'': ''})\n else:\n self.suffixes[''] = ''\n\n def toList(self):\n answer = []\n for suffix in self.suffixes.values():\n if not suffix:\n answer.append(self.value)\n continue\n for theirsuffix in suffix.toList():\n answer.append(self.value + theirsuffix)\n return answer\n \ndef autocomplete(aString, aNode):\n aString = aString.lower()\n for i, aChar in enumerate(aString):\n if aChar in aNode.suffixes:\n aNode = aNode.suffixes[aChar]\n else:\n keys = [x for x in aNode.suffixes if x.startswith(aString[i:])]\n if len(keys) == 1: \n aNode = aNode.suffixes[keys[0]]\n break\n else:\n aNode = None\n break\n if aNode: return [aString[:i] + x for x in aNode.toList()]\n else: return []\n\n# or... enslave the computer, get the job done, move on to the next, create\n# profits for your employer and reduce expensive human resource costs.\ndef autocompleteBrute(aString, wordList):\n return [x for x in wordList if x.startswith(aString.lower())]\n\n\nif __name__ == '__main__':\n\n wordList = ['doge', 'do', 'dog', 'deer', 'deal', 'done', 'dogma']\n wordDict = Node('', suffixes={})\n for word in wordList:\n wordDict.add(word)\n assert set(autocompleteBrute('de', wordList)) == set(['deer', 'deal'])\n assert set(autocomplete('de', wordDict)) == set(['deer', 'deal'])\n\n import requests\n url = 'http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt'\n wordList = requests.get(url).text.split()\n wordDict = Node('', suffixes={})\n for i, word in enumerate(wordList):\n wordDict.add(word)\n if i % 1000 == 0:\n print('adding the %dth word, %s, to wordDict...' % (i, word))\n print('len(wordList): %s' % len(wordList))\n print('len(wordDict.toList()): %s' % len(wordDict.toList()))\n print('Try something like:')\n print(' autocompleteBrute(\"word-prefix\", wordList)')\n print(' or autocomplete(\"word-prefix\", wordDict)')\n","sub_path":"problem11.py","file_name":"problem11.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"423454523","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: mapper.py\n# Author: Jesse Yang \n\nfrom tensorpack import BatchData\nimport numpy as np\nfrom six.moves import range\n\ntry:\n from .cfgs.config import cfg\nexcept Exception:\n from cfgs.config import cfg\nclass Mapper(object):\n\n def __init__(self):\n self.alphabet2token = {}\n self.token2alphabet = {}\n\n for c_id, char in enumerate(cfg.dictionary):\n self.alphabet2token[char] = c_id\n self.token2alphabet[c_id] = char\n\n\n def encode_string(self, line):\n label = []\n for char in line:\n label.append(self.alphabet2token[char])\n return label\n\n def decode_output(self, predictions):\n line = \"\"\n for label in predictions:\n line += self.token2alphabet[label]\n return line\n","sub_path":"mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"473418645","text":"class Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n if grid is None:\n return 0\n #Step 1 Search through out grid for 1's\n \n perimeter = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n perimeter += countPerimeter(grid, i, j)\n #Now we have to count perimeter at this position\n return perimeter \n \n \n def countPerimter(grid, i, j):\n count = 0\n #Where water is on left\n if j - 1 < 0 or grid[i][j-1] == 0:\n count += 1\n \n #Where water is on the right\n if j + 1 >= grid[0].length or grid[i][j + 1] == 0:\n count += 1\n \n #Where water is up \n if i - 1 < 0 or grid[i-1][j] == 0:\n count += 1\n \n #Where water is down\n if i+ 1 >= grid[0].length or grid[i + 1][j] == 0:\n count += 1\n \n return count\n","sub_path":"Interview/islandPerimeter.py","file_name":"islandPerimeter.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"334065980","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 8 16:20:03 2018\n\n@author: theoestienne\n\"\"\"\nimport pandas as pd\nfrom sklearn import metrics\nimport numpy as np\nimport SimpleITK as sitk\nimport os\n\n#%%\n\ndef foie_metrics(reference_path, prediction_path):\n\n pred = pd.read_csv(prediction_path, index_col=0)\n ref = pd.read_csv(reference_path, index_col=0)\n \n assert pred.shape[0] == ref.shape[0]\n assert pred.shape[1] == 8\n \n pred = pred.loc[ref.index]\n pred = pred.fillna(0.5)\n \n # Lesion\n y_true = ref['Lesion']\n y_pred = pred['Lesion']\n \n auc_detection = metrics.roc_auc_score(y_true, y_pred)\n \n # Malin\n y_true = ref.loc[ref['Lesion'] == True,'Malin']\n y_pred = pred.loc[ref['Lesion'] == True,'Malin']\n \n auc_malin = metrics.roc_auc_score(y_true, y_pred)\n \n \n lesions = ['Kyste', 'HNF', 'Angiome', 'Metastase', 'CHC']\n \n auc_lesions = {}\n \n for lesion in lesions:\n try:\n y_true = ref.loc[ref['Lesion'] == True,'Type de lesion'] == lesion\n y_pred = pred.loc[ref['Lesion'] == True,lesion]\n \n auc = metrics.roc_auc_score(y_true, y_pred)\n \n auc_lesions[lesion] = auc\n except Exception as e:\n print(e)\n print(lesion)\n \n auc_lesion = np.mean(list(auc_lesions.values()))\n total_score = 0.5 * auc_detection + 0.3 * auc_malin + 0.2 * auc_lesion\n \n return total_score\n\n\n# print(foie_metrics(train_csv_path, test_csv_path))\n\n\n#%%\ndef menisque_metrics(reference_path, prediction_path):\n \n pred = pd.read_csv(prediction_path, index_col=0)\n ref = pd.read_csv(reference_path, index_col=0)\n \n assert pred.shape[0] == ref.shape[0]\n assert pred.shape[1] == 5\n \n pred = pred.loc[ref.index]\n pred = pred.fillna(0.5)\n \n # Fissure\n ref['Fissure'] = np.logical_or(ref['Corne anterieure'], ref['Corne posterieure'])\n \n y_true= ref['Fissure']\n y_pred = pred['Fissure']\n \n auc_detection = metrics.roc_auc_score(y_true, y_pred)\n \n # Localisation\n y_true = ref.loc[ref['Fissure'] == True,'Corne anterieure']\n y_pred = pred.loc[ref['Fissure'] == True,'Corne anterieure']\n \n auc_position = metrics.roc_auc_score(y_true, y_pred)\n \n # Orientation\n ante = ref.loc[ref['Fissure'] == True,'Orientation anterieure'] == 'Horizontale' \n poste = ref.loc[ref['Fissure'] == True,'Orientation posterieure'] == 'Horizontale'\n \n y_true = np.logical_or(ante,poste) \n y_pred = pred.loc[ref['Fissure'] == True,'Orientation horizontale']\n \n auc_orientation = metrics.roc_auc_score(y_true, y_pred)\n \n total_score = 0.4 * auc_detection + 0.3 * auc_position + 0.3 *auc_orientation\n \n return total_score\n\n# reference_path = '/home/theoestienne/Documents/JFR/menisque/menisque_train_set.csv'\n# prediction_path = '/home/theoestienne/Documents/JFR/menisque/menisque_exemple.csv' \n\n# print(menisque_metrics(reference_path, prediction_path))\n\n#%%\ndef dice_calcul(pred, ref):\n \n pred = pred.flatten()\n ref = ref.flatten()\n \n numerateur = np.sum(np.logical_and(pred, ref))\n denominateur = np.sum(pred) + np.sum(ref)\n \n dice = 2 * numerateur / denominateur\n \n return dice\n \n\ndef cortex_metrics(reference_folder, prediction_folder):\n \n patients = [patient for patient in os.listdir(reference_folder)\n if patient.startswith('mask')]\n \n dices = []\n for patient in patients:\n prediction_path = prediction_folder + patient\n reference_path = reference_folder + patient \n \n try:\n pred = sitk.GetArrayFromImage(sitk.ReadImage(prediction_path))\n ref = sitk.GetArrayFromImage(sitk.ReadImage(reference_path))\n \n assert np.array_equal(pred, pred.astype(bool))\n \n dices.append(dice_calcul(pred,ref))\n except:\n dices.append(0)\n \n total_score = np.mean(dices)\n \n return total_score\n\n#%%\n\ndef sein_metrics(reference_path, prediction_path):\n \n pred = pd.read_csv(prediction_path, index_col=0)\n ref = pd.read_csv(reference_path, index_col=0)\n \n assert pred.shape[0] == ref.shape[0]\n assert pred.shape[1] == 18\n \n pred = pred.loc[ref.index]\n pred = pred.fillna(0.5)\n \n # Malin\n y_true= ref['Malin']\n y_pred = pred['Malin']\n \n auc_malin = metrics.roc_auc_score(y_true, y_pred)\n \n # Tissu glandulaire \n y_true = ref['Type de lesion'] == 'Tissu glandulaire'\n y_pred = pred['Tissu glandulaire']\n \n auc_tissu = metrics.roc_auc_score(y_true, y_pred)\n \n # Carcinome canalaire infiltrant\n y_true = ref['Type de lesion'] == 'Carcinome canalaire infiltrant'\n y_pred = pred['Carcinome canalaire infiltrant']\n \n auc_carcinome = metrics.roc_auc_score(y_true, y_pred)\n \n # Autres Benins\n autres_benins = ['Adenose sclerosante', 'Autre lesion proliferante',\n 'Cicatrice radiaire', 'Fibroadenome','Galactophorite', \n 'Hyperplasie canalaire sans atypie', 'Kyste', 'PASH',\n 'Papillome', 'cytosteatonecrose',\n 'ganglio intra-mammaire']\n \n y_true = ref['Type de lesion'].isin(autres_benins)\n y_pred = pred[autres_benins].sum(axis=1)\n \n auc_autre_benins = metrics.roc_auc_score(y_true, y_pred)\n \n # Autres malins\n autres_malins = ['Carcinome lobulaire infiltrant', 'Cancer triple negatif', \n 'Carcinome intracanalaire', 'Carcinome mucineux']\n \n y_true = ref['Type de lesion'].isin(autres_malins)\n y_pred = pred[autres_malins].sum(axis=1)\n \n auc_autres_malins = metrics.roc_auc_score(y_true, y_pred)\n \n total_score = 0.6 * auc_malin + 0.4/4 * (auc_tissu + auc_carcinome + auc_autre_benins + auc_autres_malins)\n \n return total_score\n\n#%%\ndef thyroide_metrics(reference_path, prediction_path):\n \n pred = pd.read_csv(prediction_path, index_col=0)\n ref = pd.read_csv(reference_path, index_col=0)\n \n assert pred.shape[0] == ref.shape[0]\n assert pred.shape[1] == 1\n \n \n pred = pred.loc[ref.index]\n pred = pred.fillna(0.5)\n \n y_true = ref['anormale']\n y_pred = pred['anormale']\n \n auc = metrics.roc_auc_score(y_true, y_pred)\n \n return auc","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":6273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"189562893","text":"\"\"\"\nMIT License\n\nCopyright (c) 2019 UCSF Hu Lab\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\n\nimport os\nimport sys\nfrom pathlib import Path\nimport datetime\nfrom array import array\nimport struct\nfrom typing import List\nfrom typing import Any\nfrom . import constant\nfrom .fixsampling import fixsamplingarr\n\n\nclass CFWBINARY:\n magic = [b'C', b'F', b'W', b'B'] # 4 characters \"CFWB\"\n Version = constant.CFWB_VERSION # 32-bit int\n secsPerTick = 0.0 # double 8-byte\n Year = 0 # 32-bit int\n Month = 0 # 32-bit int\n Day = 0 # 32-bit int\n Hour = 0 # 32-bit int\n Minute = 0 # 32-bit int\n Second = 0.0 # double 8-byte\n trigger = 0.0 # double 8-byte\n NChannels = 0 # 32-bit int\n SamplesPerChannel = 0 # 32-bit int\n TimeChannel = 0 # 32-bit int\n DataFormat = 0 # 32-bit int\n\n def __init__(self, secsPerTick: float = 0.0, Year: int = 0, Month: int = 0, Day: int = 0,\n Hour: int = 0, Minute: int = 0, Second: float = 0.0, trigger: float = 0.0,\n NChannels: int = 0, SamplesPerChannel: int = 0, TimeChannel: int = 0,\n DataFormat: int = constant.FORMAT_SHORT):\n self.secsPerTick = secsPerTick\n self.Year = Year\n self.Month = Month\n self.Day = Day\n self.Hour = Hour\n self.Minute = Minute\n self.Second = Second\n self.trigger = trigger\n self.NChannels = NChannels\n self.SamplesPerChannel = SamplesPerChannel\n self.TimeChannel = TimeChannel\n self.DataFormat = DataFormat\n\n def setValue(self, secsPerTick: float = 0.0, Year: int = 0, Month: int = 0, Day: int = 0,\n Hour: int = 0, Minute: int = 0, Second: float = 0.0, trigger: float = 0.0,\n NChannels: int = 0, SamplesPerChannel: int = 0, TimeChannel: int = 0,\n DataFormat: int = constant.FORMAT_SHORT):\n self.secsPerTick = secsPerTick\n self.Year = Year\n self.Month = Month\n self.Day = Day\n self.Hour = Hour\n self.Minute = Minute\n self.Second = Second\n self.trigger = trigger\n self.NChannels = NChannels\n self.SamplesPerChannel = SamplesPerChannel\n self.TimeChannel = TimeChannel\n self.DataFormat = DataFormat\n\n\nclass CFWBCHANNEL:\n Title = \"\" # 32 characters long\n Units = \"\" # 32 characters long\n scale = 0.0 # double 8-byte\n offset = 0.0 # double 8-byte\n RangeHigh = 0.0 # double 8-byte\n RangeLow = 0.0 # double 8-byte\n\n def __init__(self, Title: str = \"\", Units: str = \"\", scale: float = 0.0, offset: offset = 0.0,\n RangeHigh: float = 0.0, RangeLow: float = 0.0):\n self.Title = Title\n self.Units = Units\n self.scale = scale\n self.offset = offset\n self.RangeHigh = RangeHigh\n self.RangeLow = RangeLow\n\n def setValue(self, Title: str = \"\", Units: str = \"\", scale: float = 0.0, offset: offset = 0.0,\n RangeHigh: float = 0.0, RangeLow: float = 0.0):\n self.Title = Title\n self.Units = Units\n self.scale = scale\n self.offset = offset\n self.RangeHigh = RangeHigh\n self.RangeLow = RangeLow\n\n\nclass BinFileError(BaseException):\n def __init__(self, message):\n self.message = message\n\n\nclass BinFile:\n f = None\n filename = \"\"\n header = None\n channels = []\n\n def __init__(self, filename: str, mode: str):\n self.filename = filename\n self.mode = mode\n self.header = None\n self.channels = []\n\n def open(self):\n if self.mode == \"r\":\n try:\n self.f = open(self.filename, \"rb\")\n except:\n self.f = None\n raise BinFileError(\"File not found!\")\n elif self.mode == \"r+\":\n try:\n self.f = open(self.filename, \"rb+\")\n except:\n self.f = None\n raise BinFileError(\"File not found!\")\n elif self.mode == \"w\":\n try:\n outfile = Path(self.filename)\n if not outfile.exists():\n self.f = open(self.filename, \"wb\")\n else:\n self.f = None\n raise BinFileError(\"File exist already!\")\n except:\n self.f = None\n raise BinFileError(\"Cannot open file!\")\n\n def setHeader(self, header: CFWBINARY):\n self.header = header\n\n def addChannel(self, channelDef: CFWBCHANNEL):\n self.channels.append(channelDef)\n\n def readHeader(self):\n self.header = CFWBINARY()\n self.header.magic[0], self.header.magic[1], self.header.magic[2], self.header.magic[3] = struct.unpack(\"cccc\", self.f.read(4))\n self.header.Version = struct.unpack(\"i\", self.f.read(constant.INT32_SIZE))[0]\n self.header.secsPerTick = struct.unpack(\"d\", self.f.read(constant.DOUBLE_SIZE))[0]\n self.header.Year, self.header.Month, self.header.Day, self.header.Hour, self.header.Minute = struct.unpack(\"iiiii\", self.f.read(constant.INT32_SIZE * 5))\n self.header.Second, self.header.trigger = struct.unpack(\"dd\", self.f.read(constant.DOUBLE_SIZE * 2))\n self.header.NChannels, self.header.SamplesPerChannel, self.header.TimeChannel, self.header.DataFormat = struct.unpack(\"iiii\", self.f.read(constant.INT32_SIZE * 4))\n self.channels = []\n for i in range(self.header.NChannels):\n buf = self.f.read(32)\n label = buf.decode(\"utf-8\").rstrip('\\0')\n buf = self.f.read(32)\n uom = buf.decode(\"utf-8\").rstrip('\\0')\n scale, offset, rangeHigh, rangeLow = struct.unpack(\"dddd\", self.f.read(constant.DOUBLE_SIZE * 4))\n print(\"$$$$$$$$$$$$$$ scale: \"+str(scale)+\", offset: \"+str(offset))\n channel = CFWBCHANNEL(label, uom, scale, offset, rangeHigh, rangeLow)\n self.channels.append(channel)\n\n def writeHeader(self):\n # set to beginning of file\n self.f.seek(0, 0)\n self.f.write(struct.pack(\"cccc\", self.header.magic[0], self.header.magic[1], self.header.magic[2], self.header.magic[3]))\n self.f.write(struct.pack(\"i\", self.header.Version))\n self.f.write(struct.pack(\"d\", self.header.secsPerTick))\n self.f.write(struct.pack(\"i\", self.header.Year))\n self.f.write(struct.pack(\"i\", self.header.Month))\n self.f.write(struct.pack(\"i\", self.header.Day))\n self.f.write(struct.pack(\"i\", self.header.Hour))\n self.f.write(struct.pack(\"i\", self.header.Minute))\n self.f.write(struct.pack(\"d\", self.header.Second))\n self.f.write(struct.pack(\"d\", self.header.trigger))\n self.f.write(struct.pack(\"i\", self.header.NChannels))\n self.f.write(struct.pack(\"i\", self.header.SamplesPerChannel))\n self.f.write(struct.pack(\"i\", self.header.TimeChannel))\n self.f.write(struct.pack(\"i\", self.header.DataFormat))\n # Write out 'NChannels' of channel headers\n if (self.channels is not None) and (len(self.channels) > 0):\n for i in range(len(self.channels)):\n channel = self.channels[i]\n self.f.write(struct.pack(\"32s\", channel.Title.encode('utf-8')))\n self.f.write(struct.pack(\"32s\", channel.Units.encode('utf-8')))\n self.f.write(struct.pack(\"d\", channel.scale))\n self.f.write(struct.pack(\"d\", channel.offset))\n self.f.write(struct.pack(\"d\", channel.RangeHigh))\n self.f.write(struct.pack(\"d\", channel.RangeLow))\n\n def readChannelData(self, offset: float, length: float, useSecForOffset: bool, useSecForLength: bool, downSamplingRatio: float = 1.0):\n print(\"/////////////// Using local binfilepy with customized scale formula with CO2 fix///////////////\")\n offsetSampleNum = int(offset / self.header.secsPerTick) if useSecForOffset else int(offset)\n lengthSampleNum = int(length / self.header.secsPerTick) if useSecForLength else int(length)\n if (self.header.DataFormat == constant.FORMAT_DOUBLE):\n sampleSize = constant.DOUBLE_SIZE\n elif (self.header.DataFormat == constant.FORMAT_FLOAT):\n sampleSize = constant.FLOAT_SIZE\n elif (self.header.DataFormat == constant.FORMAT_SHORT):\n sampleSize = constant.SHORT_SIZE\n # offset and lenght are 0, then read entire file\n if (offsetSampleNum == 0) and (lengthSampleNum == 0):\n lengthSampleNum = self.header.SamplesPerChannel\n # do not read over the end of file\n elif (lengthSampleNum + offsetSampleNum) > self.header.SamplesPerChannel:\n lengthSampleNum = self.header.SamplesPerChannel - offsetSampleNum\n # do not read anything if offset is bigger then total sample number\n elif offsetSampleNum > self.header.SamplesPerChannel:\n lengthSampleNum = 0\n self.f.seek(constant.CFWB_SIZE + constant.CHANNEL_SIZE * self.header.NChannels + offsetSampleNum * sampleSize * self.header.NChannels, 0)\n channelArr = []\n for i in range(0, self.header.NChannels):\n channelArr.append(array(\"d\", (0,) * lengthSampleNum))\n\n for x in range(0, lengthSampleNum):\n i = 0\n for c in channelArr:\n if self.header.DataFormat == constant.FORMAT_DOUBLE:\n c[x] = struct.unpack(\"h\", self.f.read(constant.SHORT_SIZE))[0]\n elif self.header.DataFormat == constant.FORMAT_FLOAT:\n c[x] = struct.unpack(\"f\", self.f.read(constant.FLOAT_SIZE))[0]\n elif self.header.DataFormat == constant.FORMAT_SHORT:\n v = struct.unpack(\"h\", self.f.read(constant.SHORT_SIZE))[0]\n if v in constant.GAP_SHORT_VALUES:\n c[x] = constant.MIN_DOUBLE_VALUE\n else:\n #print(\"/////////////// Using local binfilepy with customized scale formula and CO2 fix, self.channels[i].scale: \"+str(self.channels[i].scale)+\", self.channels[i].offset: \"+str(self.channels[i].offset)+\", v: \"+str(v))\n #c[x] = self.channels[i].scale * (v + self.channels[i].offset)\n scale = self.channels[i].scale\n offset = self.channels[i].offset\n if self.channels[i].scale == 1.0 and self.channels[i].offset == 0.0:\n scale = 0.0205\n offset = 588\n #c[x] = 0 + self.channels[i].scale * (self.channels[i].offset - v)\n c[x] = 0 + scale * (v - offset)\n #print(f\"channels[{i}].scale: {self.channels[i].scale}, channel.offset: {self.channels[i].offset}, scale: {scale}, offset: {offset}, v: {v}, c[x]: {c[x]}\")\n i += 1\n return channelArr\n\n def writeChannelData(self, chanData: List[List[Any]], fs: int = 0, gapInSecs: int = 0):\n # 2 means the end of file\n self.f.seek(0, 2)\n numSamplesWritten = 0\n numChannels = len(chanData)\n if gapInSecs > 0:\n numSamples = gapInSecs * fs\n numSamplesWritten += numSamples\n for j in range(numSamples):\n for i in range(numChannels):\n if self.header.DataFormat == constant.FORMAT_SHORT:\n d = constant.MIN_SHORT_VALUE\n self.f.write(struct.pack(\"h\", d))\n elif self.header.DataFormat == constant.FORMAT_DOUBLE:\n d = constant.MIN_DOUBLE_VALUE\n self.f.write(struct.pack(\"d\", d))\n elif self.header.DataFormat == constant.FORMAT_FLOAT:\n d = constant.MIN_FLOAT_VALUE\n self.f.write(struct.pack(\"f\", d))\n overlappedSamples = (-1 * gapInSecs * fs) if gapInSecs < 0 else 0\n len_chanData = 0\n if len(chanData) > 0:\n len_chanData = len(chanData[0])\n numSamplesWritten += max(len_chanData - overlappedSamples, 0)\n for j in range(len_chanData):\n if j < overlappedSamples:\n continue\n for i in range(len(chanData)):\n # bug fix, prevent idx out of range\n out_of_range = j > (len(chanData[i]) - 1)\n if self.header.DataFormat == constant.FORMAT_SHORT:\n d = chanData[i][j] if not out_of_range else constant.MIN_SHORT_VALUE\n self.f.write(struct.pack(\"h\", d))\n elif self.header.DataFormat == constant.FORMAT_DOUBLE:\n d = chanData[i][j] if not out_of_range else constant.MIN_DOUBLE_VALUE\n self.f.write(struct.pack(\"d\", d))\n elif self.header.DataFormat == constant.FORMAT_FLOAT:\n d = chanData[i][j] if not out_of_range else constant.MIN_FLOAT_VALUE\n self.f.write(struct.pack(\"f\", d))\n else:\n # raise exception\n raise BinFileError(\"Unsupported array type!\")\n return numSamplesWritten\n\n def updateSamplesPerChannel(self, numSamples: int, writeToFile: bool):\n self.header.SamplesPerChannel = numSamples\n if writeToFile:\n if self.mode == \"w\" or self.mode == \"r+\":\n self.f.seek(constant.N_SAMPLE_POSITION)\n self.f.write(struct.pack(\"i\", numSamples))\n self.f.flush()\n\n def close(self):\n # print(\"Close\")\n if self.f is not None:\n self.f.flush()\n self.f.close()\n\n def __enter__(self):\n self.open()\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n","sub_path":"waveform/binfile.py","file_name":"binfile.py","file_ext":"py","file_size_in_byte":15045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"547462689","text":"import datetime\nimport json\nimport random\nimport string\nimport traceback\n\nfrom django.db import transaction\n\nfrom app.models import Game, Category, Question\nfrom app.services.error_service import AppException, FIELD_REQUIRED, INTERNAL_SERVER_ERROR\nfrom app.services.json_service import json_response\nfrom jeopardy.settings import AUTH_TOKEN_HEADER_NAME\n\n\ndef parse_json(json_string):\n if isinstance(json_string, str):\n if not json_string:\n json_string = '{}'\n return json.loads(json_string)\n else:\n json_string = json_string.decode('utf-8')\n if not json_string:\n json_string = '{}'\n return json.loads(json_string)\n\n\nclass BaseRequestEntity:\n\n def __init__(self, json_string):\n self.__dict__ = parse_json(json_string)\n\n @staticmethod\n def parse_array(json_string):\n if isinstance(json_string, str):\n return json.loads(json_string)\n else:\n return json.loads(json_string.decode('utf-8'))\n\n @staticmethod\n def raise_on_empty(**kw):\n extra = 'Отсутствующие параметры: '\n is_exception_needed = False\n for key, value in kw.items():\n if not value:\n extra += str(key) + ' '\n is_exception_needed = True\n if is_exception_needed:\n raise AppException(FIELD_REQUIRED, extra=extra)\n\n\nclass app_view(object):\n\n def __init__(self, view_func):\n self.view_func = view_func\n\n def __call__(self, request, *args, **kwargs):\n try:\n request.token = request.META.get(AUTH_TOKEN_HEADER_NAME)\n result = self.view_func(request, *args, **kwargs)\n return result\n except AppException as exception:\n exception_dict = exception.to_dict()\n print(str(datetime.datetime.utcnow()) + ' ' + str(exception_dict))\n return json_response(\n exception_dict,\n status=exception.http_code\n )\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.datetime.utcnow()) + ' ' + str(exception_text))\n exception = AppException(INTERNAL_SERVER_ERROR)\n return json_response(\n exception.to_dict(),\n status=exception.http_code\n )\n\n\ndef init_debug_data():\n with transaction.atomic():\n while True:\n token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n if Game.objects.filter(token=token, expired__gte=datetime.datetime.utcnow()).count() == 0:\n break\n\n game = Game.objects.create(token=token)\n print(token)\n\n for i in range(0, 6):\n category = Category.objects.create(name='Имя ' + str(i), round=1, game=game)\n for j in range(1, 6):\n Question.objects.create(\n text='text ' + str(i) + ' ' + str(j),\n value=100 * j,\n answer='answer ' + str(i) + ' ' + str(j),\n comment='',\n type=Question.TYPE_STANDARD,\n category=category\n )\n\n for i in range(0, 6):\n category = Category.objects.create(name='Имя ' + str(i), round=2, game=game)\n for j in range(1, 6):\n Question.objects.create(\n text='text ' + str(i) + ' ' + str(j),\n value=100 * j,\n answer='answer ' + str(i) + ' ' + str(j),\n comment='',\n type=Question.TYPE_STANDARD,\n category=category\n )\n\n for i in range(0, 6):\n category = Category.objects.create(name='Имя ' + str(i), round=3, game=game)\n Question.objects.create(\n text='text ' + str(i) + ' ' + 'f',\n answer='answer ' + str(i) + ' ' + 'f',\n value=0,\n comment='',\n type=Question.TYPE_STANDARD,\n category=category\n )\n","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"417348850","text":"\"\"\"\nA simple class to publish available available attributes of a module,\nand import-on-demand of them. Compared to lazy import - it supply a mechanism\nTo control which attributes are available without importing the module.\n\"\"\"\nimport inspect\nimport importlib\n\nfrom . import options as opts\nfrom .root_logger import logger\nfrom .parameters import Params\n\n\nclass AttributesHandler(Params):\n \"\"\"\n A simple class to gain global access to available attributes of a module,\n with import-on-demand. It is not meant to be lazy import but rather collect desired\n attributes into a single object\n Compared to lazy import - it supply a mechanism o control which attributes are available without importing the module.\n\n Multiple objects can be declared in a module.\n \"\"\"\n\n def __init__(self, attrib_params={}, module_list=[], attrib_hdlr_list=[]):\n \"\"\"\n attrib_params - a dict of available attributes {\n \"GLOBAL ATTRIBUTE_NAME\": {\n \"module\": \"MODULE_OF_ATTRIB\" (str), # relative module name (to package)\n \"package\": \"PACKAGE_OF_MODULE\" (str), # ignore/leave empty/None for caller module absolute import name\n \"attrib\": \"ATTRIBUTE_NAME\" (str), # name of attribute to get from MODULE_OF_ATTRIB\n },\n }\n\n module_list - list of loaded module to search for AttributesHandler child objects.\n attrib_hdlr_list - list of loaded AttributesHandler child objects.\n \"\"\"\n super(AttributesHandler, self).__init__()\n\n # get default package name (of caller where AttributesHandler was created)\n cur_stack = inspect.stack()\n try:\n self.package_name = inspect.getmodule(cur_stack[1][0]).__name__\n except:\n self.package_name = None\n logger.warning(\"Failed detecting package\")\n\n # attribute caching (not part of params as it should not be serialized)\n self.attrib_cache = opts.Options()\n\n # add attrib_params\n self.add_attrib_params(attrib_params)\n\n # merge available attrib from module_list.\n for module in module_list:\n for attrib_name in dir(module):\n attrib_hdlr = getattr(module, attrib_name)\n if isinstance(attrib_hdlr, AttributesHandler):\n self.add_attrib_hdlr(attrib_hdlr)\n\n # add external handlers\n for attrib_hdlr in attrib_hdlr_list:\n self.add_attrib_hdlr(attrib_hdlr)\n\n def __call__(self, *args):\n \"\"\"\n Returns a single attrib, a list of attrib, or available attribs if no arguments are given.\n \"\"\"\n if len(args) == 0:\n return self.get_attrib_list()\n elif len(args) == 1:\n return self.get_attrib(args[0])\n else:\n return [self.get_attrib(attrib) for attrib in args]\n\n def add_attrib(self, name, attrib, module=None, package=None):\n \"\"\"\n Adds an attribute.\n\n name - global name of attribute\n module - \"MODULE_OF_ATTRIB\", # ignore/leave empty for current module\n package - \"PACKAGE_OF_MODULE\", # leave empty for creation module absolute import\n attrib - \"ATTRIBUTE_NAME\", # name of attribute to get from MODULE_OF_ATTRIB\n \"\"\"\n # raise an exception if global attrib name already exists\n if (name in self.params):\n raise KeyError(\"Attribute '%s' already exists\" % (name))\n\n # build absolute module's package path\n if package is None:\n package = self.package_name\n\n # if we are given module expand module name to include package\n if module:\n # add qualifying module name if package is given\n if (package):\n module = package + \".\" + module\n else:\n # else package is our target module\n module = package\n\n # merge normalized attrib\n self.params += {\n name: {\n \"attrib\": attrib,\n \"module\": module,\n \"package\": \"\",\n },\n }\n\n def add_attrib_list(self, attrib_list, module=None, package=None, name_template=\"{attrib}\"):\n \"\"\"\n Adds a list of attributes with same module/package.\n\n attrib_list - a list of \"ATTRIBUTE_NAME\", # name of attribute to get from MODULE_OF_ATTRIB\n name - global name of attribute\n module - \"MODULE_OF_ATTRIB\", # ignore/leave empty for current module\n package - \"PACKAGE_OF_MODULE\", # leave empty for creation module absolute import\n \"name_template\" - str.format(attrib=attrib) formatting for global name of attribute\n \"\"\"\n for attrib in attrib_list:\n self.add_attrib(\n name=name_template.format(attrib=attrib),\n attrib=attrib,\n module=module,\n package=package,\n )\n\n def add_attrib_params(self, attrib_params):\n \"\"\"\n Merges external attrib_params.\n\n attrib_params - a dict of available attributes {\n \"GLOBAL ATTRIBUTE_NAME\": {\n \"module\": \"MODULE_OF_ATTRIB\", # ignore/leave empty for current module\n \"package\": \"PACKAGE_OF_MODULE\", # leave empty for creation module absolute import\n \"attrib\": \"ATTRIBUTE_NAME\", # name of attribute to get from MODULE_OF_ATTRIB\n },\n }\n \"\"\"\n for attrib_name, attrib_spec in attrib_params.items():\n self.add_attrib(attrib_name, **attrib_spec)\n\n def add_attrib_hdlr(self, attrib_hdlr):\n \"\"\"\n Merges another AttributesHandler\n \"\"\"\n if not isinstance(attrib_hdlr, AttributesHandler):\n raise TypeError(\"Expected attrib_hdlr to be an instance of AttributesHandler\")\n\n # merge other attrib_hdlr attributes\n self.add_attrib_params(attrib_hdlr.params)\n\n def get_attrib_list(self):\n \"\"\"\n Returns a list of all available attributes.\n \"\"\"\n return list(self.params.keys())\n\n def get_attrib(self, attrib):\n \"\"\"\n Returns attrib based on global name.\n \"\"\"\n if attrib in self.params:\n # check if we already cached the attrib\n if attrib not in self.attrib_cache:\n # if not, import module\n module = importlib.import_module(self.params[attrib].module)\n try:\n # read attribute fro module\n self.attrib_cache[attrib] = getattr(module, self.params[attrib].attrib)\n except Exception as e:\n raise ImportError(\"Failed to get attrib=%s from module=%s\" % (attrib, module.__name__))\n\n # return cached attrib\n return self.attrib_cache[attrib]\n else:\n raise ValueError(\"Unknown attrib = %s, please choose from: %s\" % (attrib, self.get_attrib_list()))\n","sub_path":"src/common/attributes_handler.py","file_name":"attributes_handler.py","file_ext":"py","file_size_in_byte":6886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"647144437","text":"from keras.models import load_model\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\ndef predict(roi): \n img = np.resize(roi, (28,28,1))\n im2arr = np.array(img)\n im2arr = im2arr.reshape(1,28*28)\n im2arr = im2arr.astype('float32')/255\n y_pred = model.predict_classes(im2arr)\n return y_pred\n\ndef image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):\n # initialize the dimensions of the image to be resized and\n # grab the image size\n dim = None\n (h, w) = image.shape[:2]\n\n # if both the width and height are None, then return the\n # original image\n if width is None and height is None:\n return image\n\n # check to see if the width is None\n if width is None:\n # calculate the ratio of the height and construct the\n # dimensions\n r = height / float(h)\n dim = (int(w * r), height)\n\n # otherwise, the height is None\n else:\n # calculate the ratio of the width and construct the\n # dimensions\n r = width / float(w)\n dim = (width, int(h * r))\n\n # resize the image\n resized = cv2.resize(image, dim, interpolation = inter)\n\n # return the resized image\n return resized\n\nmodel = load_model('mnist.h5')\n \nmodel.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# Load an color image in grayscale\n\nans = input(\"Cam or Video: \")\nif(ans == \"Cam\"):\n cap = cv2.VideoCapture(0)\nelse:\n cap = cv2.VideoCapture('video3.mp4')\n\nwhile(1):\n\n _, frame = cap.read()\n\n gry = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #res = cv2.resize(gry,None,fx=1/5,fy=1/5,interpolation = cv2.INTER_CUBIC)\n #shape = res.shape\n\n # Blurring using Gaussian filtering\n blur = cv2.GaussianBlur(gry, (5, 5), 0)\n\n # Binarization --- this line is from Tanny's program\n #edge = cv2.Canny(blur,70,70)\n \n ret, thresh = cv2.threshold(blur,127,255,cv2.THRESH_BINARY_INV)\n\n # Find contours\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n \n for i, cnt in enumerate (contours):\n area = cv2.contourArea(cnt)\n if(area > 250):\n x1 = True\n x2 = True\n\n x,y,w,h = cv2.boundingRect(cnt)\n\n # Stage II:\n # Aspect ratio\n aspect_ratio = float(w)/h\n if(aspect_ratio > 1.5):\n x1 = False\n\n # Orientation\n if(cnt.shape[0] > 4):\n (xo,yo),(MA,ma),angle = cv2.fitEllipse(cnt)\n if(angle > 15 and angle < 160):\n x2 = False \n\n if(x1 or x2 == True):\n #Stage II: Bouding rectangle\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,100),2)\n roi = gry[y-5:y+h+5, x-5:x+w+5]\n \n roi = cv2.GaussianBlur(roi, (5, 5), 0)\n \n roi = cv2.bitwise_not(roi)\n\n _, roi = cv2.threshold(roi,127,255,cv2.THRESH_BINARY)\n #roiRes = cv2.resize(roi,(28,28),interpolation = cv2.INTER_AREA)\n #cv2.imwrite('ROI' + str(i) + '.png',roi)\n digit = predict(roi)\n digit = digit[0]\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame,str(digit),(x - 10,y - 10), font, 3,(255,255,255),2,cv2.LINE_AA)\n \n cv2.imshow('CAM',frame)\n k = cv2.waitKey(5) & 0xFF\n if k == 27: # wait for ESC key to exit\n break\n\ncv2.destroyAllWindows()\n","sub_path":"video_test.py","file_name":"video_test.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"124418658","text":"import arcpy\nfrom arcpy import env\nimport os\n\n# This will read in every shapefile for a city/year and convert it to a CSV for further joining and use\n# Set the wildcard to be the prefix of whatever predictor is to be converted\n# i.e. \"BCaer*\" will do all airports\n# This is recursive, be sure to set the inPath to a year/city, with these outfolder names (file prefix in brackets):\n#############\n# Airports (aer)\n# Cinemas (cin)\n# Education (edu)\n# Fire (fre)\n# Health (hcr)\n# HiRoads (hrd)\n# Hiway (hwy)\n# Police (pol)\n# Rail (rll)\n# Roads (rte)\n# Trans (trs)\n# roads_only (rte_only)\n# Mjr_only (hrd_only)\n########################\n# GTFS Routes\n# GTFS Stops\n############\n\n\ninPath = \"D:/Work/Noise/Pred_Output_arc/2016/TOR/\"\narcpy.env.workspace = inPath\noutPath = \"D:/Work/Noise/aaa_CSV_CONVERTED/Predictors_CSV/2016/TOR/GTFS_dat/Routes\"\n# wildcard operator to find each file, devidfed by predictor type (see above list)\ntype = \"ONRoutes*\"\n\n# RECURSIVE to look through every distance, because of previous file structure\nfcList = []\nfor dirname, dirnames, filenames in os.walk(inPath):\n\tfor subdirname in dirnames:\n\t\tenv.workspace = os.path.join(dirname, subdirname)\n\t\tfcList = arcpy.ListFeatureClasses(wild_card=type)\n\t\tfor fc in fcList:\n\t\t\toutName = fc[:-4]\n\t\t\tarcpy.TableToTable_conversion (fc, outPath, outName + '.csv')\n","sub_path":"db_manip/convert_shp_csv.py","file_name":"convert_shp_csv.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"177224080","text":"import sys\ni=0\nfor x in sys.stdin:\n x=[int(a) for a in x.rstrip().split()]\n if i==0:\n pass\n elif i==1:\n clock1 = x\n clock1.sort()\n\n elif i==2:\n clock2 = x\n clock2.sort()\n i+=1\n \nangles=[[],[]]\nfor a, wList in zip(range(2), [clock1, clock2]):\n for x in range(1, len( clock1)):\n angles[a].append(wList[x]-wList[x-1])\n\n angles[a].append((360000-wList[-1])+wList[0])\n\n\nif ' '.join(map(str, angles[0])) in ' '.join(map(str, angles[1] * 2)):\n print(\"possible\")\nelse:\n print(\"impossible\")\n","sub_path":"newclockpictures.py","file_name":"newclockpictures.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"330618310","text":"#!/usr/bin/python\n# coding=utf-8\n\n\"\"\"\nCopyright 2012 Telefonica Investigación y Desarrollo, S.A.U\n\nThis file is part of Billing_PoC.\n\nBilling_PoC is free software: you can redistribute it and/or modify it under the terms\nof the GNU Affero General Public License as published by the Free Software Foundation, either\nversion 3 of the License, or (at your option) any later version.\nBilling_PoC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along with Billing_PoC.\nIf not, see http://www.gnu.org/licenses/.\n\nFor those usages not covered by the GNU Affero General Public License please contact with::mac@tid.es\n\"\"\"\n\n'''\nCreated on 14/01/2013\n\n@author: mac@tid.es\n'''\n\n\nfrom datetime import datetime\n\nfrom py_adyen.adyen import Adyen\nfrom py_adyen.api import Api\n\nfrom payment_gateways.gateway_interface.PaymentGateway import PaymentGateway\n\nclass Adyen_Charger (PaymentGateway):\n\n def __init__(self, model):\n super(Adyen_Charger, self).__init__(model)\n\n def get_redirect_url(self, user_data):\n\n user_data = {\n 'merchantReference': self.order,\n 'paymentAmount': self.MONEY,\n 'currencyCode': self.CURRENCY,\n 'shipBeforeDate': datetime.now(),\n 'shopperEmail': user_data.email, \n 'shopperReference': user_data.tef_account, \n 'sessionValidity': datetime.now(), \n 'recurringContract': 'RECURRING', \n }\n\n adyen_data = Adyen(user_data)\n adyen_data.sign()\n\n return adyen_data.get_redirect_url()\n\n def recurrent_payment(self, order_data, master_info):\n ws = Api()\n\n statement = order_data.statement \n reference = order_data.order_code\n\n shopper_email = master_info.email\n shopper_reference = master_info.tef_account\n\n amount = order_data.total\n currency = order_data.currency\n\n ws.authorise_recurring_payment(reference, statement, amount, currency, shopper_reference, shopper_email,\n shopper_ip=None, recurring_detail_reference='LATEST')\n","sub_path":"payment_gateways/adyen/adyen_charger.py","file_name":"adyen_charger.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"31544531","text":"chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊'\nzodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座',\n u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')\n# 下面是一个元组的嵌套\nzodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22), (7, 23), (8, 23),\n (9, 23), (10, 23), (11, 23), (12, 23))\n# (month, day) = (2, 15)\n\ncz_num = {}\nfor i in chinese_zodiac:\n cz_num[i] = 0\n\nz_num = {}\nfor i in zodiac_name:\n z_num[i] = 0\n\n# zodiac_day = filter(lambda x: x <= (month, day), zodiac_days)\n# # print(zodiac_day)\n# # print(list(zodiac_day))\n# zodiac_len = len(list(zodiac_day)) % 12\n# # print(len(list(zodiac_day)))\n# print(zodiac_name[zodiac_len])\n# i = 0\n # for zodiac_day in zodiac_days :\n # if zodiac_day <= (int_month,int_day) :\n # i = i+1\n # print('%i 月 %i 日的星座是' % (int_month,int_day)+zodiac_name[i])\n\n # for zd_num in range(len(zodiac_days)):\n # if zodiac_days[zd_num] >= (int_month,int_day):\n # print(zodiac_name[zd_num])\n # break\n # elif int_month == 12 and int_day > 23:\n # print(zodiac_name[0])\n # break\nwhile True:\n # 用户输入出生年份月份和日期\n year = int(input('请用户输入出生年份:'))\n int_month = int(input('请输入出生月份:'))\n int_day = int(input('请输入出生日期:'))\n\n n = 0\n while zodiac_days[n] < (int_month,int_day):\n if int_month == 12 and int_day > 23:\n break\n n += 1\n # 输出生肖和星座\n print(zodiac_name[n])\n\n print('%s 年的生肖是 %s' % (year,chinese_zodiac[year % 12]))\n\n cz_num[chinese_zodiac[year % 12]] += 1\n z_num[zodiac_name[n]] += 1\n\n #输出生肖和星座的打印信息\n for each_key in cz_num.keys():\n print('生肖 %s 有 %d 个'%(each_key,cz_num[each_key] ))\n\n for each_key in z_num.keys():\n print('%s 有 %d 个'%(each_key,z_num[each_key]))\n\n\n","sub_path":"Python_Learning/zodiac_v3.py","file_name":"zodiac_v3.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"543586134","text":"# coding=utf-8\nimport os, shutil\n\nimport io\nfrom base64 import encodebytes\nfrom PIL import Image\n\nfrom src.models.object_detection import ObjectDetection\nfrom src.models.paddle_ocr import PlatePaddleOCR\n\n\nclass GetResultsResource:\n def __init__(self):\n self.output_images_path = r'/home/dell/Desktop/Number Plate Detection/Data_Folder/output images'\n\n def get_response_image(self, image_path):\n pil_img = Image.open(image_path, mode='r') # reads the PIL image\n byte_arr = io.BytesIO()\n pil_img.save(byte_arr, format='PNG') # convert the PIL image to byte array\n encoded_img = encodebytes(byte_arr.getvalue()).decode('ascii') # encode as base64\n return encoded_img\n\n def get(self):\n \n #Run object dedection\n objdet = ObjectDetection()\n objdet.main()\n\n #Run OCR\n pad = PlatePaddleOCR()\n license_plate_text = pad.main()\n if license_plate_text is None:\n license_plate_text = \"License Plate is not visible!\"\n\n\n ##reuslt contains list of path images\n result = os.listdir(self.output_images_path)\n dest = r'/home/dell/Desktop/Number Plate Detection/static/output'\n try:\n os.mkdir(dest)\n except:\n for res in result:\n shutil.copy(os.path.join(self.output_images_path, res), os.path.join(dest, res))\n\n return license_plate_text, result\n\n \n def post(self):\n data_folder_path = r'/home/dell/Desktop/Number Plate Detection/Data_Folder'\n folders = ['annotations','car images','plate images','output images']\n folders_list = [os.path.join(data_folder_path,folder)for folder in folders]\n for folder in folders_list:\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))","sub_path":"src/resources/get_results.py","file_name":"get_results.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"73149437","text":"import os\nfrom setuptools import setup, find_packages\n\nimport versioneer\n\ninstall_requires = [\"tornado\", \"dask>=2.2.0\", \"distributed>=2.2.0\"]\n\nextras_require = {\n \"kerberos\": [\n 'pykerberos;platform_system!=\"Windows\"',\n 'winkerberos;platform_system==\"Windows\"',\n ]\n}\n\nsetup(\n name=\"dask-gateway\",\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n maintainer=\"Jim Crist\",\n maintainer_email=\"jiminy.crist@gmail.com\",\n license=\"BSD\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: BSD License\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: System :: Distributed Computing\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n ],\n keywords=\"dask hadoop kubernetes HPC distributed cluster\",\n description=\"A client library for interacting with a dask-gateway server\",\n long_description=(\n open(\"README.rst\").read() if os.path.exists(\"README.rst\") else \"\"\n ),\n url=\"https://gateway.dask.org/\",\n project_urls={\n \"Documentation\": \"https://gateway.dask.org/\",\n \"Source\": \"https://github.com/dask/dask-gateway/\",\n \"Issue Tracker\": \"https://github.com/dask/dask-gateway/issues\",\n },\n packages=find_packages(),\n package_data={\"dask_gateway\": [\"*.yaml\"]},\n install_requires=install_requires,\n extras_require=extras_require,\n entry_points={\n \"console_scripts\": [\n \"dask-gateway-scheduler = dask_gateway.dask_cli:scheduler\",\n \"dask-gateway-worker = dask_gateway.dask_cli:worker\",\n ]\n },\n zip_safe=False,\n)\n","sub_path":"dask-gateway/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"417594534","text":"import numpy as np\nimport pandas as pd\nimport re\nimport spacy\nimport psycopg2\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom gensim.models import LdaModel, CoherenceModel\nfrom gensim.corpora import Dictionary\nfrom collections import Counter\nfrom fuzzywuzzy import fuzz\n\n\nclass LDAModel(TransformerMixin, BaseEstimator):\n def __init__(self, tech: str = \"vanilla\"):\n techs = [\"vanilla\", \"spacy\"]\n if tech not in techs:\n raise ValueError(\"Invalid tech name. Expected one of: %s\" % techs)\n\n self.tech = tech\n self.corpus = None\n self.dictionary = None\n self.model = None\n self.token=None\n\n def fit(self, X, y=None):\n \"\"\"Fit model from given corpus\n\n Arguments:\n X {list} -- corpus\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n if self.tech == \"spacy\":\n nlp = spacy.load(\"en_core_web_sm\")\n nlp.add_pipe(self._preprocess_doc, name=\"preprocess\")\n self.X = list(map(nlp, X))\n else:\n self.X = list(map(self._tokenize, X))\n total_length = len(self.X)\n word_count = {}\n for doc in self.X:\n local_count = Counter(doc)\n for k, v in local_count.items():\n if k in word_count:\n word_count[k] += v\n else:\n word_count[k] = v\n for k, v in word_count.items():\n if v > (total_length * 0.5):\n for doc in self.X:\n try:\n doc.remove(k)\n except ValueError as e:\n pass\n self.dictionary = Dictionary(self.X)\n # print(self.dictionary)\n dic = self.dictionary\n self.corpus = [self.dictionary.doc2bow(text) for text in self.X]\n lda_model = LdaModel(\n corpus=self.corpus,\n id2word=self.dictionary,\n num_topics=20,\n random_state=100,\n update_every=1,\n chunksize=100,\n passes=10,\n alpha=\"auto\",\n per_word_topics=True,\n )\n self.model = lda_model\n return self\n\n def _preprocess_doc(self, doc) -> list:\n \"\"\"tokenization function. written by bryan\n\n Arguments:\n doc {?} -- A piece of doc\n\n Returns:\n [list] -- A list of tokens\n \"\"\"\n output = []\n for token in doc:\n if (\n token.is_stop\n or token.is_punct\n or token.like_email\n or token.is_digit\n or token.like_url\n or token.is_space\n or re.search(\"\\n\", token.text)\n ):\n continue\n output.append(token.lower_)\n return output\n\n def _tokenize(self, text) -> list:\n \"\"\"tokenization function. written by lujin zhao\n\n Arguments:\n text {?} -- a piece of doc\n\n Returns:\n list -- a list of tokens\n \"\"\"\n wordnet_lemmatizer = WordNetLemmatizer()\n en_stop = stopwords.words(\"english\")\n stops = set(en_stop)\n tokenizer = RegexpTokenizer(r\"\\w+\")\n stemmer = PorterStemmer()\n np.random.seed(42)\n if type(text) == bytes:\n bodytext = re.sub(r\"[^\\x00-\\x7f]\", r\" \", text.decode(\"utf-8\"))\n else:\n bodytext = text\n bodytext = re.sub(\"/(\\r\\n)+|\\r+|\\n+|\\t+/i\", \"\", bodytext)\n no_url = re.sub(r\"\", \" \", bodytext)\n pattern = re.compile(\n \"https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]+\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]+\\.[^\\s]{2,}\"\n )\n\n no_all_url = re.sub(pattern, \"\", no_url)\n no_email = re.sub(r\"[^@]+@[^@]+\\.[^@]+\", \"\", no_all_url)\n s = re.sub(r\"[^\\w\\s]\", \"\", no_email)\n n = re.sub(r\"\\d+\", \"\", s)\n raw = n.lower()\n token = tokenizer.tokenize(raw)\n stop = [i for i in token if not i in stops]\n stem = [stemmer.stem(i) for i in stop]\n pos_list = [\"v\", \"n\", \"a\", \"r\"]\n for p in pos_list:\n stem = [wordnet_lemmatizer.lemmatize(s, pos=p) for s in stem]\n for s in stem:\n if len(s) > 20:\n stem.remove(s)\n return stem\n\n def score(self):\n print(\"Perplexity: \", self.model.log_perplexity(self.corpus))\n coherence_model_lda = CoherenceModel(\n model=self.model, corpus=self.corpus, coherence=\"u_mass\"\n )\n coherence_lda = coherence_model_lda.get_coherence()\n print(\"Coherence Score: \", coherence_lda)\n\n def visualize(self) -> None:\n \"\"\"visualize topics in jupyterlab\n\n Returns:\n None -- [description]\n \"\"\"\n import pyLDAvis.gensim\n\n pyLDAvis.enable_notebook()\n vis = pyLDAvis.gensim.prepare(self.model, self.corpus, self.dictionary)\n return vis\n\n def get_matirx(self):\n ma = self.model.get_topics()\n return ma\n\n def topic_in_doc(self):\n tid = []\n for bow in self.corpus:\n element = self.model.get_document_topics(bow)\n tid.append(element)\n return tid\n\n def match_matrix(self, input_text):\n weight_matrix = np.asarray(self.get_matirx())\n d = dict(self.dictionary).values()\n target = list(d)\n self.token = self._tokenize(input_text)\n simi_matrix = np.zeros((len(target), len(self.token)))\n for i in range(0, len(target)):\n for e in range(0, len(self.token)):\n simi_matrix[i][e] = fuzz.ratio(self.token[e], target[i])\n\n result = np.dot(weight_matrix, simi_matrix)\n return simi_matrix\n\n\n def entry(query):\n connection = psycopg2.connect(\n \"dbname=nextcloud user=postgres password=postgres host=localhost port=5432\"\n )\n cur = connection.cursor()\n result=cur.execute(query)\n target = [result[i][3] for i in range(len(result))]\n return target\n\n\nif __name__ == \"__main__\":\n connection = psycopg2.connect(\n \"dbname=nextcloud user=postgres password=postgres host=localhost port=5432\"\n )\n cur = connection.cursor()\n cur.execute(\"SELECT * FROM coursefiles LIMIT 10\")\n\n result = cur.fetchall()\n target = [result[i][3] for i in range(len(result))]\n print(target)\n source = \"\"\"I was at my first CS job for about 4-5 months and the work was just monotonous and repetitive...\nI applied to a single job on a whim at lunch one day, had a phone screen done by 6pm, in person interview mid week, and job offer by friday. Was about a 30% raise, in a more interesting sector.\nNote: first job was web dev for a private university, 2nd (and current) is DoD contracting.\nEdit: spelling.\nAlso, this is in the middle of southwest Ohio, so it's not nearly as competitive an area as many people here.\"\"\"\n lda = LDAModel()\n lda.fit(target)\n print(lda.match_matrix(source).shape)\n\n print(dict(lda.dictionary).values())\n ########333\n print(lda.match_matrix(source))\n print(dict(lda.dictionary))\n print(lda.user_token)\n","sub_path":"GoogleArchive/googlearchive/_lda.py","file_name":"_lda.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"411416647","text":"import os\r\nimport shutil\r\nimport time\r\nimport sys\r\n\r\n\r\npath = \"C:/Users/Goofy/Documents/all artworks/autosort\"\r\n\r\ncomic_project_folder = \"C:/Users/Goofy/Documents/all artworks/Project files/Comics\"\r\ncomic_jpeg_folder = \"C:/Users/Goofy/Documents/all artworks/Comic JPEGs\"\r\n\r\nartwork_project_folder = \"C:/Users/Goofy/Documents/all artworks/Project files\"\r\nlogo_png_folder = \"C:/Users/Goofy/Documents/all artworks/Logo PNGs\"\r\nlogo_jpeg_folder = \"C:/Users/Goofy/Documents/all artworks/Logo JPEGs\"\r\n\r\n\r\ndef comic():\r\n\tfiles = os.listdir(path)\r\n\tif files == []:\r\n\t\tprint (\"no file present!\")\r\n\telse:\r\n\t\tprint (files)\r\n\t\tprint (\"What do you want to name the folder?\")\r\n\t\tname = input(\"Enter Name: \")\t\t\r\n\t\tfor file in files:\r\n\t\t\t\text = os.path.splitext(file)[1:]\r\n\t\t\t\tif ext == ('.ai',):\r\n\t\t\t\t\tshutil.move(path + '/' + file, comic_project_folder)\r\n\t\t\t\telif ext == ('.jpg',):\r\n\t\t\t\t\t#os.rename(file, file_name + \"/\" + '.jpg')\r\n\t\t\t\t\tif os.path.exists(comic_jpeg_folder + '/' + name):\r\n\t\t\t\t\t\tshutil.move(path + '/' + file, comic_jpeg_folder + '/' + name)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tos.makedirs(comic_jpeg_folder + '/' + name)\r\n\t\t\t\t\t\tshutil.move(path + '/' + file, comic_jpeg_folder + '/' + name)\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint (\"not a valid file\")\r\n\r\ndef artwork():\r\n\tfiles = os.listdir(path)\r\n\tif files == []:\r\n\t\tprint (\"no file present!\")\r\n\telse:\r\n\t\tprint (files)\r\n\t\tfor file in files:\r\n\t\t\text = os.path.splitext(file)[1:]\r\n\t\t\tif ext == ('.ai',):\r\n\t\t\t\tshutil.move(path + '/' + file, artwork_project_folder)\r\n\t\t\telif ext == ('.png',):\r\n\t\t\t\tshutil.move(path + '/' + file, logo_png_folder)\r\n\t\t\telif ext == ('.jpg',):\r\n\t\t\t\tshutil.move(path + '/' + file, logo_jpeg_folder)\r\n\r\n\r\n#Main execution of the script\r\nif len(sys.argv) != 1:\r\n\tchoice = sys.argv[1]\r\nelse:\r\n\tprint (\"Enter 1 for comics\")\r\n\tprint (\"Enter 2 for art\")\r\n\tchoice = input()\r\n\tif choice == \"1\":\r\n\t\tcomic()\r\n\t\tprint(\"Done!\")\r\n\t\ttime.sleep(2)\r\n\telif choice == \"2\":\r\n\t\tartwork()\r\n\t\tprint(\"Done!\")\r\n\t\ttime.sleep(2)\r\n\telse:\r\n\t\tprint (\"Enter Valid Feature\")\r\n\t\ttime.sleep(2)\r\n","sub_path":"my scripts/sort_Art.py","file_name":"sort_Art.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"383512050","text":"# -*- encoding: utf-8 -*-\n'''\n@File : test1.py\n@Time : 2020/04/15 08:11:40\n@Author : zjm \n@Version : 3.7.6\n@Contact : 1005564803@qq.com\n@WebSite : https://github.com/sum-123/Python-.git\n'''\n\n# here put the import lib\nimport re\ntext=input('输入邮箱地址')\nret=re.match(r'^[0-9a-zA-Z_]{4,20}@163\\.com$',text)\nprint(ret.group())\n\n","sub_path":"ClassTest/April15/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"431707844","text":"__author__ = 'aadjemonkeyrock'\nimport logging\nimport datetime\nimport json\nfrom google.appengine.api import urlfetch\n\nfrom memovent.model.activity import Activity, Media\nfrom memovent.model.readers.reader import Reader\n\n\nclass FacebookReader(Reader):\n\n @classmethod\n def use_album(cls, album):\n album == '' if album is None else album\n album = album.lower().replace('photos', '').replace(' ', '')\n\n return album not in ('cover', 'profilepictures', 'foursquare', 'instagram', 'flickr') and not album.startswith('wan2trip')\n\n def refresh_photos(self, index=0):\n \"\"\" Refreshing Facebook photos\n \"\"\"\n # Build the url\n if 'next_url' not in self.params:\n url = \"%s%s/photos/uploaded\" % (self.client.base_url, self.client.user.id)\n url_params = {'fields': 'id,name,picture,link,place,source,updated_time,backdated_time,album.fields(id,name,type,place,link)'}\n else: # Paging a result set\n url = self.params['next_url']\n url_params = {}\n\n # Get the last used album and date, this so we can add to an existing Activity\n last_date = datetime.datetime.fromtimestamp(int(self.params['last_date'])) if 'last_date' in self.params else datetime.datetime(2000, 1, 1, 12, 0, 0, 0)\n last_album = self.params['last_album'] if 'last_album' in self.params else None\n last_activity_key = self.params['last_activity_key'] if 'last_activity_key' in self.params else None\n last_activity = None\n\n response = self.client.fetch(url, url_params=url_params)\n # logging.warning('Facebook result: %s - %s' % (response.status_code, response.content))\n if response.status_code == 200:\n more = False\n\n result = json.loads(response.content)\n for d in result['data']:\n # Get timestamp and set last updated\n date = datetime.datetime.strptime(d['created_time'], \"%Y-%m-%dT%H:%M:%S+0000\")\n more = self.continue_on_timestamp(date, index=index)\n if not more:\n # logging.warning(\"We shouldn't be here anymore\")\n break\n\n # Get the album, because we might have to skip the image\n album = {'name': '', 'link': None, 'location': None, 'location_name': None}\n if 'album' in d:\n album['name'] = d['album']['name']\n album['link'] = d['album']['link']\n if 'place' in d['album']:\n p = d['album']['place']\n album['location'] = [p['location']['latitude'], p['location']['longitude']] if 'location' in p else None\n album['location_name'] = p['name'] if 'name' in p else None\n\n # Skip external stuff\n if FacebookReader.use_album(album['name']):\n # General stuff\n key = d['id']\n\n # Photo (use the real date)\n date = datetime.datetime.strptime(d['backdated_time'], \"%Y-%m-%dT%H:%M:%S+0000\") if 'backdated_time' in d else date\n title = d['name'] if 'name' in d else album['name']\n\n # Location\n location = {'location': album['location'], 'name': album['location_name']}\n if 'place' in d:\n p = d['place']\n location['location'] = [p['location']['latitude'], p['location']['longitude']] if 'location' in p else album['location']\n location['name'] = p['name'] if 'name' in p else album['location_name']\n\n # Images\n media = []\n url = d['picture'].replace('_s.jpg', '_n.jpg') # Trick to get a larger version of the picture\n # binary = urlfetch.fetch(url)\n # if binary.status_code == 200:\n # media.append(Media.add(self.service, d['id'], 'image/jpg', binary.content, caption=title, link=d['link']))\n image = Reader.fetch_image(url, optimize=False)\n if image:\n media.append(Media.add(self.service, d['id'], 'image/jpg', image, caption=title, link=d['link']))\n\n # Timezone\n timezone_offset = self.get_timezone_offset(date, location=location['location'])\n\n # Figure out if we need to create a new Activity, or add to an existing\n if (last_activity is not None or last_activity_key is not None) \\\n and last_album is not None and last_album == album['name'] \\\n and Reader.almost_equal_dates(last_date, date, (15 * 60)):\n\n if last_activity is None:\n last_activity = Activity.get(last_activity_key)\n\n # logging.warning(\" - Add: %s - %s\" % (date, title))\n activity = last_activity\n activity.link = album['link']\n # activity.title =\n activity.media += media\n activity.set_location(location['location'], location['name']) # Update location with better info\n activity.put()\n\n else:\n # logging.warning('Facebook: %s - %s - %s' % (date, album['name'], title))\n activity = Activity.add(self.service, key, date, title, link=d['link'], media=media,\n location=location['location'], location_name=location['name'],\n timezone_offset=timezone_offset)\n\n # Almost done, just keep the 'last' values for next run\n last_date = date\n last_album = album['name']\n last_activity = activity\n\n # checkout the paging\n p = result['paging']\n if more and 'next' in p: # There is more\n self.params['next_url'] = p['next']\n self.params['last_date'] = last_date.strftime('%s')\n self.params['last_album'] = last_album\n self.params['last_activity_key'] = last_activity.key.id() if last_activity else None\n self.next_page(index=index)\n else:\n # everything is processed\n self.done(index=index)\n if 'next_url' in self.params: del self.params['next_url'] # Make sure next set starts from the beginning\n self.refresh_posts(index=1)\n\n return\n\n def refresh_posts(self, index=1):\n \"\"\" Refreshing Facebook photos\n \"\"\"\n # Build the url\n if 'next_url' not in self.params:\n url = \"%s%s/posts\" % (self.client.base_url, self.client.user.id)\n url_params = {'fields': 'id,application,link,created_time,updated_time,message,story,type,place'}\n else: # Paging a result set\n url = self.params['next_url']\n url_params = {}\n\n response = self.client.fetch(url, url_params=url_params)\n # logging.warning('Facebook result: %s - %s' % (response.status_code, response.content))\n if response.status_code == 200:\n more = False\n\n result = json.loads(response.content)\n for d in result['data']:\n # Get timestamp and set last updated\n date = datetime.datetime.strptime(d['created_time'], \"%Y-%m-%dT%H:%M:%S+0000\")\n more = self.continue_on_timestamp(date, index=index)\n if not more:\n break\n\n source = d['application']['name'] if 'application' in d else \"Unknown\"\n type = d['type'] if 'type' in d else \"Unknown\"\n\n if type in ['status', 'checkin'] and 'message' in d and source not in ['Twitter', 'My Blogs', 'FriendFeed', \"AYI\"]:\n # General stuff\n keys = d['id'].split('_')\n key = keys[1]\n title = d['message']\n # Need to strip part of he ID\n link = \"https://www.facebook.com/%s/posts/%s\" % (self.client.user.id, key)\n\n # Location\n location = {'location': None, 'name': None}\n if 'place' in d:\n p = d['place']\n location['location'] = [p['location']['latitude'], p['location']['longitude']] if 'location' in p else None\n location['name'] = p['name'] if 'name' in p else None\n\n # Timezone\n timezone_offset = self.get_timezone_offset(date, location=location['location'])\n\n activity = Activity.add(self.service, key, date, title, link=link,\n location=location['location'], location_name=location['name'],\n timezone_offset=timezone_offset)\n\n # checkout the paging\n p = result['paging'] if 'paging' in result else None\n if more and p and 'next' in p: # There is more\n self.params['next_url'] = p['next']\n self.params['topic_index'] = index\n self.next_page(index=index)\n else:\n # everything is processed\n self.done(index=index)\n\n return\n\n def refresh(self):\n \"\"\" Starts the refresh, first the photos are processed and when done the status/checkins continue\n \"\"\"\n # The Topic index, this is used to 'chain' the topics in progress\n # self.refresh_photos(index=0)\n\n index = int(self.params['topic_index']) if 'topic_index' in self.params else 0\n if index == 0:\n self.refresh_photos(index=index)\n elif index == 1:\n self.refresh_posts(index=index)\n\n return","sub_path":"memovent/model/readers/implementation/facebook.py","file_name":"facebook.py","file_ext":"py","file_size_in_byte":10076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"85885901","text":"# declaracao de funcao\n# def nome_da_funcao():\n# print(\"Arquivo de funcoes\")\n\n# print(\"Nao se esquecam\")\n# nome_da_funcao() #chama a funcao nome_da_funcao\n# print(\"da ordem!\")\n\ndef somaDoisNumeros(n1, n2):\n soma = n1+n2\n print(\"A soma de n1: {} e n2: {} é: {}\".format(n1, n2, soma)) \n return soma\n\n# somaDoisNumeros(1, 3)\n\ndef somaTresNumero():\n n1 = float(input(\"Insira o n1: \"))\n n2 = float(input(\"Insira o n2: \"))\n n3 = float(input(\"Insira o n3: \"))\n\n soma = n1 + n2 + n3\n print(\"A soma de n1: {}, n2: {} e n3: {} é: {}\".format(n1, n2, n3,soma))\n\n# somaTresNumero()\n\ndef somaQuatro(n1, n2, n3, n4):\n soma1 = somaDoisNumeros(n1, n2)\n soma2 = somaDoisNumeros(n3, n4)\n somaFinal = somaDoisNumeros(soma1, soma2)\n\n print(\"A soma de {} + {} + {} + {} é: {}\".format(n1, n2, n3, n4, somaFinal))\n\nsomaQuatro(1, 2, 3, 4)","sub_path":"2ele031/lab/lab1/codes/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"642847557","text":"\nweatherSampleRate = 10\n\nimport time\nimport threading\nimport math\nimport bme680\nfrom ha import *\n\n# BME-680 temperature, humidity, pressure, VOC sensor\n\nclass BME680Interface(Interface):\n def __init__(self, name, interface=None, addr=0x77, event=None):\n Interface.__init__(self, name, interface, event=event)\n self.addr = addr\n self.lock = threading.Lock()\n self.correction = .68 # pressure correction - rough approximation in inches\n self.sensor = bme680.BME680(self.addr)\n self.sensor.set_humidity_oversample(bme680.OS_2X)\n self.sensor.set_pressure_oversample(bme680.OS_4X)\n self.sensor.set_temperature_oversample(bme680.OS_8X)\n self.sensor.set_filter(bme680.FILTER_SIZE_3)\n # self.sensor.set_gas_status(bme680.ENABLE_GAS_MEAS)\n # self.sensor.set_gas_heater_temperature(320)\n # self.sensor.set_gas_heater_duration(150)\n # self.sensor.select_gas_heater_profile(0)\n def sample():\n while True:\n with self.lock:\n try:\n while not self.sensor.get_sensor_data():\n time.sleep(.1)\n except IOError as ex:\n log(self.name, type(ex).__name__, str(ex))\n time.sleep(weatherSampleRate)\n sampleThread = LogThread(name=\"sampleThread\", target=sample)\n sampleThread.start()\n\n def read(self, addr):\n with self.lock:\n if addr == \"temp\":\n value = self.sensor.data.temperature * 9/5 + 32\n elif addr == \"humidity\":\n value = self.sensor.data.humidity\n elif addr == \"dewpoint\":\n # https://en.wikipedia.org/wiki/Dew_point\n b = 17.62\n c = 243.12\n g = math.log(self.sensor.data.humidity / 100) + ((b * self.sensor.data.temperature) / (c + self.sensor.data.temperature))\n value = (c * g) / (b - g) * 9/5 + 32\n elif addr == \"barometer\":\n value = self.sensor.data.pressure * 0.029529983071445 + self.correction\n elif addr == \"voc\":\n if self.sensor.data.heat_stable:\n value = self.sensor.data.gas_resistance\n else:\n value = 0\n else:\n value = 0\n debug('debugBME680', self.name, addr, value)\n return round(value, 2)\n","sub_path":"ha/interfaces/bme680Interface.py","file_name":"bme680Interface.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"227809112","text":"from django.shortcuts import render,redirect\nfrom django.contrib import messages\nfrom contacts import models\nfrom django.core.mail import send_mail\n# Create your views here.\n\ndef contact(request):\n if request.method == 'POST':\n listing_id = request.POST['listing_id']\n listing = request.POST['listing']\n name = request.POST['name']\n email = request.POST['email']\n phone = request.POST['phone']\n message = request.POST['message']\n user_id = request.POST['user_id']\n realtor_email = request.POST['realtor_email']\n\n # Check if user has made enquiry already\n if request.user.is_authenticated:\n user_id = request.user.id\n has_contacted = models.Contact.objects.all().filter(listing_id=listing_id,user_id=user_id)\n if has_contacted:\n messages.error(request,'You have already made an enquiry for this listing')\n return redirect('/listings/'+listing_id)\n\n\n contact = models.Contact(listing=listing, listing_id=listing_id, name=name, email=email, \n phone=phone, message=message, user_id=user_id )\n\n contact.save()\n\n #Send mail\n\n send_mail(\n 'Propert Listing Inquiry',\n 'There has been an enquiry for '+listing+ '. Sign into the admin panel for more info',\n 'amamzed.abhi15@gmail.com',\n [realtor_email,'amazed.abhi15@gmail.com'],\n fail_silently=False\n )\n\n messages.success(request,'Your request has been submitted, a realtor will get back to you soon')\n\n return redirect('/listings/'+listing_id)","sub_path":"contacts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"339476759","text":"import threading\nimport time\nimport os\nimport sys\nimport winsound\n\n\nclass CheckInternetThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n while True:\n if self.ping() == 1:\n time.sleep(5)\n if self.ping() == 1:\n time.sleep(9)\n if self.ping() == 1:\n self.sound()\n #break\n time.sleep(25)\n\n def ping(self):\n cmd = 'ping www.hao123.com'\n info = os.system(cmd)\n return info\n\n def sound(self):\n for x in range(1):\n winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)\n\n\nif __name__ == '__main__':\n a = CheckInternetThread()\n a.start()","sub_path":"Crazy/helper0_1/checkinternet.py","file_name":"checkinternet.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"279195196","text":"#####################################################################\n#\n# writer.py\n#\n# Copyright (c) 2015, Eran Egozy\n#\n# Released under the MIT License (http://opensource.org/licenses/MIT)\n#\n#####################################################################\n\nfrom __future__ import print_function\nimport numpy as np\nimport os.path\nimport wave\nfrom common.audio import Audio\n\nclass AudioWriter(object):\n def __init__(self, filebase, output_wave=True):\n super(AudioWriter, self).__init__()\n self.active = False\n self.buffers = []\n self.filebase = filebase\n self.output_wave = output_wave\n\n def add_audio(self, data, num_channels) :\n if self.active:\n # only use a single channel if we are in stereo\n if num_channels == 2:\n data = data[0::2]\n self.buffers.append(data)\n\n def toggle(self) :\n if self.active:\n self.stop()\n else:\n self.start()\n\n def start(self) :\n if not self.active:\n print('AudioWriter: start capture')\n self.active = True\n self.buffers = []\n\n def stop(self) :\n if self.active:\n print('AudioWriter: stop capture')\n self.active = False\n\n output = combine_buffers(self.buffers)\n if len(output) == 0:\n print('AudioWriter: empty buffers. Nothing to write')\n return\n\n ext = 'wav' if self.output_wave else 'npy'\n filename = self._get_filename(ext)\n print('AudioWriter: saving', len(output), 'samples in', filename)\n if self.output_wave:\n write_wave_file(output, 1, filename)\n else:\n np.save(filename, output)\n\n # look for a filename that does not exist yet.\n def _get_filename(self, ext) :\n suffix = 1\n while(True) :\n filename = '%s%d.%s' % (self.filebase, suffix, ext)\n if not os.path.exists(filename) :\n return filename\n else:\n suffix += 1\n\ndef write_wave_file(buf, num_channels, name):\n f = wave.open(name, 'w')\n f.setnchannels(num_channels)\n f.setsampwidth(2)\n f.setframerate(Audio.sample_rate)\n buf = buf * (2**15)\n buf = buf.astype(np.int16)\n f.writeframes(buf.tostring())\n\n# create single buffer from an array of buffers:\ndef combine_buffers(buffers):\n size = 0\n for b in buffers:\n size += len(b)\n\n # create a single output buffer of the right size\n output = np.empty( size, dtype=np.float32 )\n f = 0\n for b in buffers:\n output[f:f+len(b)] = b\n f += len(b)\n return output\n","sub_path":"common/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"467010739","text":"import cv2\r\nimport numpy as np\r\nfrom skew_correction.skewer import Skewer\r\n\r\ndef skewCorrection(img_path):\r\n img=cv2.imread(img_path)\r\n # orig=img.copy()\r\n # img=cv2.resize(img,None,fx=0.5,fy=0.5)\r\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n # img = cv2.GaussianBlur(img, (5, 5), 0)\r\n # img = cv2.Canny(img, 10, 50)\r\n\r\n skewer = Skewer(image_data=img)\r\n rotated = skewer.get_rotated()\r\n\r\n if skewer.is_rotated(): # Returns true or false according to any skew operation\r\n cv2.imshow(\"Rotated image\", rotated)\r\n cv2.imshow(\"image\", img)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n \r\ndef correct_skew(img_path,verbose=False):\r\n image = cv2.imread(img_path)\r\n # image = cv2.resize(image,None,fx=0.5,fy=0.5)\r\n image=image.copy()\r\n \r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n gray = cv2.bitwise_not(gray)\r\n\r\n thresh = cv2.threshold(gray, 0, 255,\r\n\tcv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\r\n \r\n coords = np.column_stack(np.where(thresh > 0))\r\n angle = cv2.minAreaRect(coords)[-1]\r\n\r\n if angle < -45: angle = -(90 + angle)\r\n else: angle = -angle\r\n \r\n (h, w) = image.shape[:2]\r\n center = (w // 2, h // 2)\r\n M = cv2.getRotationMatrix2D(center, angle, 1.0)\r\n rotated = cv2.warpAffine(image, M, (w, h),\r\n\t flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\r\n \r\n # cv2.putText(rotated, \"Angle: {:.2f} degrees\".format(angle),\r\n\t# (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\r\n \r\n if verbose:\r\n print(\"[INFO] angle: {:.3f}\".format(angle))\r\n cv2.imshow(\"Input\", image)\r\n cv2.imshow(\"Rotated\", rotated)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n \r\n return rotated\r\n","sub_path":"src/Skew.py","file_name":"Skew.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"266950939","text":"# -*- coding: utf-8 -*-\nimport csv\nimport os\nimport pickle\n\nimport numpy as np\nfrom keras import layers\nfrom keras import models\nfrom keras.models import load_model\nfrom mahjong.tile import TilesConverter\n\nfrom nn.utils.protocols.own_hand_protocol import tiles_num, tiles_unique\n\n\nclass HandWaits(object):\n model_name = 'hand.h5'\n epochs = 16\n\n def __init__(self, root_dir, data_path, print_predictions):\n self.model_path = os.path.join(root_dir, self.model_name)\n self.data_path = os.path.join(data_path, 'hand')\n self.print_predictions = print_predictions\n\n def remove_model(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def run(self):\n test_file_path = os.path.join(self.data_path, 'test.p')\n test_data = pickle.load(open(test_file_path, 'rb'))\n\n test_samples = len(test_data.input_data)\n test_input = np.asarray(test_data.input_data).astype('float32')\n test_output = np.asarray(test_data.output_data).astype('float32')\n print('Test data size =', test_samples)\n\n if not os.path.exists(self.model_path):\n data_files_temp = os.listdir(self.data_path)\n data_files = []\n for f in data_files_temp:\n if not f.endswith('.p'):\n continue\n if f.endswith('test.p'):\n continue\n\n data_files.append(f)\n\n train_files = sorted(data_files)\n print('{} files will be used for training'.format(len(train_files)))\n\n model = models.Sequential()\n model.add(layers.Dense(1024, activation='relu', input_shape=(tiles_num,)))\n model.add(layers.Dense(1024, activation='relu'))\n model.add(layers.Dense(tiles_unique, activation='sigmoid'))\n\n for n_epoch in range(self.epochs):\n print('')\n print('Processing epoch #{}...'.format(n_epoch))\n for train_file in train_files:\n print('Processing {}...'.format(train_file))\n data_path = os.path.join(self.data_path, train_file)\n train_data = pickle.load(open(data_path, \"rb\"))\n\n train_samples = len(train_data.input_data)\n train_input = np.asarray(train_data.input_data).astype('float32')\n train_output = np.asarray(train_data.output_data).astype('float32')\n\n print('Train data size =', train_samples)\n\n model.compile(\n optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['accuracy']\n )\n\n model.fit(\n train_input,\n train_output,\n epochs=1,\n batch_size=512,\n validation_data=(test_input, test_output)\n )\n\n # We save model after each epoch\n print('Saving model, please don\\'t interrupt...')\n model.save(self.model_path)\n print('Model saved')\n else:\n model = load_model(self.model_path)\n\n results = model.evaluate(test_input, test_output, verbose=1)\n print('results [loss, acc] =', results)\n\n if self.print_predictions:\n self.calculate_predictions(model, test_input, test_output)\n\n def load_data(self, path):\n data = []\n with open(path, 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n if row['player_hand'] and row['waiting']:\n data.append(row)\n return data\n\n def calculate_predictions(self, model, test_input, test_output):\n predictions = model.predict(test_input, verbose=1)\n print('predictions shape = ', predictions.shape)\n\n i = 0\n wrong_predictions = 0\n for prediction in predictions:\n hand = []\n waits = []\n pred = []\n pred_sure = []\n pred_unsure = []\n\n j = 0\n for prob in prediction:\n if prob > 0.8:\n pred_sure.append(j * 4)\n elif prob > 0.5:\n pred_unsure.append(j * 4)\n\n if prob > 0.5:\n pred.append(j * 4)\n\n j += 1\n\n j = 0\n for inp in test_input[i]:\n if inp > 0.01:\n hand.append(j)\n j += 1\n\n j = 0\n for out in test_output[i]:\n if out > 0.01:\n waits.append(j * 4)\n j += 1\n\n if set(waits) != set(pred):\n print('wrong prediction on i =', i)\n print('hand:', TilesConverter.to_one_line_string(hand))\n print('waits:', TilesConverter.to_one_line_string(waits))\n print('pred:', TilesConverter.to_one_line_string(pred))\n print('pred_sure:', TilesConverter.to_one_line_string(pred_sure))\n print('pred_unsure:', TilesConverter.to_one_line_string(pred_unsure))\n wrong_predictions += 1\n\n i += 1\n\n correct_predictions = i - wrong_predictions\n\n print('Predictions: total = %d, correct = %d, wrong = %d' % (i, correct_predictions, wrong_predictions))\n print('%% correct: %f' % (correct_predictions * 1.0 / i))\n","sub_path":"project/nn/own_hand_waits.py","file_name":"own_hand_waits.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"57854578","text":"from ..utils import mol_converter\nfrom ..typing import SpectrumType\nfrom .has_valid_smiles import has_valid_smiles\nfrom .has_valid_inchi import has_valid_inchi\n\n\ndef derive_smiles_from_inchi(spectrum_in: SpectrumType) -> SpectrumType:\n \"\"\"Find missing smiles and derive from Inchi where possible.\"\"\"\n\n spectrum = spectrum_in.clone()\n\n if has_valid_inchi(spectrum) and not has_valid_smiles(spectrum):\n inchi = spectrum.get(\"inchi\")\n smiles = mol_converter(inchi, \"inchi\", \"smi\")\n if not smiles:\n print(\"Could not convert InChI\", inchi, \"to smiles.\")\n smiles = 'n/a'\n smiles = smiles.replace('\\n', '').replace('\\t', '').replace('\\r', '')\n spectrum.set(\"smiles\", smiles)\n\n return spectrum\n","sub_path":"matchms/filtering/derive_smiles_from_inchi.py","file_name":"derive_smiles_from_inchi.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"648862280","text":"import numpy as np\nimport os \n\n\nif 'cytthon_functions' in os.listdir():\n from cytthon_functions import Functions\nelse:\n from Calculation.cytthon_functions import Functions\n \n\nclass Simu():\n \n def __init__(self,Sample,Column,Interaction, Pump, time_factor=1 ):\n self.Interaction = Interaction\n self.Sample = Sample\n self.Column = Column\n self.Pump = Pump\n self.num_length_steps = int(Column.geometry[1]*Column.n_columns//Column.dz)\n self.num_time_steps = int((Column.geometry[1]*Column.n_columns//(Column.velocity*Column.dt))*time_factor)\n self.C = np.zeros([self.num_time_steps,self.num_length_steps,len(Sample.composition)])\n self.q = np.zeros([self.num_time_steps,self.num_length_steps,len(Sample.composition)])\n self.tinj = int(self.Sample.volume//(self.Pump.volume_flow_sec*self.Column.dt))\n self.num_components = range(len(self.Sample.composition))\n \n def injection(self):\n self.C[0:self.tinj, 0 , :] = np.array([np.array(self.Sample.composition)*self.Sample.concentration for _ in np.arange(self.tinj)])\n self.C[self.tinj:self.num_time_steps,0,:] = np.array([self.Sample.disp_concentration for _ in np.arange(self.num_time_steps-self.tinj)])\n\n def simulation(self):\n const1 = -(self.Column.dz/(self.Column.dt*self.Column.velocity))\n F = self.Column.F*const1\n const1_1 = 1+const1\n inter = list(self.Interaction.ads_max*self.Interaction.adsorption)\n qq, cc = Functions.simulation_cython(self.num_time_steps, self.num_length_steps,\n self.Interaction.adsorption,\n self.C,len(self.num_components),\n self.q,inter,const1_1,const1,F)\n self.q = np.array(qq)\n self.C = np.array(cc)\n return self.q,self.C\n \n def enable(self):\n del self.C,self.q\n \nif __name__ == '__main__':\n \n pass\n \n","sub_path":"Calculation/calculation_current.py","file_name":"calculation_current.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391044576","text":"from typing import List, Optional, Any\n\nimport numpy as np\nfrom flatland.core.env_observation_builder import ObservationBuilder\nfrom flatland.core.grid.grid4_utils import get_new_position\nfrom flatland.envs.agent_utils import RailAgentStatus\nfrom flatland.envs.rail_env import fast_count_nonzero, fast_argmax, RailEnvActions\n\nfrom utils.agent_action_config import get_flatland_full_action_size\nfrom utils.agent_can_choose_helper import AgentCanChooseHelper\nfrom utils.dead_lock_avoidance_agent import DeadLockAvoidanceAgent\nfrom utils.deadlock_check import get_agent_positions, get_agent_targets\n\n\"\"\"\nLICENCE for the FastTreeObs Observation Builder \n\nThe observation can be used freely and reused for further submissions. Only the author needs to be referred to\n/mentioned in any submissions - if the entire observation or parts, or the main idea is used.\n\nAuthor: Adrian Egli (adrian.egli@gmail.com)\n\n[Linkedin](https://www.researchgate.net/profile/Adrian_Egli2)\n[Researchgate](https://www.linkedin.com/in/adrian-egli-733a9544/)\n\"\"\"\n\n\nclass FastTreeObs(ObservationBuilder):\n\n def __init__(self, max_depth: Any):\n self.max_depth = max_depth\n self.observation_dim = 35\n self.agent_can_choose_helper = None\n self.dead_lock_avoidance_agent = DeadLockAvoidanceAgent(None, get_flatland_full_action_size())\n\n def debug_render(self, env_renderer):\n agents_can_choose, agents_on_switch, agents_near_to_switch, agents_near_to_switch_all = \\\n self.agent_can_choose_helper.required_agent_decision()\n self.env.dev_obs_dict = {}\n for a in range(max(3, self.env.get_num_agents())):\n self.env.dev_obs_dict.update({a: []})\n\n selected_agent = None\n if agents_can_choose[0]:\n if self.env.agents[0].position is not None:\n self.debug_render_list.append(self.env.agents[0].position)\n else:\n self.debug_render_list.append(self.env.agents[0].initial_position)\n\n if self.env.agents[0].position is not None:\n self.debug_render_path_list.append(self.env.agents[0].position)\n else:\n self.debug_render_path_list.append(self.env.agents[0].initial_position)\n\n env_renderer.gl.agent_colors[0] = env_renderer.gl.rgb_s2i(\"FF0000\")\n env_renderer.gl.agent_colors[1] = env_renderer.gl.rgb_s2i(\"666600\")\n env_renderer.gl.agent_colors[2] = env_renderer.gl.rgb_s2i(\"006666\")\n env_renderer.gl.agent_colors[3] = env_renderer.gl.rgb_s2i(\"550000\")\n\n self.env.dev_obs_dict[0] = self.debug_render_list\n self.env.dev_obs_dict[1] = self.agent_can_choose_helper.switches.keys()\n self.env.dev_obs_dict[2] = self.agent_can_choose_helper.switches_neighbours.keys()\n self.env.dev_obs_dict[3] = self.debug_render_path_list\n\n def reset(self):\n if self.agent_can_choose_helper is None:\n self.agent_can_choose_helper = AgentCanChooseHelper()\n self.agent_can_choose_helper.build_data(self.env)\n self.debug_render_list = []\n self.debug_render_path_list = []\n\n def _explore(self, handle, new_position, new_direction, distance_map, depth=0):\n has_opp_agent = 0\n has_same_agent = 0\n has_target = 0\n has_opp_target = 0\n visited = []\n min_dist = distance_map[handle, new_position[0], new_position[1], new_direction]\n\n # stop exploring (max_depth reached)\n if depth >= self.max_depth:\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n\n # max_explore_steps = 100 -> just to ensure that the exploration ends\n cnt = 0\n while cnt < 100:\n cnt += 1\n\n visited.append(new_position)\n opp_a = self.env.agent_positions[new_position]\n if opp_a != -1 and opp_a != handle:\n if self.env.agents[opp_a].direction != new_direction:\n # opp agent found -> stop exploring. This would be a strong signal.\n has_opp_agent = 1\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n else:\n # same agent found\n # the agent can follow the agent, because this agent is still moving ahead and there shouldn't\n # be any dead-lock nor other issue -> agent is just walking -> if other agent has a deadlock\n # this should be avoided by other agents -> one edge case would be when other agent has it's\n # target on this branch -> thus the agents should scan further whether there will be an opposite\n # agent walking on same track\n has_same_agent = 1\n # !NOT stop exploring!\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n\n # agents_on_switch == TRUE -> Current cell is a switch where the agent can decide (branch) in exploration\n # agent_near_to_switch == TRUE -> One cell before the switch, where the agent can decide\n #\n agents_on_switch, agents_near_to_switch, _, _ = \\\n self.agent_can_choose_helper.check_agent_decision(new_position, new_direction)\n\n if agents_near_to_switch:\n # The exploration was walking on a path where the agent can not decide\n # Best option would be MOVE_FORWARD -> Skip exploring - just walking\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n\n if self.env.agents[handle].target in self.agents_target:\n has_opp_target = 1\n\n if self.env.agents[handle].target == new_position:\n has_target = 1\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n\n possible_transitions = self.env.rail.get_transitions(*new_position, new_direction)\n if agents_on_switch:\n orientation = new_direction\n possible_transitions_nonzero = fast_count_nonzero(possible_transitions)\n if possible_transitions_nonzero == 1:\n orientation = fast_argmax(possible_transitions)\n\n for dir_loop, branch_direction in enumerate(\n [(orientation + dir_loop) % 4 for dir_loop in range(-1, 3)]):\n # branch the exploration path and aggregate the found information\n # --- OPEN RESEARCH QUESTION ---> is this good or shall we use full detailed information as\n # we did in the TreeObservation (FLATLAND) ?\n if possible_transitions[dir_loop] == 1:\n hoa, hsa, ht, hot, v, m_dist = self._explore(handle,\n get_new_position(new_position, dir_loop),\n dir_loop,\n distance_map,\n depth + 1)\n visited.append(v)\n has_opp_agent = max(hoa, has_opp_agent)\n has_same_agent = max(hsa, has_same_agent)\n has_target = max(has_target, ht)\n has_opp_target = max(has_opp_target, hot)\n min_dist = min(min_dist, m_dist)\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n else:\n new_direction = fast_argmax(possible_transitions)\n new_position = get_new_position(new_position, new_direction)\n\n min_dist = min(min_dist, distance_map[handle, new_position[0], new_position[1], new_direction])\n\n return has_opp_agent, has_same_agent, has_target, has_opp_target, visited, min_dist\n\n def get_many(self, handles: Optional[List[int]] = None):\n self.dead_lock_avoidance_agent.reset(self.env)\n self.dead_lock_avoidance_agent.start_step(False)\n self.agent_positions = get_agent_positions(self.env)\n self.agents_target = get_agent_targets(self.env)\n observations = super().get_many(handles)\n self.dead_lock_avoidance_agent.end_step(False)\n return observations\n\n def get(self, handle: int = 0):\n # all values are [0,1]\n # observation[0] : 1 path towards target (direction 0) / otherwise 0 -> path is longer or there is no path\n # observation[1] : 1 path towards target (direction 1) / otherwise 0 -> path is longer or there is no path\n # observation[2] : 1 path towards target (direction 2) / otherwise 0 -> path is longer or there is no path\n # observation[3] : 1 path towards target (direction 3) / otherwise 0 -> path is longer or there is no path\n # observation[4] : int(agent.status == RailAgentStatus.READY_TO_DEPART)\n # observation[5] : int(agent.status == RailAgentStatus.ACTIVE)\n # observation[6] : int(agent.status == RailAgentStatus.DONE or agent.status == RailAgentStatus.DONE_REMOVED)\n # observation[7] : current agent is located at a switch, where it can take a routing decision\n # observation[8] : current agent is located at a cell, where it has to take a stop-or-go decision\n # observation[9] : current agent is located one step before/after a switch\n # observation[10] : 1 if there is a path (track/branch) otherwise 0 (direction 0)\n # observation[11] : 1 if there is a path (track/branch) otherwise 0 (direction 1)\n # observation[12] : 1 if there is a path (track/branch) otherwise 0 (direction 2)\n # observation[13] : 1 if there is a path (track/branch) otherwise 0 (direction 3)\n # observation[14] : If there is a path with step (direction 0) and there is a agent with opposite direction -> 1\n # observation[15] : If there is a path with step (direction 1) and there is a agent with opposite direction -> 1\n # observation[16] : If there is a path with step (direction 2) and there is a agent with opposite direction -> 1\n # observation[17] : If there is a path with step (direction 3) and there is a agent with opposite direction -> 1\n # observation[18] : If there is a path with step (direction 0) and there is a agent with same direction -> 1\n # observation[19] : If there is a path with step (direction 1) and there is a agent with same direction -> 1\n # observation[20] : If there is a path with step (direction 2) and there is a agent with same direction -> 1\n # observation[21] : If there is a path with step (direction 3) and there is a agent with same direction -> 1\n # observation[22] : If there is a switch on the path which agent can not use -> 1\n # observation[23] : If there is a switch on the path which agent can not use -> 1\n # observation[24] : If there is a switch on the path which agent can not use -> 1\n # observation[25] : If there is a switch on the path which agent can not use -> 1\n\n observation = np.zeros(self.observation_dim)\n visited = []\n agent = self.env.agents[handle]\n\n agent_done = False\n if agent.status == RailAgentStatus.READY_TO_DEPART:\n agent_virtual_position = agent.initial_position\n observation[4] = 1\n elif agent.status == RailAgentStatus.ACTIVE:\n agent_virtual_position = agent.position\n observation[5] = 1\n else:\n observation[6] = 1\n agent_virtual_position = (-1, -1)\n agent_done = True\n\n if not agent_done:\n visited.append(agent_virtual_position)\n distance_map = self.env.distance_map.get()\n current_cell_dist = distance_map[handle,\n agent_virtual_position[0], agent_virtual_position[1],\n agent.direction]\n possible_transitions = self.env.rail.get_transitions(*agent_virtual_position, agent.direction)\n orientation = agent.direction\n if fast_count_nonzero(possible_transitions) == 1:\n orientation = fast_argmax(possible_transitions)\n\n for dir_loop, branch_direction in enumerate([(orientation + dir_loop) % 4 for dir_loop in range(-1, 3)]):\n if possible_transitions[branch_direction]:\n new_position = get_new_position(agent_virtual_position, branch_direction)\n new_cell_dist = distance_map[handle,\n new_position[0], new_position[1],\n branch_direction]\n if not (np.math.isinf(new_cell_dist) and np.math.isinf(current_cell_dist)):\n observation[dir_loop] = int(new_cell_dist < current_cell_dist)\n\n has_opp_agent, has_same_agent, has_target, has_opp_target, v, min_dist = self._explore(handle,\n new_position,\n branch_direction,\n distance_map)\n visited.append(v)\n\n if not (np.math.isinf(min_dist) and np.math.isinf(current_cell_dist)):\n observation[11 + dir_loop] = int(min_dist < current_cell_dist)\n observation[15 + dir_loop] = has_opp_agent\n observation[19 + dir_loop] = has_same_agent\n observation[23 + dir_loop] = has_target\n observation[27 + dir_loop] = has_opp_target\n\n agents_on_switch, \\\n agents_near_to_switch, \\\n agents_near_to_switch_all, \\\n agents_on_switch_all = \\\n self.agent_can_choose_helper.check_agent_decision(agent_virtual_position, agent.direction)\n\n observation[7] = int(agents_on_switch)\n observation[8] = int(agents_on_switch_all)\n observation[9] = int(agents_near_to_switch)\n observation[10] = int(agents_near_to_switch_all)\n\n action = self.dead_lock_avoidance_agent.act(handle, None, eps=0)\n observation[30] = action == RailEnvActions.DO_NOTHING\n observation[31] = action == RailEnvActions.MOVE_LEFT\n observation[32] = action == RailEnvActions.MOVE_FORWARD\n observation[33] = action == RailEnvActions.MOVE_RIGHT\n observation[34] = action == RailEnvActions.STOP_MOVING\n\n self.env.dev_obs_dict.update({handle: visited})\n\n observation[np.isinf(observation)] = -1\n observation[np.isnan(observation)] = -1\n\n return observation\n","sub_path":"neurips2020-flatland-starter-kit/utils/fast_tree_obs.py","file_name":"fast_tree_obs.py","file_ext":"py","file_size_in_byte":15051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"105202152","text":"'''\nCreated on Feb 15, 2016\n\n@author: gavran\n'''\nfrom __future__ import print_function\n\nimport sys\nimport logging\nimport select\nimport socket\nimport traceback\nimport pdb\n\ntry:\n import urlparse\nexcept ImportError:\n import urllib.parse as urlparse\n\nfrom tornado import httputil, escape\n\ntry:\n from io import BytesIO # python 3\nexcept ImportError:\n from cStringIO import StringIO as BytesIO # python 2\n\nfrom xudd.actor import Actor\nfrom xudd.hive import Hive\nfrom xudd.tools import join_id\n\nlogging.basicConfig(level=logging.DEBUG)\n_log = logging.getLogger(__name__)\n\n\nclass Server(Actor):\n def __init__(self, hive, id):\n super(Server, self).__init__(hive, id)\n self.message_routing.update({\n 'respond': self.respond,\n 'listen': self.listen\n })\n self.requests = {}\n hive.create_actor(WebSocketHandler, id=\"http\")\n \n def listen(self, message):\n _log.debug(\"in listen\")\n print(\"in listen\")\n body = message.body\n port = body.get('port', 8000)\n host = body.get('host', '127.0.0.1')\n \n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.socket.setblocking(0) # XXX: Don't know if this helps much\n self.socket.bind((host, port))\n self.socket.listen(5) # Max 5 connections in queue\n \n while True:\n readable, writable, errored = select.select(\n [self.socket],\n [],\n [],\n .0000001) # XXX: This will surely make it fast! (?)\n \n if readable:\n _log.info('Got new request ({0} in local index)'.format(len(self.requests)))\n print('Got new request ({0} in local index)'.format(len(self.requests)))\n req = self.socket.accept()\n \n # Use the message id as the internal id for the request\n message_id = self.send_message(\n to=join_id('http', self.hive.hive_id),\n directive='handle_request',\n body={\n 'request': req\n }\n )\n \n _log.debug('Sent request to worker')\n \n self.requests.update({\n message_id: req\n })\n \n yield self.wait_on_self()\n \n def respond(self, message):\n _log.debug('Responding')\n \n sock, bind = self.requests.get(message.in_reply_to)\n sock.sendall(message.body['response'])\n sock.close()\n del self.requests[message.in_reply_to]\n _log.info('Responded')\n \nclass WebSocketHandler(Actor):\n def __init__(self, hive, id):\n super(WebSocketHandler, self).__init__(hive, id)\n self.message_routing.update({\n 'handle_request': self.handle_request\n })\n\n def handle_request(self, message):\n _log.debug(\"handling message...\")\n _log.debug(message.body['request'])\n request = message.body['request']\n socket = request[0]\n message = \"\"\n while True:\n data = socket.recv(2048)\n message += data.decode()\n if not data: \n break\n _log.debug(message)\n \n \n\n\n\n\nif __name__ == '__main__':\n hive = Hive()\n server_id = hive.create_actor(Server)\n hive.send_message(to=server_id, directive=\"listen\")\n hive.run()","sub_path":"demos/tcb_based_server_demo.py","file_name":"tcb_based_server_demo.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"318964175","text":"import csv\n\nfd=open(\"sample1.csv\",\"w\")\ndic = {\"John\": \"john@example.com\", \"Mary\": \"mary@example.com\",} #dictionary\n\ncolum_title=\"Firstname, Lastname\\n\"\nfd.write(colum_title)\n\nfor key in dic.keys():\n name=key\n email=dic[key]\n row=name +','+email+\"\\n\"\n fd.write(row)\nfd.close()","sub_path":"Excel/CSV/Writing_to_a_CSV.py","file_name":"Writing_to_a_CSV.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"533853889","text":"import json\nimport datetime\n\nfrom .models import Post, PostComment\nfrom user.models import User\n\nfrom django.views import View\nfrom django.http import HttpResponse, JsonResponse\n\nclass PostDetailView(View):\n def get(self, request, post_id):\n if Post.objects.filter(id = post_id).exists():\n post = Post.objects.get(id = post_id)\n post_attribute = {\n 'title' : post.title,\n 'description' : post.description,\n 'like' : post.like_number,\n 'view' : post.view_number,\n 'postDate' : post.published_at,\n\t }\n return JsonResponse({'post': post_attribute}, status = 200)\n\n return JsonResponse({'message': 'post_does_not_exist'}, status = 404)\n\nclass PostCommentView(View):\n def post(self, request):\n data = json.loads(request.body)\n if 'is_original' in data:\n PostComment(\n comment = data['comment'],\n post_id = data['post_id'],\n user_id = data['user_id'],\n is_original = True,\n ).save()\n else:\n PostComment(\n comment = data['comment'],\n post_id = data['post_id'],\n user_id = data['user_id'],\n is_original = False,\n original_comment_id = data['original_comment'],\n ).save()\n return JsonResponse({'message': \"success\"}, status = 200)\n\nclass PostView(View):\n def get(self, request):\n offset = int(request.GET.get('offset'))\n limit = int(request.GET.get('limit'))\n try:\n post_elements = Post.objects.all().values('id', 'title', 'like_number','published_at','view_number','first_image', 'first_text')[offset : offset + limit]\n return JsonResponse({'post_main': list(post_elements)}, status = 200)\n\n except Post.DoesNotExist:\n return JsonResponse({'message':'post_does_not_exist'}, status = 404)\n\nclass CommentView(View):\n def get(self, request):\n return JsonResponse({'comment':[]}, status=200)\n\nclass PostReviewView(View):\n def get(self, request):\n posts = Post.objects.order_by('?')[:7]\n review = [\n {'id' : post.id,\n 'title' : post.title,\n 'image' : post.first_image,\n 'likes' : post.like_number,\n 'views' : post.view_number\n } for post in posts]\n return JsonResponse({'reviews': list(review)}, status = 200)\n\n return HttpResponse(status = 404)\n","sub_path":"post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"74617349","text":"from flask import Flask\nfrom flask import request\napp = Flask(__name__)\n\n@app.route('/v1/')\ndef hello_world():\n start = request.args.get(\"start\")\n end = request.args.get(\"end\")\n return \"hello world!\"+(start,end)\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"src/test/test_flask.py","file_name":"test_flask.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"49093089","text":"import random\n\ndef check_number(user_number, counter, guessing_number):\n\n bulls_and_cows_list = [0, 0] # Bulls [0], Cows [1]\n\n if user_number == -1:\n print(guessing_number)\n return -1\n\n if len(str(user_number)) != 4:\n print(\"Warning | Provide a valid number\")\n return 1\n\n if user_number == guessing_number:\n print(\"You've won in {} step(s)!\".format(counter))\n return 2\n\n number_list = []\n for i in str(guessing_number):\n number_list.append(int(i))\n\n for i in range(1, 5):\n if str(user_number)[i - 1] in str(guessing_number) and str(user_number)[i - 1] == str(guessing_number)[i - 1]:\n number_list.pop(number_list.index(int(str(user_number)[i - 1])))\n bulls_and_cows_list[0] += 1\n elif str(user_number)[i - 1] in str(guessing_number) and int(str(user_number)[i - 1]) in number_list:\n number_list.pop(number_list.index(int(str(user_number)[i - 1])))\n bulls_and_cows_list[1] += 1\n\n print(\"Info| {} bull(s), {} cow(s)\".format(bulls_and_cows_list[0], bulls_and_cows_list[1]))\n return 0\n\ndef start_game():\n\n while True:\n\n guessing_number = random.randint(1000, 9999)\n print(\"Ive picked random number between 1000 and 9999, your turn\\n\")\n counter = 1\n\n while check_number(int(input(\"You | Pick a 4 digit number: \")), counter, guessing_number) != 2:\n counter += 1\n\nif __name__ == \"__main__\":\n\n start_game()\n","sub_path":"bullsandcows.py","file_name":"bullsandcows.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"219225801","text":"import numpy as np\nimport random\nimport scipy.misc\nimport os\nimport csv\nimport itertools\nfrom PIL import Image\nfrom PIL import ImageDraw \nfrom PIL import ImageFont\n\n\ndef ensure_dir(file_path):\n '''\n Used to ensure to create the a directory when needed\n :param file_path: path to the file that we want to create\n '''\n directory = os.path.dirname(file_path)\n if not os.path.exists(directory):\n os.makedirs(directory)\n return file_path\n#\n# #Used to initialize weights for policy and value output layers\n# def normalized_columns_initializer(std=1.0):\n# def _initializer(shape, dtype=None, partition_info=None):\n# out = np.random.randn(*shape).astype(np.float32)\n# out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))\n# return tf.constant(out)\n# return _initializer\n\n\nclass RingBuffer():\n \"\"\"\n TO-TEST: test the sampling procedure\n \"\"\"\n def __init__(self, length):\n self.buffer = np.zeros(length, dtype='f')\n self.index = 0\n\n def extend(self, x):\n \"adds array x to ring buffer\"\n x_index = (self.index + np.arange(x.size)) % self.buffer.size\n self.buffer[x_index] = x\n self.index = x_index[-1] + 1\n\n def sample(self, size):\n return np.random.choice(self.buffer, size)\n\n\nclass ExperienceBuffer():\n def __init__(self, buffer_size=50000):\n '''\n store a history of experiences that can be randomly drawn from when training the network. We can draw form the\n previous past experiment to learn\n :param buffer_size: size of the buffer\n '''\n self.buffer = []\n self.buffer_size = buffer_size\n\n def add(self, experience):\n if len(list(self.buffer)) + len(list(experience)) >= self.buffer_size:\n self.buffer[0:(len(list(experience)) + len(list(self.buffer))) - self.buffer_size] = []\n self.buffer.extend(experience)\n\n def sample(self, size):\n return np.reshape(np.array(random.sample(self.buffer, size)), [size, 5])\n\ndef set_image_gridworld(frame,measurements,step,goal,hero):\n b = np.ones([840,640,3]) * 255.0\n b = Image.fromarray(b.astype('uint8'))\n draw = ImageDraw.Draw(b)\n font = ImageFont.truetype(\"./resources/FreeSans.ttf\", 24)\n draw.text((240, 670),'Step: ' + str(step),(0,0,0),font=font)\n draw.text((240, 720),'Battery: ' + str(measurements[1]),(0,0,0),font=font)\n draw.text((240, 770),'Deliveries: ' + str(measurements[0]),(0,0,0),font=font)\n c = np.array(b)\n drone = np.array(Image.open('./resources/drone.png'))\n c[hero[0]*128:hero[0]*128+128,hero[1]*128:hero[1]*128+128,:] = drone\n battery = np.array(Image.open('./resources/battery.png'))\n c[0:128,0:128,:] = battery\n house = np.array(Image.open('./resources/house.png'))\n c[goal[0]*128:goal[0]*128+128,goal[1]*128:goal[1]*128+128,:] = house\n return c\n\ndef set_image_gridworld_reward(frame,reward,step,goal,hero):\n b = np.ones([840,640,3]) * 255.0\n b = Image.fromarray(b.astype('uint8'))\n draw = ImageDraw.Draw(b)\n font = ImageFont.truetype(\"./resources/FreeSans.ttf\", 24)\n draw.text((240, 670),'Step: ' + str(step),(0,0,0),font=font)\n draw.text((240, 720),'Deliveries: ' + str(reward),(0,0,0),font=font)\n c = np.array(b)\n drone = np.array(Image.open('./resources/drone.png'))\n c[hero[0]*128:hero[0]*128+128,hero[1]*128:hero[1]*128+128,:] = drone\n house = np.array(Image.open('./resources/house.png'))\n c[goal[0]*128:goal[0]*128+128,goal[1]*128:goal[1]*128+128,:] = house\n return c\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"301146299","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef comma_to_float(valstr):\r\n return float(valstr. decode(\"utf-8\"). replace(',', '.'))\r\n\r\n\r\n##IX.2 Auswertung des Natriumspektrums\r\n#file \"Natriumlinks2811\" ist required containing data for sodium spectrum\r\n#import data for sodium spectrum(total)\r\n# lamb_sod wavelenght of spectrum in nm\r\n#inten_sod intensity in counts\r\nlamb_sod, inten_sod= np. loadtxt('data_Na/Natriumlinks2811.txt', skiprows=17,\r\n converters= {0:comma_to_float,1:comma_to_float},\r\n comments= '>', unpack= True)\r\n\r\n#RebAbb9\r\n#plot whole sodium spectrum\r\nplt. plot(lamb_sod, inten_sod)\r\nplt. title('Natriumspektrum starke Intensiaet')\r\nplt. xlabel('Wellenlaenge / nm')\r\nplt. ylabel('Intensitaet / b.E.')\r\nplt. yscale('log')#logarithmic scale\r\nplt. ylim((1, 80000))\r\nplt. xlim((350, 800))\r\n#plt.savefig(\"Plots/Natriumspektrum_gesamt.pdf\", format= \"pdf\")\r\nplt.show()\r\nplt.close()\r\n\r\n##IX.2 Auswertung des Natriumspektrums\r\n#file \"Natriumlinks2811\" ist required containing data for sodium spectrum\r\n\r\n\r\n\r\n\r\n\r\n##IX.2 Auswertung des Natriumspektrums\r\n#file \"Natriumlinks2811\" ist required containing data for sodium spectrum\r\n#RebAbb10\r\n#plot sodium spectrum in range 300 to 540 nm\r\nplt. plot(lamb_sod, inten_sod)#In case xlim does not work, correct input data\r\nplt. title('Natriumspektrum geringer Intensitaet kurze Wellenlaengen')\r\nplt. xlabel('Wellenlaenge / nm')\r\nplt. ylabel('Intensitaet / b.E.')\r\nplt. yscale('log')#logarithmic scale\r\nplt. ylim((0, 60000))\r\nplt. xlim((350, 540))\r\nplt.show()\r\nplt.close()\r\n#plt.savefig(\"Plots/Natriumspektrum_kurz.pdf\", format= \"pdf\")\r\n\r\n#RebAbb11\r\n#plot sodium spectrum in range 600 to 850 nm\r\nplt. plot(lamb_sod, inten_sod)#In case xlim does not work, correct input data\r\nplt. title('Natriumspektrum geringer Intensitaet lange Wellenlaengen')\r\nplt. xlabel('Wellenlaenge / nm')\r\nplt. ylabel('Intensitaet / b.E.')\r\nplt. yscale('log')#logarithmic scale\r\nplt. ylim((0, 60000))\r\nplt. xlim((600, 850))\r\n#plt.savefig(\"Plots/Natriumspektrum_lang.pdf\", format= \"pdf\")\r\nplt.show()\r\nplt.close()\r\n\r\nlamb_ds, inten_ds= np. loadtxt('Sonnedireckt2811.txt', skiprows=17,\r\n converters= {0:comma_to_float,1:comma_to_float},\r\n comments= '>', unpack= True)\r\n\r\nplt. plot(lamb_ds, inten_ds, label = \"Direkektes Sonnenlicht\")\r\nplt. title('Fraunhoferlinien')\r\nplt. xlabel('Wellenlaenge / nm')\r\nplt. ylabel('Intensitaet / b.E.')\r\nplt. legend()\r\nplt. grid()\r\nplt. ylim((0, 70000))\r\nplt. xlim((200, 900))\r\nplt. savefig(\"plots/Fraunhofer.pdf\", format= \"pdf\")\r\nplt.show()\r\n#plt.close()","sub_path":"V234/V234/V234_Peaks_Na_spektrum.py","file_name":"V234_Peaks_Na_spektrum.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"352392462","text":"# 1288. Remove Covered Intervals\n\n\n# 2021/03/25\n# Runtime: 92 ms, faster than 80.84% of Python3 online submissions for Remove Covered Intervals.\n# Memory Usage: 14.6 MB, less than 95.21% of Python3 online submissions for Remove Covered Intervals.\n\n# 贪心 + 最大堆解法。其实和meeting room lc253有异曲同工之处。\n# 将区间按照始点从小到大排列,始点相同的情况下,将终点按照从大到小排列(贪心)。\n# 在遍历到每个区间时,我们需要判断当前区间是否被前面某个区间完全覆盖住。由于我们是按照始点从小到大遍历的,因此我们仅需要判断当前区间的\n# 终点是否比之前某个区间的终点要小,如果是的话,说明当前区间被覆盖住了,不可用。\n# 由此可见我们需要一个最大堆来维护遍历过的区间的终点。\n# 最终堆的size即为答案。\n# 解法还可以进一步优化。可以假想有一个堆,这个堆并不需要写出来。\n\nclass Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n max_heap = []\n intervals = sorted((l, -r) for l, r in intervals)\n for _, r in intervals:\n if max_heap and -r <= -max_heap[0]:\n continue\n heapq.heappush(max_heap, r)\n return len(max_heap)\n\n","sub_path":"1288. Remove Covered Intervals.py","file_name":"1288. Remove Covered Intervals.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"616110024","text":"import pika\nimport sys\n\nusername = \"shiwei\"\npwd = 'shiwei666666'\nuser_pwd = pika.PlainCredentials(username, pwd)\n\n# 创建连接\nconn = pika.BlockingConnection(pika.ConnectionParameters(\"localhost\", credentials=user_pwd))\n\nchannel = conn.channel()\n\nchannel.exchange_declare(exchange='topic_logs',\n exchange_type='topic')\n\nresult = channel.queue_declare(exclusive=True,\n queue=\"\",)\nqueue_name = result.method.queue\n\nbinding_keys = sys.argv[1:]\nif not binding_keys:\n sys.stderr.write(\"Usage: %s [binding_key]...\\n\" % sys.argv[0])\n sys.exit(1)\n\nfor binding_key in binding_keys:\n channel.queue_bind(exchange='topic_logs',\n queue=queue_name,\n routing_key=binding_key)\n\nprint(' [*] Waiting for logs. To exit press CTRL+C')\n\n\ndef callback(ch, method, properties, body):\n print(\" [x] %r:%r\" % (method.routing_key, body))\n\n\nchannel.basic_consume(on_message_callback = callback,\n queue=queue_name,\n auto_ack=True)\n\nchannel.start_consuming()","sub_path":"RabbitMQ_Demo/发布_订阅_广播,一对多/topic_exchange/Demo01/topic_receive_subscribe02.py","file_name":"topic_receive_subscribe02.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"649497233","text":"from configparser import ConfigParser\nimport json\nimport os\nimport sys\n\nfrom raven import Client\nfrom raven.transport.http import HTTPTransport\n\n\n# Cache this value and clients in the module to reduce overhead\nthis = sys.modules[__name__]\n\nthis.raven_config = ConfigParser(os.environ)\nthis._raven_client = None\n\n\ndef get_raven_client():\n if not this._raven_client:\n this._raven_client = Client(\n this.raven_config.get('DEFAULT', 'RAVEN_DSN'),\n transport=HTTPTransport)\n return this._raven_client\n\n\ndef unhandled_exceptions(e, event, context):\n \"\"\"Exception handler reports exceptions to sentry but does not capture them.\"\"\"\n raven_client = get_raven_client()\n\n if 'httpMethod' in event:\n extra_tags = {\n 'http_method': event['httpMethod'],\n 'path': event['path']\n }\n if 'Host' in event['headers']:\n extra_tags['host'] = event['headers']['Host']\n if 'User-Agent' in event['headers']:\n extra_tags['user_agent'] = event['headers']['User-Agent']\n if 'requestContext' in event and 'stage' in event['requestContext']:\n extra_tags['stage'] = event['requestContext']['stage']\n raven_client.context.merge({'tags': extra_tags})\n\n raven_client.context.merge({'extra': {\n 'event': event\n }})\n\n raven_client.captureException()\n return False\n\n\ndef capture_exceptions(e, event, context):\n \"\"\"\n Exception handler that makes exceptions disappear after processing them.\n\n zappa_settings.py[\"stage\"][\"remote_env] = \"exception_handler\": \"ib_common.sentry_utils.zappa_sentry.capture_exceptions\",\n \"\"\"\n\n unhandled_exceptions(e, event, context)\n return True\n","sub_path":"lib/python3.8/site-packages/ib_common/sentry_utils/zappa_sentry.py","file_name":"zappa_sentry.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"533842416","text":"import antlr3\nimport testbase\nimport unittest\n\nclass t001lexer(testbase.ANTLRTest):\n def setUp(self):\n self.compileGrammar()\n \n \n def lexerClass(self, base):\n class TLexer(base):\n def emitErrorMessage(self, msg):\n # report errors to /dev/null\n pass\n\n def reportError(self, re):\n # no error recovery yet, just crash!\n raise re\n\n return TLexer\n \n \n def testValid(self):\n stream = antlr3.StringStream('0')\n lexer = self.getLexer(stream)\n\n token = lexer.nextToken()\n self.assertEqual(token.type, self.lexerModule.ZERO)\n\n token = lexer.nextToken()\n self.assertEqual(token.type, self.lexerModule.EOF)\n \n\n def testIteratorInterface(self):\n stream = antlr3.StringStream('0')\n lexer = self.getLexer(stream)\n\n types = [token.type for token in lexer]\n\n self.assertEqual(types, [self.lexerModule.ZERO])\n \n\n def testMalformedInput(self):\n stream = antlr3.StringStream('1')\n lexer = self.getLexer(stream)\n\n try:\n token = lexer.nextToken()\n self.fail()\n\n except antlr3.MismatchedTokenException as exc:\n self.assertEqual(exc.expecting, '0')\n self.assertEqual(exc.unexpectedType, '1')\n \n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"thirdparty/antlr3-antlr-3.5/runtime/Python3/tests/t001lexer.py","file_name":"t001lexer.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"161986866","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.python.ops import rnn, rnn_cell\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot = True)\n\nn_nodes_hl1 = 700\nn_nodes_hl2 = 700\nn_nodes_hl3 = 700\nn_nodes_hl4 = 700\nn_classes = 10\nbatch_size = 128\nepochs = 40\ntile_size = 28\nn_tiles = 28\nrnn_size = 512\n\nx = tf.placeholder('float', [None, n_tiles, tile_size])\ny = tf.placeholder('float')\n\ndef neural_network_model(data):\n hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])),\n 'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}\n\n hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),\n 'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}\n\n hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),\n 'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}\n\n hidden_4_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_nodes_hl4])),\n 'biases':tf.Variable(tf.random_normal([n_nodes_hl4]))}\n\n output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl4, n_classes])),\n 'biases':tf.Variable(tf.random_normal([n_classes])),}\n\n\n l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), hidden_1_layer['biases'])\n l1 = tf.nn.relu(l1)\n\n l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']), hidden_2_layer['biases'])\n l2 = tf.nn.relu(l2)\n\n l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), hidden_3_layer['biases'])\n l3 = tf.nn.relu(l3)\n\n l4 = tf.add(tf.matmul(l3,hidden_4_layer['weights']), hidden_4_layer['biases'])\n l4 = tf.nn.relu(l4)\n\n output = tf.matmul(l4,output_layer['weights']) + output_layer['biases']\n\n return output\n\n\n\ndef rec_neural_network(x):\n layer = {'weights':tf.Variable(tf.random_normal([rnn_size,n_classes])),\n 'biases':tf.Variable(tf.random_normal([n_classes]))}\n\n x = tf.transpose(x, [1,0,2])\n x = tf.reshape(x, [-1, tile_size])\n x = tf.split(x, n_tiles, 0)\n\n lstm_cell = rnn_cell.BasicLSTMCell(rnn_size,state_is_tuple=True)\n outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)\n\n output = tf.matmul(outputs[-1],layer['weights']) + layer['biases']\n\n return output\n\n\n\n\n\ndef train_neural_network(x, epochs):\n \n #prediction = neural_network_model(x)\n prediction = rec_neural_network(x)\n\n cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )\n optimizer = tf.train.AdamOptimizer().minimize(cost)\n \n \n with tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n\n for epoch in range(epochs):\n epoch_loss = 0\n for _ in range(int(mnist.train.num_examples/batch_size)):\n epoch_x, epoch_y = mnist.train.next_batch(batch_size)\n epoch_x = epoch_x.reshape((batch_size,n_tiles, tile_size))\n\n _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})\n epoch_loss += c\n\n print('Epoch', epoch, 'completed out of',epochs,'loss:',epoch_loss)\n\n correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))\n\n accuracy = tf.reduce_mean(tf.cast(correct, 'float'))\n print('Accuracy:',accuracy.eval({x:mnist.test.images.reshape((-1, n_tiles, tile_size)), y:mnist.test.labels}))\n\n\nif __name__ == \"__main__\":\n train_neural_network(x, epochs)","sub_path":"mnist_tf_rnn.py","file_name":"mnist_tf_rnn.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"12425681","text":"import os\nimport sys\n\n\ninpath=sys.argv[1]\ninfile=sys.argv[2]\noutfull=\"/scratch/ianli/coreGR/\"+infile+\".gr\"\n\ninfp=open(inpath+infile, \"r\")\noutfp=open(outfull, \"w\")\n\nvertices=0\nedges=0\noutstring=\"\"\n\nwhile True:\n l = infp.readline().strip()\n if not l:\n break\n line = map(int, l.split(' '))\n learntID=line[0]\n if learntID > vertices:\n vertices = learntID\n for antecedentID in reversed(line[:-1]):\n if antecedentID == 0:\n break\n outstring+=str(antecedentID)+\" \"+str(learntID)+\"\\n\"\n edges+=1\n\nheader=\"p tw \"+str(vertices)+\" \"+str(edges)+\"\\n\"\noutfp.write(header)\noutfp.write(outstring)\n\ninfp.close()\noutfp.close()\n","sub_path":"scripts/dependencyToGR.py","file_name":"dependencyToGR.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"471659293","text":"from selenium import webdriver\nfrom robot.errors import RemoteError\n\n\nclass InitializeBrowser():\n def __init__(self):\n project_location=r\"C:\\Users\\Arun\\Budget_Project\"\n self._options = webdriver.ChromeOptions()\n self._options.add_argument(\"--start-maximized\")\n self._options.add_argument(\"--disable-plugins\")\n self._options.add_argument(\"--disable-extensions\")\n self._chromedriver = r\"C:\\Users\\Arun\\Budget_Project\\driver\\chromedriver.exe\"\n\n def initialize_driver(self,browser_type):\n try:\n if browser_type is \"Chrome\":\n self.driver = webdriver.Chrome(executable_path= self._chromedriver, chrome_options= self._options)\n except Exception as err:\n raise RemoteError (\"Issue in initializung browser\",fatal=False, continuable=False)\n\n\n","sub_path":"library/BrowserInitialize/initialize_browser.py","file_name":"initialize_browser.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"575611183","text":"import pygame\nimport os\n\npygame.init()\n\ncolCheck = int(input(\"What colour would you like to change from?\\n1. Red\\n2. Green\\n\\nPlease \"\n \"enter a number: \"))\n\ndisplay = pygame.display.set_mode((800, 600))\n\nred = (255, 0, 0) # setting colour values to variables\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\nyellow = (255, 255, 0)\n\norigFilename = 'test image'\norigImgPath = os.path.join('Contract4Images/ImageChange', origFilename + '.jpg')\norigImg = pygame.image.load(origImgPath).convert() # loading image\n\nimgWidth = origImg.get_width() # getting height and width of test image\nimgHeight = origImg.get_height()\n\ngreenImg = pygame.Surface((imgWidth, imgHeight)) # setting new images to same surface\nblueImg = pygame.Surface((imgWidth, imgHeight))\nyellowImg = pygame.Surface((imgWidth, imgHeight))\nredImg = pygame.Surface((imgWidth, imgHeight))\n\nif colCheck == 1:\n for i in range(imgWidth):\n for p in range(imgHeight):\n for j in range(3):\n pixelColour = origImg.get_at((i, p)) # get_at gets the colour of the pixels\n if j != 2:\n tempCol = pixelColour[0]\n pixelColour[0] = pixelColour[j + 1]\n pixelColour[j + 1] = tempCol\n if j == 0:\n greenImg.set_at((i, p), pixelColour) # set_at changes the pixel colour\n else:\n blueImg.set_at((i, p), pixelColour)\n else:\n pixelColour[1] = pixelColour[0]\n yellowImg.set_at((i, p), pixelColour)\n\n blueFilename = os.path.join('Contract4Images', origFilename + ' (Blue)' + '.png')\n pygame.image.save(blueImg, blueFilename)\n\n yellowFilename = os.path.join('Contract4Images', origFilename + ' (Yellow)' + '.png')\n pygame.image.save(yellowImg, yellowFilename)\n\n greenFilename = os.path.join('Contract4Images', origFilename + ' (Green)' + '.jpg')\n pygame.image.save(greenImg, greenFilename)\n\nelif colCheck == 2:\n for i in range(imgWidth):\n for p in range(imgHeight):\n for j in range(3):\n pixelColour = origImg.get_at((i, p)) # get_at gets the colour of the pixels\n if j != 2:\n tempCol = pixelColour[0]\n pixelColour[0] = pixelColour[j + 1]\n pixelColour[j + 1] = tempCol\n if j == 0:\n redImg.set_at((i, p), pixelColour) # set_at changes the pixel colour\n elif j != 0:\n pixelColour[2] = pixelColour[1]\n blueImg.set_at((i, p), pixelColour)\n else:\n pixelColour[0] = pixelColour[1]\n yellowImg.set_at((i, p), pixelColour)\n\n blueFilename = os.path.join('Contract4Images', origFilename + ' (Blue)' + '.png')\n pygame.image.save(blueImg, blueFilename)\n\n yellowFilename = os.path.join('Contract4Images', origFilename + ' (Yellow)' + '.png')\n pygame.image.save(yellowImg, yellowFilename)\n\n redFilename = os.path.join('Contract4Images', origFilename + ' (Red)' + '.png')\n pygame.image.save(redImg, redFilename)\n","sub_path":"Contract 4 Entity Reskinning/Contract 4.py","file_name":"Contract 4.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"650235458","text":"import os,sys\nimport numpy as np\nimport h5py, time, itertools, datetime\n\nimport torch\n\nfrom connectomics.io import *\nfrom connectomics.run import train\n\n\ndef main():\n args = get_args(mode='train')\n\n print('0. initial setup')\n\n\n print('2.0 setup model')\n model = get_model(args)\n criterion = get_criterion(args)\n monitor = get_monitor(args)\n\n print('3. setup optimizer')\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999), \n eps=1e-08, weight_decay=1e-5, amsgrad=True)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, \n patience=10000, verbose=False, threshold=0.0001, threshold_mode='rel', cooldown=0, \n min_lr=1e-7, eps=1e-08)\n \n print('4. start training')\n if args.do_chunk_tile == 0:\n train_loader = get_dataloader(args, 'train')\n train(args, train_loader, model, criterion, optimizer, scheduler, monitor, pre_iter=args.pre_model_iter)\n else:\n pre_iter = args.pre_model_iter\n tile_dataset = get_dataset(args, 'train')\n num_chunk = (args.iteration_total-pre_iter) // args.data_chunk_iter\n args.iteration_total = args.data_chunk_iter\n for chunk in range(num_chunk):\n tile_dataset.updatechunk()\n train_loader = get_dataloader(args, 'train', dataset=tile_dataset.dataset)\n train(args, train_loader, model, criterion, optimizer, scheduler, monitor, pre_iter=pre_iter)\n pre_iter += args.data_chunk_iter\n del train_loader\n \n print('5. finish training')\n if logger is not None:\n logger.close()\n if writer is not None:\n writer.close()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"420926975","text":"import pygame\nimport math\nimport random\n\npygame.init()\nsx = 500\nsy = 500\nscreen = pygame.display.set_mode((sx, sy))\ndone = False\nx = 0\ny = 0\nev = 'r'\nfl = 0\nclock = pygame.time.Clock()\ncolor = (0, 128, 255)\nsp = {0: (x, y)}\nsize = 1\npoints = 0\n\n\ndef checkOut(a1, b1, ev1):\n if a1 == sx - 20 and b1 == sy - 20:\n if ev1 == 'r' or ev1 == 'd':\n return True\n if a1 == 0 and b1 == 0:\n if ev1 == 'l' or ev1 == 'u':\n return True\n if a1 == 0 and b1 == sy - 20:\n if ev1 == 'd' or ev1 == 'l':\n return True\n if a1 == sx - 20 and b1 == 0:\n if ev1 == 'r' or ev1 == 'u':\n return True\n if a1 == sx - 20:\n if ev1 == 'r':\n return True\n if a1 == 0:\n if ev1 == 'l':\n return True\n if b1 == 0:\n if ev1 == 'u':\n return True\n if b1 == sy - 20:\n if ev1 == 'd':\n return True\n zx, zy = sp[0]\n for i in range(2, size):\n tex, tey = sp[i]\n if zx == tex and zy == tey:\n return True\n return False\n\n\ndef move(a, b, ev):\n if ev == 'r':\n if a <= sx - 40:\n a += 20\n if ev == 'l':\n if a >= 20:\n a -= 20\n if ev == 'u':\n if b >= 20:\n b -= 20\n if ev == 'd':\n if b <= sy - 40:\n b += 20\n return a, b\n\n\n# If you want snake to move through edges\ndef move2(a, b, ev):\n if ev == 'r':\n if a <= sx - 40:\n a += 20\n else:\n a = 0\n if ev == 'l':\n if a >= 20:\n a -= 20\n else:\n a = sx - 20\n if ev == 'u':\n if b >= 20:\n b -= 20\n else:\n b = sy - 20\n if ev == 'd':\n if b <= sy - 40:\n b += 20\n else:\n b = 0\n return a, b\n\n\npygame.font.init()\nmyfont = pygame.font.SysFont('Comic Sans MS', 20)\n\n\ndef drawbox(x, y, col=color):\n pygame.draw.rect(screen, col, pygame.Rect(x, y, 20, 20))\n pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(x, y, 20, 20), 2)\n # pygame.draw.rect(screen, [200, 200, 200], pygame.Rect(x,y, 20), 5)\n\n\ndef randomSnack():\n rx1 = random.randrange((sx - 20) / 20)\n ry1 = random.randrange((sy - 20) / 20)\n return rx1 * 20, ry1 * 20\n\n\nrx, ry = randomSnack()\n\nwhile not done:\n fl = 0\n screen.fill((0, 0, 0))\n screen.blit(pygame.image.load('apple.png'), (rx - 2, ry - 2))\n textsurface = myfont.render(str(points), False, (255, 255, 0))\n screen.blit(textsurface, (sx - 60, 10))\n # pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(rx, ry, 20, 20))\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\n r1 = random.randrange(255)\n g1 = random.randrange(255)\n b1 = random.randrange(255)\n color = (r1, g1, b1)\n pressed = pygame.key.get_pressed()\n if pressed[pygame.K_UP] or pressed[pygame.K_w]:\n ev = 'u'\n if pressed[pygame.K_DOWN] or pressed[pygame.K_s]:\n ev = 'd'\n if pressed[pygame.K_LEFT] or pressed[pygame.K_a]:\n ev = 'l'\n if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:\n ev = 'r'\n\n if pressed[pygame.K_q]:\n done = True\n\n x, y = move2(x, y, ev)\n nx, ny = sp[0]\n nx1, ny1 = move2(nx, ny, ev)\n\n sp[0] = (nx1, ny1)\n sp[1] = (nx, ny)\n for i in range(size - 1, 0, -1):\n nx, ny = sp[i]\n drawbox(nx, ny, color)\n tx, ty = sp[i - 1]\n sp[i] = (tx, ty)\n drawbox(nx1, ny1, (0, 0, 255))\n pygame.display.flip()\n clock.tick(10)\n if x == rx and y == ry:\n sp[size] = (rx + 1, ry + 1)\n rx, ry = randomSnack()\n size += 1\n points += 10\n # print(sp)\n if checkOut(nx, ny, ev):\n size = 1\n points = 0\n x, y = 0, 0\n sp[0] = (x, y)\n ev = 'r'\n # print(\"out\")\n","sub_path":"snake_manual.py","file_name":"snake_manual.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"227223717","text":"from CMGTools.RootTools.analyzers.TreeAnalyzer import TreeAnalyzer\n\nclass EMissTreeProducer( TreeAnalyzer ):\n '''Tree producer for the WWH and HZ -> nunu bb analysis.'''\n\n def declareVariables(self):\n\n def var( varName ):\n self.tree.addVar('float', varName)\n\n def jetVars( pName ):\n var('{pName}Mass'.format(pName=pName))\n var('{pName}Pt'.format(pName=pName))\n var('{pName}Energy'.format(pName=pName))\n var('{pName}Eta'.format(pName=pName))\n var('{pName}Phi'.format(pName=pName))\n var('{pName}Nobj'.format(pName=pName))\n var('{pName}Ntrk'.format(pName=pName))\n var('{pName}NEle'.format(pName=pName))\n var('{pName}pdgId'.format(pName=pName))\n var('{pName}NMu'.format(pName=pName))\n var('{pName}B7'.format(pName=pName))\n \n \n var('ptMiss')\n var('pMiss')\n var('eMiss')\n var('mMiss')\n var('mMissFit')\n var('ctMiss')\n var('ptVis')\n var('pVis')\n var('eVis')\n var('mVis')\n var('mVisFit')\n var('ctVis')\n var('acol')\n var('acop')\n var('sumtet')\n var('nunubb')\n var('wwh')\n var('eleele')\n var('mumu')\n var('tautau')\n var('alpha')\n var('cross')\n var('chi2mZ')\n var('chi2partiel')\n\n jetVars('Jet1')\n jetVars('Jet2')\n\n self.tree.book()\n\n\n def process(self, iEvent, event):\n\n def fill( varName, value ):\n setattr( self.tree.s, varName, value )\n\n def fJetVars( pName, particle ):\n fill('{pName}Mass'.format(pName=pName), particle.mass() )\n fill('{pName}Pt'.format(pName=pName), particle.pt() )\n fill('{pName}Eta'.format(pName=pName), particle.eta() )\n fill('{pName}Phi'.format(pName=pName), particle.phi() )\n fill('{pName}Energy'.format(pName=pName), particle.energy() )\n fill('{pName}Nobj'.format(pName=pName), particle.nConstituents() )\n fill('{pName}Ntrk'.format(pName=pName), particle.component(1).number() )\n fill('{pName}NEle'.format(pName=pName), particle.component(2).number() )\n fill('{pName}NMu'.format(pName=pName), particle.component(3).number() )\n fill('{pName}pdgId'.format(pName=pName), particle.pdgId() )\n fill('{pName}B7'.format(pName=pName), particle.btag(7) )\n\n subevent = getattr( event, self.cfg_ana.anaName )\n\n fill('ptMiss',subevent.ptMiss)\n fill('eMiss',subevent.eMiss)\n fill('pMiss',subevent.pMiss)\n fill('mMiss',subevent.mMiss)\n fill('mMissFit',subevent.mMissFit)\n fill('ctMiss',subevent.ctMiss) \n fill('ptVis',subevent.ptVis)\n fill('eVis',subevent.eVis)\n fill('pVis',subevent.pVis)\n fill('mVis',subevent.mVis)\n fill('mVisFit',subevent.mVisFit)\n fill('ctVis',subevent.ctVis) \n fill('acol',subevent.acol)\n fill('acop',subevent.acop)\n fill('sumtet',subevent.sumtet)\n fill('nunubb',subevent.nunubb)\n fill('wwh',subevent.wwh)\n fill('eleele',subevent.eleele)\n fill('mumu',subevent.mumu)\n fill('tautau',subevent.tautau)\n fill('alpha',subevent.alpha)\n fill('cross',subevent.cross)\n fill('chi2mZ',subevent.chi2mZ)\n fill('chi2partiel',subevent.chi2partiel)\n\n fJetVars('Jet1',subevent.allJets[0])\n fJetVars('Jet2',subevent.allJets[1])\n\n self.tree.fill()\n","sub_path":"CMGTools/LEP3/python/analyzers/EMissTreeProducer.py","file_name":"EMissTreeProducer.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"319652207","text":"import sys, time\nfrom functools import partial\n\nimport numpy as np\n\nfrom PyQt5 import QtCore, QtWidgets, QtGui\n\n'''\n\tfrom matplotlib.backends.backend_qt5agg import (\n\t\tFigureCanvas, NavigationToolbar2QT as NavigationToolbar)\n'''\nfrom matplotlib.backends import backend_qt5agg\n\nimport matplotlib as mpl\n#from matplotlib.figure import Figure\n\n###\nfrom bAnalysis import bAnalysis\n#import pyabf # see: https://github.com/swharden/pyABF\n\nnow = time.time()\n\nabfFile = '/Users/cudmore/Sites/bAnalysis/data/19221021.abf'\nabfFile = '/Users/cudmore/Sites/bAnalysis/data/19114001.abf'\n#myabf = pyabf.ABF(abfFile)\nba = bAnalysis(file=abfFile)\n\nx = ba.abf.sweepX\ny = ba.abf.sweepY\n\nba.getDerivative(medianFilter=5) # derivative\nba.spikeDetect0() # analysis\n\nprint (\"abf load/anaysis time:\", time.time()-now, \"sec\")\n###\n\n###\n###\nimport struct\n\ndef eq(a, b):\n\t\"\"\"The great missing equivalence function: Guaranteed evaluation to a single bool value.\n\n\tThis function has some important differences from the == operator:\n\n\t1. Returns True if a IS b, even if a==b still evaluates to False, such as with nan values.\n\t2. Tests for equivalence using ==, but silently ignores some common exceptions that can occur\n\t (AtrtibuteError, ValueError).\n\t3. When comparing arrays, returns False if the array shapes are not the same.\n\t4. When comparing arrays of the same shape, returns True only if all elements are equal (whereas\n\t the == operator would return a boolean array).\n\t\"\"\"\n\tif a is b:\n\t\treturn True\n\n\t# Avoid comparing large arrays against scalars; this is expensive and we know it should return False.\n\taIsArr = isinstance(a, (np.ndarray, MetaArray))\n\tbIsArr = isinstance(b, (np.ndarray, MetaArray))\n\tif (aIsArr or bIsArr) and type(a) != type(b):\n\t\treturn False\n\n\t# If both inputs are arrays, we can speeed up comparison if shapes / dtypes don't match\n\t# NOTE: arrays of dissimilar type should be considered unequal even if they are numerically\n\t# equal because they may behave differently when computed on.\n\tif aIsArr and bIsArr and (a.shape != b.shape or a.dtype != b.dtype):\n\t\treturn False\n\n\t# Test for equivalence.\n\t# If the test raises a recognized exception, then return Falase\n\ttry:\n\t\ttry:\n\t\t\t# Sometimes running catch_warnings(module=np) generates AttributeError ???\n\t\t\tcatcher = warnings.catch_warnings(module=np) # ignore numpy futurewarning (numpy v. 1.10)\n\t\t\tcatcher.__enter__()\n\t\texcept Exception:\n\t\t\tcatcher = None\n\t\te = a==b\n\texcept (ValueError, AttributeError):\n\t\treturn False\n\texcept:\n\t\tprint('failed to evaluate equivalence for:')\n\t\tprint(\" a:\", str(type(a)), str(a))\n\t\tprint(\" b:\", str(type(b)), str(b))\n\t\traise\n\tfinally:\n\t\tif catcher is not None:\n\t\t\tcatcher.__exit__(None, None, None)\n\n\tt = type(e)\n\tif t is bool:\n\t\treturn e\n\telif t is np.bool_:\n\t\treturn bool(e)\n\telif isinstance(e, np.ndarray) or (hasattr(e, 'implements') and e.implements('MetaArray')):\n\t\ttry: ## disaster: if a is an empty array and b is not, then e.all() is True\n\t\t\tif a.shape != b.shape:\n\t\t\t\treturn False\n\t\texcept:\n\t\t\treturn False\n\t\tif (hasattr(e, 'implements') and e.implements('MetaArray')):\n\t\t\treturn e.asarray().all()\n\t\telse:\n\t\t\treturn e.all()\n\telse:\n\t\traise Exception(\"== operator returned type %s\" % str(type(e)))\n\ndef arrayToQPath(x, y, connect='all'):\n\t\"\"\"Convert an array of x,y coordinats to QPainterPath as efficiently as possible.\n\tThe *connect* argument may be 'all', indicating that each point should be\n\tconnected to the next; 'pairs', indicating that each pair of points\n\tshould be connected, or an array of int32 values (0 or 1) indicating\n\tconnections.\n\t\"\"\"\n\n\t## Create all vertices in path. The method used below creates a binary format so that all\n\t## vertices can be read in at once. This binary format may change in future versions of Qt,\n\t## so the original (slower) method is left here for emergencies:\n\t\t#path.moveTo(x[0], y[0])\n\t\t#if connect == 'all':\n\t\t\t#for i in range(1, y.shape[0]):\n\t\t\t\t#path.lineTo(x[i], y[i])\n\t\t#elif connect == 'pairs':\n\t\t\t#for i in range(1, y.shape[0]):\n\t\t\t\t#if i%2 == 0:\n\t\t\t\t\t#path.lineTo(x[i], y[i])\n\t\t\t\t#else:\n\t\t\t\t\t#path.moveTo(x[i], y[i])\n\t\t#elif isinstance(connect, np.ndarray):\n\t\t\t#for i in range(1, y.shape[0]):\n\t\t\t\t#if connect[i] == 1:\n\t\t\t\t\t#path.lineTo(x[i], y[i])\n\t\t\t\t#else:\n\t\t\t\t\t#path.moveTo(x[i], y[i])\n\t\t#else:\n\t\t\t#raise Exception('connect argument must be \"all\", \"pairs\", or array')\n\n\t## Speed this up using >> operator\n\t## Format is:\n\t##\tnumVerts(i4) 0(i4)\n\t##\tx(f8) y(f8) 0(i4)\t<-- 0 means this vertex does not connect\n\t##\tx(f8) y(f8) 1(i4)\t<-- 1 means this vertex connects to the previous vertex\n\t##\t...\n\t##\t0(i4)\n\t##\n\t## All values are big endian--pack using struct.pack('>d') or struct.pack('>i')\n\n\tpath = QtGui.QPainterPath()\n\n\t#profiler = debug.Profiler()\n\tn = x.shape[0]\n\t# create empty array, pad with extra space on either end\n\tarr = np.empty(n+2, dtype=[('x', '>f8'), ('y', '>f8'), ('c', '>i4')])\n\t# write first two integers\n\t#profiler('allocate empty')\n\tbyteview = arr.view(dtype=np.ubyte)\n\tbyteview[:12] = 0\n\tbyteview.data[12:20] = struct.pack('>ii', n, 0)\n\t#profiler('pack header')\n\t# Fill array with vertex values\n\tarr[1:-1]['x'] = x\n\tarr[1:-1]['y'] = y\n\n\t# decide which points are connected by lines\n\tif eq(connect, 'all'):\n\t\tarr[1:-1]['c'] = 1\n\telif eq(connect, 'pairs'):\n\t\tarr[1:-1]['c'][::2] = 1\n\t\tarr[1:-1]['c'][1::2] = 0\n\telif eq(connect, 'finite'):\n\t\tarr[1:-1]['c'] = np.isfinite(x) & np.isfinite(y)\n\telif isinstance(connect, np.ndarray):\n\t\tarr[1:-1]['c'] = connect\n\telse:\n\t\traise Exception('connect argument must be \"all\", \"pairs\", \"finite\", or array')\n\n\t#profiler('fill array')\n\t# write last 0\n\tlastInd = 20*(n+1)\n\tbyteview.data[lastInd:lastInd+4] = struct.pack('>i', 0)\n\t#profiler('footer')\n\t# create datastream object and stream into path\n\n\t## Avoiding this method because QByteArray(str) leaks memory in PySide\n\t#buf = QtCore.QByteArray(arr.data[12:lastInd+4]) # I think one unnecessary copy happens here\n\n\tpath.strn = byteview.data[12:lastInd+4] # make sure data doesn't run away\n\ttry:\n\t\tbuf = QtCore.QByteArray.fromRawData(path.strn)\n\texcept TypeError:\n\t\tbuf = QtCore.QByteArray(bytes(path.strn))\n\t#profiler('create buffer')\n\tds = QtCore.QDataStream(buf)\n\n\tds >> path\n\t#profiler('load')\n\n\treturn path\n###\n###\n\nclass MultiLine(QtWidgets.QGraphicsPathItem):\n\tdef __init__(self, x, y, parent=None):\n\t\t\"\"\"x and y are 2D arrays of shape (Nplots, Nsamples)\"\"\"\n\t\t#super(QtWidgets.QGraphicsPathItem, self).__init__(parent)\n\n\t\t# abb removed\n\t\t#connect = np.ones(x.shape, dtype=bool)\n\t\t#connect[:,-1] = 0 # don't draw the segment between each trace\n\t\t#self.path = pg.arrayToQPath(x.flatten(), y.flatten(), connect.flatten())\n\n\t\tself.path = arrayToQPath(x.flatten(), y.flatten(), connect='all')\n\t\tQtWidgets.QGraphicsPathItem.__init__(self, self.path)\n\t\t#self.setPen(pg.mkPen('w'))\n\n\t'''\n\tdef shape(self): # override because QGraphicsPathItem.shape is too expensive.\n\t\tprint('MultiLine.shape() returning:', QtGui.QGraphicsItem.shape(self))\n\t\treturn QtGui.QGraphicsItem.shape(self)\n\t'''\n\n\t'''\n\tdef boundingRect(self):\n\t\t# was this\n\t\tprint('MultiLine.boundingRect() returning:', self.path.boundingRect())\n\t\treturn self.path.boundingRect()\n\n\t\t# this does nothing\n\t\t#PyQt5.QtCore.QRectF(0.0, -68.359375, 59.999950000000005, 120.849609375)\n\t\t# x, y, w, h ????\n\t\t#theRet = QtCore.QRectF(0, 0, 0, 0)\n\t\t#return theRet\n\t'''\n\nclass myQGraphicsView(QtWidgets.QGraphicsView):\n\t\"\"\"\n\tMain canvas widget\n\t\"\"\"\n\tdef __init__(self, plotThis='Vm', parent=None):\n\t\t#print('myQGraphicsView().__init__()')\n\t\tsuper(QtWidgets.QGraphicsView, self).__init__(parent)\n\n\t\tself.setBackgroundBrush(QtCore.Qt.darkGray)\n\n\t\tself.myScene = QtWidgets.QGraphicsScene()\n\n\t\tif plotThis == 'vm':\n\t\t\tlines = MultiLine(x, ba.abf.sweepY)\n\t\telif plotThis == 'dvdt':\n\t\t\tlines = MultiLine(x, ba.filteredDeriv)\n\t\telse:\n\t\t\tprint('error: myQGraphicsView() expecting plotThis in (\"vm\", \"dvdt\")')\n\n\t\tself.myScene.addItem(lines)\n\n\t\tself.setScene(self.myScene)\n\nclass MainWindow(QtWidgets.QMainWindow):\n\tdef __init__(self, parent=None):\n\t\tsuper(MainWindow, self).__init__(parent)\n\n\t\tself.buildUI()\n\n\tdef buildUI(self):\n\t\tself.centralwidget = QtWidgets.QWidget(self)\n\t\tself.centralwidget.setObjectName(\"centralwidget\")\n\n\t\tself.myQVBoxLayout = QtWidgets.QVBoxLayout(self.centralwidget)\n\n\t\t#\n\t\t# toolbar\n\t\tself.toolbarWidget = myToolbarWidget()\n\t\tself.addToolBar(QtCore.Qt.LeftToolBarArea, self.toolbarWidget)\n\n\t\t#\n\t\t# tree view of files\n\t\tself.myTableWidget = QtWidgets.QTreeWidget()\n\t\t# append to layout\n\t\tself.myQVBoxLayout.addWidget(self.myTableWidget)\n\n\t\t#\n\t\t# dv/dt plot\n\t\tself.myGraphicsView = myQGraphicsView(plotThis='dvdt') #myQGraphicsView(self.centralwidget)\n\t\tself.myQVBoxLayout.addWidget(self.myGraphicsView)\n\n\t\t#\n\t\t# vm plot\n\t\tself.myGraphicsView = myQGraphicsView(plotThis='vm') #myQGraphicsView(self.centralwidget)\n\t\tself.myQVBoxLayout.addWidget(self.myGraphicsView)\n\n\n\t\t#\n\t\t# stat plot\n\t\tstatic_canvas = backend_qt5agg.FigureCanvas(mpl.figure.Figure(figsize=(5, 3)))\n\t\tself.myQVBoxLayout.addWidget(static_canvas)\n\n\t\t# i want the mpl toolbar in the mpl canvas or sublot\n\t\t# this is adding mpl toolbar to main window -->> not what I want\n\t\t#self.addToolBar(backend_qt5agg.NavigationToolbar2QT(static_canvas, self))\n\t\t# this kinda works as wanted, toolbar is inside mpl plot but it is FUCKING UGLY !!!!\n\t\tself.mplToolbar = backend_qt5agg.NavigationToolbar2QT(static_canvas, static_canvas)\n\n\t\tself._static_ax = static_canvas.figure.subplots()\n\t\tt = np.linspace(0, 10, 501)\n\t\tself._static_ax.plot(t, np.tan(t), \".\")\n\n\t\t#\n\t\t# leave here, critical\n\t\tself.setCentralWidget(self.centralwidget)\n\nclass myToolbarWidget(QtWidgets.QToolBar):\n\tdef __init__(self, parent=None):\n\t\tprint('myToolbarWidget.__init__')\n\t\tsuper(QtWidgets.QToolBar, self).__init__(parent)\n\n\t\tbuttonName = 'Save Canvas'\n\t\tbutton = QtWidgets.QPushButton(buttonName)\n\t\tbutton.setToolTip('Load a canvas from disk')\n\t\tbutton.clicked.connect(partial(self.on_button_click,buttonName))\n\t\tself.addWidget(button)\n\n\t@QtCore.pyqtSlot()\n\tdef on_button_click(self, name):\n\t\tprint('=== myToolbarWidget.on_button_click() name:', name)\n\nif __name__ == '__main__':\n\timport logging\n\timport traceback\n\n\ttry:\n\t\tapp = QtWidgets.QApplication(sys.argv)\n\t\tw = MainWindow()\n\t\tw.resize(640, 480)\n\t\tw.show()\n\t\t#sys.exit(app.exec_())\n\texcept Exception as e:\n\t\tprint(traceback.format_exc())\n\t\t#logging.error(traceback.format_exc())\n\t\tsys.exit(app.exec_())\n\t\traise\n\tfinally:\n\t\tsys.exit(app.exec_())\n","sub_path":"tkinter_app/bAnalysisApp/fastplot1.py","file_name":"fastplot1.py","file_ext":"py","file_size_in_byte":10368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"499732206","text":"from datetime import date\r\ntrabalhador = {}\r\ntrabalhador['Nome'] = input('Nome: ')\r\nano = int(input('Ano de Nascimento: '))\r\ntrabalhador['Idade'] = date.today().year - ano\r\ntrabalhador['CTPS'] = int(input('Carteira de Trabalho (0 se não tiver): '))\r\nif trabalhador['CTPS'] != 0:\r\n trabalhador['Contratação'] = int(input('Ano de Contratação: '))\r\n trabalhador['Salario'] = float(input('Salário: R$ '))\r\n trabalhador['Aposentadoria'] = (trabalhador['Contratação'] - ano) + 35\r\nprint('-=-' * 30)\r\nfor k, v in trabalhador.items():\r\n print(f'- {k} tem o valor {v}.')","sub_path":"Mundo 03/ex092.py","file_name":"ex092.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"201560308","text":"# -*- coding: utf-8 -*-\nimport re\n\nimport scrapy\n\nfrom guazi_scrapy_project.handle_mongo import mongo\n\nfrom guazi_scrapy_project.items import GuaziScrapyProjectItem\n\n\nclass GuaziSpider(scrapy.Spider):\n name = 'guazi'\n allowed_domains = ['guazi.com']\n # start_urls = ['http://guazi.com/']\n\n def start_requests(self):\n while True:\n task = mongo.get_task('guazi_task')\n if not task:\n break\n if '_id' in task:\n task.pop('_id')\n print(task['task_url'])\n if task['item_type'] == 'list_item':\n yield scrapy.Request(\n url=task['task_url'],\n callback=self.handle_car_item,\n method='GET',\n # headers=,\n # body=,\n meta=task,\n # cookies=,\n encoding='utf-8',\n # priority=,\n dont_filter=True,\n errback=self.handle_err,\n # flags=\n )\n # yield scrapy.FormRequest()\n elif task['item_type'] == 'car_info_item':\n yield scrapy.Request(\n url=task['task_url'],\n callback=self.handle_car_info,\n method='GET',\n # headers=,\n # body=,\n meta=task,\n # cookies=,\n encoding='utf-8',\n # priority=,\n dont_filter=True,\n errback=self.handle_err,\n # flags=\n )\n\n def parse(self, response):\n pass\n # print(response.text)\n\n\n def handle_err(self, failure):\n print(failure)\n mongo.save_task('guazi_task', failure.request.meta)\n\n\n def handle_car_item(self, response):\n if '中为您找到0辆好车' in response.text:\n return\n car_item_list = response.xpath(\"//ul[@class='carlist clearfix js-top']/li\")\n # print(car_item_list)\n for car_item in car_item_list:\n car_list_info = {}\n car_list_info['car_name'] = car_item.xpath(\"./a/h2/text()\").extract_first()\n car_list_info['car_url'] = 'https://www.guazi.com' + car_item.xpath(\"./a/@href\").extract_first()\n # print(car_list_info)\n car_list_info['item_type'] = 'car_info_item'\n yield scrapy.Request(url=car_list_info['car_url'], callback=self.handle_car_info, dont_filter=True, meta=car_list_info, errback=self.handle_err)\n\n if response.xpath(\"//ul[@class='pageLink clearfix']/li[last()]//span/text()\").extract_first() == '下一页':\n value_search = re.compile(\"https://www.guazi.com/(.*?)/(.*?)/o(\\d+)i7\")\n value = value_search.findall(response.url)[0]\n response.request.meta['task_url'] = 'https://www.guazi.com/%s/%s/o%si7' % (value[0], value[1], str(int(value[2])+1))\n yield scrapy.Request(url=response.request.meta['task_url'], callback=self.handle_car_item, meta=response.request.meta, dont_filter=True, errback=self.handle_err)\n\n\n def handle_car_info(self, response):\n # print(response.text)\n car_id_search = re.compile(r\"车源号:(.*?)\\s+\")\n car_info = GuaziScrapyProjectItem()\n car_info['car_id'] = car_id_search.search(response.text).group(1)\n car_info['car_name'] = response.request.meta['car_name']\n car_info['from_url'] = response.request.meta['car_url']\n car_info['car_price'] = response.xpath(\"//span[@class='price-num']/text()\").extract_first().strip()\n # car_info['license_time'] = response.xpath(\"//ul[@class='assort clearfix']/li[@class='one']/span/text()\").extract_first().strip()\n car_info['km_info'] = response.xpath(\"//ul[@class='assort clearfix']/li[@class='two']/span/text()\").extract_first().strip()\n car_info['license_location'] = response.xpath(\"//ul[@class='assort clearfix']/li[@class='three']/span/text()\").extract()[0].strip()\n # car_info['desplacement_info'] = response.xpath(\"//ul[@class='assort clearfix']/li[@class='three']/span/text()\").extract()[1].strip()\n car_info['transmission_case'] = response.xpath(\"//ul[@class='assort clearfix']/li[@class='last']/span/text()\").extract_first().strip()\n print(car_info)\n yield car_info","sub_path":"guazi_scrapy_project/guazi_scrapy_project/spiders/guazi.py","file_name":"guazi.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"404832870","text":"import logging\nimport Queue\n\nfrom dispatch import receiver\n\nfrom common import StoppableLoopThread\nfrom trie import rlp_hash, rlp_hash_hex\nimport signals\n\nlogger = logging.getLogger(__name__)\n\n\nclass ChainManager(StoppableLoopThread):\n\n \"\"\"\n Manages the chain and requests to it.\n \"\"\"\n\n def __init__(self):\n super(ChainManager, self).__init__()\n self.transactions = set()\n self.dummy_blockchain = dict() # hash > block\n self.request_queue = Queue.Queue()\n\n def configure(self, config):\n self.config = config\n\n def bootstrap_blockchain(self):\n # genesis block\n # http://etherchain.org/#/block/\n # ab6b9a5613970faa771b12d449b2e9bb925ab7a369f0a4b86b286e9d540099cf\n if len(self.dummy_blockchain):\n return\n genesis_H = 'ab6b9a5613970faa771b12d449b2e9bb925ab7a369f'\\\n '0a4b86b286e9d540099cf'.decode('hex')\n\n def loop_body(self):\n self.process_request_queue()\n self.mine()\n\n def mine(self):\n \"in the meanwhile mine a bit, not efficient though\"\n pass\n\n def process_request_queue(self):\n try:\n cmd, data = self.request_queue.get(block=True, timeout=0.1)\n except Queue.Empty:\n return\n\n logger.debug('%r received %s datalen:%d' %\n (self, cmd, len(data or [])))\n if cmd == \"add_blocks\":\n logger.debug(\"add_blocks in queue seen\")\n self.recv_blocks(data)\n elif cmd == \"add_transactions\":\n tx_list = data[0]\n for tx in tx_list:\n self.transactions.add(tx)\n elif cmd == \"request_blocks\":\n pass\n elif cmd == 'request_transactions':\n peer_id = data[0]\n signals.transactions_data_ready(self.transactions, peer_id)\n else:\n raise Exception('unknown command:%s' % cmd)\n\n def recv_blocks(self, blocks):\n new_blocks_H = set()\n # memorize\n for block in blocks:\n h = rlp_hash(block)\n logger.debug(\"recv_blocks: %r\" % rlp_hash_hex(block))\n if h not in self.dummy_blockchain:\n new_blocks_H.add(h)\n self.dummy_blockchain[h] = block\n # ask for children\n for h in new_blocks_H:\n logger.debug(\"recv_blocks: ask for child block %r\" %\n h.encode('hex'))\n signals.remote_chain_data_requested.send(\n sender=self, parents=[h], count=1)\n\n def add_transactions(self, transactions):\n logger.debug(\"add transactions %r\" % transactions)\n for tx in tx_list:\n self.transactions.add(tx)\n\n def get_transactions(self):\n logger.debug(\"get transactions\")\n return self.transactions\n\nchain_manager = ChainManager()\n\n\n@receiver(signals.config_ready)\ndef config_chainmanager(sender, **kwargs):\n chain_manager.configure(sender)\n\n\n@receiver(signals.new_transactions_received)\ndef new_transactions_received_handler(sender, transactions, **kwargs):\n chain_manager.add_transactions(transactions)\n\n\n@receiver(signals.transactions_data_requested)\ndef transactions_data_requested_handler(sender, **kwargs):\n transactions = chain_manager.get_transactions()\n\n\n@receiver(signals.blocks_data_requested)\ndef blocks_data_requested_handler(sender, request_data, **kwargs):\n pass\n\n\n@receiver(signals.new_blocks_received)\ndef new_blocks_received_handler(sender, blocks, **kwargs):\n logger.debug(\"received blocks: %r\" % ([rlp_hash_hex(b) for b in blocks]))\n chain_manager.recv_blocks(blocks)\n","sub_path":"pyethereum/chainmanager.py","file_name":"chainmanager.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"111409505","text":"def save_dictionary(path,data):\n print('saving catalog...')\n #open('u.item', encoding=\"utf-8\")\n import json\n with open(path,'w') as outfile:\n json.dump(data, fp=outfile)\n # save to file:\n print(' catalog saved')\n########################################################################################\n########################################################################################\n########################################################################################\n########################################################################################\n\ndef read_dictionary(path):\n\n import json\n # load from file:\n g = open(path, 'r')\n print('reading ...')\n\n try:\n data = json.load(g)\n # if the file is empty the ValueError will be thrown\n except ValueError:\n data = {}\n print('reading finished!')\n return(data)\n\n########################################################################################\n########################################################################################\n########################################################################################\n########################################################################################\nfrom datetime import datetime\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search\n\n\n\ndef get_all_ids_from_elasticsearh_as_list():\n from elasticsearch import Elasticsearch\n from elasticsearch_dsl import Search\n es = Elasticsearch()\n s = Search(using=es, index='four')\n\n s = s.fields([]) # only get ids, otherwise `fields` takes a list of field names\n ids = [h.meta.id for h in s.scan()]\n return(ids)\n\n\ndef get_and_save_all_inlinks_and_outlinks_elasticsearch():\n es = Elasticsearch()\n all_ids_list=get_all_ids_from_elasticsearh_as_list()\n inlinks_dict={}\n outlinks_dict={}\n all_nodes_dict={}\n number_of_out_links_dict={}\n all_parsed_nodes_dict={}\n all_nodes_dict={}\n index=0\n for url_id in all_ids_list:\n index=index+1\n print(str(index)+'-'+url_id)\n existing_data = es.get(index='four', doc_type='document', id=url_id,\n fields=['in_links', 'out_links'])\n inlinks = set((''.join(existing_data['fields']['in_links'])).split('\\t')).intersection(set(all_ids_list))\n # inlinks = [x for x in inlinks if x in all_ids_list]\n outlinks = set((''.join(existing_data['fields']['out_links'])).split('\\t')).intersection(set(all_ids_list))\n # outlinks= [x for x in outlinks if x in all_ids_list]\n\n\n n = len(inlinks)\n values_list = [True] * n\n inlink_urls = dict(zip(inlinks, values_list))\n inlinks_dict[url_id]=inlink_urls\n # all_nodes_dict.update(inlink_urls)\n\n\n\n m = len(outlinks)\n values_list = [True] * m\n outlinks_urls = dict(zip(outlinks, values_list))\n outlinks_dict[url_id] = outlinks_urls\n # all_nodes_dict.update(outlinks_urls)\n all_parsed_nodes_dict[url_id]=True\n\n number_of_out_links_dict[url_id]=len(outlinks)\n\n save_dictionary('/Users/mohsennabian/HW4/merge_inlinks_dict.txt', inlinks_dict)\n\n save_dictionary('/Users/mohsennabian/HW4/merge_number_of_out_links_dict.txt', number_of_out_links_dict)\n save_dictionary('/Users/mohsennabian/HW4/merge_outlinks_dict.txt', outlinks_dict)\n save_dictionary('/Users/mohsennabian/HW4/merge_all_parsed_nodes_dict.txt', all_parsed_nodes_dict)\n #save_dictionary('/Users/mohsennabian/HW4/merge_all_nodes_dict.txt', all_nodes_dict)\n\ndef outlink_from_inlinks_only(my_inlink_dict):\n merge_number_of_out_links_dict={}\n outlink_from_inlink_dict={}\n heads=my_inlink_dict.keys()\n for head in heads:\n for url in my_inlink_dict[head].keys():\n print('hi')\n if url not in outlink_from_inlink_dict:\n outlink_from_inlink_dict[url]={head:True}\n else: outlink_from_inlink_dict[url].update({head:True})\n save_dictionary('/Users/mohsennabian/HW4/merge_outlinks_dict.txt',outlink_from_inlink_dict)\n\n for url in outlink_from_inlink_dict.keys():\n merge_number_of_out_links_dict[url]=len(outlink_from_inlink_dict[url])\n save_dictionary('/Users/mohsennabian/HW4/merge_number_of_out_links_dict.txt', merge_number_of_out_links_dict)\n\n\n\ndef save_sink_node_file():\n number_of_outlinks_dict = read_dictionary('/Users/mohsennabian/HW4/merge_number_of_out_links_dict.txt')\n merge_all_parsed_nodes_dict=read_dictionary('/Users/mohsennabian/HW4/merge_all_parsed_nodes_dict.txt')\n aall=merge_all_parsed_nodes_dict.keys()\n sink_dict = {}\n for id in aall:\n if id not in number_of_outlinks_dict.keys():\n sink_dict.update({id: True})\n\n for id in number_of_outlinks_dict.keys():\n if number_of_outlinks_dict[id]==0:\n sink_dict.update({id:True})\n save_dictionary('/Users/mohsennabian/HW4/merge_sink_dict.txt', sink_dict)\n\n\n\ndef M(graph_dict,p): #M(p) is the set of pages that link to page p\n\n return(graph_dict[p].keys())\n\n\ndef L(number_of_outlinks_dict,q): #L(q) is the number of out-links from page q\n\n return(number_of_outlinks_dict[q])\n\n\n\n\ndef difference():\n global PR\n global new_PR\n N = len(new_PR)\n y = 0\n if N == 0 :\n return(999)\n\n for key in PR.keys():\n key = key.replace('\\n', '')\n y=abs(PR[key]-new_PR[key])+y\n return(y/N)\n\n\n\ndef compute_page_rank(graph_dict,all_parsed_nodes_dict,number_of_outlinks_dict,sink_dict):\n\n S = sink_dict.keys()\n P = all_parsed_nodes_dict.keys()\n N = len(P)\n print(N)\n d = 0.85\n global PR\n global new_PR\n delta=9999\n PR={}\n new_PR={}\n for p in P :\n PR[p]=1/N\n while delta>0.0000000001:\n print('hi')\n sinkPR = 0\n for p in S:\n p = p.replace('\\n', '')\n sinkPR=sinkPR+PR[p]\n for p in P:\n\n p=p.replace('\\n','')\n if p=='': continue\n new_PR[p]=(1-d)/N\n new_PR[p]=new_PR[p]+d*sinkPR/N\n for q in M(graph_dict,p):\n new_PR[p]=new_PR[p]+d*PR[q]/L(number_of_outlinks_dict,q)\n delta = difference()\n print(delta)\n for p in P :\n p = p.replace('\\n', '')\n\n PR[p] = new_PR[p]\n\n\n save_dictionary('/Users/mohsennabian/HW4/merged_PR.txt', PR)\n\n\ndef dictionary_into_2sorted_list_and_save(path_to_load,path_to_save):\n mydict=read_dictionary(path_to_load)\n myvalue=sorted(mydict.values(),reverse=True)\n mykey=sorted(mydict, key=mydict.__getitem__,reverse=True)\n g=open(path_to_save,'w')\n\n for i in range(0,len(mykey)):\n\n\n sentence = ((mykey[i]) + ' = ' + str(myvalue[i]) +'\\n').encode('utf8')\n\n\n # sentense = unicode(str(sentence), errors='ignore').encode(\"utf-8\")\n try:\n g.write(sentence)\n except:\n print('bad')\n\n\n\n\nPR = {}\nnew_PR = {}\n\n# get_and_save_all_inlinks_and_outlinks_elasticsearch()\n\n#\nall_parsed_nodes_dict = read_dictionary('/Users/mohsennabian/HW4/merge_all_parsed_nodes_dict.txt')\ngraph_dict = read_dictionary('/Users/mohsennabian/HW4/merge_inlinks_dict.txt') # graph_dict={head1={tail1:true,tail2:true}}\n\n# outlink_from_inlinks_only(graph_dict)\n# save_sink_node_file()\n\n\nnumber_of_outlinks_dict = read_dictionary('/Users/mohsennabian/HW4/merge_number_of_out_links_dict.txt')\nsink_dict = read_dictionary('/Users/mohsennabian/HW4/merge_sink_dict.txt')\n#\n#\n#\n#\n#\ncompute_page_rank(graph_dict, all_parsed_nodes_dict, number_of_outlinks_dict, sink_dict)\n#\nPR = read_dictionary('/Users/mohsennabian/HW4/merged_PR.txt')\n\nimport operator\nsorted_PR = sorted(PR.items(), key=operator.itemgetter(1), reverse=True)\nprint(sorted_PR[0:100])\n\n\n\n\npath_to_load='/Users/mohsennabian/HW4/merged_PR.txt'\npath_to_save='/Users/mohsennabian/HW4/merged_PR_sorted.txt'\ndictionary_into_2sorted_list_and_save(path_to_load, path_to_save)\n\n","sub_path":"Submissions/HW4/es_tamrin.py","file_name":"es_tamrin.py","file_ext":"py","file_size_in_byte":7936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"500876694","text":"from django.conf.urls import patterns, include, url\nfrom Scheduler.forms import SchedulerItemsForm\nfrom Indigo7.views import SimpleViewListView, SimpleViewDetailView, SimpleViewCreateView, SimpleViewDeleteView, SimpleViewUpdateView\nfrom Scheduler.models import Scheduler, SchedulerItems\nfrom Scheduler.views import SchedulerDetail, SchedulerDetailCreateView, SchedulerDetailUpdateView, SchedulerDetailDeleteView\n\n\nurlpatterns = patterns('Scheduler.views', \n url(r'^(?P\\d+)/$',\n SchedulerDetail.as_view(model=Scheduler, \n template_name = \"Scheduler/scheduler_detail.html\",\n ), \n name='scheduler_detail'), \n \n url(r'^$',\n SimpleViewListView.as_view(model=SchedulerItems), \n name='scheduleitems_list'),\n \n url(r'^create/(?P\\d+)$',\n SchedulerDetailCreateView.as_view(model=SchedulerItems, \n form_class=SchedulerItemsForm, \n success_url='scheduleddays_list'), \n name='create_scheduleritems'), \n \n url(r'^create/$',\n SchedulerDetailCreateView.as_view(model=SchedulerItems, \n form_class=SchedulerItemsForm, \n success_url='scheduleddays_list'), \n name='create_scheduleritems'), \n \n url(r'^(?P\\d+)/update/(?P\\d+)/$',\n SchedulerDetailUpdateView.as_view(model=SchedulerItems, \n form_class=SchedulerItemsForm, ), \n name='update_scheduleritems'), \n\n url(r'^(?P\\d+)/delete/(?P\\d+)/$',\n SchedulerDetailDeleteView.as_view(model=SchedulerItems, ), \n name='delete_scheduleritems'), \n)","sub_path":"Scheduler/urlconf/scheduleritems.py","file_name":"scheduleritems.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"572821983","text":"# -*- coding: utf-8 -*-\n'''\nVarious APT Utilities\n@author: Joel Leclerc (MiJyn) \n'''\n\nimport apt\n\n\n# Version Comparison Operations\nlt = 0x00\nle = 0x01\neq = 0x02\nge = 0x03\ngt = 0x04\n\n\n# OpProgress implementation\nclass OpProgress(apt.progress.base.OpProgress):\n def __init__(self, update, finish):\n apt.progress.base.OpProgress.__init__(self)\n self.old_op = \"\"\n self.updatefunc = update\n self.finishfunc = finish\n\n def update(self, percent=None):\n apt.progress.base.OpProgress.update(self, percent)\n op = self.op\n if self.major_change and self.old_op:\n op = self.old_op\n self.updatefunc(op, percent)\n self.old_op = self.op\n\n def done(self):\n apt.progress.base.OpProgress.done(self)\n if self.old_op:\n self.finishfunc(self.old_op)\n self.old_op = \"\"\n\n\n# Initializes APT\ndef initApt():\n apt.apt_pkg.init()\n\n\n# Returns an APT cache\n# Note that this can take around 2-30 seconds\ndef getCache(progress=None):\n if progress:\n return apt.apt_pkg.Cache(progress)\n else:\n return apt.apt_pkg.Cache()\n\n\n# Returns an APT DepCache\n# Used for package managing\ndef getDepCache(cache):\n return apt.apt_pkg.DepCache(cache)\n\n\n# Returns a package in an APT cache\ndef getPkg(pkg, cache):\n return cache[pkg]\n\n\n# Returns the package version\ndef getPkgVersion(pkg):\n return pkg.installed.version\n\n\n# Returns an AcquireProgress\ndef getAcquireProgress():\n return apt.progress.base.AcquireProgress()\n\n\n# Returns an InstallProgress\ndef getInstallProgress():\n return apt.progress.base.InstallProgress()\n\n\n# Compares versions\ndef compVersions(v1, v2, operation):\n comp = apt.VersionCompare(v1, v2)\n if operation == lt:\n if comp < 0:\n return True\n else:\n return False\n elif operation == le:\n if comp <= 0:\n return True\n else:\n return False\n elif operation == eq:\n if comp == 0:\n return True\n else:\n return False\n elif operation == ge:\n if comp >= 0:\n return True\n else:\n return False\n elif operation == gt:\n if comp > 0:\n return True\n else:\n return False\n\n\n# Helper function for checking if a package is installed within a depcache\ndef _depCacheInstalled(package, depcache):\n if (depcache.is_auto_installed(package) or depcache.is_garbage(package) or\n depcache.is_inst_broken(package) or depcache.is_now_broken(package) or\n depcache.is_upgradeable(package)):\n return True\n else:\n return False\n\n\n# Installs a package\ndef instPkg(package, depcache, reinstall = True):\n if _depCacheInstalled(package, depcache):\n if reinstall:\n depcache.set_reinstall(package)\n return True\n else:\n return False\n else:\n depcache.mark_install(package, True, True)\n return True\n\n\n# Removes a package\ndef remPkg(package, depcache, purge = True):\n if _depCacheInstalled(package, depcache):\n depcache.mark_delete(package, purge)\n return True\n else:\n return False\n\n\n# Commits the changes\ndef commitChanges(depcache, ap, ip):\n if depcache.inst_count > 0 or depcache.del_count > 0:\n depcache.commit(ap, ip)\n return True\n else:\n return False\n","sub_path":"src/relinux/aptutil.py","file_name":"aptutil.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"318228190","text":"import os\nfrom IPython.display import display, HTML\nimport bokeh.plotting as bp\n\n\ndef save_bokeh_plot(plot, title=\"\", filename=None, basedir=\"plots\"):\n from bokeh.embed import file_html\n from bokeh.resources import CDN\n import uuid\n \n if filename is None:\n # Generate random hex string\n name = uuid.uuid4().hex[:6] + \".html\"\n filename = os.path.join(basedir, name)\n\n savedir = os.path.dirname(filename)\n if not os.path.isdir(savedir):\n os.makedirs(savedir)\n \n html = file_html(plot, CDN, title)\n with open(filename, 'w') as fd:\n fd.write(html)\n return filename\n\ndef plot_wv(Wv, vocab, num_words=1000, title=\"Word Vectors\", \n\t word_colors=None, word_sizes=None,\n\t inline=True, filename=None, **text_kw):\n \"\"\"Make an interactive plot of the (first two components) \n of the word vectors.\"\"\"\n top_counts = vocab.unigram_counts.most_common(num_words)\n selected_ids = vocab.words_to_ids(w for w,c in top_counts)\n selected_words = vocab.ids_to_words(selected_ids)\n\n px = Wv[selected_ids, 0]\n py = Wv[selected_ids, 1]\n \n p = bp.figure(title=\"Word Vectors\", \n\t\ttools=\"reset,pan,wheel_zoom,box_zoom\", \n\t\tactive_scroll=\"wheel_zoom\")\n text_kwargs = dict(text_baseline='middle',\n\t\t text_align='center')\n if word_colors is not None:\n text_kwargs['text_color'] = [word_colors[w] for w in selected_words]\n if word_sizes is not None:\n text_kwargs['text_font_size'] = [word_sizes[w] for w in selected_words]\n text_kwargs.update(text_kw) # override anything\n p.text(px, py, text=selected_words, **text_kwargs)\n \n if inline:\n bp.show(p)\n else:\n p.plot_width = 1200\n p.plot_height = 900\n filename = save_bokeh_plot(p, title=title, filename=filename)\n link_text = \"View plot \\\"%s\\\" in a new tab\" % filename\n display(HTML(\"{link_text}\".format(**locals())))\n","sub_path":"week3/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"179778138","text":"from flask import Flask, jsonify\nfrom flask import render_template\nfrom flask import request\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n\napp = Flask(__name__)\n\ndf = pd.read_csv(\"student.csv\")\ndf_dum = pd.get_dummies(df)\ndf['note_moyenne'] = ((df['G1'] + df['G2'] + df['G3'])/3).round(2)\ndf['consommation'] = ((df['Dalc'] + df['Walc'])).round(2)\n\n# Home page route\n@app.route('/')\ndef hello_world():\n\tnb_student = len(df)\n\tages = show_ages()\n\tsex = show_sex()\n\tabsenceage = show_absences_by_age()\n\thigher = show_pourcent_higher()\n\tabsences = show_absences()\n\tconso = show_conso()\n\tresult_school = show_school_results()\n\talcool_out = show_alcool_out()\n\tabsences_conso = show_absences_conso()\n\tnb_absences = show_nb_absences()\n\n\treturn render_template('home.html', ages=ages, nb_student=nb_student, sex=sex, absenceage=absenceage, higher=higher, absences=absences, conso=conso, result_school=result_school, alcool_out=alcool_out, absences_conso=absences_conso, nb_absences=nb_absences)\n\n# Show the form route\n@app.route('/show/test')\ndef show_test():\n\treturn render_template('test.html')\n\n# Process the form and generate the results\n@app.route('/trait/test', methods=[\"POST\"])\ndef trait_test():\n prenom = request.form['prenom']\n sex = request.form['sex']\n age = request.form['age']\n\n #For the first informations of user (percentage, etc...)\n percentage_age = len(df.loc[df['age'] == int(age) ]) / len(df) * 100\n df_age_sex = df.loc[df['age'] == int(age)]\n percentage_age_sex = len(df_age_sex.loc[df_age_sex['sex'] == sex]) / len(df_age_sex) * 100\n\n df_form_sex = getDataframeToSex(sex)\n df_form = getDataframeToAge(df_form_sex, age)\n\n\t# Get the data for generate the graphic about family size of student. Data user and data average\n famsize = request.form['famsize']\n df_famsize = getDataframeToFamsize(df_form, famsize)\n famsize_form = getAverageConsumption(df_famsize)\n famsize_to_compare = getAverageConsumptionToAgeWithFamsize(df, sex, famsize)\n\n\t# Get the data for generate the graphic about the parent status of student. Data user and data average\n pstatus = request.form['pstatus']\n df_pstatus = getDataframeToPstatus(df_form, pstatus)\n pstatus_form = getAverageConsumption(df_pstatus)\n pstatus_to_compare_m = getAverageConsumptionToAge(df, 'M', pstatus)\n pstatus_to_compare_f = getAverageConsumptionToAge(df, 'F', pstatus)\n\n\t# The next data to process\n activities = request.form['activities']\n internet = request.form['internet']\n Dalc = request.form['Dalc']\n Walc = request.form['Walc']\n\n\t# Send the datas to the template\n return render_template('result_test.html', prenom=prenom, sex=sex, age=age, percentage_age=percentage_age, percentage_age_sex=percentage_age_sex, famsize=famsize, \n pstatus=pstatus, Dalc=Dalc, Walc=Walc,df_form=df_form, famsize_form=famsize_form, famsize_to_compare=famsize_to_compare, \n pstatus_form=pstatus_form, pstatus_to_compare_m=pstatus_to_compare_m, pstatus_to_compare_f=pstatus_to_compare_f)\n\n#########################\n# Functions to the form #\n#########################\n\n# Get the average consumption alcohol for one week complete ( week and week-end ) \ndef getAverageConsumption(df):\n return ((df['Walc'] + df['Dalc'])/2).mean()\n\n# Get the average consumption alcohol for each age about the size of family\ndef getAverageConsumptionToAgeWithFamsize(df, sex, famsize):\n average_alcohol_age = list()\n\n df_sex = df.loc[df['sex'] == sex]\n\n for i in range(15,23):\n df_age = df_sex.loc[df_sex['age'] == i ]\n df_famsize = getDataframeToFamsize(df_age, famsize)\n average = getAverageConsumption(df_famsize)\n if math.isnan(average) :\n average = 0\n\n average_alcohol_age.append(average)\n\n return average_alcohol_age\n\n# Get the average consumption alcohol for each age\ndef getAverageConsumptionToAge(df, sex, pstatus):\n average_alcohol_age = list()\n\n df_sex = df.loc[df['sex'] == sex]\n\n for i in range(15,23):\n df_age = df_sex.loc[df_sex['age'] == i ]\n df_pstatus = getDataframeToPstatus(df_age, pstatus)\n average = getAverageConsumption(df_pstatus)\n if math.isnan(average) :\n average = 0\n\n average_alcohol_age.append(average)\n\n return average_alcohol_age\n\n# Get the dataFrame with the students according to the size family\ndef getDataframeToFamsize(df, famsize):\n df = df.loc[df['famsize'] == famsize]\n return df\n\n# Get the dataFrame with the students according to the parent status\ndef getDataframeToPstatus(df, pstatus):\n df = df.loc[df['Pstatus'] == pstatus]\n return df\n\n# Get the dataFrame with the students according to the sex\ndef getDataframeToSex(sex):\n df = pd.read_csv(\"student.csv\")\n df_sex = df.loc[df['sex'] == sex]\n return df_sex\n\n# Get the dataFrame with the students according to the age\ndef getDataframeToAge(df, age):\n if type(age) is int :\n df_age = df.loc[df['age'] == age]\n else:\n df_age = df.loc[df['age'] == int(age)]\n return df_age\n\n\n###################################\n# Functions to graphics home page #\n###################################\n\ndef show_ages():\n\tages = list(df['age'].value_counts(normalize=True).round(4) * 100)\n\treturn ages\n\ndef show_sex():\n\tres_list = list()\n\tres_list.append(df['sex'].value_counts()['F'])\n\tres_list.append(df['sex'].value_counts()['M'])\n\treturn res_list\n\ndef show_absences_by_age():\n\tdf_absences_by_age = df.groupby(['age']).mean()\n\tabsences_by_age = round(df_absences_by_age['absences'], 1)\n\tlist_absences_by_age = list(absences_by_age)\n\treturn list_absences_by_age\n\ndef show_absences():\n\tdf_romantic = df_dum.loc[(df_dum['romantic_yes'] == 1)]\n\tdf_romantic_no = df_dum.loc[(df_dum['romantic_no'] == 1)]\n\tabsences_romantic = df_romantic['absences'].median()\n\tabsences_noromantic = df_romantic_no['absences'].median()\n\tabsences_list = list()\n\tabsences_list.append(absences_romantic)\n\tabsences_list.append(absences_noromantic)\n\treturn absences_list\n\ndef show_pourcent_higher():\n\tdf_higher_yes = df_dum.loc[(df_dum['higher_yes'] == 1)]\n\tpercent_higher_yes = 100 * len(df_higher_yes) / len(df)\n\tpercent_higher = round(percent_higher_yes, 1)\n\treturn percent_higher\n\ndef show_conso():\n\tdf_conso_by_age = df.groupby(['age']).mean()\n\tconso_by_age = round(df_conso_by_age['consommation'], 1)\n\tlist_conso = list(conso_by_age)\n\treturn list_conso\n\n\ndef show_school_results():\n\tdf = pd.read_csv(\"student.csv\")\n\n\tnote_moyenne = ((df['G1'] + df['G2'] + df['G3'])/3).round(2)\n\tdf['note_moyenne'] = note_moyenne\n\n\tdf_gb = df.groupby([\"Walc\"])[['note_moyenne']].mean()\n\n\tres_list = list()\n\tfor res in df_gb['note_moyenne']:\n\t\tres_list.append(res)\n\n\treturn res_list\n\n\ndef show_alcool_out():\n\tdf_gb = df.groupby(['goout'])[[\"Dalc\", \"Walc\"]].mean()\n\n\tres_list = list()\n\tfor res in df_gb['Dalc']:\n\t\tres_list.append(res)\n\n\t# for res in df_gb['Walc']:\n\t# \tres_list.append(res)\n\n\treturn res_list\n\n\ndef show_absences_conso():\n\tdf_gb = df.groupby(['absences'])[[\"Dalc\"]].mean()\n\n\tres_list = list()\n\tfor res in df_gb['Dalc']:\n\t\tres_list.append(res)\n\n\treturn res_list\n\ndef show_nb_absences():\n\tdf_gb = df.groupby(['absences']).mean()\n\n\tres_list = list()\n\tfor res in df_gb.index:\n\t\tres_list.append(res)\n\n\treturn res_list\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"177822712","text":"import os\nfrom datetime import datetime\nimport pprint as pp\nimport shutil\n\nthisdir = os.path.dirname(os.path.abspath(__file__)) + \"\\\\\"\n\ndef make_list_of_ext_paths(search_here, ext):\n outlist = []\n for root, _, files in os.walk(search_here, topdown=False):\n for name in files:\n filepath = os.path.join(root, name)\n if filepath.endswith(ext):\n outlist.append(filepath)\n return outlist\n\ndef copy_filepaths_here(copy_here, filepath_list):\n filepath_list = [[x, \"_\".join(x.split(\"\\\\\")[-2:])] for x in filepath_list]\n #sample1 = filepath_list[0]\n #pp.pprint(sample1)\n if not os.path.exists(copy_here):\n os.makedirs(copy_here)\n for filepath in filepath_list:\n shutil.copyfile(filepath[0], os.path.join(copy_here, filepath[1]))\n\nif __name__ == \"__main__\":\n start_time = datetime.now()\n pdflist = make_list_of_ext_paths(r\"D:\\Git\\UVA_MSDS_Content\\STAT_6021_Linear_Models\", \".pdf\")\n copy_filepaths_here(r\"D:\\Git\\UVA_MSDS_Content\\STAT_6021_Linear_Models\\PDFs\", pdflist)\n #pp.pprint(pdflist)\n print(\"--- %s seconds ---\" % (datetime.now() - start_time))","sub_path":"Collect_PDFs.py","file_name":"Collect_PDFs.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"104948228","text":"# ...---... -- -.-- -. .- -- . .. ... -.-- ..- .-. .. -.--\n#Morse decoder\n#Объявляем словарь - соответствие символов коду Морзе\nmorse_dict = {\\\n \"A\": \".-\",\n \"B\": \"-...\",\n \"C\": \"-.-.\",\n \"D\": \"-..\",\n \"E\": \".\",\n \"F\": \"..-.\",\n \"G\": \"--.\",\n \"H\": \"....\",\n \"I\": \"..\",\n \"J\": \".---\",\n \"K\": \"-.-\",\n \"L\": \".-..\",\n \"M\": \"--\",\n \"N\": \"-.\",\n \"O\": \"---\",\n \"P\": \".--.\",\n \"Q\": \"--.-\",\n \"R\": \".-.\",\n \"S\": \"...\",\n \"T\": \"-\",\n \"U\": \"..-\",\n \"V\": \"...-\",\n \"W\": \".--\",\n \"X\": \"-..-\",\n \"Y\": \"-.--\",\n \"Z\": \"--..\",\n }\n\n#Разбиваем код на слова, после удаления пробельных символов в начале и конце\nmorse = (input(\"Введите сообщение в коде Морзе:\\n\")).strip()\nmorse_list = morse.split(\" \")\n\n#Генерируем двумерный списоп - разбиваем слова на символы\nmorse_letters = [each.split() for each in morse_list]\n#print(morse_letters)\n\n#Фу��кция, которая ставит в соответсвие символу в коде Морзе символ в Латинице\ndef morse_decode(dictionary, lst):\n decoded_morse = []\n for each in lst:\n print(each)\n for key, value in dictionary.items():\n if value == each:\n decoded_morse.append(key)\n return(decoded_morse)\n\n#Применяем функцию на элементах массива с символами\nmorse_list[:] = [morse_decode(morse_dict, each) for each in morse_letters]\n#Соединяем символы в слова\nmorse_list[:] = [\"\".join(each) for each in morse_list]\n#Соединяем слова в предложения\nanswear = \" \".join(morse_list)\nprint(answear)\n","sub_path":"homework8/homework8_2.py","file_name":"homework8_2.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"111003473","text":"import pytest\nfrom .utils import git_repo\nimport os\nimport glob\nimport sys\nfrom wandb import docker\n\n\n@pytest.fixture\ndef auth_config(mocker):\n mocker.patch('wandb.docker.auth_config.resolve_authconfig',\n lambda reg: {\"Username\": \"test\", \"Password\": \"test\"})\n\n\n@pytest.fixture\ndef auth_config_funky(mocker):\n mocker.patch('wandb.docker.auth_config.resolve_authconfig',\n lambda reg: {\"username\": \"test\"})\n\n\ndef test_docker_registry_custom(request_mocker, auth_config):\n auth_mock = request_mocker.register_uri('GET', \"https://gcr.io/v2/\", headers={\"Www-Authenticate\": 'Bearer realm=\"https://gcr.io/token\",service=\"gcr.io\",scope=\"repository:foo/bar:pull\"'},\n content=b'{}', status_code=401)\n token_mock = request_mocker.register_uri(\n 'GET', \"https://gcr.io/token\", content=b'{\"token\": \"test\"}')\n mani_mock = request_mocker.register_uri(\n 'HEAD', \"https://gcr.io/v2/foo/bar/manifests/rad\", headers={\"Docker-Content-Digest\": \"sha256:sickdigest\"})\n digest = docker.image_id_from_registry(\"gcr.io/foo/bar:rad\")\n assert digest == \"gcr.io/foo/bar@sha256:sickdigest\"\n\n\ndef test_registry_fucked(request_mocker, auth_config):\n auth_mock = request_mocker.register_uri(\n 'GET', \"https://crap.io/v2/\", content=b'{}', status_code=404)\n mani_mock = request_mocker.register_uri(\n 'HEAD', \"https://crap.io/v2/foo/bar/manifests/rad\", status_code=404)\n digest = docker.image_id_from_registry(\"crap.io/foo/bar:rad\")\n assert digest == None\n\n\ndef test_docker_registry_hub(request_mocker, auth_config_funky):\n request_mocker.register_uri('GET', \"https://index.docker.io/v2/\", headers={\"Www-Authenticate\": 'Bearer realm=\"https://auth.docker.io/token\",service=\"registry.docker.io\",scope=\"repository:samalba/my-app:pull,push'},\n content=b'{}', status_code=401)\n token_mock = request_mocker.register_uri(\n 'GET', \"https://auth.docker.io/token\", content=b'{\"token\": \"test\"}')\n mani_mock = request_mocker.register_uri(\n 'HEAD', \"https://registry-1.docker.io/v2/foo/bar/manifests/rad\", headers={\"Docker-Content-Digest\": \"sha256:sickdigest\"})\n docker.image_id_from_registry(\"foo/bar:rad\")\n","sub_path":"tests/test_docker.py","file_name":"test_docker.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"595192714","text":"\n'''\nAn example of how to use hbox inside vboxes\n'''\nimport wx\nimport numpy as np\n\n\n#Plotting libraries\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.backends.backend_wx import NavigationToolbar2Wx\n\n\n\nclass Window(wx.Frame):\n \n def __init__(self, *args, **kw):\n super(Window, self).__init__(*args, **kw) \n \n self.InitUI()\n self.Centre()\n self.Show(True) \n\n def InitUI(self): \n\n pnl = wx.Panel(self)\n \n vbox1 = wx.BoxSizer(wx.VERTICAL)\n hbox1 = wx.BoxSizer(wx.HORIZONTAL)\n \n # Plotting\n self.fig = plt.figure()\n self.axes = self.fig.add_subplot(111)\n #parent = self.f1 puts the figure inside the frame \n self.plotCanvas = FigureCanvas(pnl,id = -1,figure=self.fig)\n self.sinePlot()\n \n \n \n \n #Defines slider\n sldLow,sldHigh = 1,5\n self.sld = wx.Slider(pnl, value=sldLow, minValue=sldLow, maxValue=sldHigh, pos=(20, 20), \n size=(250, -1), style=wx.SL_HORIZONTAL)\n self.sld.Bind(wx.EVT_SCROLL, self.OnSliderScroll)\n hbox1.Add(self.sld,flag =wx.ALIGN_LEFT)\n \n #Defines static text for slider value\n self.txt = wx.StaticText(pnl, label=str(sldLow), pos=(20, 90)) \n hbox1.Add(self.txt,flag = wx.ALIGN_RIGHT)\n vbox1.Add(hbox1)\n \n \n #Closing button\n self.buttonClose = wx.Button(pnl, label=\"Close App\",style=wx.ALIGN_CENTRE)\n self.buttonClose.Bind(wx.EVT_BUTTON, self.closeWindow)\n vbox1.Add(self.buttonClose)\n \n #vbox contains all of the hboxes, only need to SetSizer for vbo\n pnl.SetSizer(vbox1)\n \n self.SetSize((290, 200))\n self.SetTitle('wx.Slider')\n \n def OnSliderScroll(self, e):\n \n obj = e.GetEventObject()\n val = obj.GetValue()\n self.txt.SetLabel(str(val)) \n \n def closeWindow(self,e):\n self.Close(True) \n \ndef main():\n \n app = wx.App()\n Window(None)\n app.MainLoop() \n\nif __name__ == '__main__':\n main() ","sub_path":"my_wxpython_testing/wxpython_slider.py","file_name":"wxpython_slider.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"544340928","text":"'''\r\n授業中にもかかわらず遊んでしまうdaveは、\r\n理科の実験中に、色んな重さの種類があるおもりをすべて使って、\r\nちょうど天秤が水平になるおもりの組み合わせがあるかを知りたくなったようで、それに遊び呆けてる。\r\n(すべてのおもりを使うため、使わなかったおもりはない。)\r\n\r\nあなたは、daveにその組み合わせがあるかどうか教えて、授業に集中させるようにしてください。\r\n\r\nもしそのような組み合わせがあれば possiblepossible 、なければ impossibleimpossible を出力してください。\r\n'''\r\n\r\n\r\ndef last_one(l):\r\n last_index = 0\r\n for num_i, i in enumerate(l):\r\n if i == 1:\r\n last_index = num_i\r\n return last_index\r\n\r\n\r\ndef match_sum(l, a, where_sum=0):\r\n\r\n for num_i, i in enumerate(l):\r\n #print(i, a)\r\n if i < a:\r\n r_list = match_sum(l[num_i + 1:], a - i, where_sum + num_i + 1)\r\n if -1 not in r_list:\r\n return [num_i + where_sum] + r_list\r\n else:\r\n continue\r\n elif i == a:\r\n return [num_i + where_sum]\r\n return [-1]\r\n\r\nif __name__ == '__main__':\r\n\r\n A = int(input())\r\n S = list(map(int, input().split()))\r\n S.sort()\r\n S.reverse()\r\n half_sum = sum(S) / 2\r\n\r\n if sum(S) % 2 == 1:\r\n print(\"impossible\")\r\n else:\r\n if -1 in match_sum(S, half_sum):\r\n print(\"impossible\")\r\n else:\r\n print(\"possible\")\r\n","sub_path":"omoritotennbinn.py","file_name":"omoritotennbinn.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"527768059","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。\n\n# 示例 1:\n\n# 输入: num1 = \"2\", num2 = \"3\"\n# 输出: \"6\"\n\n# 示例 2:\n\n# 输入: num1 = \"123\", num2 = \"456\"\n# 输出: \"56088\"\n\n# 说明:\n\n# num1 和 num2 的长度小于110。\n# num1 和 num2 只包含数字 0-9。\n# num1 和 num2 均不以零开头,除非是数字 0 本身。\n# 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。\n\n\nclass Solution(object):\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n result = 0\n for index1, one in enumerate(reversed(num1)):\n for index2, two in enumerate(reversed(num2)):\n one = int(one)\n two = int(two)\n result = result + (one * two * 10 ** (index1 + index2))\n\n return str(result)\n\n\nif __name__ == '__main__':\n s = Solution()\n result = s.multiply('123', '456')\n print(result)\n","sub_path":"leetcode/43.py","file_name":"43.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"511291623","text":"# Helpers\nimport base64\nimport logging\nimport os\n\nimport boto3\nfrom flask import jsonify\n\n\ndef custom_logger(name):\n formatter = logging.Formatter(\n fmt=f\"%(asctime)s - %(levelname)s - {name} - in %(\"\n f\"funcName)s:%(lineno)d - %(message)s\"\n )\n\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n\n logger = logging.getLogger(name)\n try:\n logger.setLevel(os.environ[\"LOGGER_LEVEL\"])\n except KeyError:\n logger.setLevel(\"INFO\")\n logger.addHandler(handler)\n return logger\n\n\nlogger = custom_logger(\"helpers\")\n\n\ncustom_api_errors = {\n \"400\": {\n \"error_code\": \"OPGDATA-API-INVALIDREQUEST\",\n \"error_message\": \"Invalid request, the data is incorrect\",\n \"error_title\": \"Invalid Request\",\n },\n \"401\": {\n \"error_code\": \"OPGDATA-API-UNAUTHORISED\",\n \"error_message\": \"Unauthorised (no current user and there should be)\",\n \"error_title\": \"User is not authorised\",\n },\n \"403\": {\n \"error_code\": \"OPGDATA-API-FORBIDDEN\",\n \"error_message\": \"Forbidden - The current user is forbidden from \"\n \"accessing this data (in this way)\",\n \"error_title\": \"Access Denied\",\n },\n \"404\": {\n \"error_code\": \"OPGDATA-API-NOTFOUND\",\n \"error_message\": \"That URL is not a valid route, or the item resource \"\n \"does not exist\",\n \"error_title\": \"Page not found\",\n },\n \"405\": {\n \"error_code\": \"OPGDATA-API-NOT-ALLOWED\",\n \"error_message\": \"That method is not allowed on this URL\",\n \"error_title\": \"Method not allowed\",\n },\n \"413\": {\n \"error_code\": \"OPGDATA-API-FILESIZELIMIT\",\n \"error_message\": \"Payload too large, try and upload in smaller chunks\",\n \"error_title\": \"Payload too large\",\n },\n \"415\": {\n \"error_code\": \"OPGDATA-API-MEDIA\",\n \"error_message\": \"Unsupported media type for this endpoint\",\n \"error_title\": \"Unsupported media type\",\n },\n \"500\": {\n \"error_code\": \"OPGDATA-API-SERVERERROR\",\n \"error_message\": \"Something unexpected happened internally\",\n \"error_title\": \"Internal server error\",\n },\n \"503\": {\n \"error_code\": \"OPGDATA-API-UNAVAILABLE\",\n \"error_message\": \"Service is currently unavailable. Please try again \" \"later\",\n \"error_title\": \"Service Unavailable\",\n },\n}\n\n\ndef error_message(code, message):\n\n return (\n jsonify(\n {\n \"isBase64Encoded\": False,\n \"statusCode\": code,\n \"headers\": {\"Content-Type\": \"application/json\"},\n \"body\": {\n \"error\": {\n \"code\": custom_api_errors[str(code)][\"error_code\"],\n \"title\": custom_api_errors[str(code)][\"error_title\"],\n \"message\": str(message)\n if message\n else custom_api_errors[str(code)][\"error_message\"],\n }\n },\n }\n ),\n code,\n )\n\n\ndef handle_file_source(file):\n\n if \"source\" not in file and \"s3_reference\" in file:\n\n try:\n bucket = os.environ[\"DIGIDEPS_S3_BUCKET\"]\n s3_client = get_digideps_s3_client()\n except Exception as e:\n logger.error(f\"Error handing file: {e}\")\n return None\n\n source = get_encoded_s3_object(\n s3_client=s3_client, bucket=bucket, key=file[\"s3_reference\"],\n )\n elif \"source\" in file:\n source = file[\"source\"]\n else:\n source = None\n return source\n\n\ndef get_digideps_s3_client():\n master_session = boto3.session.Session()\n sts = master_session.client(\"sts\")\n role_arn = os.environ[\"DIGIDEPS_S3_ROLE_ARN\"]\n assume_role_response = sts.assume_role(\n RoleArn=role_arn, RoleSessionName=\"data-deputy-reporting\"\n )\n\n if \"Credentials\" in assume_role_response:\n assumed_session = boto3.Session(\n aws_access_key_id=assume_role_response[\"Credentials\"][\"AccessKeyId\"],\n aws_secret_access_key=assume_role_response[\"Credentials\"][\n \"SecretAccessKey\"\n ],\n aws_session_token=assume_role_response[\"Credentials\"][\"SessionToken\"],\n )\n\n return assumed_session.client(\"s3\")\n\n\ndef get_encoded_s3_object(s3_client, bucket, key):\n\n try:\n s3_client.download_file(bucket, key, \"/tmp/{}\".format(key))\n except Exception as e:\n logger.error(f\"Error downloading file from S3: {e}\")\n return None\n\n try:\n image = open(\"/tmp/{}\".format(key), \"rb\")\n\n image_read = image.read()\n image_64_encode = base64.b64encode(image_read).decode(\"utf-8\")\n except Exception as e:\n image_64_encode = None\n logger.error(f\"Error reading file from S3: {e}\")\n\n return image_64_encode\n","sub_path":"lambda_functions/v2/functions/documents/app/api/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"621619479","text":"from unittest.mock import Mock\nimport pytest\n\n\n@pytest.fixture(scope='session')\ndef dummy_db(request):\n a = Mock()\n a.get_users.return_value = ['Kasia', 'Tomek']\n\n def func():\n print('koniec')\n\n request.addfinalizer(func)\n\n return a\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"582336953","text":"import os, glob\nimport nibabel as nib\nimport numpy as np\nfrom scipy import ndimage\nfrom scipy.ndimage import label\n\nfrom unet3d.utils.path_utils import get_filename_without_extension\n\nfrom projects.prostate.config import config, config_unet, config_dict\n\ndata_path=\"/media/guus/Secondary/3DUnetCNN_BRATS/projects/prostate/database\" \n\n\nprediction_dir=\"prediction/\\\nprostate_2018_is-256-256-128_crop-0_bias-0_denoise-0_norm-z_hist-0_ps-256-256-1_unet2d_crf-0_d-4_nb-16_loss-weighted_aug-1_model\"\n#prediction_dir=\"prediction_seperate/test\"\n\nprediction_path=os.path.join(data_path, prediction_dir)\n\ndef biggest_region_3D(im):\n struct=np.full((3,3,3),1)\n c=0\n lab, num_reg=label(im,structure=struct)\n h=np.zeros(num_reg+1)\n for i in range(num_reg):\n z=np.where(lab==(i+1),1,0)\n h[i+1]=z.sum()\n if h[i+1]==h.max():\n c=i+1\n lab=np.where(lab==c,1,0)\n return lab\n\nfor i, subject_dir in enumerate(glob.glob(os.path.join(prediction_path, \"*\"))):\n print(\"Postprocessing subject {} of {}\".format(i, len(glob.glob(os.path.join(prediction_path, \"*\")))))\n\n\n ct_im=nib.load(os.path.join(subject_dir, \"data_ct.nii.gz\"))\n affine=ct_im.affine\n\n truth_post=np.zeros((256, 256, 128), dtype=np.uint8)\n\n prost_im=nib.load(os.path.join(subject_dir, \"prediction_1.nii.gz\")).get_fdata()\n blad_im=nib.load(os.path.join(subject_dir, \"prediction_2.nii.gz\")).get_fdata()\n rect_im=nib.load(os.path.join(subject_dir, \"prediction_3.nii.gz\")).get_fdata()\n\n #binarize the images\n prost_im=np.where(prost_im>=0.5, 1, 0)\n blad_im=np.where(blad_im>=0.5, 1, 0)\n rect_im=np.where(rect_im>=0.5, 1, 0)\n\n #dilate bladder to get rid of prostate \"border\" around bladder\n blad_im=ndimage.binary_dilation(blad_im, structure=np.ones((1,1,1))).astype(blad_im.dtype)\n\n #isolate the biggest connected volume from each image\n prost_im=biggest_region_3D(prost_im)\n blad_im=biggest_region_3D(blad_im)\n rect_im=biggest_region_3D(rect_im)\n\n #assign to single multilabel image; if prostate and bladder overlap, keep bladder only\n truth_post[prost_im==1]=1\n truth_post[(prost_im==1) & (blad_im==1)]=2\n truth_post[rect_im==1]=3\n\n truth_post=nib.Nifti1Image(truth_post, affine)\n nib.save(truth_post, os.path.join(subject_dir, \"prediction.nii.gz\"))\n","sub_path":"projects/prostate/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"241818907","text":"from header_common import *\r\nfrom header_operations import *\r\nfrom header_mission_templates import *\r\nfrom header_animations import *\r\nfrom header_sounds import *\r\nfrom header_music import *\r\nfrom module_constants import *\r\n\r\nfrom module_info import wb_compile_switch as is_a_wb_mt\r\n\r\n# This file contains a heavily modified and improved version\r\n# of Chel's morale scripts. If you modify it, please leave a \r\n# note telling what you did. -CC\r\n\r\ntld_morale_triggers = [\r\n\r\n \t# This trigger always happens to prevent a \"you killed 30000 troops in this battle.\" bug when you turn battle morale on\r\n\t# after it was turned off for some time. -CC\r\n\r\n \t(1, 0, ti_once, [], [\r\n \t(get_player_agent_kill_count,\"$base_kills\",0),\r\n \t(assign,\"$new_kills_a\",0),\r\n\t\t(assign,\"$new_kills\",0),\r\n\t\t(try_begin),\r\n\t\t\t# Display the morale values once, so the players have a general idea.\r\n\t\t\t(eq, \"$tld_option_morale\", 1),\r\n\t\t\t(call_script, \"script_coherence\"), \r\n\t\t\t(call_script, \"script_healthbars\"),\r\n\t\t(try_end),\r\n \t#(assign,\"$new_enemy_kills_a\",0),\r\n\t\t#(assign,\"$new_enemy_kills\",0),\r\n \t]),\r\n\r\n\t(0, 0, 0, [(key_clicked, key_z),(eq, cheat_switch, 1)],\r\n\t[\r\n\t\t(try_for_agents, \":agent\"),\r\n\t\t\t(call_script, \"script_cf_agent_get_morale\", \":agent\"),\r\n\t\t\t(agent_get_troop_id, \":troop\", \":agent\"),\r\n\t\t\t(str_store_troop_name, s1, \":troop\"),\r\n\t\t\t(display_message, \"@{s1}'s morale: {reg1}\"),\r\n\t\t(try_end),\r\n\t]),\r\n\r\n\t# Rally your troops, five second wait inbetween. -CC\r\n \t(0, 0, 5, [(eq, \"$tld_option_morale\", 1),(get_player_agent_no, \":player\"),(agent_is_alive, \":player\"),(key_clicked, key_v)], \r\n\t[\r\n\t\t(assign,\":ally\",\"$allies_coh\"),\r\n\t\t(assign,\":enemy\",\"$enemies_coh\"),\r\n\t\t(val_sub,\":ally\",\":enemy\"),\r\n\t\t(assign, \":continue\", 0),\r\n\r\n\t\t(try_begin),\r\n\t\t\t(le, \":ally\", tld_morale_rout_allies),\r\n\t\t\t(assign, \":continue\", 1),\r\n\t\t(else_try),\r\n\t\t\t(display_message, \"@You do not need to rally your troops yet.\", color_neutral_news),\r\n\t\t(try_end),\r\n\r\n\t\t(eq, \":continue\", 1),\r\n\t\t(get_player_agent_no, \":player\"),\r\n\t\r\n\t\t(assign, \":max_rallies\", 1),\r\n\t\t(agent_get_slot, \":times_rallied\", \":player\", slot_agent_rallied),\r\n\t\t(store_attribute_level, \":cha\", \"trp_player\", ca_charisma),\r\n\t\t(store_div, \":normal_rallies\", \":cha\", 5),\r\n\t\t(val_add, \":max_rallies\", \":normal_rallies\"),\r\n\t\t(try_begin),\r\n\t\t\t(this_or_next|player_has_item, \"itm_angmar_whip_reward\"),\r\n\t\t\t(player_has_item, \"itm_horn_gondor_reward\"),\r\n\t\t\t(store_skill_level,\":horn_rallies\",\"skl_leadership\",\"trp_player\"),\r\n\t\t\t(val_div, \":horn_rallies\", 3),\r\n\t\t\t(val_add, \":max_rallies\", \":horn_rallies\"),\t\t\r\n\t\t(try_end),\r\n\t\t#(assign, reg0, \":max_rallies\"),\r\n\t\t#(assign, reg1, \":times_rallied\"),\r\n\t\t#(display_message, \"@Max Rallies: {reg0}, Times Rallied: {reg1}\"),\r\n\t\t(try_begin),\r\n\t\t\t(lt, \":times_rallied\", \":max_rallies\"),\r\n\t\t\t(call_script, \"script_troop_get_cheer_sound\", \"trp_player\"),\r\n\t\t\t#(play_sound, \"snd_evil_horn\"),\r\n\t\t\t(try_begin),\r\n\t\t\t\t(ge, reg1, 0),\r\n\t\t\t\t(agent_play_sound, \":player\", reg1),\r\n\t\t\t(try_end),\r\n\t\t\t(display_message, \"@You rally your troops!\", color_good_news),\r\n\t\t\t(val_add, \":times_rallied\", 1),\r\n\t\t\t(agent_set_slot, \":player\", slot_agent_rallied, \":times_rallied\"),\r\n\t\t\t(try_begin),\r\n\t\t\t\t(agent_get_horse, \":horse\", \":player\"),\r\n\t\t\t\t(ge, \":horse\", 0),\r\n\t\t\t\t(agent_set_animation, \":player\", \"anim_cheer_player_ride\"),\r\n\t\t\t(else_try),\r\n\t\t\t\t(agent_set_animation, \":player\", \"anim_cheer_player\"),\r\n\t\t\t(try_end),\r\n\t\t\t(try_for_agents, \":agent\"),\r\n\t\t\t\t(neq, \":agent\", \":player\"),\r\n\t\t\t\t(agent_is_human, \":agent\"),\r\n\t\t\t\t(agent_is_alive, \":agent\"),\r\n\t\t\t\t(agent_is_ally, \":agent\"),\r\n\t\t\t\t(call_script, \"script_cf_agent_get_leader_troop\", \":agent\"),\r\n\t\t\t\t(assign, \":can_rally\", 0),\r\n\t\t\t\t(try_begin),\r\n\t\t\t\t\t(eq, reg0, \"trp_player\"),\r\n\t\t\t\t\t(assign, \":can_rally\", 1),\r\n\t\t\t\t(else_try), # Give player a chance to rally allied troops\r\n\t\t\t\t\t(store_skill_level,\":ldr\",\"skl_leadership\",\"trp_player\"),\r\n\t\t\t\t\t(gt, \":ldr\", 3), # 3 or more leadership\r\n\t\t\t\t\t(store_random_in_range, \":rnd\", 0, 100),\r\n\t\t\t\t\t(store_mul, \":chance\", \":ldr\", 10),\r\n\t\t\t\t\t(gt, \":chance\", \":rnd\"),\r\n\t\t\t\t\t(assign, \":can_rally\", 1),\r\n\t\t\t\t(try_end),\r\n\t\t\t\t(eq, \":can_rally\", 1),\r\n\t\t\t\t(agent_set_slot, \":agent\", slot_agent_rallied, 1),\r\n\t\t\t\t(try_begin),\r\n\t\t\t\t\t(agent_slot_eq,\":agent\",slot_agent_routed,1),\r\n\t\t\t\t\t(agent_set_slot, \":agent\", slot_agent_routed, 0),\r\n\t\t\t\t\t(agent_clear_scripted_mode, \":agent\"),\t\t\t\r\n\t\t\t\t\t] + ((is_a_wb_mt==1) and [\t\r\n\t\t\t\t\t(agent_slot_eq, \":agent\", slot_agent_is_running_away, 1),\r\n\t\t\t\t\t(agent_set_slot, \":agent\", slot_agent_is_running_away, 0),\r\n\t\t\t\t\t(agent_stop_running_away, \":agent\"), \r\n\t\t\t\t\t] or []) + [\t\r\n\t\t\t\t(try_end),\r\n\t\t\t(try_end),\r\n\t\t(try_end),\r\n\r\n\t] + ((is_a_wb_mt==1) and [\r\n\t (try_begin),\r\n\t (neg|is_presentation_active, \"prsnt_battle\"),\r\n\t (start_presentation, \"prsnt_show_num_rallies\"),\r\n (try_end),\r\n\t] or []) + [\r\n\r\n\t]),\r\n\r\n \t# AI rallies troops -CC\r\n \t(3, 0, 0, [(eq, \"$tld_option_morale\", 1)], \r\n\t[\t\r\n\t\t(assign,\":ally\",\"$allies_coh\"),\r\n\t\t(assign,\":enemy\",\"$enemies_coh\"),\r\n\t\t(val_sub,\":ally\",\":enemy\"),\r\n\r\n\t\t# When allied troops are routed, allied commanders rally their troops!\r\n\t\t(try_begin),\r\n\t\t\t(le, \":ally\", tld_morale_rout_allies),\r\n\t\t\t(get_player_agent_no, \":player\"),\r\n\t\t\t(try_for_agents, \":agent\"),\r\n\t\t\t\t(neq, \":agent\", \":player\"),\r\n\t\t\t\t(agent_is_human, \":agent\"),\r\n\t\t\t\t(agent_is_alive, \":agent\"),\r\n\t\t\t\t(agent_is_ally, \":agent\"),\r\n\t\t\t\t(agent_get_troop_id, \":troop\", \":agent\"),\r\n\t\t\t\t(call_script, \"script_cf_agent_get_leader_troop\", \":agent\"),\r\n\t\t\t\t(eq, \":troop\", reg0),\r\n\t\t\t\t(troop_is_hero, \":troop\"),\r\n\t\t\t\t(agent_get_slot, \":times_rallied\", \":agent\", slot_agent_rallied),\r\n\t\t\t\t(store_attribute_level, \":cha\", \":troop\", ca_charisma),\r\n\t\t\t\t(store_div, \":max_rallies\", \":cha\", 5),\r\n\t\t\t\t(val_add, \":max_rallies\", 1),\r\n\t\t\t\t(try_begin),\r\n\t\t\t\t\t(call_script, \"script_count_enemy_agents_around_agent\", \":agent\", 300), # AI won't rally if surrounded. The \r\n\t\t\t\t\t(le, reg0, 0),\t\t\t\t\t\t\t\t# animation makes him vulnerable. -CC\r\n\t\t\t\t\t(store_random_in_range, \":die_roll\", 0, 101),\r\n\t\t\t\t\t(store_mul, \":rally_penalty\", \":times_rallied\", 20), # The more they have rallied, the less likely to do it again. -CC\r\n\t\t\t\t\t(store_sub, \":chance\", 80, \":rally_penalty\"),\r\n\t\t\t\t\t(lt, \":die_roll\", \":chance\"), # lil' bit of personality in AI commanders\r\n\t\t\t\t\t(lt, \":times_rallied\", \":max_rallies\"), # \":max_rallies\"\r\n\t\t\t\t\t(str_store_troop_name, s1, \":troop\"),\r\n\t\t\t\t\t#(assign, reg0, \":chance\"),\r\n\t\t\t\t\t#(assign, reg1, \":die_roll\"),\r\n\t\t\t\t\t#(assign, reg2, \":times_rallied\"),\r\n\t\t\t\t\t(agent_get_troop_id, \":troop\", \":agent\"),\r\n\t\t\t\t\t(troop_get_type, reg65, \":troop\"),\r\n (try_begin),\r\n (neq, reg65, 1), #not female\r\n (assign, reg65, 0), #make it male for strings\r\n (try_end),\r\n\t\t\t\t\t(str_store_troop_name, s5, \":troop\"),\r\n\t\t\t\t\t(display_message, \"@{s5} rallies {reg65?her:his} troops!\", color_good_news),\r\n\t\t\t\t\t(val_add, \":times_rallied\", 1),\r\n\t\t\t\t\t(agent_set_slot, \":agent\", slot_agent_rallied, \":times_rallied\"),\r\n\t\t\t\t\t(call_script, \"script_troop_get_cheer_sound\", \":troop\"),\r\n\t\t\t\t\t(try_begin),\r\n\t\t\t\t\t\t(ge, reg1, 0),\r\n\t\t\t\t\t\t(agent_play_sound, \":agent\", reg1),\r\n\t\t\t\t\t(try_end),\r\n\t\t\t\t\t(try_begin),\r\n\t\t\t\t\t\t(agent_get_horse, \":horse\", \":agent\"),\r\n\t\t\t\t\t\t(ge, \":horse\", 0),\r\n\t\t\t\t\t\t(agent_set_animation, \":agent\", \"anim_cheer_player_ride\"),\r\n\t\t\t\t\t(else_try),\r\n\t\t\t\t\t\t(agent_set_animation, \":agent\", \"anim_cheer_player\"),\r\n\t\t\t\t\t(try_end),\r\n\t\t\t\t\t(try_for_agents, \":cur_agent\"),\r\n\t\t\t\t\t\t(neq, \":agent\", \":cur_agent\"),\r\n\t\t\t\t\t\t(agent_is_human, \":cur_agent\"),\r\n\t\t\t\t\t\t(agent_is_alive, \":cur_agent\"),\r\n\t\t\t\t\t\t(agent_is_ally, \":cur_agent\"),\r\n\t\t\t\t\t\t(call_script, \"script_cf_agent_get_leader_troop\", \":cur_agent\"),\r\n\t\t\t\t\t\t(eq, \":troop\", reg0),\r\n\t\t\t\t\t\t(agent_set_slot, \":cur_agent\", slot_agent_rallied, 1),\r\n\t\t\t\t\t\t(agent_set_slot, \":cur_agent\", slot_agent_routed, 0),\r\n\t\t\t\t\t\t(agent_clear_scripted_mode, \":cur_agent\"),\r\n\t\t\t\t\t\t] + ((is_a_wb_mt==1) and [\t\r\n\t\t\t\t\t\t(agent_slot_eq, \":cur_agent\", slot_agent_is_running_away, 1),\r\n\t\t\t\t\t\t(agent_set_slot, \":cur_agent\", slot_agent_is_running_away, 0),\r\n\t\t\t\t\t\t(agent_stop_running_away, \":cur_agent\"), \r\n\t\t\t\t\t\t] or []) + [\t\r\n\t\t\t\t\t(try_end),\r\n\t\t\t\t(try_end),\r\n\t\t\t(try_end),\r\n\t\t(try_end),\r\n\r\n\t\t# When enemy troops are routed, enemy commanders rally their troops!\r\n\t\t(try_begin),\r\n\t\t\t(ge, \":ally\", tld_morale_rout_enemies),\r\n\t\t\t(try_for_agents, \":agent\"),\r\n\t\t\t\t(agent_is_human, \":agent\"),\r\n\t\t\t\t(agent_is_alive, \":agent\"),\r\n\t\t\t\t(agent_is_ally|neg, \":agent\"),\r\n\t\t\t\t(agent_get_troop_id, \":troop\", \":agent\"),\r\n\t\t\t\t(call_script, \"script_cf_agent_get_leader_troop\", \":agent\"),\r\n\t\t\t\t(eq, \":troop\", reg0),\r\n\t\t\t\t(troop_is_hero, \":troop\"),\r\n\t\t\t\t(agent_get_slot, \":times_rallied\", \":agent\", slot_agent_rallied),\r\n\t\t\t\t(store_attribute_level, \":cha\", \":troop\", ca_charisma),\r\n\t\t\t\t(store_div, \":max_rallies\", \":cha\", 5),\r\n\t\t\t\t(val_add, \":max_rallies\", 1),\r\n\t\t\t\t(try_begin),\r\n\t\t\t\t\t(call_script, \"script_count_enemy_agents_around_agent\", \":agent\", 300), # AI won't rally if surrounded. The \r\n\t\t\t\t\t(le, reg0, 0),\t\t\t\t\t\t\t\t# animation makes him vulnerable. -CC\r\n\t\t\t\t\t(store_random_in_range, \":die_roll\", 0, 101),\r\n\t\t\t\t\t(store_mul, \":rally_penalty\", \":times_rallied\", 20), # The more they have rallied, the less likely to do it again. -CC\r\n\t\t\t\t\t(store_sub, \":chance\", 80, \":rally_penalty\"),\r\n\t\t\t\t\t(lt, \":die_roll\", \":chance\"), # lil' bit of personality in AI commanders\r\n\t\t\t\t\t(lt, \":times_rallied\", \":max_rallies\"), # \":max_rallies\"\r\n\t\t\t\t\t(assign, reg0, \":chance\"),\r\n\t\t\t\t\t(assign, reg1, \":die_roll\"),\r\n\t\t\t\t\t(assign, reg2, \":times_rallied\"),\r\n\t\t\t\t\t(agent_get_troop_id, \":troop\", \":agent\"),\r\n\t\t\t\t\t(troop_get_type, reg65, \":troop\"),\r\n (try_begin),\r\n (neq, reg65, 1), #not female\r\n (assign, reg65, 0), #make it male for strings\r\n (try_end),\r\n\t\t\t\t\t(str_store_troop_name, s5, \":troop\"),\r\n\t\t\t\t\t(display_message, \"@{s5} rallies {reg65?her:his} troops!\", color_bad_news),\r\n\t\t\t\t\t(val_add, \":times_rallied\", 1),\r\n\t\t\t\t\t(agent_set_slot, \":agent\", slot_agent_rallied, \":times_rallied\"),\r\n\t\t\t\t\t(call_script, \"script_troop_get_cheer_sound\", \":troop\"),\r\n\t\t\t\t\t(try_begin),\r\n\t\t\t\t\t\t(ge, reg1, 0),\r\n\t\t\t\t\t\t(agent_play_sound, \":agent\", reg1),\r\n\t\t\t\t\t(try_end),\r\n\t\t\t\t\t(try_begin),\r\n\t\t\t\t\t\t(agent_get_horse, \":horse\", \":agent\"),\r\n\t\t\t\t\t\t(ge, \":horse\", 0),\r\n\t\t\t\t\t\t(agent_set_animation, \":agent\", \"anim_cheer_player_ride\"),\r\n\t\t\t\t\t(else_try),\r\n\t\t\t\t\t\t(agent_set_animation, \":agent\", \"anim_cheer_player\"),\r\n\t\t\t\t\t(try_end),\r\n\t\t\t\t\t(try_for_agents, \":cur_agent\"),\r\n\t\t\t\t\t\t(neq, \":agent\", \":cur_agent\"), # Ralliers don't rally themselves.\r\n\t\t\t\t\t\t(agent_is_human, \":cur_agent\"),\r\n\t\t\t\t\t\t(agent_is_alive, \":cur_agent\"),\r\n\t\t\t\t\t\t(agent_is_ally|neg, \":cur_agent\"),\r\n\t\t\t\t\t\t(call_script, \"script_cf_agent_get_leader_troop\", \":cur_agent\"),\r\n\t\t\t\t\t\t(eq, \":troop\", reg0),\r\n\t\t\t\t\t\t(agent_set_slot, \":cur_agent\", slot_agent_rallied, 1),\r\n\t\t\t\t\t\t(agent_set_slot, \":cur_agent\", slot_agent_routed, 0),\r\n\t\t\t\t\t\t(agent_clear_scripted_mode, \":cur_agent\"),\r\n\t\t\t\t\t\t] + ((is_a_wb_mt==1) and [\t\r\n\t\t\t\t\t\t(agent_slot_eq, \":cur_agent\", slot_agent_is_running_away, 1),\r\n\t\t\t\t\t\t(agent_set_slot, \":cur_agent\", slot_agent_is_running_away, 0),\r\n\t\t\t\t\t\t(agent_stop_running_away, \":cur_agent\"), \r\n\t\t\t\t\t\t] or []) + [\t\r\n\t\t\t\t\t(try_end),\r\n\t\t\t\t(try_end),\r\n\t\t\t(try_end),\r\n\t\t(try_end),\r\n\t]),\r\n\r\n \t# let the player know of his troop's morale\r\n \t(0, 0, 2, [(key_clicked, key_t),(eq, \"$tld_option_morale\", 1)], \r\n\t[\r\n\t\t(call_script, \"script_coherence\"), \r\n\t\t(call_script, \"script_healthbars\"), \r\n\t]),\r\n \r\n\t# calculate coherence once\r\n\t(1, 0, ti_once, [(eq, \"$tld_option_morale\", 1)], \r\n\t[\r\n\t\t(call_script, \"script_coherence\"), \r\n\t]),\t\t\t\t\t\t\r\n\r\n\t# morale check (changed from 15)\r\n\t(30, 0, 10, [(eq, \"$tld_option_morale\", 1)], \r\n\t[\r\n\t\t(call_script, \"script_coherence\"), \r\n\t\t(call_script, \"script_morale_check\"), \r\n ]),\r\n\r\n\t# rout check (changed from 20)\r\n\t(40, 0, 5, [(eq, \"$tld_option_morale\", 1)], \r\n\t[\r\n\t\t(call_script, \"script_coherence\"), \r\n\t\t(call_script, \"script_rout_check\"), \r\n ]),\r\n\r\n\t# Custom trigger, ensures agents get to position and when they do, remove them, but\r\n\t# only after 90 seconds, to ensure agents have time to advance and engage in \r\n\t# battle before immediately fleeing, otherwise there is no fight. -CppCoder - Changed to 3.5 mins (kham)\r\n \t(0.1, 0, 0, [(eq, \"$tld_option_morale\", 1),(store_mission_timer_a,reg1),(ge,reg1,210)], \r\n\t[\r\n\t\t(try_for_agents, \":cur_agent\"),\r\n\t\t\t(agent_is_alive, \":cur_agent\"),\r\n\t\t\t(try_begin),\r\n\t\t\t\t(agent_slot_eq,\":cur_agent\",slot_agent_routed,1),\r\n\t\t\t\t\r\n\t\t\t\t] + ((is_a_wb_mt==1) and [\r\n\r\n\t\t ## WB has an operation for fleeing - Kham\r\n\t\t (agent_start_running_away, \":cur_agent\"),\r\n\t\t (agent_set_slot, \":cur_agent\", slot_agent_is_running_away, 1),\r\n\t\t \r\n\t\t ] or [\r\n\t\t\t\t(call_script, \"script_find_exit_position_at_pos4\", \":cur_agent\"),\r\n\t\t\t\t(agent_set_scripted_destination, \":cur_agent\", pos4, 1),\r\n\t\t\t\t\r\n\t\t\t\t]) + [\r\n\r\n\t\t\t\t(agent_get_position, pos2, \":cur_agent\"),\r\n\t\t\t\t(get_distance_between_positions, \":dist\", pos4, pos2),\r\n\t\t\t\t(lt, \":dist\", 300),\r\n\t\t\t\t(store_random_in_range, \":rand\", 0, 100),\r\n\t\t\t\t(lt, \":rand\", 50),\r\n\t\t\t\t(call_script, \"script_count_enemy_agents_around_agent\", \":cur_agent\", 600),\r\n\t\t\t\t(agent_get_troop_id,\":troop_no\", \":cur_agent\"),\r\n\t\t\t\t(le|this_or_next, reg0, 0),\r\n\t\t\t\t(is_between, \":troop_no\", warg_ghost_begin, warg_ghost_end), # Lone wargs can always flee\r\n\t\t\t\t(call_script, \"script_remove_agent_from_field\", \":cur_agent\"),\r\n\t\t\t(try_end),\r\n\t\t(try_end),\r\n\t]),\r\n\r\n \t(3, 0, 3, [(eq, \"$tld_option_morale\", 1)], \r\n\t[\r\n \t(get_player_agent_kill_count,\":more_kills\",0),\r\n \t(val_sub,\":more_kills\",\"$base_kills\"),\r\n\r\n\t\t# TODO: CC: Find enemy leader(s) and calculate their morale boost.\t\r\n\r\n\t\t(try_begin),\r\n \t\t(gt,\":more_kills\",\"$new_kills_a\"),\r\n \t\t(assign,\"$new_kills_a\",\":more_kills\"),\r\n\t\t\t(assign,\"$new_kills\",\":more_kills\"),\r\n\t\t\t(val_div,\"$new_kills\",2),\r\n \t\t(assign,reg1,\":more_kills\"),\r\n \t\t(display_message,\"@You have killed {reg1} enemies in this battle!\",0x6495ed), \r\n \t\t(display_message,\"@Your bravery inspires your troops!\",0x6495ed),\r\n \t(try_end),\r\n ]),\r\n\r\n\r\n#Show num rallies\r\n] + ((is_a_wb_mt==1) and [\r\n(ti_after_mission_start, 0, ti_once, [],[(start_presentation, \"prsnt_show_num_rallies\")]),\r\n\r\n(1, 0, 0, [\r\n (this_or_next|game_key_is_down, gk_move_forward),\r\n (this_or_next|game_key_is_down, gk_move_backward),\r\n (this_or_next|game_key_is_down, gk_move_left),\r\n (game_key_is_down, gk_move_right),\r\n (neg|is_presentation_active, \"prsnt_show_num_rallies\"),\r\n (neg|is_presentation_active, \"prsnt_battle\"),\r\n (neg|main_hero_fallen),\r\n ],[ \r\n (start_presentation, \"prsnt_show_num_rallies\"),\r\n]),\r\n\r\n(0, 0, 0, [\r\n\t\t (eq, \"$show_key_binds_toggle\", 0),\r\n (key_clicked, key_insert),\r\n (this_or_next|neg|key_is_down, key_left_control),\r\n (neg|key_is_down, key_right_control),],\r\n\r\n [(assign, \"$show_key_binds_toggle\", 1),(start_presentation, \"prsnt_show_key_binds\"),\r\n]),\r\n\r\n] or []) + [\r\n\r\n]\r\n","sub_path":"ModuleSystem/module_mission_templates_morale.py","file_name":"module_mission_templates_morale.py","file_ext":"py","file_size_in_byte":15050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"550094906","text":"from HamiltonianPy import *\nimport HamiltonianPy.ED as ED\nimport HamiltonianPy.VCA as VCA\nimport numpy as np\n\nfrom DataBase import *\n\nKPOINTS = (0, 1, 3, 5)\n\ndef Chemical0(bond):\n return 1.0 if bond.spoint.pid.site in KPOINTS else 0.0\n\ndef Chemical1(bond):\n return 1.0 if not (bond.spoint.pid.site in KPOINTS) else 0.0\n\ndef Hubbard0(bond):\n return 1.0 if bond.spoint.pid.site in KPOINTS else 0.0\n\ndef Hubbard1(bond):\n return 1.0 if not (bond.spoint.pid.site in KPOINTS) else 0.0\n\ndef myvca(\n enum=13, U0=0.0, U1=0.0, Mu0=0.0, Mu1=0.0,\n emin=-8.0, emax=6.0, ne=500, nk=100, eta=0.10\n):\n cell = Lattice(\n name=\"SDCell\", rcoords=COORDS_STAR, vectors=As_STAR, neighbours=1\n )\n cluster = Lattice(\n name=\"SDCluster\", rcoords=COORDS_STAR, vectors=As_STAR, neighbours=1\n )\n site_num = len(cluster)\n\n basis = FBasis(2*site_num, enum, (enum%2)*0.5)\n config = IDFConfig(\n priority=DEFAULT_FERMIONIC_PRIORITY, pids=cluster.pids,\n map=lambda pid: Fock(atom=0, norbital=1, nspin=2, nnambu=1),\n )\n\n cgf = VCA.VGF(nstep=200, prepare=ED.EDGFP, savedata=True, run=ED.EDGF)\n vca = VCA.VCA(\n name=\"{0}-({1},{2})\".format(\"SD\", 2 * site_num, enum),\n cgf=cgf, sectors=[basis], cell=cell, lattice=cluster, config=config,\n terms=[\n Hopping(\"t0\", 1.0, neighbour=1),\n Onsite(\"Mu0\", Mu0, amplitude=Chemical0),\n Onsite(\"Mu1\", Mu1, amplitude=Chemical1),\n Hubbard(\"U0\", U0, amplitude=Hubbard0),\n Hubbard(\"U1\", U1, amplitude=Hubbard1),\n ],\n mask=[\"nambu\"], dtype=np.float64,\n )\n\n vca.register(\n VCA.EB(\n run=VCA.VCAEB,\n path=hexagon_gkm(reciprocals=cell.reciprocals, nk=nk),\n name=\"EB\", emin=emin, emax=emax, ne=ne, eta=eta, savedata=True,\n )\n )\n vca.register(\n DOS(\n run=VCA.VCADOS,\n BZ=KSpace(reciprocals=cluster.reciprocals, nk=nk),\n name=\"DOS\", emin=emin, emax=emax, ne=ne, eta=eta, savedata=True,\n )\n )\n vca.summary()\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--enum\", type=int, default=13)\n parser.add_argument(\"--Mu0\", type=float, default=0.0)\n parser.add_argument(\"--Mu1\", type=float, default=0.0)\n parser.add_argument(\"--U0\", type=float, default=0.0)\n parser.add_argument(\"--U1\", type=float, default=0.0)\n parser.add_argument(\"--emin\", type=float, default=-8.0)\n parser.add_argument(\"--emax\", type=float, default=14.0)\n parser.add_argument(\"--ne\", type=int, default=501)\n parser.add_argument(\"--nk\", type=int, default=200)\n parser.add_argument(\"--eta\", type=float, default=0.10)\n args = parser.parse_args()\n\n myvca(\n enum=args.enum,\n Mu0=args.Mu0,\n Mu1=args.Mu1,\n U0=args.U0,\n U1=args.U1,\n emin=args.emin,\n emax=args.emax,\n ne=args.ne,\n nk=args.nk,\n eta=args.eta,\n )\n","sub_path":"SiteDependentHubbardModel/DopedAt(0,1,3,5)/cpt.py","file_name":"cpt.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"17770188","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport sys\nimport rospy\n\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import Float32MultiArray\n\nimport cv2\nfrom cv_bridge import CvBridge, CvBridgeError\n\nclass AutoTracking:\n\n def __init__(self):\n self.pub = rospy.Publisher('bebop/cmd_vel', Twist)\n self.sub = rospy.Subscriber('face_position', Float32MultiArray, self.callback)\n self.center_bound = 5\n self.slope = .01\n self.vel_msg = Twist()\n\n def _does_not_detect_any_face(self, pos):\n return pos.data[2] < 1\n\n def _decision_making(self, pos):\n\n x = pos.data[0]\n self.vel_msg.angular.z = 0\n if x >= 50 or x <= -50:\n print(\"ValueError of face_position! Skip decision making\")\n return 1\n\n if self._does_not_detect_any_face(pos):\n return 0\n\n if abs(x) <= self.center_bound:\n return 0\n\n self.vel_msg.angular.z = -x * self.slope\n\n def callback(self, data):\n self._decision_making(data)\n self.pub.publish(self.vel_msg)\n\n\ndef main(args):\n rospy.init_node('following', anonymous=True)\n AutoTracking()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n rospy.loginfo(\"shutting down ...\")\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"scripts/following.py","file_name":"following.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"290290089","text":"import argparse\n\nimport requests\n\nfrom . import tenderbake\n\nRPC_CONSTANTS = \"chains/main/blocks/head/context/constants\"\nRPC_TOTAL_VOTING_POWER = \"chains/main/blocks/head/votes/total_voting_power\"\n\n\ndef fetch_constants(tezos_rpc_url):\n return requests.get(f\"{tezos_rpc_url}/{RPC_CONSTANTS}\").json()\n\n\ndef fetch_total_voting_power(tezos_rpc_url):\n return requests.get(f\"{tezos_rpc_url}/{RPC_TOTAL_VOTING_POWER}\").json()\n\n\ndef network_name_to_rpc(networks, network_name):\n url = networks.get(network_name)\n if url is None:\n raise Exception(\n f\"Unknown network. Network must be one of: {sorted(networks.keys())}\"\n )\n return url\n\n\ndef parse_args():\n\n p = argparse.ArgumentParser()\n p.add_argument(\n \"-c\",\n \"--cycles\",\n type=int,\n default=1,\n help=(\"Calculate estimates for this number of cycles. Default: %(default)s\"),\n )\n\n p.add_argument(\n \"-b\",\n \"--full-balance\",\n default=6000.0,\n type=float,\n help=(\n \"[tenderbake] Calculate estimates using this number as baker's full balance. \"\n \"Default: %(default)s\"\n ),\n )\n p.add_argument(\n \"-D\",\n \"--deposit-limit\",\n default=None,\n type=float,\n help=(\n \"[tenderbake] Calculate estimates with this deposit limit. \"\n \"If not specified, max deposit if baker's full balance. \"\n \"Default: %(default)s\"\n ),\n )\n\n p.add_argument(\n \"-d\",\n \"--delegated-balance\",\n default=0.0,\n type=float,\n help=(\n \"[tenderbake] Calculate estimates assuming this delegated balance. \"\n \"Default: %(default)s\"\n ),\n )\n\n p.add_argument(\n \"--confidence\",\n default=0.9,\n type=float,\n help=(\n \"Probability that calculated max values are not exceeded. \"\n \"Default: %(default)s\"\n ),\n )\n p.add_argument(\n \"-n\",\n \"--network\",\n default=\"mainnet\",\n help=\"name of Tezos network. Default: %(default)s\",\n )\n p.add_argument(\n \"--rpc\",\n help=\"Custom URL for Tezos node RPC, overrides one derived from --network\",\n )\n\n return p.parse_args()\n\n\ndef fetch_test_networks():\n testnets_info_url = \"https://teztnets.xyz/teztnets.json\"\n name2rpc = {}\n try:\n testnets = requests.get(testnets_info_url).json()\n except Exception:\n print(f\"Failed to get testnet info from {testnets_info_url}\")\n else:\n for (key, net) in testnets.items():\n if \"rpc_url\" not in net:\n print(f\"rpc url not provided for {key}, skipping\")\n else:\n name2rpc[net.get(\"human_name\", key).lower()] = net[\"rpc_url\"]\n name2rpc[key] = net[\"rpc_url\"]\n return name2rpc\n\n\ndef main():\n args = parse_args()\n rpc = args.rpc or network_name_to_rpc(\n dict(mainnet=\"https://mainnet.api.tez.ie\", **fetch_test_networks()),\n args.network.lower(),\n )\n constants = fetch_constants(rpc)\n total_voting_power = fetch_total_voting_power(rpc)\n preserved_cycles = constants[\"preserved_cycles\"]\n if isinstance(total_voting_power, str):\n # in Jakarta total voting power is total active stake in mutez\n total_active_stake = int(total_voting_power)\n else:\n raise Exception(\"Unexpected total_voting_power value %r\" % total_voting_power)\n # in Ithaca total voting power is the same as in previous protocols - number of rolls\n print(f\"preserved cycles: {preserved_cycles}\")\n print()\n\n minimal_stake = int(constants[\"minimal_stake\"])\n print(\n tenderbake.run(\n constants,\n total_active_stake,\n cycles=args.cycles,\n confidence=0.9,\n full_balance=args.full_balance,\n delegated_balance=args.delegated_balance,\n eligibility_threshold=minimal_stake,\n )\n )\n","sub_path":"src/py/bakestimator/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"263974137","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries LLC\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\"\"\"\n`adafruit_featherwing.neopixel_featherwing`\n====================================================\n\nHelper for using the `NeoPixel FeatherWing `_.\n\n* Author(s): Melissa LeBlanc-Williams\n\"\"\"\n\n__version__ = \"0.0.0-auto.0\"\n__repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_FeatherWing.git\"\n\nimport board\nimport neopixel\nfrom adafruit_featherwing.pixelmatrix import PixelMatrix\n\n\nclass NeoPixelFeatherWing(PixelMatrix):\n \"\"\"Class representing a `NeoPixel FeatherWing\n `_.\n\n The feather uses pins D6 by default\"\"\"\n\n def __init__(self, pixel_pin=board.D6, brightness=0.1):\n \"\"\"\n :param pin pixel_pin: The pin for the featherwing\n :param float brightness: Optional brightness (0.0-1.0) that defaults to 1.0\n \"\"\"\n super().__init__()\n self.rows = 4\n self.columns = 8\n self._matrix = neopixel.NeoPixel(\n pixel_pin,\n self.rows * self.columns,\n brightness=brightness,\n auto_write=False,\n pixel_order=neopixel.GRB,\n )\n\n def shift_up(self, rotate=False):\n \"\"\"\n Shift all pixels up\n\n :param rotate: (Optional) Rotate the shifted pixels to bottom (default=False)\n\n This example shifts 2 pixels up\n\n .. code-block:: python\n\n import time\n from adafruit_featherwing import neopixel_featherwing\n\n neopixel = neopixel_featherwing.NeoPixelFeatherWing()\n\n # Draw Red and Green Pixels\n neopixel[4, 1] = (255, 0, 0)\n neopixel[5, 1] = (0, 255, 0)\n\n # Rotate it off the screen\n for i in range(0, neopixel.rows - 1):\n neopixel.shift_up(True)\n time.sleep(.1)\n\n time.sleep(1)\n # Shift it off the screen\n for i in range(0, neopixel.rows - 1):\n neopixel.shift_up()\n time.sleep(.1)\n\n \"\"\"\n super().shift_down(rotate) # Up and down are reversed\n\n def shift_down(self, rotate=False):\n \"\"\"\n Shift all pixels down.\n\n :param rotate: (Optional) Rotate the shifted pixels to top (default=False)\n\n This example shifts 2 pixels down\n\n .. code-block:: python\n\n import time\n from adafruit_featherwing import neopixel_featherwing\n\n neopixel = neopixel_featherwing.NeoPixelFeatherWing()\n\n # Draw Red and Green Pixels\n neopixel[4, 1] = (255, 0, 0)\n neopixel[5, 1] = (0, 255, 0)\n\n # Rotate it off the screen\n for i in range(0, neopixel.rows - 1):\n neopixel.shift_down(True)\n time.sleep(.1)\n\n time.sleep(1)\n # Shift it off the screen\n for i in range(0, neopixel.rows - 1):\n neopixel.shift_down()\n time.sleep(.1)\n\n \"\"\"\n super().shift_up(rotate) # Up and down are reversed\n","sub_path":"adafruit_featherwing/neopixel_featherwing.py","file_name":"neopixel_featherwing.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"78363825","text":"\"\"\"An HTTP server to communicate with, for example::\n\n HTTPServer('http://example.com/api').request('go')\n\"\"\"\n\nfrom requests import Request, Session\n\nfrom jsonrpcclient.server import Server\n\n\nclass HTTPServer(Server):\n\n # The default HTTP header\n __DEFAULT_HTTP_HEADERS__ = {\n 'Content-Type': 'application/json', 'Accept': 'application/json'}\n\n def __init__(self, endpoint):\n \"\"\"\n :param endpoint: The server address.\n :param kwargs: HTTP headers and other options passed on to the requests\n module.\n \"\"\"\n super(HTTPServer, self).__init__(endpoint)\n self.session = Session()\n self.session.headers.update(self.__DEFAULT_HTTP_HEADERS__)\n self.last_request = None\n self.last_response = None\n\n def _send_message(\n self, request, headers=None, files=None, params=None, auth=None,\n cookies=None, **kwargs):\n \"\"\"Transport the message to the server and return the response.\n\n :param request: The JSON-RPC request string.\n :return: The JSON-RPC response.\n :rtype: A string for requests, None for notifications.\n :raise requests.exceptions.RequestException:\n Raised by the requests module in the event of a communications\n error.\n \"\"\"\n # Prepare the request\n req = Request(\n method='POST', url=self.endpoint, data=request, headers=headers,\n files=files, params=params, auth=auth, cookies=cookies)\n prepped = self.session.prepare_request(req)\n self.last_request = prepped\n # Log the request\n self._log_request(request, {'http_headers': prepped.headers})\n # Send the message\n response = self.session.send(prepped, **kwargs)\n # Log the response\n self._log_response(response.text, {'http_code': response.status_code, \\\n 'http_reason': response.reason, 'http_headers': response.headers})\n self.last_response = response\n return response.text\n","sub_path":"jsonrpcclient/http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"338973861","text":"import pygame\nimport os\n\npygame.init()\n\nscreen_width = 640\nscreen_height = 480\nscreen_size = (screen_width, screen_height)\n\nscreen = pygame.display.set_mode(screen_size)\npygame.display.set_caption(\"PyPang!\")\n\nclock = pygame.time.Clock()\n\npath = os.path.dirname(__file__)\nimg_path = os.path.join(path, \"images\")\n\n# 배경 만들기\nbackground = pygame.image.load(os.path.join(img_path, \"background.png\"))\n\n# 스테이지 만들기\nstage = pygame.image.load(os.path.join(img_path, \"stage.png\"))\nstage_height = stage.get_rect().size[1]\n\n# 캐릭터 만들기\ncharacter = pygame.image.load(os.path.join(img_path, \"character.png\"))\ncharacter_size = character.get_rect().size\ncharacter_width = character_size[0]\ncharacter_height = character_size[1]\ncharacter_x_pos = screen_width / 2 - character_width / 2\ncharacter_y_pos = screen_height - stage_height - character_height\ncharacter_to_x = 0\ncharacter_speed = 5\n\n# 무기 만들기\nweapon = pygame.image.load(os.path.join(img_path, \"weapon.png\"))\nweapon_width = weapon.get_rect().size[0]\n\n# 무기 저장소\nweapons = []\n\n# 무기 이동 속도\nweapon_speed = 10\n\n# 공 만들기\nball_images = [\n pygame.image.load(os.path.join(img_path, \"balloon1.png\")),\n pygame.image.load(os.path.join(img_path, \"balloon2.png\")),\n pygame.image.load(os.path.join(img_path, \"balloon3.png\")),\n pygame.image.load(os.path.join(img_path, \"balloon4.png\"))]\n\n# 공 속도\nball_speed_y = [-18, -15, -12, -9]\n\nballs = []\n\n# 최초 발생 공 추\nballs.append(\n {\n \"pos_x\" : 50,\n \"pos_y\" : 50,\n \"img_idx\" : 0,\n \"to_x\" : 3,\n \"to_y\" : -6,\n \"init_spd_y\" : ball_speed_y[0]\n }\n)\n\n# 사라질 무기, 공 변\nweapon_to_remove = -1\nball_to_remove = -1\n\nrunning = True\n\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n # 키 입력 처리\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n character_to_x -= character_speed\n elif event.key == pygame.K_RIGHT:\n character_to_x += character_speed\n elif event.key == pygame.K_SPACE:\n weapon_x_pos = character_x_pos + (character_width // 2) - weapon_width // 2\n weapon_y_pos = character_y_pos\n weapons.append([weapon_x_pos, weapon_y_pos])\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n character_to_x = 0\n\n # 캐릭터 위치 업데이트\n character_x_pos += character_to_x\n\n # 무기 위치 업데이트\n weapons = [ [w[0], w[1] - weapon_speed] for w in weapons]\n weapons = [ [w[0], w[1]] for w in weapons if w[1] > 0]\n\n # 공 위치 정의\n for ball_idx, ball_val in enumerate(balls):\n ball_pos_x = ball_val[\"pos_x\"]\n ball_pos_y = ball_val[\"pos_y\"]\n ball_img_idx = ball_val[\"img_idx\"]\n\n ball_size = ball_images[ball_img_idx].get_rect().size\n ball_width = ball_size[0]\n ball_height = ball_size[1]\n\n # 가로 벽 공 위치 변경\n if ball_pos_x < 0 or ball_pos_x > screen_width - ball_width:\n ball_val[\"to_x\"] *= -1\n\n # 세로 위치\n if ball_pos_y > screen_height - stage_height - ball_height:\n ball_val[\"to_y\"] = ball_val[\"init_spd_y\"]\n else:\n ball_val[\"to_y\"] += 0.5\n\n ball_val[\"pos_x\"] += ball_val[\"to_x\"]\n ball_val[\"pos_y\"] += ball_val[\"to_y\"]\n\n # 충돌 처리기\n character_rect = character.get_rect()\n character_rect.left = character_x_pos\n character_rect.top = character_y_pos\n\n for ball_idx, ball_val in enumerate(balls):\n ball_pos_x = ball_val[\"pos_x\"]\n ball_pos_y = ball_val[\"pos_y\"]\n ball_img_idx = ball_val[\"img_idx\"]\n\n ball_rect = ball_images[ball_img_idx].get_rect()\n ball_rect.left = ball_pos_x\n ball_rect.top = ball_pos_y\n\n if character_rect.colliderect(ball_rect):\n running = False\n break\n\n # 충돌 처리_무기\n for weapon_idx, weapon_val in enumerate(weapons):\n weapon_pos_x = weapon_val[0]\n weapon_pos_y = weapon_val[1]\n\n weapon_rect = weapon.get_rect()\n weapon_rect.left = weapon_pos_x\n weapon_rect.top = weapon_pos_y\n\n if weapon_rect.colliderect(ball_rect):\n weapon_to_remove = weapon_idx\n ball_to_remove = ball_idx\n break\n\n # 충돌 공, 무기 없애기\n if ball_to_remove > -1:\n del balls[ball_to_remove]\n ball_to_remove = -1\n if weapon_to_remove > -1:\n del weapons[weapon_to_remove]\n weapon_to_remove = -1\n\n # 화면그리기\n screen.blit(background, (0, 0))\n for one in weapons:\n screen.blit(weapon, (one[0], one[1]))\n\n screen.blit(stage, (0, screen_height - stage_height))\n screen.blit(character, (character_x_pos, character_y_pos))\n\n for idx, val in enumerate(balls):\n ball_pos_x = val[\"pos_x\"]\n ball_pos_y = val[\"pos_y\"]\n ball_img_idx = val[\"img_idx\"]\n screen.blit(ball_images[ball_img_idx], (ball_pos_x, ball_pos_y))\n\n pygame.display.update()\n\npygame.quit()","sub_path":"py_pang/4. collision.py","file_name":"4. collision.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"149347364","text":"import os\nimport sys\nfrom collections.abc import Sequence\nfrom pathlib import Path\nfrom typing import NoReturn\n\n\ndef main(args: Sequence[str]) -> NoReturn:\n file_type = get_type(args)\n mod_dir = Path(__file__).parent.parent.absolute()\n\n os.execlp(\n \"go\",\n \"go\",\n \"run\",\n \"-C\",\n mod_dir,\n \"github.com/bazelbuild/buildtools/buildifier\",\n \"--lint=fix\",\n \"--warnings=all\",\n f\"--type={file_type}\",\n )\n\n\ndef get_type(args: Sequence[str]) -> str:\n filename = os.path.basename(args[0] if args else \"\")\n\n name_to_type = {\n \"BUILD\": \"build\",\n \"WORKSPACE\": \"workspace\",\n }\n\n return name_to_type.get(filename, \"default\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"nvim/langservers/bin/buildifierw.py","file_name":"buildifierw.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"258494575","text":"#!/usr/bin/env python3\n\n\n\n#############\n# LIBRARIES #\n#############\n\nimport sys\nimport pandas as pd\n\n\n\ndef merge(csv_file_input):\n\t#Read CSV file and transform it into a data frame\n\tpca_input = pd.read_csv(csv_file_input,sep='\\t')\n\n\t#Merged CSV output file\n\tpca_output = pd.DataFrame()\n\n\t#Collect column headers\n\tcolumn_header = list(pca_input.columns)\n\n\t#Remove the .version of gene ID\n\tnew_geneid = pca_input['Geneid'].apply(lambda x: x.split(\".\")[0])\n\tpca_output['Geneid'] = new_geneid\n\n\t#Collect maximal length for each gene ID\n\tnew_length = pca_input.groupby(new_geneid,sort=False).max()['Length'].values\n\tpca_output['Length'] = new_length\n\n\t#Merge values of column headers\n\tfor header in column_header[6:]:\n\t\theader_values = pca_input.groupby(new_geneid,sort=False).sum()[header].values\n\t\tpca_output[header] = header_values\n\n\t#Return pc_output data frame\n\treturn pca_output\n\n\t#pca_output.to_csv(csv_file_output,sep='\\t',encoding='utf-8',index=False)\n\n\n\ndef TPM_converter(merged_input):\n\tmerged_pca_input = merged_input\n\t#merged_pca_input = pd.read_csv(csv_file_input,sep='\\t',encoding='utf-8')\n\n\t#First step: Convert into RPK values\n\ttotal_rows = len(merged_pca_input.index)\n\n\tfor each_row in range(total_rows):\n\t\tgene_length = merged_pca_input.loc[each_row]['Length']\n\t\tread_counts = merged_pca_input.loc[each_row][3:]\n\t\trpk = read_counts / gene_length\n\t\tthree_first_segment = merged_pca_input.loc[each_row][0:3]\n\t\tmerged_pca_input.loc[each_row] = three_first_segment.append(rpk)\n\n\t#Second step: Convert into TPM\n\ttotal_columns = len(merged_pca_input.columns)\n\n\tfor each_col in range(2,total_columns):\n\t\tRPK_values = merged_pca_input.ix[:,each_col]\n\t\tscaling_factor = merged_pca_input.ix[:,each_col].sum() / 1000000\n\t\tTPM_values = RPK_values / scaling_factor\n\n\t\tmerged_pca_input.ix[:,each_col] = TPM_values\n\n\treturn merged_pca_input\n\n\t#merged_pca_input.to_csv(csv_file_output,sep='\\t',encoding='utf-8',\n\t\t\t\t\t\t\t#index=False)\n\n\n\ndef normalize_TPM(TPM_input, csv_file_output):\n\ttpm_pca_input = TPM_input\n\n\t#tpm_pca_input = pd.read_csv(csv_file_input,sep='\\t',encoding='utf-8')\n\n\t#Normalizing by making deduction between TPM value and its average\n\ttotal_columns = len(tpm_pca_input.columns)\n\n\tfor each_col in range(2,total_columns):\n\t\teach_TPM_col_mean = tpm_pca_input.ix[:,each_col].mean()\n\t\tnormalized_col = tpm_pca_input.ix[:,each_col] - each_TPM_col_mean\n\t\ttpm_pca_input.ix[:,each_col] = normalized_col\n\n\ttpm_pca_input.to_csv(csv_file_output,sep='\\t',encoding='utf-8',\n\t\t\t\t\t\tindex=False)\n\n\n\ndef main(csv_file_input,csv_file_output):\n\n\t#First step: Merge versions of genes\n\tprint(\"Merging file {}...\\n\".format(csv_file_input))\n\tmerged_file = merge(csv_file_input)\n\tprint(\"Done merging.\\n\")\n\n\t#Second step: Convert merged CSV file into TPM\n\tprint(\"Converting into TPM...\\n\")\n\ttpm_file = TPM_converter(merged_file)\n\tprint(\"Done converting.\\n\")\n\n\t#Third step: Normalize TPM\n\tprint(\"Normalizing TPM...\\n\")\n\tnormalize_TPM(tpm_file, csv_file_output)\n\tprint(\"Done normalizing.\\n\")\n\n\nif __name__ == '__main__':\n\tmain(*sys.argv[1:])","sub_path":"Zu/pca/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"288002207","text":"'''\nCreated on 30 Jun 2018\n\n@author: jegramos\n'''\nfrom builtins import int\n\n# input age\n# 18 - 20 : wear special wristband\n# 21 and above : normal entry\n# below 18 : too young\n\nage = input(\"Dude, how old are you? \")\n\nif age :\n age = int(age)\n if age >= 21 : \n print(\"Okay, you can enter\")\n elif age >= 18 :\n print(\"You have to wear a wristband, bro!\")\n elif age >= 1 : \n print(\"Scram you dam brat\") \n elif age <= 0 :\n print(\"Get back when you're born!\")\nelse : \n print(\"Enter your age, bro!\")\n \n ","sub_path":"conditional_logic/project_bouncer.py","file_name":"project_bouncer.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"207327018","text":"import numpy as np\nimport operator\nimport matplotlib.pyplot as plt\n\nimport pandas\n\nimport pickle\nimport time\n\nfrom ppo_grid import PPO\nfrom ppo_grid import ActorCritic\n\nimport torch\nimport torch.nn as nn\nfrom torch.distributions import Categorical\nimport gym\n\nfrom torch.autograd import Variable\n\n#%matplotlib inline\n\n# THE INIT FILE HAS TO BE OUTSIDE INCASE THE CODE USES THE ENTIRE ITERATION STEPS\n# CHANGE IN ALL THE CODES\n\n\n# LIMITATION - Cant go back because each state has a fixed action\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Memory:\n def __init__(self):\n self.actions = []\n self.states = []\n self.logprobs = []\n self.rewards = []\n self.is_terminals = []\n \n def clear_memory(self):\n del self.actions[:]\n del self.states[:]\n del self.logprobs[:]\n del self.rewards[:]\n del self.is_terminals[:]\n\nclass GridWorld:\n\tdef __init__(self):\n\n\t\t# 5x5\n\t\tself.height = 5\n\t\tself.width = 5\n\n\t\tself.grid = np.zeros((self.height, self.width)) - 1 # initializing the values to -1?\n\t\t# can replace grid to q_table? jk no there is another called q_table\n\t\t\n\t\t# Set random start location for the agent\n\t\t#self.current_location = ( 4, np.random.randint(0,5))\n\n\t\tself.start_location = (4,0)\n\t\tself.current_location = self.start_location\n\t\t\n\t\t# 5x5 environment\n\t\tself.obstacles = [(1,3)] #,(1,2),(1,1),(3,3),(3,2),(3,1)]\n\t\t# self.goals = [(0,3),(4,4),(2,2)]\n\t\t# self.goals = [(0, 3), (2, 4), (4, 2)]\n\t\tself.goals = [(0, 3)]\n\n\t\tself.terminal_states = [self.obstacles, self.goals]\n\t\t\n\t\t# Set grid rewards for special cells\n\n\t\tfor obs in self.obstacles:\n\t\t\tself.grid[obs[0], obs[1]] = -10\n\n\t\t# for g in self.goals:\n\t\t# \tself.grid[g[0], g[1]] = 2\n\t\t# grid[a][b] = grid[a,b]\n\n\t\tself.actions = ['UP', 'DOWN', 'LEFT', 'RIGHT']\n\n\n\tdef get_available_actions(self):\n\t\treturn self.actions\n\t\n\tdef agent_on_map(self):\n\t\t\"\"\"Prints out current location of the agent on the grid (used for debugging)\"\"\"\n\t\tgrid = np.zeros(( self.height, self.width))\n\t\tgrid[ self.current_location[0], self.current_location[1]] = 1\n\t\treturn grid\n\t\n\tdef get_reward(self, new_location):\n\t\treturn self.grid[new_location[0], new_location[1]]\n\t\t\n\t\n\tdef make_step(self, action):\n\t\t\"\"\"Moves the agent in the specified direction. If agent is at a border, agent stays still\n\t\tbut takes negative reward. Function returns the reward for the move.\"\"\"\n\t\t# Store previous location\n\t\t\n\t\tlast_location = self.current_location\n\t\t# UP\n\t\tif action == 'UP':\n\t\t\t# If agent is at the top, stay still, collect reward\n\t\t\tif last_location[0] == 0:\n\t\t\t\treward = self.get_reward(last_location)\n\t\t\telse:\n\t\t\t\tself.current_location = ( self.current_location[0] - 1, self.current_location[1])\n\t\t\t\treward = self.get_reward(self.current_location)\n\t\t\n\t\t# DOWN\n\t\telif action == 'DOWN':\n\t\t\t# If agent is at bottom, stay still, collect reward\n\t\t\tif last_location[0] == self.height - 1:\n\t\t\t\treward = self.get_reward(last_location)\n\t\t\telse:\n\t\t\t\tself.current_location = ( self.current_location[0] + 1, self.current_location[1])\n\t\t\t\treward = self.get_reward(self.current_location)\n\t\t\t\n\t\t# LEFT\n\t\telif action == 'LEFT':\n\t\t\t# If agent is at the left, stay still, collect reward\n\t\t\tif last_location[1] == 0:\n\t\t\t\treward = self.get_reward(last_location)\n\t\t\telse:\n\t\t\t\tself.current_location = ( self.current_location[0], self.current_location[1] - 1)\n\t\t\t\treward = self.get_reward(self.current_location)\n\n\t\t# RIGHT\n\t\telif action == 'RIGHT':\n\t\t\t# If agent is at the right, stay still, collect reward\n\t\t\tif last_location[1] == self.width - 1:\n\t\t\t\treward = self.get_reward(last_location)\n\t\t\telse:\n\t\t\t\tself.current_location = ( self.current_location[0], self.current_location[1] + 1)\n\t\t\t\treward = self.get_reward(self.current_location)\n\t\t\t\t\n\t\treturn reward\n\n####################################\nstarttime_toruncode = time.time()\n\n# env_name = \"MountainCar-v0\"\n# # creating environment\n# env = gym.make(env_name)\nstate_dim = 2\naction_dim = 4\nprint(state_dim)\nprint(action_dim)\nrender = False\nsolved_reward = 230 # stop training if avg_reward > solved_reward\nlog_interval = 100 # print avg reward in the interval\nmax_episodes = 5000 # max training episodes\nmax_timesteps = 1000 # max timesteps in one episode\nn_latent_var = 64 # number of variables in hidden layer\nupdate_timestep = 400 # update policy every n timesteps\nlr = 0.002\nbetas = (0.9, 0.999)\ngamma = 0.99 # discount factor\nK_epochs = 4 # update policy for K epochs\neps_clip = 0.2 # clip parameter for PPO\nrandom_seed = None\n#############################################\n\t\nif random_seed:\n\ttorch.manual_seed(random_seed)\n\tenv.seed(random_seed)\n\nmemory = Memory()\nppo = PPO(state_dim, action_dim, n_latent_var, lr, betas, gamma, K_epochs, eps_clip)\nenvironment = GridWorld()\n\n# logging variables\nrunning_reward = 0\navg_length = 0\ntimestep = 0\n\nrchd_obstacles = 0 \ntime_trials = []\nrchd_order = 0\nhighest_reward = -1000\nbest_path_taken = []\nreward_per_episode = [] \n\nfor i_episode in range(1, max_episodes+1):\n\tstart_time = time.time()\n\tcumulative_reward = 0 \n\tstep = 0\n\tgame_over = False\n\twrong_order = False\n\treached_allgoals = False\n\tencountered_goals = []\n\n\tpath_taken = []\n\n\tenvironment.__init__()\n\n\twhile step < max_timesteps and game_over != True:\n\t\ttimestep += 1 \n\t\told_state = environment.current_location\n\t\tpath_taken.append(old_state)\n\n\t\tstate = np.array(old_state)\n\t\tstate = Variable(torch.from_numpy(state))\n\t\tprint(state)\n\t\tprint('State -', state)\n\t\taction = ppo.policy_old.act(state, memory)\n\n\t\treward = environment.make_step(action)\n\t\tnew_state = environment.current_location\n\t\tmemory.rewards.append(reward)\n\t\t# memory.is_terminals.append(done)\n\n\t\tif new_state in environment.goals and new_state not in encountered_goals:\n\t\t\tencountered_goals.append(new_state)\t\t\t\t\n\t\t\tif environment.goals == encountered_goals:\n\t\t\t\treward = 20\n\t\t\t\treached_allgoals = True\n\t\t\t\trchd_order += 1 \n\t\t\t\tbest_path_taken = path_taken\n\t\t\telse:\n\t\t\t\t# something wrong with this code maybe?\n\t\t\t\tif new_state != environment.goals[len(encountered_goals) - 1]:\n\t\t\t\t\treward = -10\n\t\t\t\t\twrong_order = True\n\t\t\t\telse:\n\t\t\t\t\treward = 10\n\t\t\n\t\tif timestep % update_timestep == 0:\n\t\t\tppo.update(memory)\n\t\t\tmemory.clear_memory()\n\t\t\ttimestep = 0\n\t\t\t\t\n\t\tcumulative_reward += reward\n\t\trunning_reward += reward\n\t\tstep += 1\n\n\t\tlength_match = (len(encountered_goals) == len(environment.goals))\n\t\tif new_state in environment.obstacles or wrong_order or reached_allgoals or length_match:\n\t\t\tif new_state in environment.obstacles:\n\t\t\t\trchd_obstacles += 1\n\t\t\tgame_over = True \n\n\t\n\tif highest_reward < cumulative_reward:\n\t\thighest_reward = cumulative_reward\n\t\t# best_path_taken = path_taken\n\n\treward_per_episode.append(cumulative_reward) \n\ttime_trials.append(time.time() - start_time)\n\n\tavg_length += t\n\t\n\t# stop training if avg_reward > solved_reward\n\tif running_reward > (log_interval*solved_reward):\n\t\tprint(\"########## Solved! ##########\")\n\t\ttorch.save(ppo.policy.state_dict(), './PPO_{}.pth'.format(env_name))\n\t\tbreak\n\t\t\n\t# logging\n\tif i_episode % log_interval == 0:\n\t\tavg_length = int(avg_length/log_interval)\n\t\trunning_reward = int((running_reward/log_interval))\n\t\t\n\t\tprint('Episode {} \\t avg length: {} \\t reward: {}'.format(i_episode, avg_length, running_reward))\n\t\trunning_reward = 0\n\t\tavg_length = 0\n\n#### Create the grid #####################\ngrid_visualize = np.zeros((environment.height, environment.width), dtype = object)\n\nprint('Best path taken -',best_path_taken)\nfor path in best_path_taken:\n\tgrid_visualize[path[0], path[1]] = 1\n\nfor obs in environment.obstacles:\n\tgrid_visualize[obs[0], obs[1]] = 'X'\n\ng_count = 1\nfor g in environment.goals:\n\tgrid_visualize[g[0], g[1]] = 'G' + str(g_count)\n\tg_count += 1\n\ns_l = environment.start_location\ngrid_visualize[s_l[0], s_l[1]] = 'S'\ngrid_visualize[grid_visualize == 0] = ''\n\ndf = pandas.DataFrame(grid_visualize)\nprint(df)\n\n\nend_code = time.time() - starttime_toruncode\nprint('Total time taken to run the code -', end_code)\nprint('Reward at the end of the episode - ',reward_per_episode[len(reward_per_episode) - 1])\nprint('Average Reward - ', np.mean(reward_per_episode))\n\nplt.plot(reward_per_episode)\nplt.xlabel('Episode Number')\nplt.ylabel('Rewards')\nplt.savefig('single_ag_grid.png')\nplt.show()\n\n\n# pickle.dump(agentQ.q_table, open(\"qtable_saved.pickle\", \"wb\"))","sub_path":"gridworld-ppo/ppo_singleag.py","file_name":"ppo_singleag.py","file_ext":"py","file_size_in_byte":8354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"539899594","text":"#!/usr/bin/env python\n\n# make sure to execute the following lines at the terminal before running this py file\n# source ~/catkin_ws/devel/setup.bash\n# chmod +x catkin_ws/src/kalman_filter_mg_cs169/scripts/pose_estimate.py\n\nimport rospy\nimport math\nimport numpy as np\nfrom geometry_msgs.msg import Twist, PoseStamped, PoseWithCovarianceStamped\nfrom sensor_msgs.msg import LaserScan\nfrom timeit import default_timer as timer\nfrom kalman_calculator import *\n\nINDEX = 0 # LiDAR straightforward index\nMSG_INTERVAL_TIME = 0.5 # time threshold for stopping this node after the last cmd_vel msg\nCSV_SAVE_PATH_POSE = '/home/mingi/catkin_ws/src/kalman_filter_mg_cs169/csv/pose.csv'\nCSV_SAVE_PATH_POSE_ESTIMATE = '/home/mingi/catkin_ws/src/kalman_filter_mg_cs169/csv/pose_estimate.csv'\n\n\nclass Kalman_filter_pose_laser():\n def __init__(self):\n self.cmd_subscriber = rospy.Subscriber(\"cmd_vel\", Twist, self.cmd_callback)\n self.pose_subscriber = rospy.Subscriber(\"pose\", PoseStamped, self.pose_callback)\n self.lidar_subscriber = rospy.Subscriber(\"scan\", LaserScan, self.lidar_callback)\n self.state_publisher = rospy.Publisher(\"kalman_filter\", PoseWithCovarianceStamped, queue_size=10)\n\n # initial values saving. The program is calculating based on the first time when cmd_vel is published.\n self.initial_pose = None\n self.initial_time_record_cmd = None # role as an initial time for analysis\n self.initial_time_record_pose = None\n\n # time saving variables\n self.time_record_cmd_now = None\n self.time_record_pose_now = None\n self.time_record_pose_list = []\n self.pose_msg_list = []\n self.pose_diff_list = []\n self.time_record_scan_now = None\n self.time_record_scan_list = []\n self.time_accumulation_scan_list = []\n self.first_calculation = False\n\n self.rate = rospy.Rate(15)\n\n # inital state (relative position) and error covariance for Kalman filter (based on robot foot frint)\n self.initial_x = np.array([[0]]) # relative motion's inital position\n self.initial_P = None # bring up from inital_pose.py\n\n self.X_list = []\n self.P_list = []\n\n # Even if the task is regarding pose,\n # I keep subscribing to and using cmd_vel as the algorithm is based on the time when 1st cmd and last cmd was published\n def cmd_callback(self, msg):\n # from 2nd cmd_vel msg\n if self.initial_time_record_cmd is not None:\n self.time_record_cmd_now = rospy.get_time()\n\n # initial time for cmd_vel save\n else:\n self.initial_time_record_cmd = rospy.get_time()\n self.time_record_cmd_now = self.initial_time_record_cmd\n\n def pose_callback(self, msg):\n # pose calculation since initial cmd_vel was published\n if self.initial_time_record_cmd is not None and rospy.get_time() >= self.initial_time_record_cmd:\n if self.initial_time_record_pose is not None:\n self.pose_msg_list.append(msg)\n self.time_record_pose_now = rospy.get_time()\n self.time_record_pose_list.append(self.time_record_pose_now)\n current_msg = self.pose_msg_list[-1]\n previous_msg = self.pose_msg_list[-2]\n time_difference = self.time_record_pose_list[-1] - self.time_record_pose_list[-2]\n dist_for_Xp_calc = math.sqrt((current_msg.pose.position.x - previous_msg.pose.position.x)**2 + (current_msg.pose.position.y - previous_msg.pose.position.y)**2)\n self.pose_diff_list.append((time_difference, dist_for_Xp_calc))\n\n # first pose msg receives after cmd_vel published\n else:\n self.pose_msg_list.append(msg)\n self.initial_time_record_pose = rospy.get_time()\n self.time_record_pose_now = self.initial_time_record_pose\n self.time_record_pose_list.append(self.time_record_pose_now)\n time_difference = self.time_record_pose_now - self.initial_time_record_cmd\n self.pose_diff_list.append((time_difference, 0)) # pose still 0\n\n\n def lidar_callback(self, msg):\n # under condition that cmd_vel is published after serial bridge is configured in order to calculate based on system model(pose)\n if self.initial_time_record_cmd is not None and rospy.get_time() >= self.initial_time_record_cmd:\n front_distance = msg.ranges[INDEX]\n self.time_record_scan_now = rospy.get_time()\n\n # after 1st pose msg recieved and dropping scan msg in case of inf (outlier)\n if len(self.time_record_pose_list) != 0 and front_distance != float(\"inf\"):\n # time difference of scan messages (consecutive ones)\n self.time_record_scan_list.append(self.time_record_scan_now)\n time_difference_wrt_scan = self.time_record_scan_now - self.time_record_pose_list[-1]\n base_time_difference = self.pose_diff_list[-1][0]\n base_distance = self.pose_diff_list[-1][1]\n\n # interpolation\n transition = time_difference_wrt_scan * (base_distance/base_time_difference)\n\n # from second calculation\n if self.first_calculation == True:\n x, P = kalman_calculator_pose(transition, front_distance, self.X_list[-1], self.P_list[-1])\n self.X_list.append(x)\n self.P_list.append(P)\n self.time_accumulation_scan_list.append(self.time_accumulation_scan_list[-1] + (self.time_record_scan_list[-1] - self.time_record_scan_list[-2]))\n # print(\"from 2nd kalman\", x)\n\n # very first calculation\n else:\n x, P = kalman_calculator_pose(transition, front_distance, self.initial_x, self.initial_P)\n self.X_list.append(x)\n self.P_list.append(P)\n self.first_calculation = True\n self.time_accumulation_scan_list.append(self.time_record_scan_now - self.initial_time_record_cmd)\n # print(\"first kalman\", x)\n\n elif len(self.time_record_pose_list) == 0: # when length 0\n print(\"pose not yet received!\")\n\n\n def spin(self):\n state_message = PoseWithCovarianceStamped()\n # http://docs.ros.org/melodic/api/geometry_msgs/html/msg/PoseWithCovariance.html => row major list 6 x 6 matrix\n\n while not rospy.is_shutdown():\n # after receiving the first cmd_vel\n if len(self.X_list) != 0:\n state_message.header.stamp = rospy.Time.now()\n state_message.header.frame_id = \"odom_kf\"\n state_message.pose.pose.position.x = self.X_list[-1] + self.initial_pose.pose.pose.position.x\n state_message.pose.pose.position.y = 0\n state_message.pose.pose.position.z = 0\n state_message.pose.pose.orientation.x =0\n state_message.pose.pose.orientation.y =0\n state_message.pose.pose.orientation.z =0\n state_message.pose.pose.orientation.w =1\n state_message.pose.covariance[0] = self.P_list[-1]\n\n self.state_publisher.publish(state_message)\n self.rate.sleep() # publish PoseWithCovarianceStamped msg as per designated Hz\n\n if rospy.get_time() - self.time_record_cmd_now > MSG_INTERVAL_TIME:\n pose_path_list = []\n pose_path_time = []\n scalar_X_list = []\n scalar_P_list = []\n\n # Task 2 - C: path based on pose and scan\n for i in range(len(self.X_list)):\n scalar_X_list.append(np.asscalar(self.X_list[i]))\n scalar_P_list.append(np.asscalar(self.P_list[i]))\n\n # Task 2 - A: path based on pose\n for k in range(len(self.pose_diff_list)):\n if k == 0:\n pose_path_time.append(self.pose_diff_list[k][0])\n pose_path_list.append(self.pose_diff_list[k][1])\n else:\n pose_path_time.append(self.pose_diff_list[k][0] + pose_path_time[k-1])\n pose_path_list.append(self.pose_diff_list[k][1] + pose_path_list[k-1]) # recursively accumulate the pose path\n\n print(\"finished!\")\n\n # Data check on screen\n print(\"pose_path\", pose_path_list, \"length\", len(pose_path_list))\n print(\"pose_path_time\", pose_path_time)\n print(\"X_list\", scalar_X_list, \"length\", len(scalar_X_list))\n print(\"X_time\", self.time_accumulation_scan_list, \"length\", len(self.time_accumulation_scan_list))\n #print(\"P_list\", scalar_P_list, \"length\", len(scalar_P_list))\n\n # file save function\n csv_data_saver(CSV_SAVE_PATH_POSE, pose_path_time, pose_path_list)\n csv_data_saver(CSV_SAVE_PATH_POSE_ESTIMATE, self.time_accumulation_scan_list, scalar_X_list)\n\n rospy.signal_shutdown(\"finish!\")\n\n # Don't be confused. initial_P comes from initial_pose.py\n # initial odom position is also saved in self.initial pose; however, initial_x is relative motion of foot frint\n def update_pose_msg(self):\n self.initial_pose = rospy.wait_for_message(\"initialpose\", PoseWithCovarianceStamped)\n self.initial_P = np.array([[self.initial_pose.pose.covariance[0]]])\n print(\"initial accepted\", self.initial_P)\n\n\ndef main():\n kalman_filter_pose_laser = Kalman_filter_pose_laser()\n kalman_filter_pose_laser.update_pose_msg()\n kalman_filter_pose_laser.spin()\n\n\nif __name__ ==\"__main__\":\n rospy.init_node(\"kalman_filter_pose_and_laser\")\n main()\n","sub_path":"scripts/pose_estimate.py","file_name":"pose_estimate.py","file_ext":"py","file_size_in_byte":9976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"590944673","text":"import asyncio\nimport json\n\nfrom aiokafka import AIOKafkaProducer\n\nfrom core.ports.event_producer import EventProducer\n\nclass KafkaEventProducer(EventProducer):\n \"\"\"\n A kafka event publisher.\n \"\"\"\n def __init__(\n self,\n bootstrap_servers,\n topics,\n # group,\n log_service,\n ):\n super().__init__(\n log_service=log_service\n )\n self.bootstrap_servers = bootstrap_servers\n self.topics = topics\n # self.group = group\n\n self.is_started = False\n\n # Flush\n\n async def flush(self, event):\n \"\"\"\n Actually publishes the event,\n (called after request is done in the 'action' decorator).\n \"\"\"\n\n if not self.producer:\n raise Exception(\n (\n \"Kafka event publisher couldn't publish because \"\n \"producer has not been created.\"\n )\n )\n\n await self.producer.send_and_wait(\n *self.topics,\n json.dumps(event.serialize()).encode()\n )\n\n async def start(self):\n await self.create_producer()\n await self.connect(\n retry_backoff=6,\n max_retries=3,\n )\n\n async def stop(self):\n if not self.producer:\n self.log_service.warning(\n (\n \"Kafka event publisher was instructed to stop \"\n \"but it doesn't seem to be started (no producer).\"\n )\n )\n else:\n await self.disconnect()\n\n async def connect(self, retry_backoff=6, max_retries=12):\n \n created = False\n error = None\n retry_backoff = retry_backoff\n retries = 0\n max_retries = max_retries\n\n while (not created) and retries < max_retries:\n try:\n await self.producer.start()\n self.producer_connected = True\n created = True\n\n except Exception as e:\n self.log_service.error(\n (\n \"{} failed to connect to: {} \"\n \"(retrying in {} secs..), exception: {}\"\n ).\n format(\n \"Kafka Event Publisher\",\n self.bootstrap_servers,\n retry_backoff,\n str(e)\n )\n )\n error = str(e)\n retries += 1\n\n await asyncio.sleep(retry_backoff)\n\n if not created:\n raise Exception(\n (\n \"{} failed to connect to: {} \"\n \"after {} retries, error: {}.\"\n ).\n format(\n \"Kafka Event Publisher\",\n self.bootstrap_servers,\n retries,\n error\n )\n )\n\n await self.wait_for_connect()\n\n print(\n \"Kafka event publisher connected to {} @ {}\".\n format(\n self.topics,\n self.bootstrap_servers\n )\n )\n\n async def disconnect(self):\n \n await self.producer.stop()\n\n self.producer_connected = False\n\n async def wait_for_connect(self, timeout=60):\n waited = 0\n while not self.producer_connected:\n await asyncio.sleep(1)\n waited = waited + 1\n if waited > timeout:\n raise Exception(\n \"Couldn't connect to kafka, timed out after {} secs\".\n format(\n timeout\n )\n )\n\n # Publishing\n\n async def create_producer(self):\n self.producer = AIOKafkaProducer(\n loop=asyncio.get_event_loop(),\n bootstrap_servers=self.bootstrap_servers\n )\n ","sub_path":"src/infrastructure/adapters/kafka/kafka_event_producer.py","file_name":"kafka_event_producer.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"264982344","text":"\nfrom getmac import get_mac_address\nimport serial.tools.list_ports\n\ndef findPort(find):\n ports = list(serial.tools.list_ports.comports())\n for p in ports:\n currentPort = str(p)\n if(currentPort.endswith(find)):\n return(currentPort.split(\" \")[0])\n\n\ndef findDuePort():\n ports = list(serial.tools.list_ports.comports())\n for p in ports:\n currentPort = str(p[2])\n if(currentPort.find(\"PID=2341\")>=0):\n return(p[0])\n\ndef findNanoPorts():\n ports = list(serial.tools.list_ports.comports())\n outPorts = []\n for p in ports:\n currentPort = str(p)\n if(currentPort.endswith(\"FT232R USB UART\")):\n outPorts.append(currentPort.split(\" \")[0])\n\n return outPorts\n\ndef findSabrentPorts():\n ports = list(serial.tools.list_ports.comports())\n outPorts = []\n for p in ports:\n currentPort = str(p[2])\n if(currentPort.find(\"PID=067B\")>=0):\n outPorts.append(str(p[0]).split(\" \")[0])\n return outPorts\n\ndef findOzonePort():\n ports = list(serial.tools.list_ports.comports())\n ozonePort = []\n for p in ports:\n currentPort = str(p[2])\n if(currentPort.find(\"PID=067B\")>=0):\n ozonePort.append(str(p[0]).split(\" \")[0])\n return ozonePort\n\ndef findAirMarPort():\n ports = list(serial.tools.list_ports.comports())\n for p in ports:\n currentPort = str(p[2])\n if(currentPort.find(\"PID=067B\")>=0):\n return(p[0])\n\ndef findMacAddress():\n macAddress= get_mac_address(interface=\"eth0\")\n if (macAddress!= None):\n return macAddress.replace(\":\",\"\")\n\n macAddress= get_mac_address(interface=\"docker0\")\n if (macAddress!= None):\n return macAddress.replace(\":\",\"\")\n\n macAddress= get_mac_address(interface=\"enp1s0\")\n if (macAddress!= None):\n return macAddress.replace(\":\",\"\")\n\n macAddress= get_mac_address(interface=\"wlan0\")\n if (macAddress!= None):\n return macAddress.replace(\":\",\"\")\n\n return \"xxxxxxxx\"\n\n\n\ndataFolderReference = \"/home/teamlary/mintsData/reference\"\ndataFolderMQTTReference = \"/home/teamlary/mintsData/referenceMQTT\"\ndataFolder = \"/home/teamlary/mintsData/raw\"\ndataFolderMQTT = \"/home/teamlary/mintsData/rawMQTT\"\nairMarPort = findAirMarPort()\nduePort = findDuePort()\nnanoPorts = findNanoPorts()\nozonePort = findOzonePort()\nshow2Port = findPort(\"CP2104 USB to UART Bridge Controller\")\nmacAddress = findMacAddress()\nlatestDisplayOn = True\nlatestOn = True\n\n# For MQTT \nmqttOn = True\nmqttCredentialsFile = 'mintsXU4/credentials.yml'\nmqttBroker = \"mqtt.circ.utdallas.edu\"\nmqttPort = 8883 # Secure port\n\n\ngpsPort = findPort(\"GPS/GNSS Receiver\")\n\n\nif __name__ == \"__main__\":\n # the following code is for debugging\n # to make sure everything is working run python3 mintsDefinitions.py \n print(\"Mac Address : {0}\".format(macAddress))\n print(\"Data Folder Reference: {0}\".format(dataFolderReference))\n print(\"Data Folder Raw : {0}\".format(dataFolder))\n print(\"GPS Port : {0}\".format(gpsPort))\n print(\"airmar Port : {0}\".format(airMarPort))\n print(\"Latest On : {0}\".format(latestDisplayOn))\n print(\"Latest On : {0}\".format(latestOn))\n print(\"MQTT On : {0}\".format(mqttOn))\n print(\"MQTT Credentials File : {0}\".format(mqttCredentialsFile))\n print(\"MQTT Broker and Port : {0}, {1}\".format(mqttOn,mqttPort))\n \n\n #-------------------------------------------#\n print(\"Nano Ports :\")\n for dev in nanoPorts:\n print(\"\\t{0}\".format(dev))","sub_path":"firmware/xu4Mqqt/mintsXU4/mintsDefinitions.py","file_name":"mintsDefinitions.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"313590364","text":"import os\nimport sys\nimport json\nimport mysql.connector\nimport geocoder\nimport googlemaps\n\ng = geocoder.ip('me').latlng\n#\"57.8765\",\"1.98765\"\n\n\n\ndef hos():\n places = gmaps.places_nearby(location=(co[0], co[1]), rank_by='distance', type='hospital', name='Hospital',\n language='en')\n print(places['results'][0]['plus_code']['global_code'])\n hospital=[]\n for i in range(len(places['results'])):\n t = places['results'][i]['name']\n if ('hospital' in t.lower()):\n hospital.append([t, places['results'][i]['id']])\n return hospital\n\n\ndef pol(co):\n places = gmaps.places_nearby(location=(co[0],co[1]), rank_by='distance', type='police', name='police',\n language='en')\n #print(places['results'][0])\n police=[]\n for i in range(len(places['results'])):\n t = places['results'][i]['name']\n if ('police' in t.lower()):\n police.append([t, places['results'][i]['id']])\n return police\n\n\ndef firest():\n places = gmaps.places_nearby(location=(co[0], co[1]), rank_by='distance', type='police', name='police',\n language='en')\n print(places['results'][0])\n fire=[]\n for i in range(len(places['results'])):\n t = places['results'][i]['name']\n if ('fire' in t.lower()):\n fire.append([t, places['results'][i]['id']])\n return fire\n\n\nrun=True\nwhile(run):\n files=os.listdir('/media/data/')\n if(len(files)==0):\n \n continue\n else:\n current=files[0]\n with open('/media/data/'+current,\"r\") as f:\n temp = json.load(f)\n print(temp)\n co=(temp['0'],temp['1'])\n api_key=\"\"\n gmaps = googlemaps.Client(key=api_key)\n print(co)\n police=pol(co)\n conn=mysql.connector.connect(host=\"\",user=\"\",passwd=\"\",database=\"temp\")\n print(conn)\n mycursor=conn.cursor()\n for i in range(len(police)):\n sql=\"insert into temptable values(null,%s,%s);\"\n val=(police[i][1],temp['2'])\n mycursor.execute(sql, val)\n\n\n val=(\"teh\",temp['2'])\n mycursor.execute(sql, val)\n conn.commit()\n os.remove('/media/data/' + current)\n ","sub_path":"client-server/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"174847714","text":"import unittest\nimport pandas as pd\nimport numpy as np\nimport lima\nimport os\n\nclass LimaTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls._lima = lima.Lima(password=os.environ['LIMA_PASSWORD'])\n cls._lima.delete_frame('test')\n\n @classmethod\n def tearDownClass(cls):\n pass\n\nclass FrameTest(LimaTest):\n def setUp(self):\n f = pd.DataFrame(np.arange(12).reshape(3,4),columns=['a','b','c','d'],\n index=pd.date_range('1/1/2019',periods=3,freq='B'))\n FrameTest._lima.write_frame('test', f)\n\n def tearDown(self):\n FrameTest._lima.delete_frame('test')\n \n def test_read(self):\n f = FrameTest._lima.read_frame('test')\n self.assertEqual(f.shape[1], 4)\n self.assertEqual(f.shape[0], 3)\n self.assertEqual(f.sum().sum(), 66)\n\n def test_append_row(self):\n f = pd.DataFrame(np.arange(4).reshape(1,4),columns=['a','b','c','d'],\n index=pd.date_range('1/4/2019',periods=1,freq='B'))\n FrameTest._lima.write_frame('test', f)\n f = FrameTest._lima.read_frame('test')\n self.assertEqual(f.shape[1], 4)\n self.assertEqual(f.shape[0], 4)\n self.assertEqual(f.sum().sum(), 72)\n\n def test_append_row(self):\n f = pd.DataFrame(np.arange(3).reshape(3,1),columns=['e'],\n index=pd.date_range('1/1/2019',periods=3,freq='B'))\n FrameTest._lima.write_frame('test', f)\n f = FrameTest._lima.read_frame('test')\n self.assertEqual(f.shape[1], 5)\n self.assertEqual(f.shape[0], 3)\n self.assertEqual(f.sum().sum(), 69)\n\nclass SeriesTest(LimaTest):\n def setUp(self):\n s = pd.Series(np.arange(3), index=pd.date_range('1/1/2019',periods=3,freq='B'))\n SeriesTest._lima.write_series('test', s)\n\n def tearDown(self):\n SeriesTest._lima.delete_series('test')\n \n def test_read(self):\n s = SeriesTest._lima.read_series('test')\n self.assertEqual(len(s), 3)\n self.assertEqual(s.sum(), 3)\n\n def test_read_before(self):\n s = SeriesTest._lima.read_series('test', '2018-12-31')\n self.assertEqual(len(s), 4)\n self.assertEqual(s.iloc[0], 0)\n\n def test_read_after(self):\n s = SeriesTest._lima.read_series('test', stop='2019-01-05')\n self.assertEqual(len(s), 4)\n self.assertEqual(s.iloc[-1], 0)\n\n def test_append(self):\n a = pd.Series(np.arange(3), index=pd.date_range('1/4/2019',periods=3,freq='B'))\n SeriesTest._lima.write_series('test', a)\n s = SeriesTest._lima.read_series('test')\n self.assertEqual(len(s), 6)\n self.assertEqual(s.sum(), 6)\n\n def test_append_with_pad(self):\n a = pd.Series(np.arange(3), index=pd.date_range('1/5/2019',periods=3,freq='B'))\n SeriesTest._lima.write_series('test', a)\n s = SeriesTest._lima.read_series('test')\n self.assertEqual(len(s), 7)\n self.assertEqual(s.sum(), 6)\n\n def test_replace(self):\n a = pd.Series(10, index=pd.date_range('1/2/2019',periods=1,freq='B'))\n SeriesTest._lima.write_series('test', a)\n s = SeriesTest._lima.read_series('test')\n self.assertEqual(len(s), 3)\n self.assertEqual(s.sum(), 12)\n\n def test_prepend(self):\n a = pd.Series(np.arange(3), index=pd.date_range('12/31/2018',periods=3,freq='B'))\n SeriesTest._lima.write_series('test', a)\n s = SeriesTest._lima.read_series('test')\n self.assertEqual(len(s), 3)\n self.assertEqual(s.sum(), 3)\n\nclass MultiIndexFrameTest(LimaTest):\n\n def tearDown(self):\n MultiIndexFrameTest._lima.delete_frame('test')\n\n def test_square(self):\n index = pd.MultiIndex.from_product([pd.date_range('1/1/2019',periods=5,freq='B'),['x','y','z']])\n f = pd.DataFrame(np.arange(45).reshape(15,3),columns=['a','b','c'], index=index)\n MultiIndexFrameTest._lima.write_frame('test', f)\n f = MultiIndexFrameTest._lima.read_frame('test')\n f.loc['2019-01-07'].shape == (3,3)\n f.loc['2019-01-07'].iloc[2,2] == 44\n f.loc['2019-01-07','x']['a'] == 36\n\n def test_rect(self):\n index = pd.MultiIndex.from_product([pd.date_range('1/1/2019',periods=5,freq='B'),['x','y','z','aa','bb']])\n f = pd.DataFrame(np.arange(75).reshape(25,3),columns=['a','b','c'], index=index)\n MultiIndexFrameTest._lima.write_frame('test', f)\n f = MultiIndexFrameTest._lima.read_frame('test')\n f.loc['2019-01-07'].shape == (5,3)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"495834018","text":"import os\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n\ndef get_google_mobility_data(filename=None):\n \"\"\"Download Google Community mobility report data\n\n This function downloads, formats and returns the available Belgian Google Community mobility report data.\n A copy of the downloaded dataset is automatically saved in the /data/raw folder.\n \n Parameters\n -----------\n filename: string\n filename and extension to automatically save the generated visualisation of the data\n argument is optional\n\n Returns\n -----------\n dates : pd.DatetimeIndex\n datetimes for which a data point is available\n retail_recreation : np.array\n Mobility trends for places such as restaurants, cafés, shopping centres, theme parks, museums, libraries and cinemas.\n grocery : np.array\n Mobility trends for places such as grocery shops, food warehouses, farmers markets, specialty food shops and pharmacies.\n parks: np.array\n Mobility trends for places such as local parks, national parks, public beaches, marinas, dog parks, plazas and public gardens.\n transport: np.array\n Mobility trends for places that are public transport hubs, such as underground, bus and train stations.\n work: np.array\n Mobility trends for places of work.\n residential: np.array\n Mobility trends for places of residence.\n\n Notes\n ----------\n Mobility data can be extracted as a report for any country from: https://www.google.com/covid19/mobility/\n Dataset was downloaded from: 'https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv?cachebust=2dcf78defb92930a'\n Documentation by Google on data collection can be found here : https://www.google.com/covid19/mobility/data_documentation.html?hl=nl\n\n Example use\n -----------\n dates, retail_recreation, grocery, parks, transport, work, residential = get_google_mobility_data(filename='community_report.svg')\n \"\"\"\n\n # Data source\n url = 'https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv?cachebust=2dcf78defb92930a'\n\n # download raw data\n raw = pd.read_csv(url)\n # save a copy in the raw folder\n abs_dir = os.path.dirname(__file__)\n rel_dir = os.path.join(abs_dir, '../../../data/raw/google/community_mobility_data.csv')\n raw.to_csv(rel_dir,index=False)\n # Extract only Belgian data\n raw=raw[raw['country_region']=='Belgium']\n data=raw[raw['sub_region_1'].isnull().values]\n\n # Assign data to output variables\n retail_recreation=np.array(data.loc[:,'retail_and_recreation_percent_change_from_baseline'].tolist())\n grocery=np.array(data.loc[:,'grocery_and_pharmacy_percent_change_from_baseline'].tolist())\n parks=np.array(data.loc[:,'parks_percent_change_from_baseline'].tolist())\n transport=np.array(data.loc[:,'transit_stations_percent_change_from_baseline'].tolist())\n work=np.array(data.loc[:,'workplaces_percent_change_from_baseline'].tolist())\n residential=np.array(data.loc[:,'residential_percent_change_from_baseline'].tolist())\n dates = pd.date_range(data.astype(str)['date'].tolist()[0], freq='D', periods=residential.size)\n data_lst=[[retail_recreation,grocery],[parks,transport],[work,residential]]\n titleText=[['Retail and recreation','Groceries and pharmacy'],['Parks','Transit stations'],['Workplaces','Residential']]\n\n # using the variable axs for multiple Axes\n fig, ax = plt.subplots(3,2,figsize=(15,12))\n for i in range(3):\n for j in range(2):\n ax[i,j].plot(dates,data_lst[i][j])\n ax[i,j].axvline(x='13-03-2020',color='k',linestyle='--')\n ax[i,j].set_ylabel('% compared to baseline')\n # Hide the right and top spines\n ax[i,j].spines['right'].set_visible(False)\n ax[i,j].spines['top'].set_visible(False)\n # Only show ticks on the left and bottom spines\n ax[i,j].yaxis.set_ticks_position('left')\n ax[i,j].xaxis.set_ticks_position('bottom')\n # enable the grid\n ax[i,j].grid(True)\n # Set title\n ax[i,j].set_title(titleText[i][j],{'fontsize':18})\n # Format dateticks\n ax[i,j].xaxis.set_major_locator(mdates.MonthLocator())\n ax[i,j].xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d-%m-%Y'))\n ax[i,j].autoscale(enable=True)\n\n plt.tight_layout()\n\n if filename is not None:\n plt.savefig(filename,dpi=600,bbox_inches='tight',orientation='portrait',papertype='a4')\n else:\n plt.show()\n\n return dates,retail_recreation,grocery,parks,transport,work,residential","sub_path":"src/covid19model/data/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"208975121","text":"#!/usr/bin/env python3\n\"\"\"Module for parsing webpages for image links.\n\nContains methods and external modules required for fetching the HTML source\ncode from a webpage, and then parsing through it for links leading directly\nto images.\n\"\"\"\nimport re\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom pyimgscraper.helpers import ScrapeException\n\n\ndef get_html(url: str) -> bs:\n \"\"\"Gets HTML of a webpage.\n\n Takes an URL, and sends a HTTP get request to it, and returns the content\n of the request as a BeautifulSoup object.\n\n Args:\n url: URL to fetch the HTML from.\n\n Returns: Soup object of the HTML of an URL.\n\n \"\"\"\n source = requests.get(url)\n soup = bs(source.text, 'html.parser')\n return soup\n\n\ndef get_urls(soup: bs, regex: str) -> list[str]:\n \"\"\"Parse soup object of HTML for image links.\n\n Searches a BeautifulSoup object for every link matching to a regex\n pattern, and returns them as a list.\n\n Args:\n soup (bs): BeautifulSoup object of HTML.\n regex (str): (Raw) string representation of a regex pattern to search.\n\n Returns: List of image link URLs in string format.\n \"\"\"\n rex = re.compile(regex)\n tags = soup.findAll('a', attrs={'href': rex})\n links = [tag['href'] for tag in tags]\n if len(links) == 0:\n raise ScrapeException('No links found in the response!')\n return links\n","sub_path":"pyimgscraper/parse_links.py","file_name":"parse_links.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"157394937","text":"from OFS.SimpleItem import SimpleItem\nfrom plone.app.contentrules.browser.formhelper import AddForm, EditForm\nfrom plone.contentrules.rule.interfaces import IRuleElementData, IExecutable\nfrom Products.CMFPlone import PloneMessageFactory as _p\nfrom zope.formlib import form\nfrom zope.component import adapts\nfrom zope import interface\nfrom zope import schema\n\nfrom collective.favoriting.actions.vocabularies import favoritingChoice\nfrom collective.favoriting.browser.favoriting_view import VIEW_NAME\nfrom collective.favoriting.i18n import _\n\n\nclass IFavoritingAction(interface.Interface):\n \"\"\"Definition of the configuration available for a favoriting action.\"\"\"\n\n favoriting = schema.Choice(\n title=_(u\"Change favoriting\"),\n vocabulary=favoritingChoice\n )\n\n\nclass FavoritingAction(SimpleItem):\n interface.implements(IFavoritingAction, IRuleElementData)\n\n favoriting = 'favorite'\n element = 'collective.favoriting.actions.Favoriting'\n summary = _(u'Change if the object is in the user\\'s favorites or not.')\n\n\nclass FavoritingActionExecutor(object):\n interface.implements(IExecutable)\n adapts(interface.Interface, IFavoritingAction, interface.Interface)\n\n def __init__(self, context, element, event):\n self.context = context\n self.element = element\n self.event = event\n\n def __call__(self):\n favoriting = self.element.favoriting\n obj = self.event.object\n manager = obj.restrictedTraverse(VIEW_NAME)\n if not manager.isin():\n if favoriting == 'favorite':\n manager.add()\n else:\n manager.rm()\n return True\n\n\nclass FavoritingActionAddForm(AddForm):\n form_fields = form.FormFields(IFavoritingAction)\n label = _(u'Add favoriting action')\n description = _(u'An action which can add or remove an object '\n u'to the user favorites')\n form_name = _p(u'Configure element')\n\n def create(self, data):\n a = FavoritingAction()\n form.applyChanges(a, self.form_fields, data)\n return a\n\n\nclass FavoritingActionEditForm(EditForm):\n form_fields = form.FormFields(IFavoritingAction)\n label = _(u'Edit favoriting action')\n description = _(u'An action which can add or remove an object '\n u'to the user favorites')\n form_name = _p(u'Configure element')\n","sub_path":"collective/favoriting/actions/favoriting.py","file_name":"favoriting.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"459239230","text":"import turtle\nimport copy\nimport random\n\nscreen = turtle.Screen()\nscreen.setup(800, 800)\nscreen.title(\"Tic Tac Toe - PythonTurtle.Academy\")\nscreen.setworldcoordinates(-5, -5, 5, 5)\nscreen.bgcolor('light gray')\nscreen.tracer(0, 0)\nturtle.hideturtle()\n\n\ndef draw_board():\n turtle.pencolor('green')\n turtle.pensize(10)\n turtle.up()\n turtle.goto(-3, -1)\n turtle.seth(0)\n turtle.down()\n turtle.fd(6)\n turtle.up()\n turtle.goto(-3, 1)\n turtle.seth(0)\n turtle.down()\n turtle.fd(6)\n turtle.up()\n turtle.goto(-1, -3)\n turtle.seth(90)\n turtle.down()\n turtle.fd(6)\n turtle.up()\n turtle.goto(1, -3)\n turtle.seth(90)\n turtle.down()\n turtle.fd(6)\n\n\ndef draw_circle(x, y):\n turtle.up()\n turtle.goto(x, y - 0.75)\n turtle.seth(0)\n turtle.color('red')\n turtle.down()\n turtle.circle(0.75, steps=100)\n\n\ndef draw_x(x, y):\n turtle.color('blue')\n turtle.up()\n turtle.goto(x - 0.75, y - 0.75)\n turtle.down()\n turtle.goto(x + 0.75, y + 0.75)\n turtle.up()\n turtle.goto(x - 0.75, y + 0.75)\n turtle.down()\n turtle.goto(x + 0.75, y - 0.75)\n\n\ndef draw_piece(i, j, p):\n if p == 0: return\n x, y = 2 * (j - 1), -2 * (i - 1)\n if p == 1:\n draw_x(x, y)\n else:\n draw_circle(x, y)\n\n\ndef draw(b):\n draw_board()\n for i in range(3):\n for j in range(3):\n draw_piece(i, j, b[i][j])\n screen.update()\n\n\n# return 1 if player 1 wins, 2 if player 2 wins, 3 if tie, 0 if game is not over\ndef gameover(b):\n if b[0][0] > 0 and b[0][0] == b[0][1] and b[0][1] == b[0][2]: return b[0][0]\n if b[1][0] > 0 and b[1][0] == b[1][1] and b[1][1] == b[1][2]: return b[1][0]\n if b[2][0] > 0 and b[2][0] == b[2][1] and b[2][1] == b[2][2]: return b[2][0]\n if b[0][0] > 0 and b[0][0] == b[1][0] and b[1][0] == b[2][0]: return b[0][0]\n if b[0][1] > 0 and b[0][1] == b[1][1] and b[1][1] == b[2][1]: return b[0][1]\n if b[0][2] > 0 and b[0][2] == b[1][2] and b[1][2] == b[2][2]: return b[0][2]\n if b[0][0] > 0 and b[0][0] == b[1][1] and b[1][1] == b[2][2]: return b[0][0]\n if b[2][0] > 0 and b[2][0] == b[1][1] and b[1][1] == b[0][2]: return b[2][0]\n p = 0\n for i in range(3):\n for j in range(3):\n p += (1 if b[i][j] > 0 else 0)\n if p == 9:\n return 3\n else:\n return 0\n\n\ndef play(x, y):\n global turn\n if turn == 'x': return\n\n i = 3 - int(y + 5) // 2\n j = int(x + 5) // 2 - 1\n if i > 2 or j > 2 or i < 0 or j < 0 or b[i][j] != 0: return\n if turn == 'x':\n b[i][j], turn = 1, 'o'\n else:\n b[i][j], turn = 2, 'x'\n draw(b)\n r = gameover(b)\n if r == 1:\n screen.textinput(\"Game over!\", \"X won!\")\n elif r == 2:\n screen.textinput(\"Game over!\", \"O won!\")\n elif r == 3:\n screen.textinput(\"Game over!\", \"Tie!\")\n if r > 0: turtle.bye()\n _, move = max_node(b, -2, 2)\n b[move[0]][move[1]] = 1\n draw(b)\n r = gameover(b)\n if r == 1:\n screen.textinput(\"Game over!\", \"X won!\")\n elif r == 2:\n screen.textinput(\"Game over!\", \"O won!\")\n elif r == 3:\n screen.textinput(\"Game over!\", \"Tie!\")\n if r > 0: turtle.bye()\n turn = 'o'\n\n\nb = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\ndraw(b)\nturn = 'x'\nscreen.onclick(play)\n\n\n# turtle.mainloop()\n\ndef max_node(b, alpha, beta):\n r = gameover(b)\n if r == 1:\n return 1, None\n elif r == 2:\n return -1, None\n elif r == 3:\n return 0, None\n\n score = -2\n # find all possible next moves\n pm = list()\n for i in range(3):\n for j in range(3):\n if b[i][j] == 0: pm.append((i, j))\n random.shuffle(pm)\n for (i, j) in pm:\n if b[i][j] == 0:\n nb = copy.deepcopy(b)\n nb[i][j] = 1\n cs, _ = min_node(nb, alpha, beta)\n if score < cs:\n score = cs\n move = (i, j)\n alpha = max(alpha, cs)\n if alpha >= beta: return score, move\n return score, move\n\n\ndef min_node(b, alpha, beta):\n r = gameover(b)\n if r == 1:\n return 1, None\n elif r == 2:\n return -1, None\n elif r == 3:\n return 0, None\n\n score = 2\n # find all possible next moves\n pm = list()\n random.shuffle(pm)\n for i in range(3):\n for j in range(3):\n if b[i][j] == 0: pm.append((i, j))\n for (i, j) in pm:\n if b[i][j] == 0:\n nb = copy.deepcopy(b)\n nb[i][j] = 2\n cs, _ = max_node(nb, alpha, beta)\n if score > cs:\n score = cs\n move = (i, j)\n beta = min(beta, cs)\n if alpha >= beta : return score, move\n return score, move\n\n\n_, move = max_node(b, -2, 2)\nb[move[0]][move[1]] = 1\ndraw(b)\nturn = 1\nscreen.mainloop()","sub_path":"Tic Tac Toe Turtle.py","file_name":"Tic Tac Toe Turtle.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"642707038","text":"import pandas as pd\nimport os\nimport importlib\n\n\ndef load_corrupted_sentences_to_df(sent_df: pd.DataFrame,\n corrupted_text_file1: str, corrupted_text_file2: str, wer: float = 0.25):\n \"\"\"\n :param sent_df: DataFrame containing original sentences from corpus in columns labeled sent_1 and sent_2\n :param corrupted_text_file1: str path to text file with corrupted version of sent_1\n :param corrupted_text_file2: str path to text file with corrupted version of sent_2\n :return: sent_df_with_corrupted_sentences: DataFrame with 2 new columns containing corrupted sentences\n \"\"\"\n corrupted_sent_1 = pd.read_csv(corrupted_text_file1, sep='\\t', header=None)\n corrupted_sent_2 = pd.read_csv(corrupted_text_file2, sep='\\t', header=None)\n sent_df_with_corrupted_sentences = sent_df.copy()\n sent_df_with_corrupted_sentences['corrupted_sent_1'] = corrupted_sent_1\n sent_df_with_corrupted_sentences['corrupted_sent_2'] = corrupted_sent_2\n sent_df_with_corrupted_sentences['WER'] = wer\n return sent_df_with_corrupted_sentences\n\n\nif __name__ == \"__main__\":\n load_df = importlib.import_module('01_load_sentences')\n sentence_df = load_df.download_sick('https://raw.githubusercontent.com/alvations/stasis'\n '/master/SICK-data/SICK_train.txt', set_name='sick_train')\n corrupt_path1 = os.path.expanduser('~/data/sentences/corrupt/corrupted_sick_train_sent1.txt')\n corrupt_path2 = os.path.expanduser('~/data/sentences/corrupt/corrupted_sick_train_sent2.txt')\n sentence_df = load_corrupted_sentences_to_df(sentence_df, corrupt_path1, corrupt_path2)\n print('done!')\n","sub_path":"src/data/03_load_corrupted_sentences.py","file_name":"03_load_corrupted_sentences.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"53130272","text":"# Importación de flask\nimport datetime\nfrom flask import Flask, render_template, request, jsonify, redirect, make_response, abort\nfrom flask_cors import CORS\n#from flask_bootstrap import Bootstrap\n\n\n# Instaciación de la apliación\napp = Flask(__name__)\nCORS(app)\n#Bootstrap(app)\n\n\nclass Pg:\n paginachat = '
'\n paginachat += ''\n paginachat += ''\n paginachat += '
'\n paginachat += ''\n paginachat += '
'\n contenidoPagina = \"\"\n\n\n@app.route('/a')\ndef testing():\n abort(500, \"Esta es una respuesta\")\n\n\n@app.route('/b')\ndef testing2():\n abort(400)\n\n\n@app.route('/c')\ndef testing3():\n abort(418)\n\n\n@app.route('/d')\ndef testing4():\n redirect('/a')\n\n\n@app.route('/Cookie', methods=[\"POST\", \"GET\", \"TRACE\"])\ndef cookiefunc():\n print(request.cookies)\n return request.cookies\n\n\n@app.route(\"/getCookie\", methods=[\"GET\", \"POST\"])\ndef cookie():\n resp = make_response(render_template('cookie.html') + str({\"sesion\": \"evasion\"}))\n resp.set_cookie(\"sesion\", \"evasion\", httponly=True)\n return resp\n\n\n@app.route(\"/useCookie\", methods=[\"POST\"])\ndef usecookie():\n res = request.form.get(\"value\")\n coo = request.cookies\n if res is None:\n abort(400, \"no value\")\n else:\n rsult = str(coo) + res + \"\\n\" + render_template('cookie.html')\n print(rsult)\n return rsult\n\n\n\"\"\"\n@app.route(\"/\")\ndef index():\n return render_template(\"index_bootstrap.html\")\n\n\n@app.route(\"/signup\")\ndef signup():\n return render_template(\"signup_bootstrap.html\")\n\n\n@app.route(\"/dashboard\")\ndef dashboard():\n return render_template(\"dashboard_bootstrap.html\")\n\n\n@app.route(\"/login\")\ndef login():\n return render_template(\"login_bootstrap.html\")\n\"\"\"\n\n\n# Configuración - index\n@app.route('/foro')\ndef chat():\n return Pg.paginachat + Pg.contenidoPagina\n\n\n@app.route('/clear')\ndef borrarcontenido():\n Pg.contenidoPagina = \"\"\n return redirect(\"/\")\n\n\n@app.route('/postMensaje', methods=[\"POST\"])\ndef addchat():\n temp = request.form.get('content')\n Pg.contenidoPagina += \"
\" + str(temp).replace('<', '')\n return redirect(\"/\")\n\n\n# Ejecución\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=9090, debug=False)\n","sub_path":"Python/ScriptsAntiguos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"1767471","text":"\n## \n##\n## Interface to allow remote kerberos authentication via Multiplexor\n## \n##\n##\n##\n##\n## TODO: RPC auth type is not implemented or tested!!!!\n\nimport enum\nimport asyncio\n\nfrom aiosmb.authentication.spnego.asn1_structs import KRB5Token\nfrom minikerberos.gssapi.gssapi import get_gssapi, GSSWrapToken\nfrom minikerberos.protocol.asn1_structs import AP_REQ, AP_REP, TGS_REP\nfrom minikerberos.protocol.encryption import Enctype, Key, _enctype_table\n\nfrom mpnop.operator import MPNOPerator\n\nimport enum\nimport io\nimport os\n\nfrom asn1crypto.core import ObjectIdentifier\n\nclass KRB5_MECH_INDEP_TOKEN:\n\t# https://tools.ietf.org/html/rfc2743#page-81\n\t# Mechanism-Independent Token Format\n\n\tdef __init__(self, data, oid, remlen = None):\n\t\tself.oid = oid\n\t\tself.data = data\n\n\t\t#dont set this\n\t\tself.length = remlen\n\t\n\t@staticmethod\n\tdef from_bytes(data):\n\t\treturn KRB5_MECH_INDEP_TOKEN.from_buffer(io.BytesIO(data))\n\t\n\t@staticmethod\n\tdef from_buffer(buff):\n\t\t\n\t\tstart = buff.read(1)\n\t\tif start != b'\\x60':\n\t\t\traise Exception('Incorrect token data!')\n\t\tremaining_length = KRB5_MECH_INDEP_TOKEN.decode_length_buffer(buff)\n\t\ttoken_data = buff.read(remaining_length)\n\t\t\n\t\tbuff = io.BytesIO(token_data)\n\t\tpos = buff.tell()\n\t\tbuff.read(1)\n\t\toid_length = KRB5_MECH_INDEP_TOKEN.decode_length_buffer(buff)\n\t\tbuff.seek(pos)\n\t\ttoken_oid = ObjectIdentifier.load(buff.read(oid_length+2))\n\t\t\n\t\treturn KRB5_MECH_INDEP_TOKEN(buff.read(), str(token_oid), remlen = remaining_length)\n\t\t\n\t@staticmethod\n\tdef decode_length_buffer(buff):\n\t\tlf = buff.read(1)[0]\n\t\tif lf <= 127:\n\t\t\tlength = lf\n\t\telse:\n\t\t\tbcount = lf - 128\n\t\t\tlength = int.from_bytes(buff.read(bcount), byteorder = 'big', signed = False)\n\t\treturn length\n\t\t\n\t@staticmethod\n\tdef encode_length(length):\n\t\tif length <= 127:\n\t\t\treturn length.to_bytes(1, byteorder = 'big', signed = False)\n\t\telse:\n\t\t\tlb = length.to_bytes((length.bit_length() + 7) // 8, 'big')\n\t\t\treturn (128+len(lb)).to_bytes(1, byteorder = 'big', signed = False) + lb\n\t\t\n\t\t\n\tdef to_bytes(self):\n\t\tt = ObjectIdentifier(self.oid).dump() + self.data\n\t\tt = b'\\x60' + KRB5_MECH_INDEP_TOKEN.encode_length(len(t)) + t\n\t\treturn t[:-len(self.data)] , self.data\n\n\nclass ISC_REQ(enum.IntFlag):\n\tDELEGATE = 1\n\tMUTUAL_AUTH = 2\n\tREPLAY_DETECT = 4\n\tSEQUENCE_DETECT = 8\n\tCONFIDENTIALITY = 16\n\tUSE_SESSION_KEY = 32\n\tPROMPT_FOR_CREDS = 64\n\tUSE_SUPPLIED_CREDS = 128\n\tALLOCATE_MEMORY = 256\n\tUSE_DCE_STYLE = 512\n\tDATAGRAM = 1024\n\tCONNECTION = 2048\n\tCALL_LEVEL = 4096\n\tFRAGMENT_SUPPLIED = 8192\n\tEXTENDED_ERROR = 16384\n\tSTREAM = 32768\n\tINTEGRITY = 65536\n\tIDENTIFY = 131072\n\tNULL_SESSION = 262144\n\tMANUAL_CRED_VALIDATION = 524288\n\tRESERVED1 = 1048576\n\tFRAGMENT_TO_FIT = 2097152\n\tHTTP = 0x10000000\n\nclass SMBKerberosMPN:\n\tdef __init__(self, settings):\n\t\tself.iterations = 0\n\t\tself.settings = settings\n\t\tself.operator = settings.operator\n\t\tself.agent_id = settings.agent_id\n\t\tself.mode = 'CLIENT'\n\t\tself.ksspi = None\n\t\tself.client = None\n\t\tself.target = None\n\t\tself.gssapi = None\n\t\tself.etype = None\n\t\tself.session_key = None\n\t\tself.seq_number = None\n\t\t\n\t\tself.setup()\n\t\t\n\tdef setup(self):\n\t\treturn\n\n\tdef get_seq_number(self):\n\t\t\"\"\"\n\t\tFetches the starting sequence number. This is either zero or can be found in the authenticator field of the \n\t\tAP_REQ structure. As windows uses a random seq number AND a subkey as well, we can't obtain it by decrypting the \n\t\tAP_REQ structure. Insead under the hood we perform an encryption operation via EncryptMessage API which will \n\t\tyield the start sequence number\n\t\t\"\"\"\n\t\treturn self.seq_number\n\t\t\n\tasync def encrypt(self, data, message_no):\n\t\treturn self.gssapi.GSS_Wrap(data, message_no)\n\t\t\n\tasync def decrypt(self, data, message_no, direction='init', auth_data=None):\n\t\treturn self.gssapi.GSS_Unwrap(data, message_no, direction=direction, auth_data=auth_data)\n\t\n\tdef get_session_key(self):\n\t\treturn self.session_key\n\t\n\tasync def authenticate(self, authData = None, flags = None, seq_number = 0, is_rpc = False):\n\t\t#authdata is only for api compatibility reasons\n\t\tif self.operator is None:\n\t\t\t\tself.operator = MPNOPerator(self.settings.get_url())\n\t\t\t\tasyncio.create_task(self.operator.run())\n\t\t\t\tawait asyncio.wait_for(self.operator.connected_evt.wait(), timeout=self.settings.timeout)\n\t\tif self.ksspi is None:\n\t\t\tself.ksspi, err = await self.operator.create_sspi(self.agent_id)\n\t\t\tif err is not None:\n\t\t\t\treturn None, None, err\n\t\ttry:\n\t\t\tif is_rpc == True:\n\t\t\t\tif self.iterations == 0:\n\t\t\t\t\tflags = ISC_REQ.CONFIDENTIALITY | \\\n\t\t\t\t\t\t\tISC_REQ.INTEGRITY | \\\n\t\t\t\t\t\t\tISC_REQ.MUTUAL_AUTH | \\\n\t\t\t\t\t\t\tISC_REQ.REPLAY_DETECT | \\\n\t\t\t\t\t\t\tISC_REQ.SEQUENCE_DETECT|\\\n\t\t\t\t\t\t\tISC_REQ.USE_DCE_STYLE\n\t\t\t\t\t\n\t\t\t\t\tcontext_attributes, apreq, err = await self.ksspi.kerberos('cifs/%s' % self.settings.target, context_attributes = flags.value)\n\t\t\t\t\tif err is not None:\n\t\t\t\t\t\traise err\n\n\t\t\t\t\tself.iterations += 1\n\t\t\t\t\treturn apreq, True, None\n\t\t\t\t\n\t\t\t\telif self.iterations == 1:\n\t\t\t\t\tcontext_attributes, data, err = await self.ksspi.kerberos(target_name = 'cifs/%s' % self.settings.target, context_attributes = flags.value, token_data = authData)\n\t\t\t\t\tif err is not None:\n\t\t\t\t\t\treturn None, None, err\n\t\t\t\t\tself.session_key, err = await self.ksspi.get_sessionkey()\n\t\t\t\t\tif err is not None:\n\t\t\t\t\t\treturn None, None, err\n\t\t\t\t\t\t\n\t\t\t\t\taprep = AP_REP.load(data).native\n\t\t\t\t\tsubkey = Key(aprep['enc-part']['etype'], self.session_key)\n\t\t\t\t\tself.gssapi = get_gssapi(subkey)\n\n\t\t\t\t\tif aprep['enc-part']['etype'] != 23: #no need for seq number in rc4\n\t\t\t\t\t\traw_seq_data, err = await self.ksspi.get_sequenceno()\n\t\t\t\t\t\tif err is not None:\n\t\t\t\t\t\t\treturn None, None, err\n\t\t\t\t\t\tself.seq_number = GSSWrapToken.from_bytes(raw_seq_data[16:]).SND_SEQ\n\t\t\t\t\t\n\t\t\t\t\tself.iterations += 1\n\t\t\t\t\tawait self.ksspi.disconnect()\n\t\t\t\t\treturn data, False, None\n\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\traise Exception('SSPI Kerberos -RPC - auth encountered too many calls for authenticate.')\n\t\t\t\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tcontext_attributes, apreq, err = await self.ksspi.kerberos(target_name = 'cifs/%s' % self.settings.target)\n\t\t\t\t#print('MULTIPLEXOR KERBEROS SSPI, APREQ: %s ERROR: %s' % (apreq, res))\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\t\n\t\t\t\tself.session_key, err = await self.ksspi.get_sessionkey()\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tawait self.ksspi.disconnect()\n\n\t\t\t\treturn apreq, False, None\n\t\texcept Exception as e:\n\t\t\treturn None, None, err\n","sub_path":"aiosmb/authentication/kerberos/mpn.py","file_name":"mpn.py","file_ext":"py","file_size_in_byte":6299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"188940333","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 14 22:57:49 2015\n\n@author: zstechly\nTrying to make a costas loop in python instead of matlab\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft, fftshift\nfrom scipy import signal\n\nFs = 200e6;\nf = 10e6;\nphs = 0;\nlength = 50000;\nsig_rx = np.zeros(length)\nwave_cos = np.zeros(length)\nwave_sin = np.zeros(length)\ntheta = np.zeros(length+1)\nsig_rx_cos = np.zeros(length)\nsig_rx_sin = np.zeros(length)\nsig_cos_trail = np.zeros(10);\nsig_sin_trail = np.zeros(10);\nsig_result_mult = np.zeros(length)\nphi=0.8\nfreq_err = 3e3;\nmu = 0.001;\nfor x in range(length):\n sig_rx[x]=scipy.math.cos(2*scipy.math.pi*f/Fs*x+phi)\n\nplt.figure(1)\nplt.plot(20*np.log10(abs(fft(sig_rx))))\n\ncoeffs = scipy.signal.firwin(10,0.1);\n\n\n# now down convert it with sine / cosine\nfor x in range(1,length):\n wave_cos[x] = scipy.math.cos(2*np.pi*(f+freq_err)/Fs*x+theta[x])\n wave_sin[x] = scipy.math.sin(2*np.pi*(f+freq_err)/Fs*x+theta[x])\n sig_rx_cos[x] = sig_rx[x] * wave_cos[x];\n sig_rx_sin[x] = sig_rx[x] * wave_sin[x];\n sig_cos_trail[1:9] = sig_cos_trail[0:8];\n sig_sin_trail[1:9] = sig_sin_trail[0:8];\n sig_cos_trail[0] = sig_rx_cos[x]\n sig_sin_trail[0] = sig_rx_sin[x]\n sig_result_mult[x] = np.average(sig_cos_trail) * np.average(sig_sin_trail)\n theta[x+1] = theta[x] - mu*sig_result_mult[x]\n\n\nsig_rx_cos_filt = 2*signal.convolve(coeffs,sig_rx_cos);\nsig_rx_sin_filt = 2*signal.convolve(coeffs,sig_rx_sin);\n\nplt.figure(2)\nplt.plot(theta)\nplt.title(\"Theta\")\n\n\n#lets figure out slope\nslope = (theta[40000]-theta[20000]) / (40000-20000)*Fs/6e3\nprint(slope)\n\ncoeff_transpose = coeffs.T\n","sub_path":"references/costas.py","file_name":"costas.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"420715709","text":"import urllib.request # 웹브라우저에서 html문서를 얻어오기 위해 통신하기 위한 모듈\nfrom bs4 import BeautifulSoup # html문서 검색 모듈\nimport os\nimport re\n\n\ndef get_save_path():\n save_path = input('Enter the file name and file location : ')\n save_path = save_path.replace('\\\\', '/')\n\n # 폴더가 없으면 폴더를 만드는 작업\n if not os.path.isdir(os.path.split(save_path)[0]):\n os.mkdir(os.path.split(save_path)[0])\n\n return save_path\n\n\ndef fetch_list_url(page):\n params = []\n\n for cnt in range(1,page+1):\n list_url = \"http://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp\".format(cnt)\n ###여기에 스크롤링할 웹페이지의 url 을 붙여넣습니다.\n request_header = urllib.parse.urlencode({\"page\":cnt}) # page=1\n request_header = request_header.encode(\"utf-8\") # b'page=1' 이런 형식으로 바꿔줘야 함\n\n url = urllib.request.Request(list_url, request_header) # url 요청에 따른 http 통신 헤더값을 얻어낸다\n # request_header 를 써줘야 해당 페이지 url 불러옴\n # 이런 정보 불러옴\n res = urllib.request.urlopen(url).read().decode(\"utf-8\") # 영어가 아닌 한글을 담아내기 위한 문자셋인 유니코드 문자셋을\n # 사용해서 html 문서와 html 문서내의 한글을 res 변수에 담는다. (유니코드 안쓰면 글씨 다 깨짐)\n # < a href = \"JavaScript:onView ('20170504000603')\" title = \"주택가 무속인 미취학 아동 보호 \" > 주택가 무속인 미취학 아동보호 < / a >\n # 여기서 onView함수 안의 20170504000603 을 불러와야 함\n\n soup = BeautifulSoup(res, \"html.parser\") # res html 문서를 BeautifulSoup 모듈을 사용해서 검색할수있도록 설정\n\n for link in soup.find_all('li', class_='pclist_list_tit2'):\n try:\n\n params.append(re.sub('[^0-9]','',link.a[\"href\"])) # link.a[\"href\"] = link.find('a')[href]\n # '20170504000603'\n # params.append(re.search('[0-9]{14}', link.a[\"href\"]).group()) # 이렇게 해도 됨.\n # '20170504000603'\n except: #
처럼 비어있는 곳이 있기 때문에 try except를 사용해야 한다.\n continue\n # print(params)\n return params\n\ndef fetch_list_url2(page):\n params2 = fetch_list_url(page)\n f = open(get_save_path(),'w',encoding='utf-8')\n format_dic = {0: '============ 제목 ============',\n 1: '============ 날짜 ============',\n 2: '============ 민원 ============',\n 3: '============ 답변 ============',\n 4: '='*50+'\\n'}\n\n for param in params2:\n list_url = 'http://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_vie.jsp'\n request_header = urllib.parse.urlencode({'RCEPT_NO' : param })\n request_header = request_header.encode('utf-8')\n\n url = urllib.request.Request(list_url, request_header) # url 요청에 따른 http 통신 헤더값을 얻어낸다\n res = urllib.request.urlopen(url).read().decode(\"utf-8\") # 영어가 아닌 한글을 담아내기 위한 문자셋인 유니코드 문자셋을\n soup = BeautifulSoup(res, \"html.parser\") # res html 문서를 BeautifulSoup 모듈을 사용해서 검색할수있도록 설정\n\n soup2 = soup.find('div', class_='form_table')\n soup3 = soup2.find_all('td')\n\n for idx, script in enumerate(soup3):\n f.write(format_dic[idx] + '\\n' + script.get_text(strip=True, separator='\\n')+'\\n')\n f.write(format_dic[4]+'\\n')\n f.close()\n\nfetch_list_url2(50)\n\n","sub_path":"PythonClass/crawling/crawling(no_page).py","file_name":"crawling(no_page).py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"12438124","text":"from baike_spider import url_manager\r\nfrom baike_spider import html_downloader\r\nfrom baike_spider import html_parser\r\nfrom baike_spider import html_outputer\r\n\r\n\r\nclass SpiderMain(object):\r\n def __init__(self):\r\n self.urls = url_manager.UrlManager()\r\n self.downloader = html_downloader.HtmlDownloader()\r\n self.parser = html_parser.HtmlParser()\r\n self.outputer = html_outputer.HtmlOutputer()\r\n\r\n def craw(self, url):\r\n print('爬取页面')\r\n count = 1\r\n self.urls.addNewUrl(url)\r\n while self.urls.hasNewUrl():\r\n try:\r\n newUrl = self.urls.getNewUrl()\r\n print('爬取页面%s' % newUrl)\r\n htmlCont = self.downloader.download(newUrl)\r\n newUrls, newData = self.parser.parse(newUrl, htmlCont)\r\n self.urls.addNewUrls(newUrls)\r\n self.outputer.collectData(newData)\r\n if count == 10:\r\n break\r\n count += 1\r\n except:\r\n print('爬取失败')\r\n self.outputer.outputHtml()\r\n\r\n\r\nif __name__ == '__main__':\r\n root_url = 'http://baike.baidu.com/view/21087.htm'\r\n obj_spider = SpiderMain()\r\n obj_spider.craw(root_url)\r\n","sub_path":"baike_spider/spider_main.py","file_name":"spider_main.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"619768243","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-,\n# @File : jane.py\n# @Desc : \n# @Author: \n# @Time :\n# @Version: 1.0\n# @License : Copyright(C),Drcnet\nimport json\nimport re\nfrom jane import md\nfrom scrapy import Selector\nfrom pymongo import MongoClient\n\n\nclass Jane(object):\n\n def get_info(self, url, category, type):\n \"\"\"\n 请求并解析数据\n :param url:\n :return:\n \"\"\"\n res = md.requests_build(url)\n response = Selector(text=res.content.decode('utf-8', errors='ignore'))\n product_li_s = response.xpath('//div[@id=\"J_goodsList\"]/ul/li')\n for product_li in product_li_s:\n item = dict()\n item['product_price'] = product_li.xpath('.//div[@class=\"p-price\"]//text()').extract()\n item['product_price'] = ''.join(item['product_price']).strip() if item['product_price'] else ''\n item['product_id'] = product_li.xpath('./@data-sku').extract_first()\n item['product_img'] = product_li.xpath('.//div[@class=\"p-img\"]//img//@src').extract_first()\n item['product_detail_url'] = product_li.xpath('.//div[@class=\"p-img\"]//a//@href').extract_first()\n item['product_shop_name'] = product_li.xpath('.//a[@class=\"curr-shop hd-shopname\"]//@title').extract_first()\n item['product_shop_url'] = product_li.xpath('.//a[@class=\"curr-shop hd-shopname\"]//@href').extract_first()\n item['product_detail'] = product_li.xpath('.//div[@class=\"p-name p-name-type-2\"]//text()').extract()\n item['product_detail'] = ''.join(item['product_detail']).strip() if item['product_detail'] else ''\n item['product_category'] = category\n item['type'] = type\n item['cn'] = 'jd'\n item['_id'] = item.get('product_id')\n print(item)\n md.data_storage_mongodb(item)\n\n def run(self):\n \"\"\"\n 程序入口\n :return:\n \"\"\"\n goods_dict = {\n '美妆': ['口红', '粉底', '眉笔', '眼影', '遮暇'],\n '食品': ['辣条', '鸭脖', '薯片', '可乐', '瓜子'],\n '电子产品': ['手机', '耳机', '平板', '笔记本电脑', '音响'],\n '家电': ['冰箱', '空调', '洗衣机', '电视', '扫地机器人'],\n '包': ['行李箱', '双肩包', '挎包', '钱包', '电脑包']\n }\n for goods_cat, goods_list in goods_dict.items():\n for goods in goods_list:\n url = 'https://search.jd.com/Search?keyword={}'.format(goods)\n self.get_info(url, goods, goods_cat)\n\n\nif __name__ == \"__main__\":\n vu = Jane()\n vu.run()\n","sub_path":"2020spring/2018312276/EXAM/电商商品优选分析/电商商品优选分析/数据爬取清洗/jane/jane.py","file_name":"jane.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"496244113","text":"# Questão 11. Construa uma função que receba uma data no formato DD/MM/AAAA \n# e devolva uma string no formato D de mes_por_extenso de AAAA. Opcionalmente, \n# valide a data e retorne NULL caso a data seja inválida. (Pesquisar sobre \n# expressão regular para resolver a questão para validar o texto por extenso.)\n\nimport re\n\ndef mes_por_extenso(data):\n x = re.search(\"\\d{2}/\\d{2}/\\d{4}\", data)\n\n if x:\n\n dia, mes, ano = data.split('/')\n if mes == \"01\":\n print(dia,\"de Janeiro\",ano)\n elif mes == \"02\":\n print(dia,\"de Fevereiro\",ano)\n elif mes == \"03\":\n print(dia,\"de Março\",ano)\n elif mes == \"04\":\n print(dia,\"de Abril\",ano)\n elif mes == \"05\":\n print(dia,\"de Maio\",ano)\n elif mes == \"06\":\n print(dia,\"de Junho\",ano)\n elif mes == \"07\":\n print(dia,\"de Julho\",ano)\n elif mes == \"08\":\n print(dia,\"de Agosto\",ano)\n elif mes == \"09\":\n print(dia,\"de Setembro\",ano)\n elif mes == \"10\":\n print(dia,\"de Outubro\",ano)\n elif mes == \"11\":\n print(dia,\"de Novembro\",ano)\n elif mes == \"12\":\n print(dia,\"de Dezembro\",ano)\n else:\n print('Mês inválido')\n else:\n print('Não esta em formato DD/MM/AAAA')\n \ndata = input(\"Data em formato DD/MM/AAAA\\n\")\nmes_por_extenso(data)","sub_path":"ProgramsToRead/ExercisesLists/Lista05/Exer11Lista05.py","file_name":"Exer11Lista05.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"45972357","text":"import time\r\nimport picoweb\r\nimport sys\r\nimport pycom\r\nimport universal_functions\r\nfrom network import WLAN\r\nimport CentralController\r\nimport Room\r\nfrom data import zonelist,networklist,NodeParam,nodelist\r\n\r\n#Node Parameters:\r\n#Name set in boot\r\n#PW set in boot\r\n#Zone set in setupQ\r\n#Mode set in setupQ\r\n#Damper Position\r\n#Damper Command\r\n#Central Status\r\n#Damper Status\r\n#Room Status\r\n#Last Comm Central\r\n#Last Comm Room\r\n#Setpoint\r\n#Room Temp\r\n#Central Temp\r\n\r\n#placeholder for zone list\r\nzones = [\"Office\", \"Bedroom1\", \"Bedroom2\"]\r\n\r\nstart_time = time.time()\r\npycom.heartbeat(False)\r\nuf = universal_functions\r\nLastTime = {\"Central\":0,\"Room\":0,\"Damper\":0}\r\nFault = {\"Central\":0,\"Room\":0,\"Damper\":0}\r\n\r\nNodeParam['DamperPos'] = 0\r\nNodeParam['DamperCMD'] = 0\r\nNodeParam['CtrlStat'] = 0xFFA500\r\nNodeParam['RoomStat'] = 0xFFA500\r\nNodeParam['DmprStat'] = 0xFFA500\r\nNodeParam['LstComCtrl'] = 0\r\nNodeParam['LstComRoom'] = 0\r\nNodeParam['RoomSetPt'] = 70\r\n\r\nCommParam = {}\r\n\r\napp = picoweb.WebApp(None)\r\n\r\n@app.route(\"/\")\r\ndef index(req, resp):\r\n yield from picoweb.start_response(resp)\r\n yield from resp.awrite(\"Hello World!
setup
status
commissioning
\")\r\n\r\n@app.route(\"/setup\")\r\ndef index(req, resp):\r\n print(zonelist)\r\n yield from picoweb.start_response(resp, content_type = \"text/html\")\r\n yield from app.render_template(resp, \"setup.tpl\",(networklist, zonelist))\r\n yield from resp.awrite('index')\r\n\r\n@app.route(\"/setupQ\")\r\ndef query(req, resp):\r\n setuptime = time.time()\r\n queryString = req.qs\r\n parameters = uf.qs_parse(queryString)\r\n yield from resp.awrite('index'+ \"\\n\")\r\n for k,v in parameters.items():\r\n yield from resp.awrite(\"{0} : {1}\".format(k, v) + \"\\n\")\r\n NodeParam[k] = v\r\n\r\n print('Parameters')\r\n print(NodeParam)\r\n zone = parameters.get('Zone')\r\n if len(zone)>0:\r\n NodeParam['Zone']=zone.replace('+',\" \")\r\n name = NodeParam['Name'] + \"-\" + NodeParam['Zone']\r\n NodeParam['Name'] = name\r\n #uf.join_network(NodeParam['Network'],NodeParam['Network_PW'])\r\n #uf.updateRTC()\r\n uf.initialize_network(NodeParam['Name'], NodeParam['PW'])\r\n print(\"total time taken this loop: \", time.time() - setuptime)\r\n if NodeParam['Mode'] == 'Central':\r\n print(\"Central Controller!\")\r\n CentralController.CentralControlLoop()\r\n if NodeParam['Mode'] == 'Temperature':\r\n # the node should wait until it identifies a damper w/ matching zone\r\n print(\"Room!\")\r\n Room.PhoneHome()\r\n\r\n@app.route(\"/status\")\r\ndef html(req, resp):\r\n NodeParam['RoomTmp'] = uf.checktemp('22')\r\n queryString = req.qs\r\n if len(queryString) > 0:\r\n parameters = uf.qs_parse(queryString)\r\n NodeParam['RoomSetPt'] = parameters.get('RoomSetPt')\r\n print(\"new node param:\")\r\n print(NodeParam)\r\n yield from picoweb.start_response(resp, content_type = \"text/html\")\r\n yield from app.render_template(resp, \"status.tpl\", (NodeParam,))\r\n\r\n@app.route(\"/CentralStatus\")\r\ndef query(req, resp):\r\n pycom.heartbeat(False)\r\n if NodeParam.get(\"Mode\") == 'Damper':\r\n queryString = req.qs\r\n Central_Status = uf.qs_parse(queryString)\r\n print(\"Time Since last Room Update: \", time.time() - LastTime['Room'])\r\n print(\"Time Since last Central Update: \", time.time() - LastTime['Central'])\r\n LastTime['Central'] = time.time()\r\n\r\n print(\"Central Temp:\"+Central_Status['Temp'])\r\n\r\n color = [0x0000FF,0x007f00,0x7f0000]\r\n temp = uf.checktemp('22')\r\n if Central_Status['Fault'] == 'Blue':\r\n Fault['Central'] = color[0]\r\n\r\n if Central_Status['Fault'] == 'Green':\r\n Fault['Central'] = 0x007f00\r\n\r\n if Central_Status['Fault'] == 'Red':\r\n Fault['Central'] = 0x7f0000\r\n\r\n uf.blink(Fault)\r\n yield from picoweb.start_response(resp)\r\n yield from resp.awrite(\"Received, Central Temp: {} My Temp {}\".format(Central_Status['Temp'],temp))\r\n\r\n@app.route(\"/RoomStatus\")\r\ndef query(req, resp):\r\n pycom.heartbeat(False)\r\n if NodeParam.get(\"Mode\") == 'Damper':\r\n queryString = req.qs\r\n Room_Status = uf.qs_parse(queryString)\r\n print(\"Time Since last Central Update: \", time.time() - LastTime['Central'])\r\n print(\"Time Since last Room Update: \", time.time() - LastTime['Room'])\r\n LastTime['Room'] = time.time()\r\n\r\n Room_Status.get(\"Fault\")\r\n color = [0x0000FF,0x007f00,0x7f0000]\r\n if Room_Status.get(\"Fault\") == 'Blue':\r\n Fault['Room'] = color[0]\r\n if Room_Status.get(\"Fault\") == 'Green':\r\n Fault['Room'] = color[1]\r\n if Room_Status.get(\"Fault\") == 'Red':\r\n Fault['Room'] = color[2]\r\n uf.blink(Fault)\r\n yield from picoweb.start_response(resp)\r\n yield from resp.awrite(\"Received\")\r\n\r\n@app.route(\"/zones\")\r\ndef index(req, resp):\r\n yield from picoweb.start_response(resp)\r\n yield from resp.awrite(\"This Page Will Provide Information on Each Zone\")\r\n yield from resp.awrite('index')\r\n\r\n@app.route(\"/centralcontroller\")\r\ndef index(req, resp):\r\n yield from picoweb.start_response(resp)\r\n yield from resp.awrite(\"This Page Will Provide Information on Each Zone\")\r\n yield from resp.awrite('index')\r\n\r\n@app.route(\"/commissioning\")\r\ndef index(req, resp):\r\n yield from picoweb.start_response(resp, content_type = \"text/html\")\r\n yield from app.render_template(resp, \"commissioningsetup.tpl\",(zones,))\r\n\r\n@app.route(\"/commissioningmode\")\r\ndef index(req, resp):\r\n queryString = req.qs\r\n if len(queryString) > 0:\r\n parameters = uf.qs_parse(queryString)\r\n NodeParam['RoomSetPt'] = parameters.get('RoomSetPt')\r\n for k,v in parameters.items():\r\n CommParam[k] = v\r\n print(k,v)\r\n yield from picoweb.start_response(resp, content_type = \"text/html\")\r\n yield from app.render_template(resp, \"commissioningmode.tpl\",(CommParam,))\r\n\r\n@app.route(\"/damperadjust\")\r\ndef index(req, resp):\r\n yield from picoweb.start_response(resp, content_type = \"text/html\")\r\n yield from app.render_template(resp, \"damperadjust.tpl\")\r\n\r\n@app.route(\"/eject\")\r\ndef index(req, resp):\r\n yield from picoweb.start_response(resp)\r\n yield from resp.awrite(\"eject\")\r\n sys.exit()\r\n\r\napp.run(debug=True,host=\"192.168.4.1\")\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"499114007","text":"#!/usr/bin/env python\n\n# A number of functions to communicate with the Webfaction API for Hello World Devs projects. This module was built to be used on the Tyson Steele projects by Joe Karasek.\n\nclass Webfaction(object):\n def __init__(self, server, siteConfig):\n self.siteConfig = siteConfig\n self.server = server\n self.session_id, self.account = server.login(\n \tsiteConfig.userName,\n \tsiteConfig.userPass,\n \tsiteConfig.machineName,\n \t1)\n\n def checkApp(self):\n appList = self.server.list_apps(self.session_id)\n for app in appList:\n if self.siteConfig.appName == app['name']:\n return True\n return False\n\n def createApp(self, appType='static_php56'):\n self.server.create_app(\n \t\tself.session_id,\n \t\tself.siteConfig.appName,\n \t\tappType,\n \t\tFalse,\n \t\t'',\n \t\tFalse)\n\n def checkSite(self):\n websiteList = self.server.list_websites(self.session_id)\n for website in websiteList:\n \tif self.siteConfig.websiteName == website['name']:\n \t\treturn website\n return False\n\n def createSite(self):\n self.server.create_website(self.session_id,\n \t\tself.siteConfig.websiteName,\n \t\tself.siteConfig.ipAddress,\n \t\tFalse,\n \t\t[self.siteConfig.domainName],\n \t\t[self.siteConfig.appName, '/'])\n\n def checkDomain(self):\n domainList = self.server.list_domains(self.session_id)\n for domain in domainList:\n \tif domain['domain'] == self.siteConfig.domainName:\n \t\treturn True\n return False\n\n def createDomain(self):\n self.server.create_domain(\n \t\tself.session_id,\n \t\tself.siteConfig.domainName)\n\n def gitClone(self):\n initGit = \"cd /home/danlinn/webapps/\"+self.siteConfig.appName+\" && if [ -e index.html ]; then rm index.html; fi && git clone -q \" + self.siteConfig.repoUrl + \" . 2>&1 | grep -v 'warning: You appear to have cloned an empty repository.'\"\n self.server.system(self.session_id, initGit)\n\n def gitPull(self):\n gitPull = \"cd /home/danlinn/webapps/\"+self.siteConfig.appName+\" && git pull -q origin master\"\n self.server.system(self.session_id, gitPull)\n\n # def addHtaccess(server, session_id, siteConfig):\n","sub_path":"scripts/hwdevs.py","file_name":"hwdevs.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"109596690","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.http import JsonResponse, HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\n\n# Create your views here.\nfrom django.views.decorators.http import require_POST\n\nfrom actions.utils import create_action\nfrom common.decorators import ajax_required\nfrom images.forms import ImageCreateForm\nfrom images.models import Image\n\n\n@login_required\ndef image_create(req):\n if req.method == 'POST':\n form = ImageCreateForm(req.POST)\n if form.is_valid():\n cd = form.cleaned_data\n new_item = form.save(False)\n new_item.user = req.user\n new_item.save()\n create_action(req.user, 'Bookmarked image', new_item)\n messages.success(req, 'Image berhasil ditambah')\n return redirect(new_item.get_absolute_url())\n else:\n form = ImageCreateForm(req.GET)\n\n cx = {\n 'section': 'images',\n 'formKey': form\n }\n\n return render(req, 'images/create.html', cx)\n\n\ndef image_detail(req, img_id, slug):\n image = get_object_or_404(Image, id=img_id, slug=slug)\n image.total_view = image.total_view.__add__(1)\n image.save()\n cx = {\n 'section': 'images',\n 'imageKey': image,\n 'totalViewKey': image.total_view,\n }\n return render(req, 'images/detail.html', cx)\n\n\n# Build custom decorators for your views if you find that you are repeating the same checks in multiple views.\n@ajax_required\n@login_required\n@require_POST\ndef image_like(req):\n image_id = req.POST.get('id')\n action = req.POST.get('action')\n if image_id and action:\n try:\n image = Image.objects.get(id=image_id)\n if action == 'like':\n image.users_like.add(req.user)\n create_action(req.user, 'likes', image)\n else:\n image.users_like.remove(req.user)\n return JsonResponse({'status': 'ok'})\n\n except Image.DoesNotExist:\n pass\n\n return JsonResponse({'status': 'error'})\n\n\n@login_required\ndef image_list(req):\n img = Image.objects.all()\n paginator = Paginator(img, 8)\n page = req.GET.get('page')\n try:\n img = paginator.page(page)\n except PageNotAnInteger:\n img = paginator.page(1)\n except EmptyPage:\n if req.is_ajax():\n return HttpResponse('')\n img = paginator.page(paginator.num_pages)\n\n cx = {\n 'section': 'images',\n 'imgKey': img,\n }\n\n if req.is_ajax():\n return render(req, 'images/list_ajax.html', cx)\n\n return render(req, 'images/list.html', cx)\n\n\n@login_required\ndef image_ranking(req):\n image_rank = Image.objects.all().order_by('-total_view')\n most_viewed = list(image_rank)\n cx = {\n 'section': 'images',\n 'mostViewedKey': most_viewed,\n }\n return render(req, 'images/ranking.html', cx)\n","sub_path":"antoniomele_bookmarks/images/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"609896362","text":"# -*- coding:utf-8 -*-\r\nimport json, settings\r\nimport chengeHanToZen\r\nimport raritysArray\r\nimport re\r\nimport sys\r\nfrom requests_oauthlib import OAuth1Session\r\nfrom janome.tokenizer import Tokenizer\r\n\r\n\r\n\"\"\"\r\nカード名をtxtから全て取得\r\n\"\"\"\r\ndef getCardList():\r\n cardList = []\r\n f = open('cardListReplaced.txt', encoding='utf-8')\r\n listnames = f.readline()\r\n while listnames:\r\n cardList.append(listnames.replace('\\n', ''))\r\n listnames = f.readline()\r\n f.close()\r\n return cardList\r\n\r\n\r\n\"\"\"\r\n形態素解析にかけた行からカード名の一部と思われる部分のみを抜き出し、それを配列にして返す\r\n\"\"\"\r\ndef matchPieses(lineAnalyze):\r\n restoreArray = []\r\n for token in lineAnalyze:\r\n partOfSpeech0 = token.part_of_speech.split(',')[0]\r\n partOfSpeech2 = token.part_of_speech.split(',')[2]\r\n\r\n #名詞、組織でない部分は除外\r\n if partOfSpeech0 != u'名詞':\r\n continue\r\n if partOfSpeech2 == u'組織':\r\n continue\r\n\r\n #「・」や「ー」のせいでうまく検索できない可能性があるため、空白に置き換える\r\n result = token.surface.replace('・', '')\r\n\r\n #半角カナを全角に、全角英字を半角に変換\r\n chengedResult = chengeHanToZen.Han2Zen(result, chengeHanToZen.KANA)\r\n chengedResult = chengeHanToZen.Zen2Han(chengedResult, chengeHanToZen.ASCII|chengeHanToZen.DIGIT)\r\n\r\n #配列として抽出要素を保存\r\n restoreArray.append(chengedResult)\r\n return restoreArray\r\n\r\n\r\n\"\"\"\r\nカードリストからツイートにあった文字を完全に含んでるカード名を取り出す\r\n\"\"\"\r\ndef checkList(pieces, cardList, pieceNumber):\r\n resultCardList = [] #検索してヒットしたカード名を保存するリスト\r\n nextNumber = pieceNumber + 1 #配列の次\r\n\r\n if pieces == []: #ツイートにあった言葉の配列が空だったら存在しないと返す\r\n return 'not exist'\r\n\r\n for name in cardList:\r\n #ツイートにあった言葉が入っている名前があれば別配列に保存\r\n if name.find(pieces[pieceNumber]) >= 0:\r\n resultCardList.append(name)\r\n\r\n #カード名がただ一つに決まった場合は、決まった段階の言葉「以降」の言葉を別の配列に入れて返す\r\n if len(resultCardList) == 1:\r\n notNamePieces = pieces[nextNumber:]\r\n unionArray = []\r\n unionArray.append(resultCardList[0])\r\n unionArray.append(notNamePieces)\r\n return unionArray\r\n\r\n #ツイートにあった言葉を検索し終え、かつ残ったカード名が一件ならそれを、一件でなければ存在しないことを返す\r\n if len(pieces) == nextNumber:\r\n return 'not exist'\r\n\r\n #条件に合致しなければ検索結果のリストで再帰\r\n if len(resultCardList) > 0:\r\n return checkList(pieces, resultCardList, nextNumber)\r\n else:\r\n return 'not exist'\r\n\r\n\r\n\"\"\"\r\n買取金額のみを取り出す\r\n\"\"\"\r\ndef onlyValues(notNamePieces, pattern):\r\n value = []\r\n\r\n for checkNow in notNamePieces:\r\n\r\n rarityPattern = pattern\r\n if re.findall(rarityPattern, checkNow) != []:\r\n break\r\n\r\n #'円'や'\\'が含まれている可能性があるので、正規表現で数字のみ取得\r\n pattern = r'([0-9]+)'\r\n value = re.findall(pattern, checkNow)\r\n\r\n if value != []:\r\n return value[0]\r\n\r\n return \"No Value\"\r\n\r\n\r\n\"\"\"\r\n対象のカード名の買取金額のみの配列を作成\r\n\"\"\"\r\ndef makeNewArrayOfValue(nameAndValuesArray, checkWord, pattern):\r\n onlyValuesArray = []\r\n for nameAndValuesArray in results:\r\n\r\n #検索対象と同じ名前のカードのみに処理をする\r\n if nameAndValuesArray[0] == checkWord:\r\n values = onlyValues(nameAndValuesArray[1], pattern)\r\n if values != \"No Value\": #平均計算の際に邪魔なのでここで減らす\r\n value = int(values)\r\n #「1900,3200」など「,」でレアリティの区別をつけている際、前処理で,を消しているために「19003200」となってしまう\r\n #そのため、金額の上限を定めて回避する\r\n #また、一桁のデータが紛れ込むこともあるので回避\r\n if value < 999999:\r\n if value > 10:\r\n onlyValuesArray.append(value)\r\n\r\n return onlyValuesArray\r\n\r\n\r\n\"\"\"\r\n平均計算\r\n\"\"\"\r\ndef calcAve(data):\r\n sum = 0\r\n for value in data:\r\n print(value)\r\n sum += value\r\n return int(sum / len(data))\r\n\r\n\r\n\"\"\"\r\n初期設定\r\n\"\"\"\r\nCK = settings.CONSUMER_KEY\r\nCS = settings.CONSUMER_SECRET\r\nAT = settings.ACCESS_TOKEN\r\nATS = settings.ACCESS_TOKEN_SECRET\r\ntwitter = OAuth1Session(CK, CS, AT, ATS)\r\n\r\nurl = \"https://api.twitter.com/1.1/search/tweets.json?tweet_mode=extended\"\r\n\r\ntweetlines = [] #抽出した文字群を入れる配列\r\nresults = [] #検索して一致したものを入れる配列\r\nyugiohList = getCardList()\r\n\r\n\r\n\"\"\"\r\n入力に関する部分\r\n\"\"\"\r\nprint(\"調べたいカード名を入力してください\")\r\nwhile True:\r\n checkWord = \"\" #検索対象の名前を保存しておくため\r\n yesOrNo = \"\"\r\n keyword = input('>>')\r\n\r\n for cardName in yugiohList:\r\n if cardName.find(keyword) >= 0:\r\n print(\"「\" + cardName + \"」\")\r\n checkWord = cardName\r\n break\r\n\r\n if checkWord != \"\":\r\n print(\"このカードでよろしいですか?\")\r\n print(\"よろしければ「Y」、間違っていれば「N」を入力してください\")\r\n yesOrNo = input('>>')\r\n\r\n if yesOrNo == \"Y\" or yesOrNo == \"y\" or yesOrNo == \"Y\" or yesOrNo == \"y\":\r\n print(\"検索��開始します\")\r\n break\r\n\r\n elif yesOrNo == \"N\" or yesOrNo == \"n\" or yesOrNo == \"N\" or yesOrNo == \"n\":\r\n print(\"再入力してください\")\r\n\r\n else:\r\n print(\"無効な入力がありました\")\r\n print(\"プログラムを終了します\")\r\n sys.exit(0)\r\n\r\n else:\r\n print(\"一致する検索結果が見つかりませんでした\")\r\n print(\"再入力してください\")\r\n\r\n\r\n\"\"\"\r\n検索から除くレアリティを表す文字列を指定する\r\n\"\"\"\r\narraysArray = []\r\narraysArray.append(raritysArray.yugiohSecret)\r\narraysArray.append(raritysArray.yugiohAsia)\r\n\r\npattern = r'('\r\nfor array in arraysArray:\r\n for rarity in array:\r\n pattern += '^' + rarity + '$'\r\n if rarity != array[-1]:\r\n pattern += '|'\r\npattern += ')'\r\n\r\n\r\n\"\"\"\r\nTwitterでの検索\r\n\"\"\"\r\nkeyword = keyword + ' 買取 遊戯王 -rt'\r\nparams = {'q' : keyword, 'count' : 100}\r\nreq = twitter.get(url, params = params)\r\n\r\nif req.status_code == 200:\r\n search_timeline = json.loads(req.text)\r\n\r\n \"\"\"\r\n 言語処理開始\r\n \"\"\"\r\n t = Tokenizer(mmap=True)\r\n for tweet in search_timeline['statuses']:\r\n print('----------------------------------------------------')\r\n\r\n print(tweet['full_text'])\r\n tweet = tweet['full_text'].replace(\",\", \"\")\r\n splitedTweet = tweet.split('\\n') #ツイートを改行で分割\r\n\r\n #分割した文字列について回す\r\n for matchline in splitedTweet:\r\n lineAnalyze = t.tokenize(matchline) #形態素解析を実行\r\n\r\n #抽出できた文字群を格納\r\n restoreArray = matchPieses(lineAnalyze)\r\n tweetlines.append(restoreArray)\r\n\r\n #一行ごとのカード名要素ごとにカードリストを検索\r\n for lines in tweetlines:\r\n checkResult = checkList(lines, yugiohList, 0)\r\n #存在していたら配列に加える\r\n if checkResult != 'not exist':\r\n results.append(checkResult)\r\n\r\n\r\n #確認用\r\n print('$----------------------------------------------------$')\r\n onlyValueArray = makeNewArrayOfValue(results, checkWord, pattern)\r\n print(checkWord + \"の平均買取金額は\"+ str(calcAve(onlyValueArray)) + \"円です\")\r\n print(\"また、最高値は\" + str(max(onlyValueArray)) + \"円です\")\r\nelse:\r\n print(\"ERROR: %d\" % req.status_code)","sub_path":"searchOnTwitter.py","file_name":"searchOnTwitter.py","file_ext":"py","file_size_in_byte":8405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"215055080","text":"from django.views.generic import View\nfrom django.shortcuts import render, redirect, Http404, HttpResponse\nfrom django.db import transaction, IntegrityError\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom home.util_home import HomeUtil\nfrom home.util_request import RequestUtil\nfrom home.utils import MessageCenter, Pagination\n\nfrom .util_student import StudentContainer\n\n\n@login_required(login_url='/')\ndef index_view(request):\n\n if request.method == 'GET':\n app_page = request.GET.get('ap', 1)\n e_page = request.GET.get('ep', 1)\n p_page = request.GET.get('pp', 1)\n student = StudentContainer(request.user)\n if student.get_student() is None:\n return redirect('student:new')\n msgs = MessageCenter.get_messages('student', student.get_student())\n a = student.get_applications()\n apps = Pagination(a if a else [], 15)\n events = Pagination(student.get_saved_events(), 15)\n posts = Pagination(student.get_newest_posts(), 5)\n context = {\n 'student': student.get_student(),\n 'applications': apps.get_page(app_page),\n 'old_apps': student.get_old_applications(),\n 'events': events.get_page(e_page),\n 'posts': posts.get_page(p_page),\n 'resumes': student.get_resumes(),\n 'messages': msgs,\n 'notifications': MessageCenter.get_notifications('student', student.get_student()),\n 'tab': 'home',\n }\n MessageCenter.clear_msgs(msgs)\n return render(request, 'student/index.html', context)\n\n raise Http404\n\n\nclass NewStudentView(LoginRequiredMixin, View):\n template_name = 'student/student_form.html'\n login_url = '/'\n redirect_field_name = 'redirect_to'\n\n def get(self, request):\n context = {\n 'countries': HomeUtil.get_countries(),\n 'states': HomeUtil.get_states(),\n 'programs': HomeUtil.get_student_programs(),\n 'majors': HomeUtil.get_majors(),\n }\n return render(request, self.template_name, context)\n\n def post(self, request):\n student = StudentContainer(request.user)\n rq = RequestUtil()\n i = rq.get_student_info(request)\n context = {\n 'countries': HomeUtil.get_countries(),\n 'states': HomeUtil.get_states(),\n 'programs': HomeUtil.get_student_programs(),\n 'majors': HomeUtil.get_majors(),\n }\n if i:\n\n try:\n with transaction.atomic():\n if student.new_student(i, request.user):\n m = 'Student profile created successfully.'\n MessageCenter.new_message('student', student.get_student(), 'success', m)\n return redirect('student:index')\n else:\n raise IntegrityError\n except IntegrityError:\n context['student'] = i\n context['errors'] = student.get_form().errors\n\n else:\n context['errors'] = rq.get_errors()\n\n return render(request, self.template_name, context)\n\n\nclass EditStudentView(LoginRequiredMixin, View):\n template_name = 'student/student_form.html'\n login_url = '/'\n redirect_field_name = 'redirect_to'\n\n def get(self, request):\n student = StudentContainer(request.user)\n context = {\n 'student': student.get_student(),\n 'countries': HomeUtil.get_countries(),\n 'states': HomeUtil.get_states(),\n 'programs': HomeUtil.get_student_programs(),\n 'majors': HomeUtil.get_majors(),\n 'tab': 'profile',\n }\n return render(request, self.template_name, context)\n\n def post(self, request):\n student = StudentContainer(request.user)\n rq = RequestUtil()\n i = rq.get_student_info(request)\n context = {\n 'student': student.get_student(),\n 'countries': HomeUtil.get_countries(),\n 'states': HomeUtil.get_states(),\n 'programs': HomeUtil.get_student_programs(),\n 'majors': HomeUtil.get_majors(),\n 'tab': 'profile',\n }\n if i:\n\n try:\n with transaction.atomic():\n if student.edit_student(i):\n m = 'Student profile edited successfully.'\n MessageCenter.new_message('student', student.get_student(), 'success', m)\n return redirect('student:index')\n else:\n raise IntegrityError\n except IntegrityError:\n context['errors'] = student.get_form().errors\n\n else:\n context['errors'] = str(rq.get_errors())\n\n return render(request, self.template_name, context)\n\n\n@login_required(login_url='/')\ndef history_view(request):\n\n if request.method == 'GET':\n app_page = request.GET.get('ap', 1)\n e_page = request.GET.get('ep', 1)\n n_page = request.GET.get('np', 1)\n student = StudentContainer(request.user)\n if student.get_student() is None:\n return redirect('student:new')\n ap = Pagination(student.get_all_applications(), 10)\n ep = Pagination(student.get_all_saved_events(), 10)\n np = Pagination(list(MessageCenter.get_all_notifications('student', student.get_student())), 10)\n context = {\n 'student': student.get_student(),\n 'all_notifications': np.get_page(n_page),\n 'applications': ap.get_page(app_page),\n 'events': ep.get_page(e_page),\n 'tab': 'history',\n }\n return render(request, 'student/history.html', context)\n\n raise Http404\n\n\n@login_required(login_url='/')\ndef profile_view(request):\n\n if request.method == 'GET':\n student = StudentContainer(request.user)\n if student.get_student() is None:\n return redirect('student:new')\n else:\n s = student.get_student()\n context = {\n 'student': s,\n 'user': student.get_user(),\n 'notifications': MessageCenter.get_notifications('student', s),\n 'tab': 'profile'\n }\n return render(request, 'student/profile.html', context)\n\n raise Http404\n\n\n@login_required(login_url='/')\ndef student_not_new(request):\n\n if request.method == 'GET':\n student = StudentContainer(request.user)\n if student.not_new():\n return HttpResponse('good', status=200)\n else:\n return HttpResponse(str(student.get_errors()), status=400)\n\n raise Http404\n\n\n#\n#\n# API VIEWS\n#\n#\n\n","sub_path":"student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"114521710","text":"def fatorial(n, show=False):\n \"\"\"\n -> Calculando o fatorial de um numero.\n :param n: o numero a ser calculado.\n :param show: (opcional) Mostrar ou nao a conta.\n :return: o valor do fatorial de um numero n.\n \"\"\"\n f = 1\n for c in range(n, 0, -1):\n if show:\n if c >1:\n print(f'{c} x ', end='')\n else:\n print(' = ', end='')\n f *= c\n return f\n\n\n\n# programa principal\n#print(fatorial(5, show=True))\nhelp(fatorial)","sub_path":"exercicios/ex102.py","file_name":"ex102.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"88010897","text":"#!/usr/bin/env python\r\nfrom random import randint, sample, uniform\r\nfrom acme import Product\r\n\r\nADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']\r\nNOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', 'Computer']\r\n\r\n\r\ndef generate_products(num_products=30) -> list:\r\n \"\"\"Generates a list of 30 products\"\"\"\r\n products = []\r\n for i in range(num_products):\r\n prod = Product(f'{ADJECTIVES[randint(0,4)]} {NOUNS[randint(0,4)]}')\r\n prod.weight = randint(5,100)\r\n prod.price = randint(5,100)\r\n prod.flammability = uniform(0.0,2.5)\r\n products.append(prod)\r\n return products\r\n\r\n\r\ndef _build_report_metrics(products):\r\n \"\"\"Builds unique_names count, average_price, average_weight, average_flam to send to\r\n the inventory report function\"\"\"\r\n unique_names = len(set([i.name for i in products]))\r\n average_price = sum([i.price for i in products]) / len(products)\r\n average_weight = sum([i.weight for i in products]) / len(products)\r\n average_flam = sum([i.flammability for i in products]) / len(products)\r\n\r\n return unique_names, average_price, average_weight, average_flam\r\n\r\n\r\ndef inventory_report(products: list) -> str:\r\n \"\"\"Gives a detailed report on created products\"\"\"\r\n unique_names, average_price, average_weight, average_flam = _build_report_metrics(products)\r\n\r\n report = f'''ACME CORPORATION OFFICIAL INVENTORY REPORT\r\n Unique product names: {unique_names}\r\n Average price: {average_price}\r\n Average weight: {average_weight}\r\n Average flammability: {average_flam}'''\r\n \r\n return print(report)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n inventory_report(generate_products())","sub_path":"lambdata_Vincent_Emma/acme_report.py","file_name":"acme_report.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"44914969","text":"\"\"\"\n 166 - Fraction to Recurring Decimal\n @author oneshan\n @version 1.0 3/8/2017\n\"\"\"\n\n\nclass Solution(object):\n def fractionToDecimal(self, numerator, denominator):\n \"\"\"\n :type numerator: int\n :type denominator: int\n :rtype: str\n \"\"\"\n\n # Note: -50 / 8 = -6.25\n isNeg = (numerator * denominator) < 0\n numerator = abs(numerator)\n denominator = abs(denominator)\n\n q = numerator / denominator\n r = numerator % denominator\n\n # Case 1 -- without fractional part\n if r == 0:\n return ('', '-')[isNeg] + str(q)\n\n ans = [str(q), '.']\n table = {}\n idx = len(ans)\n\n while True:\n # Case 2 -- the fractional part does not repeat\n if r == 0:\n break\n\n r *= 10\n q = r / denominator\n\n # Case 3 -- the fractional part is repeating\n if r in table:\n ans.insert(table[r], '(')\n ans.append(')')\n break\n\n ans.append(str(q))\n table[r] = idx\n idx += 1\n r = r % denominator\n\n return ('', '-')[isNeg] + \"\".join(ans)\n","sub_path":"leetcode/166_fractionToRecurringDecimal.py","file_name":"166_fractionToRecurringDecimal.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"610532773","text":"import json\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n#matplotlib config\ndef matplotlib_setup(figsize_x=8.3, figsize_y=4.2):\n import matplotlib as mpl\n cmap = cm.jet\n mpl.rcParams['axes.labelsize'] = 9\n mpl.rcParams['xtick.labelsize'] = 9\n mpl.rcParams['ytick.labelsize'] = 9\n mpl.rcParams['legend.fontsize'] = 9\n #rcParams['font.family'] = 'serif'\n #rcParams['font.serif'] = ['Computer Modern Roman']\n #mpl.rcParams['text.usetex'] = True\n mpl.rcParams['figure.figsize'] = 7.3, 4.2\n mpl.rcParams['axes.labelweight'] = 'bold'\n mpl.rcParams['font.weight'] = 'bold'\n mpl.rcParams['axes.linewidth'] = 0.75 \n mpl.rcParams['lines.linewidth'] = 2\n mpl.rcParams['axes.linewidth'] = 0.75 \n mpl.rcParams['lines.linewidth'] = 2\n mpl.rcParams['lines.markersize'] = 8\n mpl.rcParams['legend.numpoints'] = 1\n # figure size in inch\n mpl.rcParams['figure.figsize'] = figsize_x, figsize_y\n # figure dots per inch\n mpl.rcParams['figure.dpi'] = 300\n mpl.rcParams['figure.autolayout'] = True\n \n#Load curve data\nperco = []; rand = []; corre = []; std_perco = []; std_rand = []; std_corre = []\nwith open('.\\percentage_percolation.json', \"r\") as fichier:\n perco = json.load(fichier)\nwith open('.\\std_percolation.json', \"r\") as fichier:\n std_perco = json.load(fichier)\nwith open('.\\percentage_random.json', \"r\") as fichier:\n rand = json.load(fichier)\nwith open('.\\std_random.json', \"r\") as fichier:\n std_rand = json.load(fichier)\nwith open('.\\percentage_correlated.json', \"r\") as fichier:\n corre = json.load(fichier)\nwith open('.\\std_correlated.json', \"r\") as fichier:\n std_corre = json.load(fichier)\t\n\n#make the plot\nmatplotlib_setup(4,3)\nPmax = 12; phi = 0.15\n\naxes = plt.gca()\naxes.set_ylim([0,3])\nplt.rc('text', usetex=True)\nplt.errorbar( range(11)[1:], perco, yerr = std_perco, fmt='o--', color= 'b', label='percolation')\nplt.errorbar( range(11)[1:], rand, yerr = std_rand, fmt='o--', color= 'r', label='random')\nplt.errorbar( range(11)[1:], corre, yerr = std_corre, fmt = 'o--', color= 'g', label='correlated')\nplt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True)\nplt.xlabel(r\" \\textbf{ $ N_{COAL}$ }\",fontsize=14)\nplt.ylabel('Social Welfare')\n\nplt.savefig('test.pdf')\nplt.savefig('test.png')\n","sub_path":"figure7_with_green_curve_v1/Python/plot_fig.py","file_name":"plot_fig.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"205800818","text":"import os\nimport asyncio\nfrom metaapi_cloud_sdk import MetaApi\nfrom metaapi_cloud_sdk import CopyFactory\n\n# your MetaApi API token\ntoken = os.getenv('TOKEN') or ''\n# your master MetaApi account id\nmaster_account_id = os.getenv('MASTER_ACCOUNT_ID') or ''\n# your slave MetaApi account id\nslave_account_id = os.getenv('SLAVE_ACCOUNT_ID') or ''\n\n\nasync def configure_copyfactory():\n api = MetaApi(token)\n copy_factory = CopyFactory(token)\n\n try:\n global master_account_id\n global slave_account_id\n accounts = await api.metatrader_account_api.get_accounts()\n master_metaapi_account = next((a for a in accounts if a.id == master_account_id), None)\n if (not hasattr(master_metaapi_account, 'application')) or master_metaapi_account.application != 'CopyFactory':\n raise Exception('Please specify CopyFactory application field value in your MetaApi '\n 'account in order to use it in CopyFactory API')\n\n slave_metaapi_account = next((a for a in accounts if a.id == slave_account_id), None)\n if (not hasattr(slave_metaapi_account, 'application')) or slave_metaapi_account.application != 'CopyFactory':\n raise Exception('Please specify CopyFactory application field value in your MetaApi '\n 'account in order to use it in CopyFactory API')\n\n configuration_api = copy_factory.configuration_api\n copyfactory_accounts = await configuration_api.get_accounts()\n master_account = next((a for a in copyfactory_accounts if a['connectionId'] == master_metaapi_account.id),\n None)\n if master_account:\n master_account_id = master_account['_id']\n else:\n master_account_id = configuration_api.generate_account_id()\n await configuration_api.update_account(master_account_id, {\n 'name': 'Demo master account',\n 'connectionId': master_metaapi_account.id,\n 'subscriptions': []\n })\n\n strategies = await configuration_api.get_strategies()\n strategy = next((a for a in strategies if a['connectionId'] == master_metaapi_account.id),\n None)\n if strategy:\n strategy_id = strategy['_id']\n else:\n strategy_id = await configuration_api.generate_strategy_id()\n strategy_id = strategy_id['id']\n\n # create a strategy being copied\n await configuration_api.update_strategy(strategy_id, {\n 'name': 'Test strategy',\n 'description': 'Some useful description about your strategy',\n 'connectionId': master_metaapi_account.id\n })\n slave_account = next((a for a in copyfactory_accounts if a['connectionId'] == slave_metaapi_account.id),\n None)\n if slave_account:\n await configuration_api.remove_account(slave_account['_id'])\n slave_account_id = configuration_api.generate_account_id()\n\n # subscribe slave CopyFactory accounts to the strategy\n await configuration_api.update_account(slave_account_id, {\n 'name': 'Demo slave account',\n 'connectionId': slave_metaapi_account.id,\n 'subscriptions': [\n {\n 'strategyId': strategy_id,\n 'multiplier': 1\n }\n ]\n })\n\n print('Please note that it can take some time for CopyFactory to initialize accounts. During this time the '\n 'MetaApi accounts may redeploy a couple of times. After initialization finishes, you can copy trades '\n 'from your master to slave account.')\n except Exception as err:\n print(api.format_error(err))\n\n\nasyncio.run(configure_copyfactory())\n","sub_path":"examples/exampleGenerator/copyTradeExample.py","file_name":"copyTradeExample.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"584557187","text":"import sys\n\ndef main():\n\n rectangles = []\n for line in sys.stdin:\n line = line.strip('\\n').split()\n line = list(map(int,line))\n rectangles.append(list(line))\n output_list = []\n\n for rect in rectangles:\n x1, y1, x2, y2 = [int(coord) for coord in rect]\n for i in range(y1, y2 + 1):\n prev = output_list[i] if i < len(output_list) else ''\n if len(prev) < x2:\n prev += ' ' * (x2 - len(prev) + 1)\n prev = prev[:x1] + '#' * (x2 - x1 + 1) + prev[x2 + 1:]\n if i < len(output_list):\n output_list[i] = prev\n else:\n output_list.append(prev)\n\n output = '\\n'.join(output_list)\n print(output)\nmain()","sub_path":"2ºAno/2ºSemestre/LA2/retangulos_v2.py","file_name":"retangulos_v2.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"201010432","text":"#!/usr/bin/env python3\n\nclass CustomJoin():\n \n def __init__(self, alternate_spellings_file = '../data/district_alternate_spellings.csv', \n phem_file = '../data/phem_sample_clean.csv', \n hmis_file = '../data/hmis_sample_clean.csv',\n output_file = '../output/joined_table.csv'):\n \n # set filenames\n self.alternate_spellings_file = alternate_spellings_file\n self.phem_file = phem_file\n self.hmis_file = hmis_file\n self.output_file = output_file\n \n # initialize data structures\n self.alternate_spellings = dict()\n self.hmis_array = [] # holds rows of hmis table\n self.phem_array = [] # holds rows of phem table\n \n self.hmis_positions = dict() # key: (district, year, month) value: (corresponding row number in hmis_array)\n self.phem_positions = dict() # key: (district, year, month) value: (corresponding row number in phem_array)\n \n self.joined_table_header = []\n self.joined_table = []\n \n self.hmis_header_row = []\n self.phem_header_row = []\n \n self.hmis_row_len = 0\n self.phem_row_len = 0\n \n def parse_alternate_spellings(self):\n '''\n Parses alternate spellings file and populates the class dictionary\n '''\n # - default district name itself is not always in the list of matches -> add defaultu district name to set\n # - some default district names are not unique\n # Aregoba is an example for a non-unique district name.\n # Workaround: include region and zone to the key, make it a tuple: (region, zone, district)\n \n file = open(self.alternate_spellings_file, 'r')\n \n # get column names, remove newline character\n col_names = file.readline().split(\",\")\n col_names[-1] = col_names[-1].strip()\n \n for line in file:\n li = line.split(',')\n li[-1] = li[-1].strip()\n \n ## DEBUG: check if a key already exists!\n if (li[0], li[2]) in self.alternate_spellings:\n print(\"PANIC! Key {} already in dict\".format((li[0],li[2])))\n break\n ##\n \n # initialize set for new key, key is a 3-tuple with (region, zone, district)\n self.alternate_spellings[(li[0], li[1], li[2])] = set()\n \n for i in li[2:]:\n if i == '':\n continue\n # lower case version gets more matches\n i_lower = i.lower()\n self.alternate_spellings[(li[0], li[1], li[2])].add(i_lower)\n #self.alternate_spellings[(li[0], li[2])].add(i)\n file.close()\n\n\n def get_default_spelling(self, some_district_spelling):\n '''\n input: string, a district name in some spelling\n output: returns default spelling of that district\n NOTE: if no default spelling is found (no perfect match), then original\n spelling is returned\n NOTE: could do fuzzy matching or Levenshtein distance, but\n that could lead to false positives and potential data loss\n '''\n\n for key, value in self.alternate_spellings.items():\n if some_district_spelling.lower() in value:\n return key[2]\n \n # ideally: catch an exception and log event if no district is found,\n # print('WARNING: no default spelling found for {}. Keeping original.'.format(some_district_spelling))\n return some_district_spelling\n\n \n def parse_hmis(self):\n '''\n input: hmis file\n output: void, populates 2d-list containing the rows of the hmis file\n and populates hmis_positions dictionary linking key and array positions.\n also creates the hmis header row\n \n NOTE: li[3] = region (not used for now)\n li[4] = district\n li[14] = month (ethiopian)\n li[15] = year (ethiopian)\n '''\n \n file = open(self.hmis_file, 'r')\n \n # get column names, remove newline character\n col_names = file.readline().split(\",\")\n col_names[-1] = col_names[-1].strip()\n \n self.hmis_row_len = len(col_names)\n \n for col in col_names:\n self.hmis_header_row.append(col + \" (HMIS)\")\n \n rownum = 0\n for line in file:\n li = line.split(',')\n li[-1] = li[-1].strip()\n \n # replace district name with default district name\n li[4] = self.get_default_spelling(li[4])\n \n self.hmis_array.append(li)\n # store rownum in dict\n if (li[4], li[15], li[14]) in self.hmis_positions:\n self.hmis_positions[(li[4], li[15], li[14])].append(rownum)\n # log: 'WARNING: hmis, more than one row belongs to the same key'\n # See README.md\n else:\n self.hmis_positions[(li[4], li[15], li[14])] = [rownum]\n rownum +=1\n \n file.close()\n \n \n def parse_phem(self):\n '''\n input: phem file\n output: void, populates 2d-list containing the rows of the phem file\n and populates phem_positions dictionary linking key and array positions\n creates phem header row\n \n NOTE: li[0] = region\n li[2] = district\n li[-2] = month (ethiopian)\n li[-1] = year (ethiopian)\n '''\n\n file = open(self.phem_file, 'r')\n \n # get column names, remove newline character\n col_names = file.readline().split(\",\")\n col_names[-1] = col_names[-1].strip()\n \n self.phem_row_len = len(col_names)\n \n for col in col_names:\n self.phem_header_row.append(col + \" (PHEM)\")\n \n rownum = 0\n for line in file:\n li = line.split(',')\n li[-1] = li[-1].strip()\n \n li[2] = self.get_default_spelling(li[2])\n\n self.phem_array.append(li)\n \n # store rownum in dict\n if (li[2], li[-1], li[-2]) in self.phem_positions:\n self.phem_positions[(li[2], li[-1], li[-2])].append(rownum)\n else:\n self.phem_positions[(li[2], li[-1], li[-2])] = [rownum]\n rownum += 1\n \n file.close()\n \n \n\n def perform_full_outer_join(self):\n '''\n void, generate joined table array\n '''\n # phem_v and hmis_v are arrays. Why? A given key 2-tuple (district, date) might not be unique.\n # In this case iterate through all lines that have identical key. See README.md for details\n \n for hmis_k, hmis_v in self.hmis_positions.items():\n first_two_cols = [hmis_k[0], str(hmis_k[1]) + '-' + str(hmis_k[2])]\n\n if hmis_k in self.phem_positions:\n for ii in hmis_v:\n for jj in self.phem_positions[hmis_k]:\n self.joined_table.append(first_two_cols + self.hmis_array[ii] \n + self.phem_array[jj])\n else:\n for ii in hmis_v:\n self.joined_table.append(first_two_cols + self.hmis_array[ii] + [''] * self.phem_row_len)\n \n for phem_k, phem_v in self.phem_positions.items():\n first_two_cols = [phem_k[0], str(phem_k[1]) + '-' + str(phem_k[2])]\n if phem_k not in self.hmis_positions:\n for ii in phem_v:\n self.joined_table.append(first_two_cols + [''] * self.hmis_row_len + self.phem_array[ii]) \n \n\n def create_joined_table_header_row(self):\n self.joined_table_header = ['District Name', 'Date'] + self.hmis_header_row + self.phem_header_row\n \n def write_result(self):\n file = open(self.output_file, 'w')\n \n # write header\n header_string = \", \".join([str(i) for i in self.joined_table_header])\n file.write(header_string + '\\n')\n\n # write rows\n for row in sorted(self.joined_table):\n row_string = \", \".join([str(i) for i in row])\n file.write(row_string + '\\n')\n \n file.close()\n\n\nif __name__ == \"__main__\":\n\n cj = CustomJoin()\n cj.parse_alternate_spellings()\n cj.parse_hmis()\n cj.parse_phem()\n cj.perform_full_outer_join()\n cj.create_joined_table_header_row()\n cj.write_result()\n\n","sub_path":"src/custom_full_join.py","file_name":"custom_full_join.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"361544935","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\n# https://segmentfault.com/a/1190000015440560\n\nimport os\nimport sys\n\n# 科学计算包numpy,pandas,\n# 可视化matplotlib,seaborn,\n# 以及机器学习包sklearn\n\n\nimport pandas as pd\nfrom pandas import DataFrame\nimport numpy as np\nimport seaborn as sns\nimport matplotlib as mpl\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\n\nplt.style.use(\"fivethirtyeight\")\nsns.set_style({'font.sans-serif':['simhei','Arial']})\n\n'''\n解决中文方块问题\n'''\n## ---- 解决中文方块问题\n\nplt.rcParams['font.family'] = ['Arial Unicode MS'] #解决中文显示方块问题\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体设置-黑体\nplt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\n\n## ------\n\n# 检查Python版本\nfrom sys import version_info\nif version_info.major != 3:\n raise Exception('请使用Python 3 来完成此项目')\n\n\n# 导入二手房数据\nlianjia_df = pd.read_csv('lianjia.csv')\ndisplay(lianjia_df.head(n=2))\n\n# 检查缺失值情况\n#lianjia_df.info()\n\n# 数据描述\nprint(lianjia_df.describe())\n\n\n# 添加新特征房屋均价\ndf = lianjia_df.copy()\ndf['PerPrice'] = lianjia_df['Price']/lianjia_df['Size']\n\n# 重新摆放列位置\ncolumns = ['Region', 'District', 'Garden', 'Layout', 'Floor', 'Year', 'Size', 'Elevator', 'Direction', 'Renovation', 'PerPrice', 'Price']\ndf = pd.DataFrame(df, columns = columns)\n\n# 重新审视数据集\ndisplay(df.head(n=2))\n\n# 对二手房区域分组对比二手房数量和每平米房价\ndf_house_count = df.groupby('Region')['Price'].count().sort_values(ascending=False).to_frame().reset_index()\ndf_house_mean = df.groupby('Region')['PerPrice'].mean().sort_values(ascending=False).to_frame().reset_index()\n\nprint(df_house_count)\nprint(df_house_mean)\n\nf, [ax1,ax2,ax3] = plt.subplots(3,1,figsize=(20,15))\nsns.barplot(x='Region', y='PerPrice', palette=\"Blues_d\", data=df_house_mean, ax=ax1)\nax1.set_title('北京各大区二手房每平米单价对比',fontsize=15)\nax1.set_xlabel('区域')\nax1.set_ylabel('每平米单价')\n\nsns.barplot(x='Region', y='Price', palette=\"Greens_d\", data=df_house_count, ax=ax2)\nax2.set_title('北京各大区二手房数量对比',fontsize=15)\nax2.set_xlabel('区域')\nax2.set_ylabel('数量')\n\nsns.boxplot(x='Region', y='Price', data=df, ax=ax3)\nax3.set_title('北京各大区二手房房屋总价',fontsize=15)\nax3.set_xlabel('区域')\nax3.set_ylabel('房屋总价')\n\nplt.show()\n\n#\n# # f, [ax1,ax2] = plt.subplots(1, 2, figsize=(15, 5))\n# # # 建房时间的分布情况\n# # sns.distplot(df['Size'], bins=20, ax=ax1, color='r')\n# # sns.kdeplot(df['Size'], shade=True, ax=ax1)\n# # # 建房时间和出售价格的关系\n# # sns.regplot(x='Size', y='Price', data=df, ax=ax2)\n# # # plt.show()\n#\n#\n#\n#\n# print(df.loc[df['Size']< 10])\n#\n# print(df.loc[df['Size']>1000])\n#\n#\n# df = df[(df['Layout']!='叠拼别墅') & (df['Size']<1000)]\n#\n#\n# f, [ax1,ax2] = plt.subplots(1, 2, figsize=(20, 10))\n#\n# sns.distplot(df['Size'],bins=20,ax=ax1,color='r')\n# sns.kdeplot(df['Size'],shade=True,ax=ax1)\n#\n# sns.regplot(x='Size',y='Price',data=df,ax=ax2)\n# # plt.show()\n#\n#\n# f,ax1 = plt.subplots(figsize=(20,15))\n# sns.countplot(y='Layout',data=df,ax=ax1)\n# ax1.set_title('房屋huxing',fontsize=20)\n# ax1.set_xlabel('数量')\n# ax1.set_ylabel('户型')\n#\n# # plt.show()\n#\n#\n# # print(df['Renovation'].filter(df['Renovation']=='毛坯').value_counts())\n#\n#\n# df['Renovation'] = df.loc[(df['Renovation'] != '南北'), 'Renovation']\n#\n# print(df['Renovation'].value_counts())\n#\n#\n# # 画幅设置\n# f, [ax1,ax2,ax3] = plt.subplots(1, 3, figsize=(20, 5))\n# sns.countplot(df['Renovation'], ax=ax1)\n# sns.barplot(x='Renovation', y='Price', data=df, ax=ax2)\n# sns.boxplot(x='Renovation', y='Price', data=df, ax=ax3)\n# # plt.show()\n#\n#\n# # len算条数\n# misn = len(df.loc[(df['Elevator'].isnull()), 'Elevator'])\n#\n# print('Elevator缺失值数量为:'+ str(misn))\n#\n#\n#\n#\n# # 由于存在个别类型错误,如简装和精装,特征值错位,故需要移除\n# df['Elevator'] = df.loc[(df['Elevator'] == '有电梯')|(df['Elevator'] == '无电梯'), 'Elevator']\n#\n# # 填补Elevator缺失值\n# df.loc[(df['Floor']>6)&(df['Elevator'].isnull()), 'Elevator'] = '有电梯'\n# df.loc[(df['Floor']<=6)&(df['Elevator'].isnull()), 'Elevator'] = '无电梯'\n#\n#\n# f, [ax1,ax2] = plt.subplots(1, 2, figsize=(20, 10))\n#\n# sns.countplot(df['Elevator'], ax=ax1)\n# ax1.set_title('有无电梯数量对比',fontsize=15)\n# ax1.set_xlabel('是否有电梯')\n# ax1.set_ylabel('数量')\n#\n# sns.barplot(x='Elevator', y='Price', data=df, ax=ax2)\n# ax2.set_title('有无电梯房价对比',fontsize=15)\n# ax2.set_xlabel('是否有电梯')\n# ax2.set_ylabel('总价')\n# plt.show()\n\n\n\n\n\n#Year 特征分析\n\n# grid = sns.FacetGrid(df, row='Elevator', col='Renovation', palette='seismic',size=4)\n# grid.map(plt.scatter, 'Year', 'Price')\n# grid.add_legend()\n\n# plt.show()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"analysis/lianjia/lianjia.py","file_name":"lianjia.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"583912594","text":"\"\"\"The module in which the visualization takes place,\nthe implementation of the mechanics\nof worms, food, weather events.\"\"\"\nimport configparser\nimport logging\nimport random\nfrom typing import List, Dict\nimport cv2\nimport numpy as np\n\nfrom common_types import Colors, Neighbors, NEIGHBOURS_VALUES\nfrom weather import Rain, Tornado\nfrom worm import Worm, Food, create_genome\n\n\nclass Cell:\n \"\"\"Container with objects located at certain coordinates on the map.\"\"\"\n\n def __init__(self):\n self.worms = []\n self.food = []\n\n\nclass World:\n \"\"\"The main class in which the mechanics are implemented.\"\"\"\n\n def __init__(self, height: int = 100, width: int = 100,\n worms_num: int = 250, food_num: int = 1000):\n self.cells: Dict[tuple, Cell] = {}\n self.worms: List[Worm] = []\n self.food: List[Food] = []\n\n for y in range(height):\n for x in range(width):\n self.cells[(x, y)] = Cell()\n\n self.rains: List[Rain] = []\n self.tornadoes: List[Tornado] = []\n self.name: str = 'World'\n self.height = height\n self.width = width\n\n self.populate(worms_num)\n self.sow_food(food_num)\n\n def get_random_pos(self) -> tuple:\n \"\"\"get a random coordinates on the map.\"\"\"\n return random.randrange(0, self.width), random.randrange(0, self.height)\n\n def populate(self, worms_num: int = 250) -> None:\n \"\"\"Places a given number of worms at random map coordinates.\"\"\"\n for i in range(worms_num):\n pos = self.get_random_pos()\n worm = Worm(pos)\n worm.genetics.genotype = create_genome()\n worm.newborn_genetics_boost(worm.genetics.genotype)\n self.cells[pos].worms.append(worm)\n self.worms.append(worm)\n\n def sow_food(self, food_num: int = 1000) -> None:\n \"\"\"Places a given number of food objects at random map coordinates.\"\"\"\n for i in range(food_num):\n pos = self.get_random_pos()\n food_unit = Food(pos)\n self.cells[pos].food.append(food_unit)\n self.food.append(food_unit)\n\n def rain_emergence(self) -> None:\n \"\"\"creates a new Rain object.\"\"\"\n self.rains.append(Rain(self.get_random_pos()))\n\n def tornado_emergence(self) -> None:\n \"\"\"creates a new Tornado object.\"\"\"\n self.tornadoes.append(Tornado(self.get_random_pos()))\n\n @property\n def worms_by_initiative(self) -> List[Worm]:\n \"\"\"Sorts list of worms by initiative.\"\"\"\n return sorted(world.worms, key=lambda worm: worm.get_initiative())\n\n def worms_at(self, location_cell: tuple) -> List[Worm]:\n \"\"\"Returns list of worms located on the cell.\"\"\"\n if location_cell in self.cells:\n return self.cells[location_cell].worms\n return []\n\n def food_at(self, location_cell: tuple) -> List[Food]:\n \"\"\"Returns list of food objects located on the cell.\"\"\"\n if location_cell in self.cells:\n return self.cells[location_cell].food\n return []\n\n def has_food_at(self, location_cell: tuple) -> bool:\n \"\"\"True if in the cell located food.\"\"\"\n return location_cell in self.cells and len(self.cells[location_cell].food) > 0\n\n @staticmethod\n def move(pos, direction):\n \"\"\"Changes coordinates.\"\"\"\n return pos[0] + direction[0], pos[1] + direction[1]\n\n def get_neighbours_worms(self, location_cell: tuple, border_x: int, border_y: int) -> dict:\n \"\"\"Returns dict(key=neighbours cell, value=list of worms in the cell).\"\"\"\n neighbours_worms = {}\n\n x, y = location_cell[0], location_cell[1]\n\n if y > 0:\n neighbours_worms[Neighbors.UP] = \\\n world.worms_at(self.move(location_cell, Neighbors.UP.value))\n if y < border_y - 1:\n neighbours_worms[Neighbors.DOWN] = \\\n world.worms_at(self.move(location_cell, Neighbors.DOWN.value))\n if x > 0:\n neighbours_worms[Neighbors.LEFT] = \\\n world.worms_at(self.move(location_cell, Neighbors.LEFT.value))\n if x < border_x - 1:\n neighbours_worms[Neighbors.RIGHT] = \\\n world.worms_at(self.move(location_cell, Neighbors.RIGHT.value))\n return neighbours_worms\n\n def get_neighbours_food(self, location_cell: tuple) -> list:\n \"\"\"Returns list of neighbours cells with food.\"\"\"\n neighbours_food = []\n for val in NEIGHBOURS_VALUES:\n if world.has_food_at(self.move(location_cell, val)):\n neighbours_food.append(val)\n return neighbours_food\n\n def get_the_longest_genotype_at(self, location_cell: tuple) -> int:\n \"\"\"Compares the genotype lengths of the worms in the cell\n and returns the highest value.\"\"\"\n genotype_owners = self.worms_at(location_cell)\n lengths = [len(creature.genetics.genotype) for creature in genotype_owners]\n return max(lengths, default=0)\n\n def worms_is_not_relatives(self, location_cell: tuple) -> list:\n \"\"\"Returns a list of non-related worms with unique genotypes.\"\"\"\n worms_at_location = self.worms_at(location_cell)\n if len(worms_at_location) == 1:\n return worms_at_location\n families: List[float] = []\n worms_is_not_relatives = []\n for worm in worms_at_location:\n if len(families) == 0:\n families.append(worm.genetics.family_affinity)\n worms_is_not_relatives.append(worm)\n continue\n overlap = False\n for family in families:\n if abs(worm.genetics.family_affinity - family) < 1e-12:\n overlap = True\n break\n if overlap is False:\n families.append(worm.genetics.family_affinity)\n worms_is_not_relatives.append(worm)\n return worms_is_not_relatives\n\n def genetic_variability(self, location_cell: tuple) -> list:\n \"\"\"Shuffles parental genotypes into a new one.\"\"\"\n parents = self.worms_is_not_relatives(location_cell)\n if len(parents) == 1 and len(parents[0].genetics.genotype) > 0:\n return parents[0].genetics.genotype\n new_genotype = []\n new_genotype_length = self.get_the_longest_genotype_at(location_cell)\n gene_counter = 0\n while gene_counter <= new_genotype_length:\n if len(parents) > 0:\n for parent in parents:\n try:\n new_genotype.append(parent.genetics.genotype[gene_counter])\n\n except IndexError:\n parents.remove(parent)\n gene_counter -= 1\n gene_counter += 1\n else:\n break\n return new_genotype\n\n\nclass WorldProcessor:\n \"\"\"Base class of processors.\"\"\"\n\n def __init__(self):\n pass\n\n def process(self, world_object: World) -> None:\n \"\"\"Base method of processors.\"\"\"\n\n\nclass Visualizer(WorldProcessor):\n \"\"\"Visualizing processor.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Visualize the map of world with objects\n from Worm and Weather modules.\"\"\"\n vis = np.zeros((world_object.height, world_object.width, 3), dtype='uint8')\n worm_color = [Colors.WHITE, Colors.BLUE, Colors.GREEN, Colors.YELLOW]\n for rain in world_object.rains:\n for coordinate in rain.all_coordinates:\n vis[coordinate[1],\n coordinate[0]] \\\n = Colors.SKY_BLUE.value\n for tornado in world_object.tornadoes:\n for coordinate in tornado.all_coordinates:\n vis[coordinate[1],\n coordinate[0]] \\\n = Colors.GREY.value\n for worm in world_object.worms:\n if worm.get_generation() < 4:\n vis[worm.coordinates[1],\n worm.coordinates[0]] \\\n = worm_color[int(worm.get_generation())].value\n else:\n vis[worm.coordinates[1],\n worm.coordinates[0]] = Colors.WHITE.value\n\n for food_unit in world_object.food:\n vis[food_unit.coordinates[1],\n food_unit.coordinates[0]] \\\n = Colors.FOOD.value\n\n scale = 4\n vis = cv2.resize(vis, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST)\n\n cv2.imshow('vis', vis)\n cv2.waitKey(1)\n\n\nclass AddFoodProcessor(WorldProcessor):\n \"\"\"Add food objects on the map every iteration.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Add food objects at the random coordinates on the map.\"\"\"\n growth = random.randint(10, 20)\n for i in range(growth):\n pos = world_object.get_random_pos()\n food_unit = Food(pos)\n world_object.cells[pos].food.append(food_unit)\n world_object.food.append(food_unit)\n\n\nclass AgingProcessor(WorldProcessor):\n \"\"\"Increase age of worms every iteration.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Increase age of worms.\"\"\"\n for worm in world_object.worms:\n worm.age += 1\n\n\nclass ZeroEnergyProcessor(WorldProcessor):\n \"\"\"Processor decreases health of worms without energy.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Slowly decrease health of worms without energy.\"\"\"\n for worm in world_object.worms_by_initiative:\n if worm.get_energy() <= 0:\n worm.health -= 0.1\n\n\nclass WormsMovementProcessor(WorldProcessor):\n \"\"\"Processor moves worms on the map.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"The worms assess the danger and the presence of food\n in neighboring cells, then move to a random one of the most acceptable. \"\"\"\n for worm in world_object.worms_by_initiative:\n if worm.dead:\n continue\n enemies = [enemy for enemy in world_object.worms_at(worm.coordinates)\n if enemy is not worm]\n affordable_food = world_object.food_at(worm.coordinates)\n worm_in_danger = worm.is_dangerous(\n worm.max_danger_at_location(world_object.worms_at(worm.coordinates)))\n\n if worm_in_danger or (len(affordable_food) == 0 and len(enemies) == 0):\n neighbours_worms = world_object.get_neighbours_worms(\n worm.coordinates, world_object.width, world_object.height)\n safe_steps = worm.get_safe_steps(neighbours_worms)\n if len(safe_steps) != 0:\n steps_with_food = world_object.get_neighbours_food(worm.coordinates)\n dcoord = random.choice(worm.get_best_steps(safe_steps, steps_with_food))\n\n world_object.cells[worm.coordinates].worms.remove(worm)\n worm.move(dcoord, world_object.width, world_object.height)\n world_object.cells[worm.coordinates].worms.append(worm)\n\n\nclass PoisonProcessor(WorldProcessor):\n \"\"\"Processor of poison effects on the worms.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"If the worm is poisoned, it loses its life.\"\"\"\n for worm in world_object.worms_by_initiative:\n worm.poison_effect()\n\n\nclass FightProcessor(WorldProcessor):\n \"\"\"Processor of worms strikes.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Every worm strikes another not a relatives worm\n at the same cell.\"\"\"\n for worm in world_object.worms_by_initiative:\n targets = world_object.worms_at(worm.coordinates)\n if len(targets) == 0:\n continue\n target = random.choice(targets)\n\n if target is worm:\n continue\n\n if worm.is_relative_to(target):\n continue\n\n worm.strike(target)\n target.strike(worm)\n\n\nclass LevelUpProcessor(WorldProcessor):\n \"\"\"Processor of level ups effects.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Each worm that has reached\n a certain value of experience increases its level.\"\"\"\n for worm in world_object.worms:\n worm.level_up()\n\n\nclass FoodPickUpProcessor(WorldProcessor):\n \"\"\"Processor of pick ups food objects by worms.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Each worm picks up food if it is in the cage.\"\"\"\n for eater in world_object.worms_by_initiative:\n targets = world_object.food_at(eater.coordinates)\n if len(targets) != 0:\n target = random.choice(targets)\n eater.eat(target)\n\n\nclass EatenFoodRemover(WorldProcessor):\n \"\"\"Processor delete eaten food.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"delete all food without nutritional value.\"\"\"\n eaten_food = [food_unit for food_unit in world_object.food if food_unit.eaten]\n for food in eaten_food:\n world_object.cells[food.coordinates].food.remove(food)\n world_object.food.remove(food)\n\n\nclass CorpseGrindingProcessor(WorldProcessor):\n \"\"\"Processor goes through the list of worms,\n if there are dead in their cells,\n the living receive a bonus.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Worms receive a bonus for killed worms in the same cell as they are.\"\"\"\n for worm in world_object.worms:\n if not worm.dead:\n continue\n\n eaters = world_object.worms_at(worm.coordinates)\n for eater in eaters:\n if eater.dead:\n continue\n eater.health += worm.get_level() + worm.get_damage() + worm.get_initiative()\n eater.energy += (worm.get_level() + worm.get_damage() + worm.get_initiative()) * 10\n\n\nclass DeadWormsRemover(WorldProcessor):\n \"\"\"Processor goes through the list of worms if they are dead and removes them.\"\"\"\n\n def __init__(self):\n super().__init__()\n self.dead_worms = 0\n\n def process(self, world_object: World) -> None:\n \"\"\"Delete dead worms.\"\"\"\n number_of_worms_before = len(world_object.worms)\n dead_worms = [worm for worm in world_object.worms if worm.dead]\n for worm in dead_worms:\n cell = world_object.cells[worm.coordinates]\n cell.worms.remove(worm)\n world_object.worms.remove(worm)\n dead_worms_in_round = number_of_worms_before - len(world_object.worms)\n self.dead_worms += dead_worms_in_round\n print('dead', self.dead_worms)\n\n\nclass WormDivisionProcessor(WorldProcessor):\n \"\"\"Creates new worms with genotypes derived from parental worms.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Creates a worm with a parental genotype\n or with a genotype mixed from the genotypes\n of non-relatives worms in the cell.\"\"\"\n for parent in world_object.worms:\n if parent.get_divisions_limit() == 0:\n continue\n child = Worm(parent.coordinates)\n child.genetics.genotype = world_object.genetic_variability(parent.coordinates)\n world_object.cells[parent.coordinates].worms.append(child)\n world_object.worms.append(child)\n child.genetics.family_affinity = parent.genetics.family_affinity + 0.00000000000001\n child.newborn_genetics_boost(child.genetics.genotype)\n parent.divisions_limit -= 1\n child.generation = parent.get_generation() + 1\n\n\nclass MutationProcessor(WorldProcessor):\n \"\"\"Creates a random changes in the worm's genotype.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"With a certain probability creates\n a random change in the worm's genotype\n (add, del or exchange gene).\"\"\"\n for worm in world_object.worms:\n mutation_probability_throw = random.randint(1, 100)\n worm.mutation_metamorphosis(mutation_probability_throw)\n\n\nclass WeatherEventsEmergenceProcessor(WorldProcessor):\n \"\"\"Creates a new weather objects.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"With a certain probability creates\n a new Rain or Tornado object.\"\"\"\n if len(world_object.rains) < 5:\n chance_throw = random.randrange(0, 10)\n if chance_throw >= 8:\n world_object.rain_emergence()\n\n if len(world_object.tornadoes) < 3:\n chance_throw = random.randrange(0, 10)\n if chance_throw >= 8:\n world_object.tornado_emergence()\n\n\nclass WeatherMovementsProcessor(WorldProcessor):\n \"\"\"Moves weather objects on the map.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Moves weather objects and update list of occupied coordinates.\"\"\"\n if world_object.rains:\n for rain in world_object.rains:\n rain.move(world_object.width, world_object.height)\n rain.upscaling(world_object.width, world_object.height)\n\n if world_object.tornadoes:\n for tornado in world_object.tornadoes:\n tornado.move(world_object.width, world_object.height)\n tornado.upscaling(world_object.width, world_object.height)\n\n\nclass WeatherEffectsProcessor(WorldProcessor):\n \"\"\"Applies effects of the weather objects.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"Tornado scatters worms and food,\n Rain decrease health/energy of worms\n and decrease nutritional_value of food.\"\"\"\n if len(world_object.rains) > 0:\n for rain in world_object.rains:\n for coordinate in rain.all_coordinates:\n worms_in_cell = world_object.worms_at(coordinate)\n food_in_cell = world_object.food_at(coordinate)\n rain.raining_effect(worms_in_cell, food_in_cell)\n\n if len(world_object.tornadoes) > 0:\n for tornado in world_object.tornadoes:\n for coordinate in tornado.all_coordinates:\n worms_in_cell = world_object.worms_at(coordinate)\n food_in_cell = world_object.food_at(coordinate)\n cell = world_object.cells[coordinate]\n cell.worms = []\n cell.food = []\n tornado.tornado_effect(worms_in_cell, food_in_cell,\n world_object.width, world_object.height)\n for worm in worms_in_cell:\n world_object.cells[worm.coordinates].worms.append(worm)\n for food in food_in_cell:\n world_object.cells[food.coordinates].food.append(food)\n\n\nclass WeatherEventsRemover(WorldProcessor):\n \"\"\"Delete expired weather objects.\"\"\"\n\n def process(self, world_object: World) -> None:\n \"\"\"If duration of weather objects is over\n delete the weather object.\"\"\"\n for rain in world_object.rains:\n if rain.duration <= 0:\n world_object.rains.remove(rain)\n\n for tornado in world_object.tornadoes:\n if tornado.duration <= 0:\n world_object.tornadoes.remove(tornado)\n\n\nclass AnalyticsProcessor(WorldProcessor):\n \"\"\"Displays info in the console.\"\"\"\n\n def __init__(self):\n super().__init__()\n self.iterations = 0\n self.step = 0\n\n def process(self, world_object: World) -> None:\n \"\"\"Displays iteration number and total number of worms on the map.\"\"\"\n self.iterations += 1\n self.step += 1\n print('iter', self.iterations)\n print('number of worms', len(world_object.worms))\n if self.step == 100:\n logging.debug('Program is working correctly')\n self.step = 0\n\n\nif __name__ == \"__main__\":\n\n config = configparser.ConfigParser()\n config.read('config.ini')\n logging_levels = {'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'WARNING': logging.WARNING,\n 'ERROR': logging.ERROR,\n 'CRITICAL': logging.CRITICAL}\n\n logging_level = config.get('LOGGER', 'level')\n\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging_levels.get(logging_level))\n\n WORLD_HEIGHT = int(config.get('WORLD', 'height'))\n WORLD_WIDTH = int(config.get('WORLD', 'width'))\n WORLD_START_WORMS_NUM = int(config.get('WORLD', 'worms_num'))\n WORLD_START_FOOD_NUM = int(config.get('WORLD', 'food_num'))\n\n world = World(WORLD_HEIGHT, WORLD_WIDTH, WORLD_START_WORMS_NUM, WORLD_START_FOOD_NUM)\n valid_processors = {\n 'agingprocessor': AgingProcessor,\n 'zeroenergyprocessor': ZeroEnergyProcessor,\n 'poisonprocessor': PoisonProcessor,\n 'weathereventsemergenceprocessor': WeatherEventsEmergenceProcessor,\n 'addfoodprocessor': AddFoodProcessor,\n 'weathermovementsprocessor': WeatherMovementsProcessor,\n 'weathereffectsprocessor': WeatherEffectsProcessor,\n 'wormsmovementprocessor': WormsMovementProcessor,\n 'fightprocessor': FightProcessor,\n 'corpsegrindingprocessor': CorpseGrindingProcessor,\n 'foodpickupprocessor': FoodPickUpProcessor,\n 'deadwormsremover': DeadWormsRemover,\n 'eatenfoodremover': EatenFoodRemover,\n 'weathereventsremover': WeatherEventsRemover,\n 'levelupprocessor': LevelUpProcessor,\n 'wormdivisionprocessor': WormDivisionProcessor,\n 'mutationprocessor': MutationProcessor,\n 'analyticsprocessor': AnalyticsProcessor,\n 'visualizer': Visualizer}\n\n processors = []\n\n for option in config.options('PROCESSORS'):\n if option not in valid_processors.keys():\n logging.error('Unknown processor')\n raise ValueError('Unknown processor')\n if config.getboolean('PROCESSORS', option) is True:\n proc = valid_processors[option]\n processors.append(proc())\n\n PROCESS = True\n\n while PROCESS is True:\n for proc in processors:\n proc.process(world)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"59521554","text":"class Vektor(object):\n\tdef __init__(self,a,b,c):\n\t\tself.data = [a,b,c]\n\tdef __mul__(self,other):\n\t\tif isinstance(other, Vektor):\n\t\t\tergebnis = 0.0\n\t\t\tfor i in range(0,3):\n\t\t\t\tergebnis = ergebnis + \\\n\t\t\t\tself.data[i] * other.data[i]\n\t\t\treturn ergebnis\n\t\telse:\n\t\t\treturn Vektor(other*self.data[0],\n\t\t\t\tother*self.data[1],\n\t\t\t\tother*self.data[2])\n\tdef __rmul__(self,other):\n\t\treturn self.__mul__(other)\n\n\tdef __mod__(self,other):\n\t\tif isinstance(other, Vektor):\n\t\t\th = Vektor(1,1,1)\n\t\t\th.data[0]=self.data[1]*other.data[2] - self.data[2]*other.data[1]\n\t\t\th.data[1]=self.data[2]*other.data[0] - self.data[0]*other.data[2]\n\t\t\th.data[2]=self.data[0]*other.data[1] - self.data[1]*other.data[0]\n\t\t\treturn h\n\t\telse:\n\t\t\tprint(\"Kreuzprodukt nur zwischen Vektoren möglich\")\n\t\n\tdef spat(self, a, b):\n\t\tif isinstance(self, Vektor) & isinstance(a, Vektor) & isinstance(b, Vektor):\n\t\t\treturn ((a%b)*self)\n\t\telse:\n\t\t\tprint(\"Spatprodukt nur für Vektoren möglich\")\n\t\t\t\nif __name__ == '__main__':\n a = Vektor(1,2,3)\n b = Vektor(0.1, 0.01, 0.001)\n c = Vektor(1,1,1)\n print(c.spat(2,b))\n # x=a%3\n z=a%b\n print(\"Kreuzprodukt\",z.data)\n","sub_path":"Blatt6/vektoren.py","file_name":"vektoren.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"590331766","text":"import math\nimport numpy as np\nfrom pymatgen import Structure, Site\n\n\"\"\"\nThis is a collection of methods to get quantities from documents stored in the \nionic mobility MongoDB. For somewhat historical reasons, some quantities are \nstored in the database and some are derived on the fly; this may change in the \nfuture. These methods could use some refactoring (many repetitive calls to e.g.\nget_diffuser_index), but they work for now. To-do:\n - Add transition metal radius and charge fetching.\n - Other properties...\n\"\"\"\n\n# Global variables\nstored = [\"path_energy\", \"path_length\", \"coordination\", \n \"effective_coordination\", \"average_bond_length\", \"distortion_index\",\n \"activation_energy\"]\nderived = [\"path_percentage\", \"volume_per_anion\", \"min_cation_distance\", \n \"min_anion_distance\", \"av_delta_cation\", \"site_e_diff\", \n \"site_cn_diff\", \"min_cat_dist\", \"min_anion_dist\", \n \"displacements_by_site\"]\nworking_ions = [\"Li\", \"Na\", \"Ca\", \"Mg\", \"Zn\"]\nanions = [\"O\", \"S\", \"Se\", \"F\"]\n\n\ndef call_derivation(prop, doc):\n \"\"\"call_derivation\n A helper method to call individual functions for property derivation.\n :param prop: The property we seek to compute (String)\n :param doc: A MongoDB document.\n :return: Results of calling the specific derivation function.\n \"\"\"\n func_dict = {\n \"path_percentage\": path_percentage,\n \"volume_per_anion\": vol_per_anion,\n \"min_cation_distance\": min_cation_activated,\n \"min_anion_distance\": min_anion_activated,\n \"av_delta_cn\": calc_cn_change,\n \"site_e_diff\": site_energy_difference,\n \"site_cn_diff\": site_cn_diff,\n \"min_cat_dist\": min_cation_along_path,\n \"min_anion_dist\": min_anion_along_path,\n \"displacements_by_site\": get_all_displacements,\n }\n return func_dict[prop](doc)\n\n\ndef get_diffuser_index(structures, ion):\n \"\"\"get_diffuser_index\n From a list of NEB images (Structure objects), finds index of diffuser.\n :param structures: A list of Pymatgen Structure object (NEB trajectory)\n :param ion: Diffusing ion identity (String)\n :return: Integer giving the index of the diffusing atom in species list.\n \"\"\"\n diff_ion_index, max_path_length = 0.0, 0.0\n for i, s in enumerate(structures[0].sites):\n if str(s.specie) == ion:\n path_length = get_path_length(structures, i)\n if path_length > max_path_length:\n max_path_length = path_length\n diff_ion_index = i\n return diff_ion_index\n\n\ndef get_path_length(structures, d_i):\n \"\"\"get_path_length\n Gets the path length along the NEB trajectory.\n :param structures: List of structures comprising the NEB trajectory.\n :param d_i: Index of the atom whose diffusion path we seek.\n :return: Path length in angstroms\n \"\"\"\n d = 0\n for i in range(len(structures) - 1):\n d += structures[i][d_i].distance(structures[i + 1][d_i])\n return d\n\n\ndef determine_working_ion(s):\n \"\"\"determine_working_ion\n Determines the identity of the working ion.\n :param s: A structure object.\n :return: A String matching the working ion element.\n \"\"\"\n comp_dict = s.composition.as_dict()\n return [el for el in comp_dict if el in working_ions][0]\n\n\ndef path_percentage(doc):\n \"\"\"path_percentage\n Normalizes the NEB image coordinates to a distance along the path.\n :param doc: MongoDB document.\n :return: A list of percentage values for each image.\n \"\"\"\n structures = [Structure.from_dict(s) for s in doc[\"neb_images\"]]\n w_i = determine_working_ion(structures[0])\n d_i = get_diffuser_index(structures, w_i)\n path_total = doc[\"NEB_analysis\"][\"path_length\"]\n percentage_list = [0]\n for i in range(len(structures) - 1):\n path_distance += structures[i][d_i].distance(structures[i + 1][d_i])\n percentage_list.append(path_distance / path_sum*100)\n return percentage_list\n\n\ndef vol_per_anion(doc):\n \"\"\"vol_per_anion\n Calculates the volume per anion in a structure.\n :param doc: MongoDB document\n :return: A volume in A^3/anion in unit cell.\n \"\"\"\n s = Structure.from_dict(doc[\"neb_images\"][0])\n num_anions = 0\n for ion in anions:\n num_anions += len(s.indices_from_symbol(ion))\n return s.lattice.volume/num_anions\n\n\ndef min_cation_activated(doc):\n \"\"\"min_cation_activated\n Gets the minimum distance to the cation in the activated state.\n :param doc: MongoDB document.\n :return: Minimum activated-state cation distance along path.\n \"\"\"\n structures = [Structure.from_dict(s) for s in doc[\"neb_images\"]]\n neb_energies = [float(e) for e in doc[\"NEB_analysis\"][\"path_energy\"]]\n max_energy = max(neb_energies)\n activated_state_index = neb_energies.index(max_energy)\n w_i = determine_working_ion(structures[0])\n d_i = get_diffuser_index(structures, w_i)\n return get_cat_dist_in_struct(structures[activated_state_index], d_i)\n\n\ndef min_anion_activated(doc):\n \"\"\"min_anion_activated\n Gets the mininmum distance to the anion in the activated state.\n :param doc: MongoDB document.\n :return: Minimum activation state anion distance along the path.\n \"\"\"\n structures = [Structure.from_dict(s) for s in doc[\"neb_images\"]]\n neb_energies = [float(e) for e in doc[\"NEB_analysis\"][\"path_energy\"]]\n max_energy = max(neb_energies)\n activated_state_index = neb_energies.index(max_energy)\n w_i = determine_working_ion(structures[0])\n d_i = get_diffuser_index(structures, w_i)\n return get_anion_dist_in_struct(structures[activated_state_index], d_i)\n\n\ndef get_cat_dist_in_struct(s, d_i):\n \"\"\"get_cat_dist_in_struct\n Finds the nearest distance to a cation in structure s.\n :param s: A Pymatgen Structure object.\n :param d_i: Index of the diffusing ion.\n :return: Distance to the closest cation from the diffusing ion.\n \"\"\"\n cat_dists = [site.distance(s.sites[d_i]) for i, site in enumerate(s.sites)\n if i != d_i and str(site.specie) not in anions]\n return min(cat_dists)\n\n\ndef get_anion_dist_in_struct(s, d_i):\n \"\"\"get_anion_dist_in_struct\n Finds the nearest distance to an anion in structure s.\n :param s: A Pymatgen Structure object.\n :param d_i: Index of the diffusing ion.\n :return: Distance to the closest anion from the diffusing ion.\n \"\"\"\n anion_dists = [site.distance(s.sites[d_i]) for i, site in enumerate(s.sites)\n if i != d_i and str(site.specie) in anions]\n return min(anion_dists)\n\n\ndef calc_cn_change(doc):\n \"\"\"calc_cn_change\n Calculates the change in effective coordination number along the NEB path.\n :param doc: MongoDB document.\n :return: The average change in ECN.\n \"\"\"\n avgs = []\n ecn_list = np.array(doc[\"NEB_analysis\"][\"effective_coordination\"])\n max_coord = np.amax(ecn_list)\n min_coord = np.amin(ecn_list)\n return max_coord - min_coord\n\n\ndef site_energy_difference(doc):\n \"\"\"site_energy_difference\n Returns the energy difference (in meV) between images 0 and N/2.\n :param doc: MongoDB document.\n :return: Out of N images, returns E_{N/2} - E_{0} (in units of meV)\n \"\"\"\n es = [float(e) for e in doc[\"NEB_analysis\"][\"path_energy\"]]\n return get_intermediate_difference(es)\n\n\ndef site_cn_diff(doc):\n \"\"\"site_cn_difference\n Gets the change in coordination number from starting to intermediate state.\n :param doc: MongoDB document.\n :return: ECN_{N/2} - ECN_{0} out of N images.\n \"\"\"\n ecns = [float(ecn) for ecn in doc[\"NEB_analysis\"][\"effective_coordination\"]]\n return get_intermediate_difference(ecns)\n\n\ndef get_intermediate_difference(q_a):\n \"\"\"get_intermediate_difference\n Gets the difference in a quantity between starting and intermediate sites.\n :param q_a: Array of some quantity defined along NEB trajectory.\n :return: Difference in quantity between image 0 and image N/2.\n \"\"\"\n if len(q_a) % 2 == 0:\n v_int = (q_a[len(q_a)/2] + q_a[(len(q_a)/2) - 1]) / 2\n else:\n v_int = (q_a[int(math.floor(len(q_a)/2))])\n return v_int - q_a[0]\n\n\ndef min_cation_along_path(doc):\n \"\"\"min_cation_along_path\n Gets the distance to the nearest cation along the whole path.\n :param doc: MongoDB document.\n :return: A list of distances to closest cation along the NEB trajectory.\n \"\"\"\n structures = [Structure.from_dict(s) for s in doc[\"neb_images\"]]\n neb_energies = [float(e) for e in doc[\"NEB_analysis\"][\"path_energy\"]]\n max_energy = max(neb_energies)\n activated_state_index = neb_energies.index(max_energy)\n w_i = determine_working_ion(structures[0])\n d_i = get_diffuser_index(structures, w_i)\n cat_dists = [get_cat_dist_in_struct(s, d_i) for i, s in \n enumerate(structures)]\n return cat_dists\n\n\ndef min_anion_along_path(doc):\n \"\"\"min_anion_along_path\n Gets the distance to the nearest anion along the whole path.\n :param doc: MongoDB document.\n :return: A list of distances to closest anion along NEB trajectory.\n \"\"\"\n structures = [Structure.from_dict(s) for s in doc[\"neb_images\"]]\n neb_energies = [float(e) for e in doc[\"NEB_analysis\"][\"path_energy\"]]\n max_energy = max(neb_energies)\n activated_state_index = neb_energies.index(max_energy)\n w_i = determine_working_ion(structures[0])\n d_i = get_diffuser_index(structures, w_i)\n anion_dists = [get_anion_dist_in_struct(s, d_i) for i, s in \n enumerate(structures)]\n return anion_dists\n\n\ndef get_all_displacements(doc):\n \"\"\"get_all_displacements\n Get the summed displacement of all sites along the NEB trajectory.\n :param doc: MongoDB document.\n :return: [summed_displacement_site_0, ..., summed_displacement_site_N]\n \"\"\"\n displacement_list = []\n structures = [Structure.from_dict(s) for s in doc[\"neb_images\"]]\n for i, s in enumerate(structures[0].sites):\n displacement_along_path = get_site_displacements(structures, i)\n displacement_list.append(displacement_along_path)\n return displacement_list\n\n\ndef get_site_displacement(s_a, site_index):\n \"\"\"get_site_displacement\n Gets the displacement of a particular site along the trajectory.\n :param s_a: Array of structures across the trajectory.\n :param site_index: Index of the site whose displacement we seek.\n :return: Summed displacement along the path.\n \"\"\"\n # Note: Site.distance returns vector magnitudes, so no worries about signage.\n displacement = 0\n for i in range(len(s_a) - 1):\n site_in_current_img = s_a[i][site_index]\n site_in_next_img = s_a[i + 1][site_index]\n displacement += site_in_current_img.distance(site_in_next_img)\n return displacement\n","sub_path":"ionic_mobility/database_getter.py","file_name":"database_getter.py","file_ext":"py","file_size_in_byte":10766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"342219110","text":"#!/usr/bin/env python\n# infoNode.py\n# This node subscribes to topics and posts them to the API server\n\nimport rospy\nimport rospkg\nimport yaml\nfrom riptide_msgs.msg import ControlStatus\n\nrpack = rospkg.RosPack()\nconfig_path = rpack.get_path('RoboThoughts') + \"backend/src/cfg/infoNode_cfg.yml\"\npubs = {}\ncfg = {}\n\ndef depth_callback(msg):\n depth = msg.current\n\n\ndef loadConfig():\n global cfg\n with open(config_path, 'r') as stream:\n cfg = yaml.load(stream)\n\ndef main():\n loadConfig()\n depth_sub = rospy.Subscriber(cfg['depth_topic'], Depth, depth_callback)\n\n rospy.spin()\n\nif __name__ == \"__main__\":\n rospy.init_node(\"infoNode\")\n main()","sub_path":"backend/src/infoNode.py","file_name":"infoNode.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"21119643","text":"from pyspark.ml import Pipeline\nfrom pyspark.ml.linalg import Vectors\nfrom pyspark.ml.feature import StringIndexer, OneHotEncoderEstimator, VectorAssembler\nfrom pyspark.ml.classification import LogisticRegression, OneVsRest\nfrom pyspark.sql import SparkSession\n\nif __name__ == \"__main__\":\n spark = SparkSession\\\n .builder\\\n .appName(\"EstimatorTransformerParam\")\\\n .getOrCreate()\n \n # Define Columns\n originColumns = [\"win\",\"b1\",\"b2\",\"b3\",\"b4\",\"b5\",\"b6\",\"b7\",\"b8\",\"b9\",\"b10\", \\\n \"p1\",\"p1p\",\"p2\",\"p2p\",\"p3\",\"p3p\",\"p4\",\"p4p\",\"p5\",\"p5p\",\"p6\",\"p6p\",\"p7\",\"p7p\",\"p8\",\"p8p\",\"p9\",\"p9p\",\"p10\",\"p10p\"]\n labelColumn = \"win\"\n stringColumns = [\"p1p\", \"p2p\", \"p3p\", \"p4p\", \"p5p\", \"p6p\", \"p7p\", \"p8p\", \"p9p\", \"p10p\",]\n indexColumns = [column+\"_i\" for column in stringColumns]\n vectorColumns = [column+\"_v\" for column in indexColumns]\n featureColumns = []\n for column in originColumns:\n if column != labelColumn and not column in stringColumns:\n featureColumns.append(column)\n for column in vectorColumns:\n featureColumns.append(column)\n \n # Load DataFrame\n data = spark.read.load(\"data/3187/yzh/t6.csv\",format=\"csv\",sep=',',inferSchema=\"true\",header=\"false\")\n data = data.toDF(*originColumns)\n\n # Turn string to index\n indexers = [StringIndexer(inputCol=column,outputCol=column+\"_i\").fit(data) for column in stringColumns]\n data = Pipeline(stages=indexers).fit(data).transform(data)\n # Turn index to vector\n encoder = OneHotEncoderEstimator(inputCols=indexColumns,outputCols=vectorColumns)\n data = encoder.fit(data).transform(data)\n # Combine vectors to one\n assembler = VectorAssembler(inputCols=featureColumns,outputCol=\"features\")\n data = assembler.transform(data)\n\n # Split data into train and test\n rSplit = data.randomSplit([0.97,0.03], 100)\n dataTrain = rSplit[0].select(\"features\", labelColumn)\n dataTest = rSplit[1].select(\"features\", labelColumn)\n\n # Creat, train, fit model\n lr = LogisticRegression(maxIter=20,regParam=0.01)\n ovr = OneVsRest(classifier=lr)\n model = ovr.fit(dataTrain.withColumnRenamed(labelColumn, \"label\"))\n result = model.transform(dataTest).select(labelColumn, \"prediction\").collect()\n \n # Check, show result\n counter = [0,0]\n for row in result:\n counter[0] += 1\n if row[labelColumn] == row.prediction:\n counter[1] += 1\n print(\"----- Mission Complite -----\")\n print(f\"Predicted {counter[0]} items, and {counter[1]} are correct.\")\n print(f\"Correct rate is {round(counter[1]/counter[0]*10000)/100}%\")\n print(\"\")\n\n spark.stop()\n","sub_path":"python/ml/one_vs_rest.py","file_name":"one_vs_rest.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"84059915","text":"#!/usr/bin/env python3\n\nfrom logic import *\n\nimport pickle, gzip, os, random\nimport pruebasUtil\n\npruebas = pruebasUtil.Grader()\nrespuestas = pruebas.load('ejercicios')\n\n# name: nombre de una formula (usada para cargar los modelos)\n# predForm: la formula predicha en las respuestas\n# preconditionForm: solo considera modelos tal que preconditionForm es verdadero\ndef checkFormula(name, predForm, preconditionForm=None):\n filename = os.path.join('modelos', name + '.pklz')\n objects, targetModels = pickle.load(gzip.open(filename))\n # Si existe una condicion previa, cambia la formula a lo siguiente\n preconditionPredForm = And(preconditionForm, predForm) if preconditionForm else predForm\n predModels = performModelChecking([preconditionPredForm], findAll=True, objects=objects)\n ok = True\n def hashkey(model): return tuple(sorted(str(atom) for atom in model))\n targetModelSet = set(hashkey(model) for model in targetModels)\n predModelSet = set(hashkey(model) for model in predModels)\n for model in targetModels:\n if hashkey(model) not in predModelSet:\n pruebas.fail(\"Tu formula (%s) dice que este modelo es FALSE, pero debe ser TRUE:\" % predForm)\n ok = False\n printModel(model)\n return\n for model in predModels:\n if hashkey(model) not in targetModelSet:\n pruebas.fail(\"Tu formula (%s) dice que el siguiente modelo es TRUE, pero debe ser FALSE:\" % predForm)\n ok = False\n printModel(model)\n return\n pruebas.addMessage('Coinciden los %d modelos' % len(targetModels))\n pruebas.addMessage('Ejemplo de modelo: %s' % rstr(random.choice(targetModels)))\n pruebas.assignFullCredit()\n\n# name: nombre de una formula (usada para cargar los modelos)\n# predForms: formula predicha en las respuestas\n# predQuery: formula de consulta predicha en las respuestas\ndef addParts(name, numForms, predictionFunc):\n # aqui tenemos una formula individual (0:numForms), all (combina todo)\n def check(part):\n predForms, predQuery = predictionFunc()\n if len(predForms) < numForms:\n pruebas.fail(\"Queria %d formulas, pero obtuve %d formulas:\" % (numForms, len(predForms)))\n for form in predForms: print(('-', form))\n return\n if part == 'all':\n checkFormula(name + '-all', AndList(predForms))\n elif part == 'run':\n # Ejecutar sobre una base conocimiento\n kb = createModelCheckingKB()\n\n # Necesito decir a KB sobre los objetos para realizar la verificacion del modelo.\n filename = os.path.join('modelos', name + '-all.pklz')\n objects, targetModels = pickle.load(gzip.open(filename))\n for obj in objects:\n kb.tell(Atom('Object', obj))\n\n # Agrega las formulas\n for predForm in predForms:\n response = kb.tell(predForm)\n showKBResponse(response)\n pruebas.requireIsEqual(CONTINGENT, response.status)\n response = kb.ask(predQuery)\n showKBResponse(response)\n\n else: # Verifica una parte de la formula\n checkFormula(name + '-' + str(part), predForms[part])\n\n def createCheck(part): return lambda : check(part) # Para crear la clausura\n\n for part in list(range(numForms)) + ['all', 'run']:\n if part == 'all':\n description = 'prueba de implementacion de %s para %s' % (part, name)\n elif part == 'run':\n description = 'prueba de implementacion de %s para %s' % (part, name)\n else:\n description = 'prueba de implementacion de la declaracion %s para %s' % (part, name)\n pruebas.addBasicPart(name + '-' + str(part), createCheck(part), maxPoints=1, maxSeconds=10000, description=description)\n\n############################################################\n# Problem 1: Logica proposicional\n\npruebas.addBasicPart('1a', lambda : checkFormula('1a', respuestas.formula1a()), 2, description='Prueba la implementacion de la formula 1a')\npruebas.addBasicPart('1b', lambda : checkFormula('1b', respuestas.formula1b()), 2, description='Prueba la implementacion de la formula 1b')\npruebas.addBasicPart('1c', lambda : checkFormula('1c', respuestas.formula1c()), 2, description='Prueba la implementacion de la formula 1c')\n\n############################################################\n# Problema 2: Logica de primer orden\n\nformula2a_precondition = AntiReflexive('Mother')\nformula2b_precondition = AntiReflexive('Child')\nformula2c_precondition = AntiReflexive('Child')\nformula2d_precondition = AntiReflexive('Parent')\npruebas.addBasicPart('2a', lambda : checkFormula('2a', respuestas.formula2a(), formula2a_precondition), 2, description='Prueba la implementacion de la formula 2a')\npruebas.addBasicPart('2b', lambda : checkFormula('2b', respuestas.formula2b(), formula2b_precondition), 2, description='Prueba la implementacion de la formula 2b')\npruebas.addBasicPart('2c', lambda : checkFormula('2c', respuestas.formula2c(), formula2c_precondition), 2, description='Prueba la implementacion de la formula 2c')\npruebas.addBasicPart('2d', lambda : checkFormula('2d', respuestas.formula2d(), formula2d_precondition), 2, description='Prueba la implementacion de la formula 2d')\n\n############################################################\n# Problema 3: Puzzle\n\n# Agrega 3a-[0-5], 3a-all, 3a-run\naddParts('3a', 6, respuestas.liar)\n\n############################################################\n# Problema 5: Enteros pares y impares\n\n# Agrega 5a-[0-5], 5a-all, 5a-run\naddParts('5a', 6, respuestas.ints)\n\npruebas.addManualPart('5b', 10, description='Prueba el argumento de que no hay un modelo finito donde las 7 formulas sean consistentes')\n\n############################################################\n\n\npruebas.grade()\n","sub_path":"CC441_Inteligencia_Artificial/tareas y examenes/LAB's/Laboratorio1/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"343659436","text":"import warnings\nfrom os import path\n\nimport matplotlib.pyplot as plt\nimport sympy as sy\nfrom numpy import array, arange, ndarray, ceil, log10, floor, NaN, append\n\nfrom .curve_simplification import ramer_douglas\nfrom .helpers import Circle, x, CustomExpr, Slope, Horizontal, sqrt\n\ng = 9.81 # m/s^2 Erdbeschleunigung\nny = 1.31e-6 # m^2/s bei 10°C von Wasser\n\n\n########################################################################################################################\n########################################################################################################################\nclass CrossSection:\n \"\"\"main class\n A Class that should help to generate custom cross section shapes for the SWMM software.\n\n Attributes:\n label (str): name/label/number of the cross section\n description (Optional[str]): optional description of the cross section\n shape (list): descriptions of the cross section as commands in a list\n accuracy (int): number of decimal points to use for the export\n working_directory (str): directory where the files get saved\n unit (str): unit of entered values\n double (bool): if the cross section two separate cross sections\n \"\"\"\n\n def __init__(self, label, description=None, height=None, width=None, working_directory='', unit=None):\n \"\"\"Initialise the cross section class\n\n Args:\n label (str): main name/label/number of the cross section\n description (Optional[str]): optional description of the cross section\n height (float): absolute height of the CS\n width (Optional[float]): absolute width of the CS (optional) can be estimated\n working_directory (str): directory where the files are saved\n unit (Optional[str]): enter unit to add the unit in the plots\n \"\"\"\n self.label = label\n self.description = ''\n if description is not None:\n self.description = str(description).strip()\n\n self._height = height\n self._width = width\n self.shape = list()\n self._shape_description = None # functions to describe the cross section\n self.accuracy = 3\n self.working_directory = working_directory\n self.unit = unit\n self.double = False\n\n # _______________________________\n # Profile data\n self.points = list()\n\n # _______________________________\n # print('_' * 30)\n # print(self)\n\n # _______________________________\n # calculate stationary flow\n self._area_v = None\n self._r_hyd_v = None\n self._l_u_v = None\n self._r_hyd_v = None\n self._v_v = None\n\n # _______________________________\n # number of points to describe the shape of the cross section\n # 100 is the limit of points which can be used as a SWMM shape\n self.max_number_points = 100\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n return '{}: {}'.format(self.label, self.description)\n\n @property\n def height(self):\n \"\"\"\n absolute height of the CS\n\n Returns:\n float: absolute height of the CS\n \"\"\"\n return self._height\n\n @property\n def width(self):\n \"\"\"\n absolute width of the CS\n\n Returns:\n float: absolute width of the CS\n \"\"\"\n return self._width\n\n def get_width(self):\n \"\"\"\n get absolute width of cross section\n\n Returns:\n float: width of cross section\n \"\"\"\n if not self.get_points():\n return None\n else:\n return max(self.points[1]) * 2\n\n @property\n def out_filename(self):\n \"\"\"\n filename of the figure/text-file to be created\n\n Returns:\n str: filename\n\n \"\"\"\n return path.join(self.working_directory, str(self.label))\n\n def _reset_shape(self):\n self.points = list()\n self._shape_description = None\n\n def add(self, x_or_expr, y=None):\n \"\"\"\n add part of cross section\n\n can be a:\n\n - function/expression\n - point (x,y) coordinates\n - boundary condition (x or y) of a surrounding function = only x or y is given and the other is :obj:`None`\n - slope (x=slope, y=unit of slope)\n\n\n Args:\n x_or_expr (Optional[float , None, CustomExpr]):\n\n - :obj:`float` : x coordinate or x-axis boundary or slope if any str keyword is used in argument ``y``\n - :obj:`CustomExpr` : Expression/function for the cross section part,\n i.e.: :obj:`shape_generator.Circle`, :obj:`Slope`, :obj:`Vertical`, :obj:`Horizontal`\n - :obj:`None` : if a y-axis boundary is given\n\n y (Optional[float,str]): y coordinate of unit of slope\n\n - :obj:`float` : x coordinate or x-axis boundary\n - :obj:`None` : if a x-axis boundary is given or an expression in ``x_or_expr``\n - :obj:`str` : argument x is a slope\n\n - ``slope`` : ready to use slope 1 / :math:`\\\\Delta` y\n - ``°slope`` : slope as an angle in degree (°)\n - ``%slope`` : slope in percentage (%)\n\n \"\"\"\n self._reset_shape()\n\n if isinstance(x_or_expr, CustomExpr):\n self.shape.append(x_or_expr)\n\n else:\n if x_or_expr is not None:\n x = float(x_or_expr)\n else:\n x = x_or_expr\n\n if isinstance(y, str) and 'slope' in y:\n if x == 0:\n self.shape.append(Horizontal())\n else:\n unit = y.replace('slope', '')\n self.shape.append(Slope(x, unit=unit))\n\n else:\n if y is not None:\n y = float(y)\n\n self.shape.append((x, y))\n\n def set_double_cross_section(self):\n \"\"\"\n make the cross section as a double section (=Doppelprofil)\n \"\"\"\n self.double = True\n\n @property\n def shape_description(self):\n \"\"\"\n list of functions to describe the cross section shape\n\n Returns:\n list: description of the cross section shape\n \"\"\"\n if self._shape_description is None:\n # result list\n function = list()\n\n def add_slope_to_function(point0, point1):\n start = point0[0]\n end = point1[0]\n yi = Slope.from_points(point0, point1)\n function.append((start, end, yi))\n\n # boundary condition\n last_point = (0, 0)\n final_point = (self.height, 0)\n\n for i, shape_i in enumerate(self.shape):\n\n # _________________________________\n # boundary condition\n if (i + 1) == len(self.shape):\n shape_next = final_point\n else:\n shape_next = self.shape[i + 1]\n\n # _________________________________\n # if isinstance(shape_i, tuple) and shape_i[1] == 'slope':\n # shape_i = Slope(shape_i[0])\n # shape_i.set_start_point(last_point)\n\n # ____________________________________________________________\n if isinstance(shape_i, tuple):\n\n if (shape_i[0] is None) or (shape_i[1] is None):\n # this part is only used as boundary condition\n if shape_next == final_point:\n start = last_point[0]\n end = shape_next[0]\n yi = Slope.from_points(last_point, shape_next)\n function.append((start, end, yi))\n\n continue\n\n if last_point[1] is not None:\n start = last_point[0]\n end = shape_i[0]\n yi = Slope.from_points(last_point, shape_i)\n function.append((start, end, yi))\n\n if shape_next == final_point:\n start = shape_i[0]\n end = shape_next[0]\n yi = Slope.from_points(shape_i, shape_next)\n function.append((start, end, yi))\n\n # ________________________________\n\n last_point = (end, shape_i[1])\n\n # ____________________________________________________________\n elif isinstance(shape_i, CustomExpr):\n yi = shape_i\n\n if isinstance(yi, Slope) and yi.x0 is None:\n yi.set_start_point(last_point)\n\n start = last_point[0]\n\n if isinstance(yi, Horizontal):\n if isinstance(shape_next, tuple):\n yi.set_points(last_point, shape_next)\n\n elif isinstance(shape_next, CustomExpr):\n warnings.warn('must be implemented', FutureWarning)\n\n else:\n if isinstance(shape_next, tuple):\n end = shape_next[0]\n\n if end is None and shape_next[1] is not None:\n end = sy.solve(yi.expr() - shape_next[1], x)[0]\n\n elif isinstance(shape_next, CustomExpr):\n res = sy.solve(yi.expr() - shape_next.expr(), x)\n if len(res) == 0:\n from scipy.optimize import minimize_scalar\n end = minimize_scalar(lambda j: float((yi.expr() - shape_next.expr()).subs(x, j)),\n bounds=(start, self.height), method='bounded').x\n\n elif len(res) == 1:\n end = float(res[0])\n else:\n # multiple results\n # TODO: how to handle it\n end = float(res[0])\n\n else:\n raise NotImplementedError('Unknown Input in shape')\n\n end = float(end)\n\n if start == end:\n warnings.warn('unused part of the shape detected. Ignoring this part.')\n continue\n\n function.append((start, end, yi))\n\n # ____________________________\n if isinstance(shape_next, tuple) and shape_next[1] is not None:\n last_point = (end, shape_next[1])\n else:\n last_point = (end, float(yi.solve(end)))\n\n # ____________________________________________________________\n self._shape_description = function\n\n return self._shape_description\n\n def _get_points_legacy(self):\n \"\"\"create absolute point coordinates and write it into :py:attr:`~df_abs`\n\n To create a :obj:`pandas.DataFrame` of all the points to describe the cross section.\n This function replaces the Expressions given in :py:attr:`~add` to points with x and y coordinates\n and writes them into the :py:attr:`~df_abs` attribute.\n\n Returns:\n pandas.DataFrame: absolute point coordinates\n \"\"\"\n # number of expressions used in shape\n warnings.warn('get_points | legacy mode')\n num_functions = sum([isinstance(i[2], Circle) for i in self.shape_description])\n\n step = None\n # if functions are used in shape\n\n if num_functions:\n # number of fixed points in shape\n num_points = (len(self.shape_description) - num_functions) * 2\n\n # calculate the net height of the circle functions.\n function_steps = {i: s[1] - s[0] for i, s in enumerate(self.shape_description) if\n isinstance(self.shape_description[i][2], Circle)}\n # step size used to discretise the expressions\n step = sum(function_steps.values()) / (self.max_number_points - num_points)\n\n min_step = 1 * 10 ** (-self.accuracy) * self.height\n if step < min_step:\n step = min_step\n\n x = list()\n y = list()\n\n for start, end, f in self.shape_description:\n if isinstance(f, Circle):\n # this_step = (end - start) / floor((end - start) / step)\n # print(step, ' vs ', this_step)\n nx = arange(start, end + step, step).clip(max=end)\n ny = f.solve(nx)\n x += list(nx)\n y += list(ny)\n elif isinstance(f, Horizontal):\n x0, y0 = f.start_point()\n x1, y1 = f.end_point()\n x += [x0, x1]\n y += [y0, y1]\n else:\n nx = array([start, end])\n x += list(nx)\n y += list(f.solve(nx))\n\n return x, y\n\n def get_points(self):\n \"\"\"create absolute point coordinates and write it into :py:attr:`~points`\n\n To create a :obj:`list[tuple]` of all the points to describe the cross section.\n This function replaces the Expressions given in :py:attr:`~add` to points with x and y coordinates\n and writes them into the :py:attr:`~points` attribute.\n\n Returns:\n list[list[float,float]]: absolute point coordinates\n \"\"\"\n if not self.points:\n step = 10 ** (-self.accuracy) * self.height\n # if functions are used in shape\n\n x = list()\n y = list()\n\n for start, end, f in self.shape_description:\n if isinstance(f, Circle):\n nx = arange(start, end + step, step).clip(max=end)\n ny = f.solve(nx)\n x += list(nx)\n y += list(ny)\n elif isinstance(f, Horizontal):\n x0, y0 = f.start_point()\n x1, y1 = f.end_point()\n x += [x0, x1]\n y += [y0, y1]\n else:\n nx = array([start, end])\n x += list(nx)\n y += list(f.solve(nx))\n x, y = zip(*ramer_douglas(list(zip(x, y)), dist=step))\n\n if len(x) > self.max_number_points:\n x, y = self._get_points_legacy()\n\n # -------------------------\n # prevent duplicate x values (raises SWMM error)\n if len(x[1:-1]) != len(set(x[1:-1])):\n x = list(x)\n for i in range(1, len(x)-1):\n if (x[i] != 0) and (x[i] == x[i-1]):\n x[i] += step\n\n # -------------------------\n self.points = x, y\n\n return self.points\n\n def _check_points(self):\n \"\"\"\n remove errors from the point cloud, ie.:\n - remove duplicates,\n - (if specified) remove points which overlap the overall cross section width and\n - other errors...\n \"\"\"\n df = self.df_rel # (self.df_abs / self.height).copy()\n df = df.round(self.accuracy)\n df = df.drop_duplicates()\n\n if self.width is not None and any(df['y'] > self.width / 2):\n df['y'] = df['y'].clip_upper(self.width / 2)\n warnings.warn('had to clip the width')\n\n # print((arctan(df['x'].diff() / df['y'].diff())/ pi * 180).head(10))\n df = df.dropna()\n\n if self.double:\n df['y'] *= 2\n\n # delete errors\n df = df[df['x'].expanding().max() == df['x']].copy()\n\n # # change x duplicates\n # dupls = df['x'].duplicated(keep=False)\n # if dupls.any():\n # nx = df['x'][dupls]\n #\n # def raise_values(s):\n # return s + Series(index=s.index, data=range(len(s.index))) * 10 ** (-self.accuracy)\n #\n # nx = nx.groupby(nx).apply(raise_values)\n # df.loc[nx.index, 'x'] = nx\n\n self._df_abs = (df * self.height).copy()\n\n def profile_figure(self, relative=False, half=False) -> plt.Figure:\n \"\"\"create a plot of the cross section\"\"\"\n def custom_round(x_, base):\n return base * ceil(float(x_) / base)\n\n x, y = self.get_points()\n hi = array(x)\n wi = array(y)\n\n w = wi.max()\n h = hi.max()\n\n # -------------------------\n fig, ax = plt.subplots()\n\n # -------------------------\n if relative:\n hi /= h\n wi /= h\n\n xlim = 1\n ylim = 1\n base = 0.2\n\n # -------------------------\n ax.set_ylabel('rel H')\n ax.set_xlabel('B/H')\n ax.set_title('{}: {}'.format(self.label, self.description))\n\n else:\n base = 10 ** floor(log10(w))\n xlim = custom_round(w, base)\n ylim = custom_round(h, base)\n\n # -------------------------\n n = self.label\n if self.label != self.description:\n n += ': {}'.format(self.description)\n\n ax.set_title('{}\\n{:0.0f}x{:0.0f}'.format(n, h, custom_round(w * 2, base/2)) +\n (self.unit if self.unit is not None else ''))\n\n # -------------------------\n if half:\n xlim_left = 0\n else:\n\n xlim_left = -xlim\n\n hi = append(hi, hi[::-1])\n wi = append(wi, wi[::-1]*-1)\n\n # -------------------------\n ax.plot(wi, hi, marker='.', ls='-', zorder=1000000, clip_on=False)\n\n # -------------------------\n # ax.legend().remove()\n ax.set_aspect('equal', 'box')\n ax.set_xticks(arange(xlim_left, xlim, base), minor=False)\n if base / 2 != 0:\n ax.set_xticks(arange(xlim_left, xlim, base / 2), minor=True)\n\n ax.set_yticks(arange(0, ylim, base), minor=False)\n if base / 2 != 0:\n ax.set_yticks(arange(0, ylim, base / 2), minor=True)\n\n # ax.set_axis_off()\n # ax.set_frame_on(False)\n # ax.axis()\n ax.tick_params(which='both', length=0, width=0, labelbottom=False, labeltop=False, labelleft=False,\n labelright=False, bottom=False, top=False, left=False, right=False)\n\n ax.set_xlim(xlim_left, xlim)\n ax.set_ylim(0, ylim)\n ax.grid(True)\n # ax.grid(True, which='minor', linestyle=':', linewidth=0.5)\n ax.set_xlabel(None)\n ax.set_axisbelow(True)\n\n # ------------------\n fig.tight_layout()\n return fig\n\n ####################################################################################################################\n # testing new functions\n ####################################################################################################################\n def b_w_t(self, hi):\n \"\"\"\n width of the cross section at a certain height\n (Wasseroberflächenbreite im teilgefüllten Querschnitt)\n\n Args:\n hi (float | numpy.ndarray): a certain height\n\n Returns:\n float | numpy.ndarray: width at the certain height\n \"\"\"\n if isinstance(hi, ndarray):\n w = array([NaN] * hi.size)\n # w = hi.copy()\n\n for i, (lower, upper, f) in enumerate(self.shape_description):\n b = (hi >= lower) & (hi <= upper)\n w[b] = f.solve(hi[b])\n\n return w * 2\n else:\n for lower, upper, f in self.shape_description:\n if lower <= hi <= upper:\n return f.solve(hi) * 2\n\n def l_u_t(self, hi):\n \"\"\"\n wetted perimeter in the partially filled cross section at a certain water level height\n (benetzter Umfang im teilgefüllten Querschnitt)\n\n Args:\n hi (float | numpy.ndarray): a certain height\n\n Returns:\n float | numpy.ndarray: wetted perimeter at the certain height\n \"\"\"\n if isinstance(hi, ndarray):\n l = array([0.] * hi.size)\n\n for i, (lower, upper, f) in enumerate(self.shape_description):\n b = hi > upper\n l[b] += f.length(lower, upper)\n\n b = (hi >= lower) & (hi <= upper)\n l[b] += f.length(lower, hi[b])\n\n else:\n l = 0\n for lower, upper, f in self.shape_description:\n if hi > upper:\n l += f.length(lower, upper)\n elif lower <= hi <= upper:\n l += f.length(lower, hi)\n break\n else:\n break\n\n return l * 2\n\n @property\n def l_u_v(self):\n \"\"\"\n wetted perimeter of the full filled cross section\n (benetzter Umfang im vollgefüllten Querschnitt)\n\n Returns:\n float | numpy.ndarray: wetted perimeter\n \"\"\"\n if self._l_u_v is None:\n self._l_u_v = self.l_u_t(self.height)\n return self._l_u_v\n\n def area_t(self, hi):\n \"\"\"\n flow area in the partially filled cross section at a certain water level height\n (Fließquerschnitt im teilgefüllten Querschnitt)\n\n Args:\n hi (float | numpy.ndarray): a certain height\n\n Returns:\n float | numpy.ndarray: flow area at the certain height\n \"\"\"\n if isinstance(hi, ndarray):\n a = array([0.] * hi.size)\n\n for i, (lower, upper, f) in enumerate(self.shape_description):\n b = hi > upper\n a[b] += f.area(lower, upper)\n\n b = (hi >= lower) & (hi <= upper)\n a[b] += f.area(lower, hi[b])\n\n else:\n a = 0\n for lower, upper, f in self.shape_description:\n if hi > upper:\n a += f.area(lower, upper)\n elif lower <= hi <= upper:\n a += f.area(lower, hi)\n break\n else:\n break\n\n return a * 2\n\n @property\n def area_v(self):\n \"\"\"\n flow area of the full filled cross section\n (Fließquerschnitt im vollgefüllten Querschnitt)\n\n Returns:\n float | numpy.ndarray: flow area\n \"\"\"\n if self._area_v is None:\n self._area_v = self.area_t(self.height)\n return self._area_v\n\n def r_hyd_t(self, hi):\n \"\"\"\n hydraulic radius in the partially filled cross section at a certain water level height\n (hydraulischer Radius im teilgefüllten Querschnitt)\n\n Args:\n hi (float | numpy.ndarray): a certain height\n\n Returns:\n float | numpy.ndarray: hydraulic radius at the certain height\n \"\"\"\n return self.area_t(hi) / self.l_u_t(hi)\n\n @property\n def r_hyd_v(self):\n \"\"\"\n hydraulic radius of the full filled cross section\n (hydraulischer Radius im vollgefüllten Querschnitt)\n\n Returns:\n float | numpy.ndarray: hydraulic radius\n \"\"\"\n if self._r_hyd_v is None:\n self._r_hyd_v = self.area_v / self.l_u_v\n return self._r_hyd_v\n\n ####################################################################################################################\n def velocity_v(self, slope, k):\n \"\"\"\n calculate velocity in partially filled sewer channel\n\n Args:\n slope (float): ablosute slope in m/m\n k (float): Betriebliche Rauhigkeit in mm\n\n Returns:\n float: full filling velocity in m/s\n\n References:\n DWA-A 110 Section 4.1.1 Vollfüllung\n \"\"\"\n if self._v_v is None:\n self._v_v = dict()\n\n if k not in self._v_v:\n self._v_v[k] = dict()\n\n if slope not in self._v_v[k]:\n self._v_v[k][slope] = None\n\n if self._v_v[k][slope] is None:\n r_hyd = self.r_hyd_v / 1000 # from mm to m\n J = slope # / 1000\n k = k / 1000 # from mm to m\n self._v_v[k][slope] = (\n -2 * log10(2.51 * ny / (4 * r_hyd * sqrt(2 * g * J)) + k / (14.84 * r_hyd)) * sqrt(\n 2 * g * 4 * r_hyd * J))\n\n return self._v_v[k][slope]\n\n def velocity_t(self, hi, slope, k):\n \"\"\"\n calculate velocity in partially filled sewer channel\n\n Args:\n hi (float): water level = height in mm\n slope (float): ablosute slope in m/m\n k (float): Betriebliche Rauhigkeit in mm\n\n Returns:\n float: velocity in m/s\n\n References:\n DWA-A 110 Section 4.1.2 Teilfüllung\n \"\"\"\n return (self.r_hyd_t(hi) / self.r_hyd_v) ** 0.625 * self.velocity_v(slope, k)\n\n def flow_t(self, hi, slope, k):\n \"\"\"\n\n Args:\n hi (float): water level = height in mm\n slope (float): ablosute slope in m/m\n k (float): Betriebliche Rauhigkeit in mm\n\n Returns:\n float: flow rate in L/s\n \"\"\"\n return self.velocity_t(hi, slope, k) * self.area_t(hi) * 1.0e-6 * 1000\n\n def flow_v(self, slope, k):\n \"\"\"\n\n Args:\n slope (float): absolute slope in m/m\n k (float): Betriebliche Rauhigkeit in mm\n\n Returns:\n float: full filling flow rate in L/s\n \"\"\"\n return self.velocity_v(slope, k) * self.area_v * 1.0e-6 * 1000\n\n ####################################################################################################################\n def h_t(self, Q_t, slope, k):\n \"\"\"\n get the height of the water level based on the known flow\n\n Args:\n Q_t (float): flow in L/s\n slope (float): absolute slope in m/m\n k (float): Betriebliche Rauhigkeit in mm\n\n Returns:\n float: height of the water level\n \"\"\"\n # hi = '?'\n # self.flow_t(hi, slope, k)\n # self.flow_v(slope, k)\n from scipy.optimize import minimize_scalar\n res = minimize_scalar(lambda hi: abs(Q_t - self.flow_t(hi, slope, k)), bounds=(0, self.height),\n method='bounded')\n return res.x\n","sub_path":"shape_generator/shape_generator.py","file_name":"shape_generator.py","file_ext":"py","file_size_in_byte":26471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"534484295","text":"#!/usr/bin/env python33\n\n\"\"\"\nConfiguration for P1 ADC single-chip board\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom builtins import super\nfrom builtins import int\nfrom builtins import range\nfrom builtins import hex\nfrom builtins import str\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import object\nimport sys \nimport string\nimport time\nimport copy\nimport os.path\nimport subprocess\nfrom femb_python.femb_udp_P1A01 import FEMB_UDP\nfrom femb_python.test_measurements.adc_clk_tst.femb_udp_cmdline import FPGA_UDP\nfrom femb_python.configuration.config_base import FEMB_CONFIG_BASE, FEMBConfigError, SyncADCError, InitBoardError, ConfigADCError, ReadRegError\nfrom femb_python.configuration.adc_asic_reg_mapping_P1 import ADC_ASIC_REG_MAPPING\nfrom femb_python.test_measurements.adc_clk_tst.adc_asic_reg_mapping import ADC_ASIC_REG_MAPPING_NEW# fix/update!\nfrom femb_python.test_instrument_interface.keysight_33600A import Keysight_33600A\nfrom femb_python.test_instrument_interface.rigol_dp800 import RigolDP800\n\nclass FEMB_CONFIG(FEMB_CONFIG_BASE):\n\n def __init__(self,exitOnError=True):\n super().__init__(exitOnError=exitOnError)\n #declare board specific registers\n self.FEMB_VER = \"adctestP1single_clkTest\"\n self.REG_RESET = 0 # checked (good)\n self.REG_ASIC_RESET = 1 # checked (good)\n self.REG_ASIC_SPIPROG = 2 # checked (good)\n self.REG_SEL_CH = 7 # checked (good)\n self.REG_HS = 17 # checked (wtf)\n self.REG_ADCSPI_BASE = 0x200 # 512 in decimal updated (good)\n self.REG_ADCSPI_RDBACK_BASE = 0x250 # 592 in decimal updated (good)\n\n self.REG_LATCHLOC1_4 = 4 # checked (good) latch_loc0(7 downto 0)\n self.REG_CLKPHASE = 6 # checked (good) is it the same as phase control?\n\n self.REG_LATCHLOC1_4_data_1MHz = 0x6060604 # update\n self.REG_CLKPHASE_data_1MHz = 0x14 # update\n self.REG_LATCHLOC1_4_data_2MHz = 0x6060604 # update\n self.REG_CLKPHASE_data_2MHz = 0x14 # update\n\n self.ADC_TESTPATTERN = [0x12, 0x345, 0x678, 0xf1f, 0xad, 0xc01, 0x234, 0x567, 0x89d, 0xeca, 0xff0, 0x123, 0x456, 0x789, 0xabc, 0xdef]\n\n ##################################\n # external clock control registers\n ##################################\n self.FPGA_FREQ_MHZ = 200 # frequency of FPGA clock in MHz\n self.REG_EXTCLK_PERIOD = 20\n\n self.REG_EXTCLK_INV = 21 # checked (good)\n self.REG_EXTCLK_RST_OFF = 22 # checked (good) \n self.REG_EXTCLK_RST_WID = 23 # checked (good)\n self.REG_EXTCLK_READ_OFF = 24 # checked (good)\n self.REG_EXTCLK_READ_WID = 25 # checked (good)\n self.REG_EXTCLK_IDXM_OFF = 26 # checked (good)\n self.REG_EXTCLK_IDXM_WID = 27 # checked (good)\n self.REG_EXTCLK_IDXL_OFF = 28 # checked (good)\n self.REG_EXTCLK_IDXL_WID = 29 # checked (good)\n self.REG_EXTCLK_IDL1_OFF = 30 # checked (good)\n self.REG_EXTCLK_IDL1_WID = 31 # checked (good)\n self.REG_EXTCLK_IDL2_OFF = 32 # checked (good)\n self.REG_EXTCLK_IDL2_WID = 33 # checked (good)\n self.REG_EXTCLK_PLL_STEP0 = 34 # checked (good)\n self.REG_EXTCLK_PLL_STEP1 = 35 # checked (good)\n self.REG_EXTCLK_PLL_STEP2 = 36 # checked (good)\n\n self.EC_RST_OFF = 0\n self.EC_RST_WID = 50\n self.EC_RD_OFF = 490\n self.EC_RD_WID = 10\n self.EC_IDXM_OFF = 210\n self.EC_IDXM_WID = 285\n self.EC_IDXL_OFF = 490\n self.EC_IDXL_WID = 10\n self.EC_IDL1_OFF = 50\n self.EC_IDL1_WID = 190\n self.EC_IDL2_OFF = 490\n self.EC_IDL2_WID = 10\n self.EC_PLL_STEP0 = 0x0014000d #0x000b000f # found in labview\n self.EC_PLL_STEP1 = 0x00120006 #0x000e0008 # found in labview\n self.EC_PLL_STEP2 = 0x80190009 # found in labview\n self.inv_rst=True\n self.inv_read=False\n self.inv_idxm=False\n self.inv_idxl=False\n self.inv_idl=False\n #self.inv_clk_dis=True\n\n ##################################\n ##################################\n\n self.NASICS = 1\n self.NCHNS = 16\n self.FUNCGENINTER = Keysight_33600A(\"/dev/usbtmc1\",1)\n self.POWERSUPPLYINTER = RigolDP800(\"/dev/usbtmc0\",[\"CH2\",\"CH3\",\"CH1\"]) # turn on CH2 first\n self.F2DEFAULT = 0\n self.CLKDEFAULT = \"fifo\"\n\n self.frame_size = 0x0efb\n self.BPS = 13 #Bytes per sample\n\n ## Firmware update related variables\n self.FIRMWAREVERSION = \"A01\"\n self.FIRMWAREPATH2MHZ = \"/home/oper/Documents/CarlosForkedRepo/femb_python/femb_python/test_measurements/adc_clk_tst/S_SKT_ADC_CHP_TST.sof\"\n self.FIRMWAREPATH1MHZ = \"/home/oper/Documents/CarlosForkedRepo/femb_python/femb_python/test_measurements/adc_clk_tst/S_SKT_ADC_CHP_TST.sof\"\n self.FIRMWAREPROGEXE = \"/opt/sw/intelFPGA/17.0/qprogrammer/bin/quartus_pgm\"\n #self.FIRMWAREPROGCABLE = \"USB-Blaster\"\n self.FIRMWAREPROGCABLE = \"USB-BlasterII\"\n self.SAMPLERATE = 2e6\n\n #initialize FEMB UDP object\n self.femb = FEMB_UDP()\n self.adc_reg = ADC_ASIC_REG_MAPPING()\n self.adc_reg_new = ADC_ASIC_REG_MAPPING_NEW()\n self.femb_eh = FPGA_UDP()\n self.PC_IP = self.femb_eh.PC_IP\n self.FPGA_IP = self.femb_eh.FPGA_IP\n\n\n def selectChannel(self,asic,chan,hsmode=1,singlechannelmode=None):\n \"\"\"\n asic is chip number 0 to 7\n chan is channel within asic from 0 to 15\n hsmode: if 0 then streams all channels of a chip, if 1 only te selected channel. defaults to 1\n singlechannelmode: not implemented\n \"\"\"\n hsmodeVal = int(hsmode) & 1;\n asicVal = int(asic)\n if (asicVal < 0 ) or (asicVal >= self.NASICS ) :\n print( \"femb_config_femb : selectChan - invalid ASIC number, only 0 to {} allowed\".format(self.NASICS-1))\n return\n chVal = int(chan)\n if (chVal < 0 ) or (chVal > 15 ) :\n print(\"femb_config_femb : selectChan - invalid channel number, only 0 to 15 allowed\")\n return\n\n #print( \"Selecting ASIC \" + str(asicVal) + \", channel \" + str(chVal))\n self.femb.write_reg(8, 0x80000001) # WIB_MODE <= reg8_p(0) \n \"\"\"\n self.femb.write_reg ( self.REG_HS, hsmodeVal)\n regVal = (chVal << 8 ) + asicVal\n self.femb.write_reg( self.REG_SEL_CH, regVal)\n \"\"\"\n\n def programFirmware(self, firmware):\n \"\"\"\n Programs the FPGA using the firmware file given.\n \"\"\"\n if self.FIRMWAREPROGCABLE == \"USB-BlasterII\":\n # this programmer is too fast for our board \n # (or linux or something) so we have to slow it down\n jtagconfig_commandline = os.path.dirname(self.FIRMWAREPROGEXE)\n jtagconfig_commandline = os.path.join(jtagconfig_commandline,\"jtagconfig\")\n jtagconfig_commandline += \" --setparam 1 JtagClock 6M\"\n print(jtagconfig_commandline)\n subprocess.run(jtagconfig_commandline.split(),check=True)\n commandline = \"{} -c {} -m jtag -o p;{}\".format(self.FIRMWAREPROGEXE,self.FIRMWAREPROGCABLE,firmware)\n commandlinelist = commandline.split()\n print(commandline)\n print(commandlinelist)\n subprocess.run(commandlinelist,check=True)\n\n def checkFirmwareProgrammerStatus(self):\n \"\"\"\n Prints a debug message for the firmware programmer\n \"\"\"\n jtagconfig_commandline = os.path.dirname(self.FIRMWAREPROGEXE)\n jtagconfig_commandline = os.path.join(jtagconfig_commandline,\"jtagconfig\")\n if self.FIRMWAREPROGCABLE == \"USB-BlasterII\":\n # this programmer is too fast for our board \n # (or linux or something) so we have to slow it down\n jtagconfig_commandline_speed = jtagconfig_commandline +\" --setparam 1 JtagClock 6M\"\n print(jtagconfig_commandline_speed)\n subprocess.run(jtagconfig_commandline_speed.split())\n subprocess.run(jtagconfig_commandline.split())\n\n def programFirmware1Mhz(self):\n self.programFirmware(self.FIRMWAREPATH1MHZ)\n self.SAMPLERATE = 1e6\n\n def programFirmware2Mhz(self):\n self.programFirmware(self.FIRMWAREPATH2MHZ)\n self.SAMPLERATE = 2e6\n\n def getClockStr(self):\n latchloc1 = self.femb.read_reg(self.REG_LATCHLOC1_4)\n clkphase = self.femb.read_reg(self.REG_CLKPHASE)\n if latchloc1 is None:\n return \"Register Read Error\"\n #if latchloc5 is None:\n # return \"Register Read Error\"\n if clkphase is None:\n return \"Register Read Error\"\n return \"Latch Loc: {:#010x} Clock Phase: {:#010x}\".format(latchloc1,clkphase) #,latchloc5\n\n def getSyncStatus(self):\n return [None],[True],None\n\n \"\"\"\n testing\n \"\"\"\n\n def get_data_chipXchnX(self, chip, chn, packets = 1):\n \n if (chn < -1 ) or (chn > self.NCHNS ):\n print (\"FEMB CONFIG --> get_data_chipXchnX() -> Error: Channel must be between 0 and 15, or -1 for all channels\")\n return\n \n if (chip < 0 ) or (chip > self.NASICS ):\n print (\"FEMB CONFIG --> get_data_chipXchnX() -> Error: Chip must be between 0 and {}\".format(self.chip_num))\n return\n\n badSync = 0\n expVal = 1 #expected value\n k = 0\n for i in range(15):\n self.femb.write_reg(7, 0) # CHN_select <= reg7_p(7-0) \n time.sleep(0.01)\n self.femb.write_reg(7, chn) # CHN_select <= reg7_p(7-0) \n time.sleep(0.01)\n data = self.femb_eh.get_data_packets(data_type = \"int\", num = packets, header = False)\n #data1 = self.femb.get_data(num = packets)\n #print(\"normal: {} \".format(data[0:20]))\n #print(\"new: {} \".format(data1[0:20]))\n try:\n if (k > 0):\n print (\"get_data_chipXchnX --> Now doing another test\")\n #print (data[0:13])\n if (data[0] != 0xFACE):\n #If FACE isn't the first 2 bytes, turn WIB mode off and then on and try again\n self.femb.write_reg(8,0) # Turn WIB Mode Off\n time.sleep(0.01)\n self.femb.write_reg(8,1) # Turn WIB Mode On\n time.sleep(0.01)\n\n if (k > 14):\n #print (\"chipXchnX--> Error in get_data_chipXchnX: return None\")\n #print (hex(data[0]))\n #print (data)\n data = None\n badSync = 1\n expVal = 0\n return data, bs, ex # data none causes errors\n else:\n #print (\"chipXchnX--> Error in get_data_chipXchnX: Packet format error\")\n #print (\"k = {}\".format(k))\n #print (data[0:13])\n k += 1\n else:\n #print (\"chipXchnX--> Found header, break loop\")\n #print (\"k = {}\".format(k))\n #print (data[0:13])\n break\n except IndexError:\n print (\"FEMB CONFIG --> Something was wrong with the incoming data\")\n print (data)\n \n test_length = len(data)\n full_samples = test_length // self.BPS\n chn_data = []\n \n for i in range (full_samples):\n if (chn == 7):\n chn_data.append(data[(self.BPS*i)+1] & 0x0FFF)\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 6):\n chn_data.append(((data[(self.BPS*i)+2] & 0x00FF) << 4) + ((data[(self.BPS*i)+1] & 0xF000) >> 12))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 5):\n chn_data.append(((data[(self.BPS*i)+3] & 0x000F) << 8) + ((data[(self.BPS*i)+2] & 0xFF00) >> 8))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 4):\n chn_data.append(((data[(self.BPS*i)+3] & 0xFFF0) >> 4))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 3):\n chn_data.append(data[(self.BPS*i)+4] & 0x0FFF)\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 2):\n chn_data.append(((data[(self.BPS*i)+5] & 0x00FF) << 4) + ((data[(self.BPS*i)+4] & 0xF000) >> 12))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 1):\n chn_data.append(((data[(self.BPS*i)+6] & 0x000F) << 8) + ((data[(self.BPS*i)+5] & 0xFF00) >> 8))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 0):\n chn_data.append(((data[(self.BPS*i)+6] & 0xFFF0) >> 4))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 15):\n chn_data.append(data[(self.BPS*i)+7] & 0x0FFF)\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 14):\n chn_data.append(((data[(self.BPS*i)+8] & 0x00FF) << 4) + ((data[(self.BPS*i)+7] & 0xF000) >> 12))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 13):\n chn_data.append(((data[(self.BPS*i)+9] & 0x000F) << 8) + ((data[(self.BPS*i)+8] & 0xFF00) >> 8))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 12):\n chn_data.append(((data[(self.BPS*i)+9] & 0xFFF0) >> 4))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 11):\n chn_data.append(data[(self.BPS*i)+10] & 0x0FFF)\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 10):\n chn_data.append(((data[(self.BPS*i)+11] & 0x00FF) << 4) + ((data[(self.BPS*i)+10] & 0xF000) >> 12))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 9):\n chn_data.append(((data[(self.BPS*i)+12] & 0x000F) << 8) + ((data[(self.BPS*i)+11] & 0xFF00) >> 8))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == 8):\n chn_data.append(((data[(self.BPS*i)+12] & 0xFFF0) >> 4))\n #print(\"chn: {} val: {}\".format(chn,chn_data))\n if (chn == -1):\n return (data)\n \n return chn_data, badSync, expVal\n\n def fixUnsyncNew(self, adc):\n\n print(\"\\n femb_config_sbnd.py -> fixUnsyncNew() -> adc = \" + str(adc) + \"\\n\") \n \n adcNum = int(adc)\n if (adcNum < 0) or (adcNum > 3):\n print (\"FEMB_CONFIG--> femb_config_femb : testLink - invalid asic number\")\n return\n\n initLATCH1_4 = self.femb.read_reg( self.REG_LATCHLOC1_4)\n initPHASE = self.femb.read_reg( self.REG_CLKPHASE)\n \n #loop through sync parameters\n shiftMask = (0xFF << 8*adcNum)\n initSetting = (initLATCH1_4 & shiftMask) >> (8*adcNum)\n print (\"FEMB_CONFIG--> First testing around default value of {}\".format(initSetting))\n for phase in range(0,4,1):\n clkMask = (0x3 << (adcNum * 2))\n testPhase = ( (initPHASE & ~(clkMask)) | (phase << (adcNum * 2)) ) \n self.femb.write_reg(self.REG_CLKPHASE, testPhase)\n #print (\"Init Setting is {}\".format(hex(initSetting)))\n #print (\"Will test {}, {}, and {}\".format(initSetting - 1, initSetting, initSetting + 1))\n for shift in range(initSetting - 1,initSetting + 2,1):\n print (\"\\n\\tfemb_config_sbnd.py -> fixUnsyncNew -> This time, we're testing {}\\n\".format(shift))\n testShift = ( (initLATCH1_4 & ~(shiftMask)) | (shift << 8*adcNum) )\n self.femb.write_reg(self.REG_LATCHLOC1_4, testShift)\n print (\"FEMB_CONFIG--> Trying to sync Chip {} with Latch Lock:{} and Phase:{}\".format(adcNum, \n hex(testShift), hex(testPhase)))\n \n #test link\n unsync, syncDicts = self.testUnsyncNew(adcNum)\n if unsync == True :\n print (\"FEMB_CONFIG--> ADC {} synchronized\".format(adc))\n self.REG_LATCHLOC1_4_data = testShift\n self.REG_CLKPHASE_data = testPhase\n return True\n #Then try all settings\n print (\"FEMB_CONFIG--> Now testing the rest of them\")\n for phase in range(0,4,1):\n clkMask = (0x3 << (adcNum * 2))\n testPhase = ( (initPHASE & ~(clkMask)) | (phase << (adcNum * 2)) ) \n self.femb.write_reg(self.REG_CLKPHASE, testPhase)\n #First test latch lock settings close to default values\n shiftMask = (0xFF << 8*adcNum)\n initSetting = initLATCH1_4 & shiftMask\n for shift in range(0,16,1):\n testShift = ( (initLATCH1_4 & ~(shiftMask)) | (shift << 8*adcNum) )\n self.femb.write_reg(self.REG_LATCHLOC1_4, testShift)\n print (\"FEMB_CONFIG--> Trying to sync Chip {} with Latch Lock:{} and Phase:{}\".format(adcNum, \n hex(testShift), hex(testPhase)))\n \n #test link\n unsync, syncDicts = self.testUnsyncNew(adcNum)\n if (unsync == 0):\n print (\"FEMB_CONFIG--> ADC {} synchronized\".format(adc))\n self.REG_LATCHLOC1_4_data = testShift\n self.REG_CLKPHASE_data = testPhase\n return True\n #if program reaches here, sync has failed\n print (\"FEMB_CONFIG--> ADC SYNC process failed for ADC # \" + str(adc))\n return False\n\n\n def testUnsyncNew(self, adc):\n print(\"Starting testUnsync adc: \",adc)\n adcNum = int(adc)\n badSync = 0 #\n syncDicts = [{}]*16 #\n syncDataCounts = [{} for i in range(16)] # data for each channel\n\n if (adcNum < 0 ) or (adcNum > 3 ):\n print (\"testUnsyncNew()--> asic number must be between 0 and 3\")\n badSync = 1\n return badSync\n \n clkphase = self.femb.read_reg(self.REG_CLKPHASE)\n latchloc = self.femb.read_reg(self.REG_LATCHLOC1_4)\n \n for phase in range(0,3,1):\n self.femb.write_reg(self.REG_CLKPHASE, clkphase)\n print(\"\\ntestUnsync Latch Loc: {:#010x} Clock Phase: {:#x}\".format\n (latchloc,clkphase))\n\n for j in range(50): #reset sync error\n self.femb_eh.write_reg(11, 1) # ERROR_RESET <= reg11_p(0)\n time.sleep(0.01)\n self.femb_eh.write_reg(11, 0) # ERROR_RESET <= reg11_p(0)\n time.sleep(0.01)\n \n if (adc == 0):\n conv_error = self.femb_eh.read_reg(12) # reg12_i => x\"\" & CONV_ERROR \n header_error = self.femb_eh.read_reg(13) # reg13_i => HDR2_ERROR & HDR1_ERROR \n \n error = False\n \n if (conv_error != 0):\n error = True # conv error\n \n if (header_error != 0):\n error = True # header error\n\n if (error == True): \n print (\"testUnsyncNew() -> conv error: {} header error: {} : {}\".format\n (conv_error,header_error, j)) # no errors\n\n if (error == False):\n print (\"testUnsyncNew() -> conv error: {} header error: {} : {}\".format\n (conv_error,header_error, j)) #break loop if no error found\n badSync = 0\n break\n\n elif (j > 45):\n badSync = 1\n break\n else:\n self.configAdcAsicNew(False)\n if (badSync == 1):\n clkphase = clkphase + 1\n else:\n break\n\n for ch in range(0,16,1):\n syncDicts[ch][\"data\"] = True\n syncDicts[ch][\"maxCodeMatchesExpected\"] = True\n for test in range(0,1,1):\n data, bs, ex = self.get_data_chipXchnX(chip = adcNum, chn = ch, packets = 1)\n if (ex == 0):\n syncDicts[ch][\"maxCodeMatchesExpected\"] = False \n if (data == None):\n badSync = 1 # Sync response didn't come in\n syncDicts[ch][\"data\"] = False\n continue\n if (bs == 0):\n syncDicts[ch][\"data\"] = True\n syncDicts[ch][\"maxCodeMatchesExpected\"] = True\n for samp in data[0:len(data)]:\n if samp != self.ADC_TESTPATTERN[ch]:\n print (\"testUnsyncNew() -> chip {} chn {} wr {} rb {}\".format\n (adcNum, ch, hex(self.ADC_TESTPATTERN[ch]), hex(samp)))\n badSync = 1\n break\n else:\n print (\"testUnsyncNew() -> chip {} chn {} wr {} rb {}\".format\n (adcNum, ch, hex(self.ADC_TESTPATTERN[ch]), hex(samp)))\n badSync = 0\n break\n if (badSync == 1 ):\n break\n\n return badSync, syncDicts\n\n\n def FinalSyncCheck(self):\n print (\"\\n FINAL SYNC CHECK\\n\")\n for a in range(0,self.NASICS,1):\n \n self.adc_reg_new.set_adc_global(chip = a, f5 = 1) # Test DATA\n self.configAdcAsicNew(False)\n\n # quad board settings:\n #self.select_chip(chip = a)\n \n # single board settings:\n #select_chip is not necessary\n\n badSync = 0\n expV = 1\n clkphase = self.femb.read_reg(self.REG_CLKPHASE)\n latchloc = self.femb.read_reg(self.REG_LATCHLOC1_4)\n \n for phase in range(0,3,1):\n self.femb.write_reg(self.REG_CLKPHASE, clkphase)\n print(\"\\nInitializing with Latch Loc: {:#010x} Clock Phase: {:#x}\".format\n (latchloc,clkphase))\n #for itry in range(10):\n for ch in range(0,16,1):\n data, badSync, expV = self.get_data_chipXchnX(chip = a, chn = ch, packets = 1)\n if (len(data) == 0):\n print (\"FEMB_CONFIG--> Sync response bad. Exiting()\")\n return 1\n\n if (badSync == 0):\n for samp in data[0:len(data)]:\n if samp != self.ADC_TESTPATTERN[ch]:\n badSync = 1 \n print (\"FinalSync--> chp {} chn {} wr: {} rb: {}\".format(a, ch, hex\n (self.ADC_TESTPATTERN[ch]), hex(samp)))\n else:\n badSync = 0 \n print (\"FinalSync--> chp {} chn {} wr: {} rb: {}\".format(a, ch, hex\n (self.ADC_TESTPATTERN[ch]), hex(samp)))\n break\n\n if badSync == 1:\n break\n #print(\"time after checking the sample {}\".format(time.time()))\n if badSync == 0:\n break\n else:\n clkphase = clkphase + 1\n\n #print(\"time after checking 100 samples {}\".format(time.time()))\n if badSync == 1:\n self.femb.write_reg( 9, 1)\n sys.exit(\"FEMB_CONFIG--> Failed final check looking at channel test values\")\n\n self.configAdcAsicNew(False)\n print (\"FEMB_CONFIG--> Chip {} recieved the correct test values!\".format(a))\n \n badSync, syncDicts = self.testUnsyncNew(a) #checks conv error & header error\n if (badSync == 1):\n self.femb.write_reg(9, 1)\n sys.exit(\"FEMB_CONFIG--> Sync failed in the final check\") \n\n \n self.femb.write_reg(14,0)\n # clk # 00-internal (0), 01-external, 10-internal monostable (2), 11-internal\n # frqc # 0-2MHz Monostable, 1-1MHz monostable\n # en_gr # 0 disable offset, 1 enable offset\n # slsb # 0 full current steering, 1 test data\n # f0 # 0 fifo write pointer internal IDL, 1 external IDL\n # f1 # 0 normal, 1 obsolete\n # f2 # 0 signal gen on, 1 signal gen off\n # f3 # 0 IDL delayed 5-10 ns, 1 IDL delay one clk cycle\n # f4 # \n # f5 # 0 adc data, 1 test data\n self.adc_reg_new.set_adc_chip(chip = a, d = 6, pcsr=1, pdsr=0, slp=0, tstin=1, clk = 2, frqc = 1, f0 = 0, f4 = 0, f5 = 0)\n self.configAdcAsicNew(True)\n\n\n for j in range(10): #reset sync error\n self.femb_eh.write_reg(11, 1) # ERROR_RESET <= reg11_p(0)\n time.sleep(0.01)\n self.femb_eh.write_reg(11, 0) # ERROR_RESET <= reg11_p(0)\n time.sleep(0.01)\n conv_error = self.femb_eh.read_reg(12) # reg12_i => x\"\" & CONV_ERROR \n header_error = self.femb_eh.read_reg(13) # reg13_i => HDR2_ERROR & HDR1_ERROR \n error = False\n \n if (conv_error != 0):\n error = True # conv error\n \n if (header_error != 0):\n error = True # header error\n\n if (error == True): \n print (\"testUnsyncNew() -> conv error: {} header error: {} : {}\".format(conv_error,header_error, j)) # no errors\n\n if (error == False):\n print (\"testUnsyncNew() -> conv error: {} header error: {} : {}\".format(conv_error,header_error, j)) #break loop if no error found\n break\n\n elif (j > 8):\n badSync = 1\n break\n else:\n self.configAdcAsicNew(False)\n #print (\"Loop {}\".format(j))\n\n def reConfigAdcAsicNew(self, to_print = True, enableOffsetCurrent=None,offsetCurrent=None,testInput=None,\n freqInternal=None,sleep=None,pdsr=None,pcsr=None,\n clockMonostable=None,clockExternal=None,clockFromFIFO=None,\n sLSB=None,f0=None,f1=None,f2=None,f3=None,f4=None,f5=None):\n\n \"\"\"\n % ADC ASIC CUSTOMIZATION\n \"\"\"\n if enableOffsetCurrent is None:\n enableOffsetCurrent=0\n if offsetCurrent is None:\n offsetCurrent=0\n else:\n offsetCurrent = int(\"{:04b}\".format(offsetCurrent)[::-1],2) # need to reverse bits, use string/list tricks\n if testInput is None:\n testInput=-1\n if freqInternal is None:\n freqInternal=-1\n if sleep is None:\n sleep=-1\n if pdsr is None:\n pdsr=-1\n if pcsr is None:\n pcsr=-1\n if sLSB is None:\n sLSB = -1\n if f1 is None:\n f1 = -1\n if f2 is None:\n f2 = -1\n if f3 is None:\n f3 = -1\n if f4 is None:\n f4 = -1\n if f5 is None:\n f5 = -1\n if not (clockMonostable or clockExternal or clockFromFIFO):\n clockExternal=True\n clk=0\n if clockExternal:\n clk=2\n elif clockFromFIFO:\n clk=0\n if (clockExternal == None):\n clk = 2 # automatically set to external\n if f0 is None:\n if clockExternal:\n f0 = 1\n else:\n f0 = 0\n if clockExternal:\n self.extClock(enable=True)\n #else:\n #self.extClock(enable=False)\n\n self.adc_reg_new.set_adc_chip(d = 6, pcsr=1, pdsr=0, slp=0, tstin=1, clk = clk, f0 = f0, f5 = 0)\n self.femb.write_reg( self.REG_ASIC_SPIPROG, 0x30)\n self.femb.write_reg( self.REG_ASIC_SPIPROG, 0)\n\n def configAdcAsicNew(self, to_print = True, enableOffsetCurrent=None,offsetCurrent=None,testInput=None,\n freqInternal=None,sleep=None,pdsr=None,pcsr=None,\n clockMonostable=None,clockExternal=None,clockFromFIFO=None,\n sLSB=None,f0=None,f1=None,f2=None,f3=None,f4=None,f5=None):\n\n Adcasic_regs = self.adc_reg_new.REGS\n #Adcasic_regs = self.adc_reg.REGS\n #ADC ASIC SPI registers\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0x40)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0)\n time.sleep(0.01)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0x20)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0)\n time.sleep(0.01)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0x40)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0)\n time.sleep(0.01)\n\n if (to_print == True):\n print (\"configAdcAsicNew -> Config ADC ASIC SPI\")\n for k in range(10): \n i = 0\n for regNum in range(self.REG_ADCSPI_BASE,self.REG_ADCSPI_BASE+len(Adcasic_regs),1):\n self.femb.write_reg( regNum, Adcasic_regs[i])\n i = i + 1\n \n if (to_print == True): # Write ADC ASIC SPI to FPGA\n print (\"\\t FEMB_CONFIG--> CONFIG() -> Program ADC ASIC SPI\")\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 0)\n time.sleep(.05)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 1)\n time.sleep(.05)\n self.femb.write_reg ( self.REG_ASIC_SPIPROG, 1)\n time.sleep(.05)\n\n if (to_print == True): # Print to screen\n print (\"FEMB_CONFIG--> Check ADC ASIC SPI\")\n \n readback_regs = []\n i = 0\n for regNum in range(self.REG_ADCSPI_RDBACK_BASE,self.REG_ADCSPI_RDBACK_BASE+len(Adcasic_regs),1):\n readback_regs.append(self.femb_eh.read_reg(regNum))\n #print(\"configAdcAsicNew() -> rb reg: {:#010x} from base: {:#010x}\".format(\n #regNum, Adcasic_regs[i]))\n i = i + 1\n \n i=0\n for i in range (0,len(readback_regs),1):\n if (Adcasic_regs[i] != readback_regs[i]):\n print (\"FEMB_CONFIG --> CONFIG() ERROR -> configAdcAsicNew() -> Adcasic_reg val incorrect = \" + str(hex(Adcasic_regs[i])) + \" , rb_reg = \" + str(hex(readback_regs[i])) )\n else:\n continue\n print (\"femb_config_sbnd.py -> configAdcAsicNew() -> Adcasic_reg correct = \" + str(hex(Adcasic_regs[i])) + \" , rb_reg = \" + str(hex(readback_regs[i])) )\n \n# val = self.femb.read_reg ( self.REG_ASIC_SPIPROG ) \n wrong = False\n if (wrong == True and k == 9):\n print (\"\\tFEMB_CONFIG--> CONFIG() -> SPI_Status\")\n print (hex(val))\n sys.exit(\"\\tFEMB_CONFIG--> CONFIG() -> femb_config_femb : Wrong readback. ADC SPI failed\")\n return\n \n elif (wrong == 0): \n if (to_print == True):\n print(\"FEMB_CONFIG--> ADC ASIC SPI is OK\")\n break\n \n def extClock(self, enable=True):\n self.femb_eh.write_reg(14, 0) #set 200MHz adc clock \n\n clock = 1./ self.FPGA_FREQ_MHZ * 1000. # clock now in ns (5*10^(-9))\n mult = 1\n denominator = clock/mult\n cl1 = self.EC_RST_OFF // denominator\n cl2 = self.EC_RST_WID // denominator\n cl3 = self.EC_RD_OFF // denominator\n cl4 = self.EC_RD_WID // denominator\n cl5 = self.EC_IDXM_OFF // denominator\n cl6 = self.EC_IDXM_WID // denominator\n cl7 = self.EC_IDXL_OFF // denominator\n cl8 = self.EC_IDXL_WID // denominator\n cl9 = self.EC_IDL1_OFF // denominator\n cl10 = self.EC_IDL1_WID // denominator\n cl11 = self.EC_IDL2_OFF // denominator\n cl12 = self.EC_IDL2_WID // denominator\n inv=0\n if self.inv_rst: #INV_RST\n inv += 1 << 0\n if self.inv_read: #INV_READ\n inv += 1 << 1\n if self.inv_idxm: #INV_IDXM\n inv += 1 << 2\n if self.inv_idxl: #INV_IDXL\n inv += 1 << 3\n if self.inv_idl: #INV_IDL\n inv += 1 << 4\n #Coarse Control\n self.femb_eh.write_reg(21, inv)\n self.femb_eh.write_reg(22, cl1) # RESET Offset \n self.femb_eh.write_reg(23, cl2) # RESET Width\n self.femb_eh.write_reg(24, cl3) # READ Offset\n self.femb_eh.write_reg(25, cl4) # READ Width\n self.femb_eh.write_reg(26, cl5)#self.EC_IDXM_OFF) # IDXM Offset\n self.femb_eh.write_reg(27, cl6)#self.EC_IDXM_WID) # IDXM Width \n self.femb_eh.write_reg(28, cl7)#self.EC_IDXL_OFF) # IDXL Offset\n self.femb_eh.write_reg(29, cl8)#self.EC_IDXL_WID) # IDXL Width\n self.femb_eh.write_reg(30, cl9)#self.EC_IDL1_OFF) # IDL1 Offset\n self.femb_eh.write_reg(31, cl10)#self.EC_IDL1_WID) # IDL1 Width \n self.femb_eh.write_reg(32, cl11)#self.EC_IDL2_OFF) # IDL2 Offset\n self.femb_eh.write_reg(33, cl12)#self.EC_IDL2_WID) # IDL2 Width\n #Fine Control\n self.femb_eh.write_reg(34, self.EC_PLL_STEP0) # C0 & C1 fine clock settings \n self.femb_eh.write_reg(35, self.EC_PLL_STEP1) # C2 & C3 fine clock settings\n self.femb_eh.write_reg(36, self.EC_PLL_STEP2) # C2 & C3 fine clock settings\n\n def syncADCNew(self,iASIC=None):\n print(\"\\nsyncADCNew - BEGIN\\n\")\n alreadySynced = True\n for a in range(0,self.NASICS,1):\n print(\"FEMB_CONFIG--> Test ADC \" + str(a))\n self.adc_reg_new.set_adc_global(chip = a, f5 = 1) # Test DATA\n self.configAdcAsicNew(False)\n unsync, syncDicts = self.testUnsyncNew(a)\n if unsync != 0:\n alreadySynced = False\n print(\"FEMB_CONFIG--> ADC not synced, try to fix\")\n response = self.fixUnsyncNew(a)\n if (response != True):\n sys.exit (\" FEMB_CONFIG --> ADC {} could not sync\".format(a))\n elif (unsync == 1):\n print (\"FEMB_CONFIG--> ADC {} synced!\".format(a))\n \n self.adc_reg_new.set_adc_global(chip = a, f5 = 1) # Test DATA\n self.configAdcAsicNew(True)\n \n self.FinalSyncCheck()\n latchloc1_4 = self.femb.read_reg(self.REG_LATCHLOC1_4) \n clkphase = self.femb.read_reg(self.REG_CLKPHASE)\n if self.SAMPLERATE == 1e6:\n self.REG_LATCHLOC1_4_data_1MHz = latchloc1_4\n self.REG_CLKPHASE_data_1MHz = clkphase\n else: # 2 MHz\n self.REG_LATCHLOC1_4_data_2MHz = latchloc1_4\n self.REG_CLKPHASE_data_2MHz = clkphase\n\n print (\"FEMB_CONFIG--> Final Latch latency \" + str(hex(latchloc1_4)))\n print (\"FEMB_CONFIG--> Final Phase Shift \" + str(hex(clkphase)))\n print (\"FEMB_CONFIG--> ADC passed Sync Test!\")\n\n return not alreadySynced,latchloc1_4,clkphase \n\n def resetBoardNew(self): #cp 1/17/18\n #\n # resetFEMBBoard()\n # sends a 1 to register 1 for \"instantaneous\" ASIC reset.\n # sends a 0 to register 1 to ensure reset is not locked in.\n #\n # procedure:\n # line 29: FPGA to ASIC reset\n # line 30: wait 5 ms\n # line 31: FPGA to ASIC disable reset\n #\n \n print (\"resetBoardNew - BEGIN\")\n #Reset FEMB system\n self.femb.write_reg ( self.REG_RESET, 1)\n time.sleep(5.)\n self.femb.write_reg ( self.REG_RESET, 0)\n time.sleep(2.)\n print (\"FEMB_CONFIG--> Reset FEMB is DONE\\n\")\n\n\n def initBoardNew(self):\n #\n # initBoard()\n # \tset up default registers. \n # \tinitializes clock settings\n #\n print(\"\\ninitBoardNew - BEGIN\\n\")\n\n # Frame size is multiple of 13, so 0xFACE is consistently the first 2 bytes.\n frame_size = self.frame_size\n if (frame_size%13 != 0):\n frame_size = 13 * (frame_size//13)\n \n self.femb.write_reg(10, frame_size)\n time.sleep(0.1)\n \n if (self.femb.read_reg(10) != frame_size):\n sys.exit(\"FEMB_CONFIG--> initBoard() -> Frame Size not set correctly, something wrong with FPGA communication\")\n \n print (\"FEMB_CONFIG--> initBoard() -> Chip tester version {}\".format(hex(self.femb.read_reg(0x101))))\n\n # Set to WIB Mode and start by reading out chip 1\n # Channel Setting is irrelevant in WIB mode\n self.femb.write_reg(8, 0x80000001) # WIB_MODE <= reg8_p(0)\n self.femb.write_reg(7, 0x80000000) # CHN_select <= reg7_p(7 downto 0)\n\n \"\"\" SHIFT DATA BUS \"\"\"\n clockphase = self.REG_CLKPHASE_data_2MHz\n for iTry in range(5):\n self.femb.write_reg( self.REG_CLKPHASE, ~clockphase)\n time.sleep(0.05)\n self.femb.write_reg( self.REG_CLKPHASE, ~clockphase)\n time.sleep(0.05)\n self.femb.write_reg( self.REG_CLKPHASE, 0x14)\n time.sleep(0.05)\n self.femb.write_reg( self.REG_CLKPHASE, clockphase)\n time.sleep(0.05)\n\n # LATCH_LOC_0 <= reg4_p(7 downto 0)\n self.femb.write_reg(self.REG_LATCHLOC1_4, self.REG_LATCHLOC1_4_data_2MHz)\n \n \"\"\" SHIFT DATA BUS \"\"\"\n # CLK_selectx <= reg6_p(7 downto 0)\n self.femb.write_reg(self.REG_CLKPHASE, self.REG_CLKPHASE_data_2MHz)\n inv=0\n if self.inv_rst: #INV_RST\n inv += 1 << 0\n if self.inv_read: #INV_READ\n inv += 1 << 1\n if self.inv_idxm: #INV_IDXM\n inv += 1 << 2\n if self.inv_idxl: #INV_IDXL\n inv += 1 << 3\n if self.inv_idl: #INV_IDL\n inv += 1 << 4\n\n clock = 1./ self.FPGA_FREQ_MHZ * 1000. # clock now in ns (5*10^(-9))\n mult = 1\n denominator = clock/mult\n cl1 = self.EC_RST_OFF // denominator\n cl2 = self.EC_RST_WID // denominator\n cl3 = self.EC_RD_OFF // denominator\n cl4 = self.EC_RD_WID // denominator\n cl5 = self.EC_IDXM_OFF // denominator\n cl6 = self.EC_IDXM_WID // denominator\n cl7 = self.EC_IDXL_OFF // denominator\n cl8 = self.EC_IDXL_WID // denominator\n cl9 = self.EC_IDL1_OFF // denominator\n cl10 = self.EC_IDL1_WID // denominator\n cl11 = self.EC_IDL2_OFF // denominator\n cl12 = self.EC_IDL2_WID // denominator\n \"\"\"\n print(\"set RSET CLK OFF: {}\".format(cl1))\n print(\"set RSET CLK WID: {}\".format(cl2))\n print(\"set READ CLK OFF: {}\".format(cl3))\n print(\"set READ CLK WID: {}\".format(cl4))\n print(\"set IDXM CLK OFF: {}\".format(cl5))\n print(\"set IDXM CLK WID: {}\".format(cl6))\n print(\"set IDXL CLK OFF: {}\".format(cl7))\n print(\"set IDXL CLK WID: {}\".format(cl8))\n print(\"set IDL1 CLK OFF: {}\".format(cl9))\n print(\"set IDL1 CLK WID: {}\".format(cl10))\n print(\"set IDL2 CLK OFF: {}\".format(cl11))\n print(\"set IDL2 CLK WID: {}\".format(cl12))\n \"\"\"\n self.femb_eh.write_reg(21, inv)\n self.femb_eh.write_reg(14, 0) #set 200MHz adc clock \n self.femb_eh.write_reg(22, cl1) # RESET Offset \n self.femb_eh.write_reg(23, cl2) # RESET Width\n self.femb_eh.write_reg(24, cl3) # READ Offset\n self.femb_eh.write_reg(25, cl4) # READ Width\n self.femb_eh.write_reg(26, cl5)#self.EC_IDXM_OFF) # IDXM Offset\n self.femb_eh.write_reg(27, cl6)#self.EC_IDXM_WID) # IDXM Width \n self.femb_eh.write_reg(28, cl7)#self.EC_IDXL_OFF) # IDXL Offset\n self.femb_eh.write_reg(29, cl8)#self.EC_IDXL_WID) # IDXL Width\n self.femb_eh.write_reg(30, cl9)#self.EC_IDL1_OFF) # IDL1 Offset\n self.femb_eh.write_reg(31, cl10)#self.EC_IDL1_WID) # IDL1 Width \n self.femb_eh.write_reg(32, cl11)#self.EC_IDL2_OFF) # IDL2 Offset\n self.femb_eh.write_reg(33, cl12)#self.EC_IDL2_WID) # IDL2 Width\n #Fine Control\n self.femb_eh.write_reg(34, self.EC_PLL_STEP0) # C0 & C1 fine clock settings \n self.femb_eh.write_reg(35, self.EC_PLL_STEP1) # C2 & C3 fine clock settings\n self.femb_eh.write_reg(36, self.EC_PLL_STEP2) # C2 & C3 fine clock settings\n\n #set default value to FEMB ADCs\n #clk = 2 is external\n #clk = 0 is internal\n self.adc_reg_new.set_adc_board(d=6, pcsr=1, pdsr=0, slp=0, tstin=1,\n clk = 0, frqc = 1, en_gr = 0, f0 = 0, f1 = 0, \n f2 = 0, f3 = 0, f4 = 0, f5 = 1, slsb = 0) # set to internal 1/31/18 cp\n \n self.femb.write_reg( self.REG_ASIC_SPIPROG, 0x30)\n self.femb.write_reg( self.REG_ASIC_SPIPROG, 0)\n self.configAdcAsicNew(False)\n","sub_path":"femb_python/configuration/configs/adcTest_P1single_clkTest.py","file_name":"adcTest_P1single_clkTest.py","file_ext":"py","file_size_in_byte":41537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"501945480","text":"# -- coding: utf-8 --\n\n##@package carrier\n#\tKlasy przechowywujące nośne.\n\nimport numpy\n\n##\tKlasa odpowiada za generowanie i przechowywanie nośnej.\nclass Carrier(object):\n\n\t## Konstruktor klasy Carrier\n\t#\t@param productSignal Obiekt klasy przechowywującej rozproszoną wiadomość.\n\tdef __init__(self, productSignal):\n\n\t\t## Wektor nośnej.\n\t\tself.carrier = numpy.empty(0, dtype=numpy.float64)\n\n\t\tamp = numpy.sqrt(2*productSignal.chipFrequency/productSignal.seq.shape[1])\n\t\tself.carrier = numpy.array(numpy.sin(numpy.multiply(productSignal.probes, \\\n\t\t\t2*numpy.pi*productSignal.chipFrequency)))\n\t\t\n\t\tself.carrier = numpy.multiply(self.carrier, amp)\n\n","sub_path":"carrier.py","file_name":"carrier.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"423147363","text":"import ctypes\nfrom datetime import datetime\n\n\n#\n# Enumerations\n#\n\n\nclass ControlOperation:\n \"\"\"\n Type of device control operation. See PULL SDK docs\n \"\"\"\n output = 1\n cancel_alarm = 2\n restart = 3\n\n\nclass RelayGroup:\n \"\"\"\n Device relay group. See PULL SDK docs\n \"\"\"\n lock = 1\n aux = 2\n\n\nVERIFY_MODES = {\n '1': 'Only finger',\n '3': 'Only password',\n '4': 'Only card',\n '11': 'Card and password',\n '200': 'Others'\n}\n\nEVENT_TYPES = {\n '0': 'Normal Punch Open',\n '1': 'Punch during Normal Open Time Zone',\n '2': 'First Card Normal Open (Punch Card)',\n '3': 'Multi-Card Open (Punching Card)',\n '4': 'Emergency Password Open',\n '5': 'Open during Normal Open Time Zone',\n '6': 'Linkage Event Triggered',\n '7': 'Cancel Alarm',\n '8': 'Remote Opening',\n '9': 'Remote Closing',\n '10': 'Disable Intraday Normal Open Time Zone',\n '11': 'Enable Intraday Normal Open Time Zone',\n '12': 'Open Auxiliary Output',\n '13': 'Close Auxiliary Output',\n '14': 'Press Fingerprint Open',\n '15': 'Multi-Card Open (Press Fingerprint)',\n '16': 'Press Fingerprint during Normal Open Time Zone',\n '17': 'Card plus Fingerprint Open',\n '18': 'First Card Normal Open (Press Fingerprint)',\n '19': 'First Card Normal Open (Card plus Fingerprint)',\n '20': 'Too Short Punch Interval',\n '21': 'Door Inactive Time Zone (Punch Card)',\n '22': 'Illegal Time Zone',\n '23': 'Access Denied',\n '24': 'Anti-Passback',\n '25': 'Interlock',\n '26': 'Multi-Card Authentication (Punching Card)',\n '27': 'Unregistered Card',\n '28': 'Opening Timeout',\n '29': 'Card Expired',\n '30': 'Password Error',\n '31': 'Too Short Fingerprint Pressing Interval',\n '32': 'Multi-Card Authentication (Press Fingerprint)',\n '33': 'Fingerprint Expired',\n '34': 'Unregistered Fingerprint',\n '35': 'Door Inactive Time Zone (Press Fingerprint)',\n '36': 'Door Inactive Time Zone (Exit Button)',\n '37': 'Failed to Close during Normal Open Time Zone',\n '101': 'Duress Password Open',\n '102': 'Opened Accidentally',\n '103': 'Duress Fingerprint Open',\n '200': 'Door Opened Correctly',\n '201': 'Door Closed Correctly',\n '202': 'Exit button Open',\n '203': 'Multi-Card Open (Card plus Fingerprint)',\n '204': 'Normal Open Time Zone Over',\n '205': 'Remote Normal Opening',\n '220': 'Auxiliary Input Disconnected',\n '221': 'Auxiliary Input Shorted',\n '255': 'Actually that obtain door status and alarm status',\n}\n\nENTRY_EXIT_TYPES = {\n '0': 'Entry',\n '1': 'Exit',\n '2': 'None'\n}\n\n\n#\n# Device model-specific classes\n#\n\nclass ZK400:\n \"\"\"ZKAccess C3-400\"\"\"\n relays = 8\n relays_def = (\n 1, 2, 3, 4,\n 1, 2, 3, 4\n )\n groups_def = (\n RelayGroup.aux, RelayGroup.aux, RelayGroup.aux, RelayGroup.aux,\n RelayGroup.lock, RelayGroup.lock, RelayGroup.lock, RelayGroup.lock\n )\n\n\nclass ZK200:\n \"\"\"ZKAccess C3-200\"\"\"\n relays = 4\n relays_def = (1, 2, 1, 2)\n groups_def = (RelayGroup.aux, RelayGroup.aux, RelayGroup.lock, RelayGroup.lock)\n\n\nclass ZK100:\n \"\"\"ZKAccess C3-100\"\"\"\n relays = 2\n relays_def = (1, 2)\n groups_def = (RelayGroup.aux, RelayGroup.lock)\n\n\n#\n# Main class\n#\n\n\nclass ZKAccess:\n \"\"\"\n Main class to work on. Contains interface for working with device, implements SDK calls and holds current state\n \"\"\"\n @property\n def device_model(self):\n \"\"\"Device model class. Read only\"\"\"\n return self._device_model\n\n @property\n def connstr(self):\n \"\"\"Device connection string. Read only.\"\"\"\n return self._connstr\n\n @property\n def dll_object(self):\n \"\"\"DLL object. Read only.\"\"\"\n return self._dll_object\n\n @property\n def handle(self):\n \"\"\"Device handle. Has 'None' value if it's not connected to device. Read only.\"\"\"\n return self._handle\n\n def __init__(self, dllpath, connstr=None, device_model=ZK400):\n \"\"\"\n Constructor. Takes path to DLL and device connection string.\n :param dllpath: Required. Full path to plcommpro.dll\n :param connstr: Optional. Device connection string. Connect will be performed if this specified.\n :param device_model: Optional. Device model class. Default is ZK400\n \"\"\"\n self._handle = None\n self._connstr = None\n self._device_model = device_model\n\n self._dll_object = ctypes.WinDLL(dllpath)\n\n if connstr:\n self.connect(connstr)\n\n def __del__(self):\n if self._handle:\n self.disconnect()\n\n def __enter__(self):\n if not self._handle:\n self.connect(self.connstr)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if self._handle:\n self.disconnect()\n\n def connect(self, connstr):\n \"\"\"\n Connect to device using connection string, ex:\n 'protocol=TCP,ipaddress=192.168.22.201,port=4370,timeout=4000,passwd='\n :param connstr: Device connection string\n :raises RuntimeError: if already connected\n :raises ConnectionError: connection attempt was unsuccessful\n :return:\n \"\"\"\n if self._handle:\n raise RuntimeError('Already connected')\n\n self._connstr = connstr\n self._handle = self._dll_object.Connect(connstr)\n if self._handle == 0:\n self._handle = None\n raise ConnectionError(\"Unable to connect device using connstr '{}'\".format(connstr))\n\n def disconnect(self):\n \"\"\"\n Disconnect from device\n :return:\n \"\"\"\n if not self._handle:\n return\n\n self._dll_object.Disconnect(self._handle)\n self._handle = None\n\n def enable_relay(self, group, number, timeout):\n \"\"\"\n Enable specified relay for the given time. Already enabled relay keep its state, but timeout overwrites with new\n value.\n :param group: Relay group, see RelayGroup enum. Number between 1 and 4\n :param number: Relay number in specified group\n :param timeout: Seconds the relay will be enabled. Number between 0 and 255\n :raises ValueError: invalid parameter\n :raises RuntimeError: operation failed\n :return:\n \"\"\"\n if number < 1 or number > self.device_model.relays:\n raise ValueError(\"Incorrect relay number: {}\".format(number))\n if timeout < 0 or timeout > 255:\n raise ValueError(\"Incorrect timeout: {}\".format(timeout))\n\n self.zk_control_device(\n ControlOperation.output,\n number,\n group,\n timeout,\n 0\n )\n\n def enable_relay_list(self, l, timeout):\n \"\"\"\n Enable relays by mask for the given time. Receives list with desired relays state: non-zero means enabled,\n zero means disabled. This action overwrites previous relays state.\n\n E.g. [1, 0, 0, 0, 0, 0, 1, 0] means 1, 7 relays get turned on in order as they placed on the device. Other\n ones get turned off.\n :param l: list with relays states\n :param timeout: Seconds the relay will be enabled. Number between 0 and 255\n :raises RuntimeError: operation failed\n :return:\n \"\"\"\n if timeout < 0 or timeout > 255:\n raise ValueError(\"Incorrect timeout: {}\".format(timeout))\n if len(l) != self.device_model.relays:\n raise ValueError(\"Relay list length '{}' is not equal to relays count '{}'\"\n .format(len(l), self.device_model.relays))\n\n for i in range(self.device_model.relays):\n if l[i]:\n self.zk_control_device(\n ControlOperation.output,\n self.device_model.relays_def[i],\n self.device_model.groups_def[i],\n timeout,\n 0\n )\n\n def read_events(self, buffer_size=4096):\n \"\"\"\n Read events from the device\n :param buffer_size:\n :return:\n \"\"\"\n raw = self.zk_get_rt_log(buffer_size)\n *events_s, empty = raw.split('\\r\\n')\n\n return (ZKRealtimeEvent(s) for s in events_s)\n\n def zk_control_device(self, operation, p1, p2, p3, p4, options_str=''):\n \"\"\"\n Device control machinery method. Read PULL SDK docs for parameters meaning\n :param operation: Number, operation id\n :param p1: Number, depends on operation id\n :param p2: Number, depends on operation id\n :param p3: Number, depends on operation id\n :param p4: Number, depends on operation id\n :param options_str: String, depends on operation id\n :raises RuntimeError: if operation was failed\n :return: dll function result code, 0 or positive number\n \"\"\"\n res = self.dll_object.ControlDevice(\n self.handle,\n operation,\n p1,\n p2,\n p3,\n p4,\n options_str\n )\n if res < 0:\n raise RuntimeError('ControlDevice failed, params: ({}), returned: {}'.format(\n ','.join((str(self.handle), str(operation), str(p1), str(p2), str(p3), str(p4), str(options_str))),\n str(res)\n ))\n\n return res\n\n def zk_get_rt_log(self, buffer_size):\n \"\"\"\n Machinery method for retrieving events from device.\n :param buffer_size: Required. Buffer size in bytes that filled with contents\n :raises RuntimeError: if operation was failed\n :return: raw string with events\n \"\"\"\n buf = ctypes.create_string_buffer(buffer_size)\n\n res = self.dll_object.GetRTLog(self.handle, buf, buffer_size)\n if res < 0:\n raise RuntimeError('GetRTLog failed, returned: {}'.format(str(res)))\n\n return buf.value.decode('utf-8')\n\n\n#\n# Device event\n#\n\nclass ZKRealtimeEvent:\n \"\"\"\n Represents one realtime event occured on the device\n Since the device returns event as string we need to parse it to the structured view. This class does this.\n \"\"\"\n __slots__ = (\n 'time',\n 'pin',\n 'card',\n 'door',\n 'event_type',\n 'entry_exit',\n 'verify_mode'\n )\n\n def __init__(self, s=None):\n \"\"\"\n :param s: Optional. Event string to be parsed.\n \"\"\"\n if s:\n self.parse(s)\n\n def parse(self, s):\n \"\"\"\n Parse one event string and fills out slots\n :param s: event string\n :raises ValueError: event string is invalid\n :return:\n \"\"\"\n if s == '' or s == '\\r\\n':\n raise ValueError(\"Empty event string\")\n\n items = s.split(',')\n if len(items) != 7:\n raise ValueError(\"Event string has not 7 comma-separated parts\")\n\n items[0] = datetime.strptime(items[0], '%Y-%m-%d %H:%M:%S')\n for i in range(len(self.__slots__)):\n setattr(self, self.__slots__[i], items[i])\n","sub_path":"pyzkaccess.py","file_name":"pyzkaccess.py","file_ext":"py","file_size_in_byte":11065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"385381839","text":"import spacy\nfrom spacy.lang.en.stop_words import STOP_WORDS\nfrom sklearn.feature_extraction.text import CountVectorizer\n\ndef textSummarizationUsingRanking(txt):\n # From input tuple of words, we change \n whole_text = readWholeText(txt)\n # Get corpus from whole text\n corpus, doc = getCorpus(whole_text)\n # Count word frequency in text\n word_frequency = featureExtraction(whole_text, corpus)\n # Sort word frequency and get new value for word frequency (divided by highest freq)\n sorted_word_frequency = getRelativeFrequencyOfWords(word_frequency)\n # Set the sentence ranking and top score of sentence\n sentences_ranking, top_sentences = getSentenceRanking(sorted_word_frequency, doc)\n # Get the summarization\n summary = getSummaryText(sentences_ranking, top_sentences)\n\n return summary\n\ndef readWholeText(text):\n # Joining the text bcs the returned value is tuple\n whole_text = \" \".join(text)\n return whole_text\n\ndef getCorpus(text):\n # Use the library\n nlp = spacy.load('en_core_web_sm')\n doc = nlp(text)\n print(doc)\n\n # Lower case the text \n corpus = [sent.text.lower() for sent in doc.sents]\n\n # Define the global variable\n global text_len\n text_len = 0\n # Count the text length\n for sent in doc.sents:\n text_len += len(sent)\n print(\"\\nText length: \", text_len)\n\n return corpus, doc\n\ndef featureExtraction(text, corpus):\n # Clean the stop words\n cv = CountVectorizer(stop_words=list(STOP_WORDS))\n # Feature extraction\n cv_fit = cv.fit_transform(corpus)\n\n word_list = cv.get_feature_names()\n count_list = cv_fit.toarray().sum(axis=0)\n \n word_frequency = dict(zip(word_list, count_list))\n return word_frequency\n\ndef getRelativeFrequencyOfWords(frequency):\n # Sort the frequency value we got before\n val = sorted(frequency.values())\n print(\"Values: \")\n print(val)\n\n # Take word which the value is in top 3 highest value from the list\n higher_word_frequency = [word for word, freq in frequency.items() if freq in val[-3:]]\n print(\"\\nWords with higher frequencies: \")\n print(higher_word_frequency)\n \n # Take the highest value from the list \n higher_frequency = val[-1]\n for word in frequency.keys():\n # Update the value of each word in dictionary with new value\n frequency[word] = (frequency[word] / higher_frequency)\n return frequency\n\n# Create sentence ranking from each word value\ndef getSentenceRanking(frequency, doc):\n sentence_rank = {}\n # For each sentence in text\n for sent in doc.sents:\n # For each word in sentence\n for word in sent:\n if word.text.lower() in frequency.keys():\n if sent in sentence_rank.keys():\n sentence_rank[sent] += frequency[word.text.lower()]\n else:\n sentence_rank[sent] = frequency[word.text.lower()]\n else:\n continue\n\n top_sentences = (sorted(sentence_rank.values())[::-1])\n top_sent = top_sentences[:3]\n print(\"\\nTop sentences : \")\n print(top_sent)\n\n return sentence_rank, top_sent\n\ndef getSummaryText(rank, top_sent):\n summary = []\n for sent, strength in rank.items():\n if strength in top_sent:\n summary.append(sent)\n else:\n continue\n \n summary_text = \"\"\n sum_len = 0\n for i in summary:\n summary_text = summary_text + \" \" + str(i)\n sum_len += len(i)\n \n # text_reduced = sum_len / text_len*100\n # summary_text = summary_text + \"\\n\\n\" + \"Text reduced to : \" + str(\"{:.1f}%\".format(text_reduced)) + \" (\" + str(sum_len) + \"/\" + str(text_len) + \")\"\n summary_text = summary_text + \"\\n\\n\" + \"Text reduced from : \" + str(text_len) + \" words to \" + str(sum_len)\n\n print(\"\\nSummary : \" + summary_text)\n print(\"\\nSummary length : \", sum_len)\n return summary_text","sub_path":"TextSummarizationRanking.py","file_name":"TextSummarizationRanking.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"375408715","text":"try:\n import unzip_requirements\nexcept ImportError:\n pass\n\nimport os\nimport django\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'data_portal.settings.base')\ndjango.setup()\n\n# ---\n\nimport logging\n\nfrom data_processors.pipeline.services import libraryrun_srv\nfrom libumccr import libjson\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef handler(event, context):\n \"\"\"event payload dict\n {\n 'gds_volume_name': \"bssh.xxxx\",\n 'gds_folder_path': \"/Runs/cccc.gggg\",\n 'instrument_run_id': \"yyy\",\n 'run_id': \"zzz\",\n 'sample_sheet_name': \"SampleSheet.csv\",\n 'runinfo_name': \"RunInfo.xml\",\n }\n\n :param event:\n :param context:\n :return: list of library id\n \"\"\"\n logger.info(f\"Start processing create LibraryRun from Sequence\")\n logger.info(libjson.dumps(event))\n\n payload = {\n 'gds_volume_name': event['gds_volume_name'],\n 'gds_folder_path': event['gds_folder_path'],\n 'instrument_run_id': event['instrument_run_id'],\n 'run_id': event['run_id'],\n 'sample_sheet_name': event.get('sample_sheet_name', \"SampleSheet.csv\"),\n 'runinfo_name': event.get('runinfo_name', \"RunInfo.xml\"),\n }\n\n library_run_list = libraryrun_srv.create_library_run_from_sequence(payload)\n\n results = []\n for library_run in library_run_list:\n results.append(library_run.library_id)\n\n logger.info(libjson.dumps(results))\n\n return results\n","sub_path":"data_processors/pipeline/lambdas/libraryrun.py","file_name":"libraryrun.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"152876522","text":"__author__ = 'christopher'\n\nimport parse\nimport thread\nimport commands\nimport memorydb\nimport playerdb\nimport logger\nimport runtime\nimport event\nimport util\n\n\n\n\n\ndef route(line):\n try:\n p = parse.parse_log(line)\n\n if p.type == \"Filtered\":\n pass\n\n if p.type == \"GMSG\":\n logger.log(p.formatted_text)\n\n if p.type == \"SystemEvent\":\n if p.event == \"Stats\":\n runtime.time = p.time\n runtime.fps = p.fps\n runtime.heap = p.heap\n runtime.max = p.max\n runtime.chunks = p.chunks\n\n runtime.cgo = p.cgo\n runtime.ply = p.ply\n runtime.zom = p.zom\n runtime.ent = p.ent\n runtime.items = p.items\n\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"Version\":\n runtime.version = p.version\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"Port\":\n runtime.server_port = p.port\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"MaxPlayers\":\n runtime.max_players = p.max_players\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"GameMode\":\n runtime.game_mode = p.game_mode\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"World\":\n runtime.world = p.world\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"GameName\":\n runtime.game_name = p.game_name\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.event == \"Difficulty\":\n runtime.difficulty = p.difficulty\n if runtime.gui:\n system_event = []\n system_event.append(\"SystemUpdate\")\n event.gui_event.append(system_event)\n\n if p.type == \"GameEvent\":\n if p.event == \"Airdrop\":\n location = util.format_coor(p.location)\n memorydb.airdrops.append(p.location)\n logger.log(\"Airdrop: \" + location)\n playerdb.save_airdrop(p.location)\n if runtime.server:\n commands.say(\"Airdrop: \" + location)\n\n if p.type == \"GameEvent\":\n if p.event == \"Horde\":\n logger.log(\"Spawning Wandering Horde\")\n if runtime.server:\n commands.say(\"Spawning Wandering Horde\")\n\n if p.type == \"PlayerEvent\":\n if p.event == \"Connected\":\n #logger.log(\"Player Connected: \" + p.name)\n memorydb.add_online_player(p.name)\n player_event = []\n player_event.append(\"PlayerUpdate\")\n event.gui_event.append(player_event)\n if runtime.server:\n thread.start_new_thread(commands.send_motd,(p.name,))\n\n\n if p.event == \"Disconnected\":\n #logger.log(\"Player Disconnected: \" + p.name)\n memorydb.remove_online_player(p.name)\n player_event = []\n player_event.append(\"PlayerUpdate\")\n event.gui_event.append(player_event)\n\n if p.event == \"Died\":\n player = memorydb.get_player_from_name(p.name)\n player.bag = player.location\n playerdb.save_player(p.name)\n logger.log_verbose(\"Setting \" + player.name + \" revive point to: \" + util.format_coor(player.location))\n logger.log(p.formatted_text)\n if runtime.server:\n commands.pm(player.name, \"Setting your revive point to: \"+ util.format_coor(player.location))\n\n if p.event == \"Update\":\n memorydb.add_online_player(p.name)\n player_event = []\n player_event.append(\"PlayerUpdate\")\n event.gui_event.append(player_event)\n if memorydb.player_exists_from_name(p.name):\n memorydb.update_player(p)\n else:\n memorydb.add_player(p.name, p.entityid, p.steamid, p.ip)\n logger.log_verbose(\"Adding new player: \" + p.name)\n playerdb.save_player(p.name)\n\n if p.type == \"PlayerCommand\":\n if p.event == \"Sethome\":\n logger.log(p.formatted_text)\n memorydb.set_player_home(p.name)\n player = memorydb.get_player_from_name(p.name)\n logger.log(\"Setting \"+util.format_coor(player.home) + \" as home for \" + player.name)\n playerdb.save_player(p.name)\n if runtime.server:\n commands.pm(player.name,\"Home has been set to: \" + util.format_coor(player.home))\n\n\n if p.event == \"Home\":\n player = memorydb.get_player_from_name(p.name)\n logger.log(p.formatted_text)\n if player.home == \"\":\n logger.log_verbose(\"No home set for: \" + player.name)\n if runtime.server:\n commands.pm(player.name, \"You need to set a home first\")\n else:\n logger.log_verbose(\"Teleporting \"+player.name + \" to \" + util.format_coor(player.home))\n if runtime.server:\n commands.teleport(player.name,player.home)\n\n\n if p.event == \"Setpoi\":\n logger.log(p.formatted_text)\n player = memorydb.get_player_from_name(p.name)\n playerdb.save_poi(p.name,p.poiname,player.location)\n memorydb.add_poi(p.name,p.poiname)\n logger.log(\"Poi set for \"+p.name +\" with name \"+ p.poiname +\" at: \" + util.format_coor(player.location))\n if runtime.server:\n commands.pm(player.name,\"Poi \" + p.poiname + \" set: \"+ util.format_coor(player.location))\n\n\n if p.event == \"Poi\":\n logger.log(p.formatted_text)\n location = memorydb.get_poi(p.name,p.poiname)\n if location == \"\":\n if runtime.server:\n commands.pm(p.name,\"No poi with that name.\")\n else:\n logger.log(\"Teleporting \"+p.name + \" to \" + util.format_coor(location))\n if runtime.server:\n commands.teleport(p.name,location)\n\n\n if p.event == \"Listpoi\":\n logger.log(p.formatted_text)\n if runtime.server:\n player = memorydb.get_player_from_name(p.name)\n if len(player.pois) == 0:\n commands.pm(p.name,\"No pois to list\")\n for poi in player.pois:\n name = poi.split(\",\")[0]\n location = poi.split(\",\")[1]\n commands.pm(player.name,name + \": \" + util.format_coor(location))\n\n if p.event == \"Removepoi\":\n logger.log(p.formatted_text)\n if memorydb.poi_exists(p.name,p.poiname):\n memorydb.remove_poi(p.name,p.poiname)\n playerdb.delete_poi(p.name,p.poiname)\n if runtime.server:\n commands.pm(p.name,\"Poi \" + p.poiname+ \" has been removed\")\n\n else:\n if runtime.server:\n commands.pm(p.name,\"No poi with that name\")\n\n if p.event == \"Clearpoi\":\n logger.log(p.formatted_text)\n memorydb.remove_all_pois(p.name)\n playerdb.delete_all_poi(p.name)\n if runtime.server:\n commands.pm(p.name,\"All pois have been removed\")\n\n if p.event == \"Killme\":\n logger.log(p.formatted_text)\n if runtime.server:\n commands.kill_player(p.name)\n\n if p.event == \"Help\":\n logger.log(p.formatted_text)\n if runtime.server:\n commands.help(p.name)\n\n if p.event == \"Bag\":\n logger.log(p.formatted_text)\n if runtime.server:\n player = memorydb.get_player_from_name(p.name)\n if player.bag != \"\":\n commands.teleport(p.name,player.bag)\n\n if p.event == \"Goto\":\n logger.log(p.formatted_text)\n if runtime.server:\n if memorydb.player_exists_from_name(p.othername):\n commands.teleport(p.name,p.othername)\n else:\n commands.pm(p.name,\"Player does not exist: \" + p.othername)\n\n if p.event == \"Where\":\n logger.log(p.formatted_text)\n if runtime.server:\n player = memorydb.get_player_from_name(p.name)\n commands.pm(p.name,\"Current location: \" + util.format_coor(player.location))\n\n if p.event == \"Drop\":\n logger.log(p.formatted_text)\n if runtime.server:\n for drop in memorydb.airdrops:\n if util.is_coor_formatted(drop):\n commands.pm(p.name,\"Airdrop: \" + drop)\n else:\n commands.pm(p.name,\"Airdrop: \" + util.format_coor(drop))\n\n if p.event == \"Claim\":\n logger.log(p.formatted_text)\n found = 0\n if runtime.server:\n player = memorydb.get_player_from_name(p.name)\n obj1 = player.location\n for drop in memorydb.airdrops:\n if util.in_radius(obj1,drop,runtime.drop_claim_radius):\n memorydb.airdrops.remove(drop)\n playerdb.delete_airdrop(drop)\n if util.is_coor_formatted(drop):\n commands.pm(p.name,\"You have claimed the airdrop at: \" + str(drop))\n else:\n commands.pm(p.name,\"You have claimed the airdrop at: \" + str(util.format_coor(drop)))\n found = 1\n if found == 0:\n commands.pm(p.name,\"You need to be in a \" + str(runtime.drop_claim_radius) + \" block radius of an airdrop to claim\")\n\n if p.type == \"\":\n logger.log_verbose(p.formated_text)\n\n except Exception as e:\n print(e.message)","sub_path":"director.py","file_name":"director.py","file_ext":"py","file_size_in_byte":11519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"283797302","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport wx\nimport wx.grid\nimport armid\n\nclass ThreatTable(wx.grid.PyGridTableBase):\n def __init__(self,threats):\n wx.grid.PyGridTableBase.__init__(self)\n self.colLabels = ['Threat','Likelihood']\n self.data = {}\n idx = 0\n for threat,likelihood in threats:\n self.data[(idx,0)] = threat\n self.data[(idx,1)] = likelihood\n self.likelihoodChoices = ['Incredible','Improbable','Remote','Occasional','Probable','Frequent']\n\n def GetNumberRows(self):\n return len(self.data) / 2\n\n def GetNumberCols(self):\n return 2\n\n def GetColLabelValue(self,col):\n return self.colLabels[col]\n\n def IsEmptyCell(self,row,col):\n return False\n\n def GetValue(self,row,col):\n return self.data.get((row,col))\n\n def SetValue(self,row,col,value):\n self.data[(row,col)] = value\n\n def addThreat(self,threatName):\n pos = (len(self.data) / 2)\n self.data[(pos,0)] = threatName\n self.data[(pos,1)] = ''\n grid = self.GetView()\n if grid:\n grid.BeginBatch()\n msg = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_ROWS_INSERTED,pos,1)\n grid.ProcessTableMessage(msg)\n grid.SetReadOnly(pos,0)\n grid.SetCellEditor(pos,1,wx.grid.GridCellChoiceEditor(self.likelihoodChoices))\n grid.EndBatch()\n\n def load(self,threats):\n idx = 0\n grid = self.GetView()\n if grid:\n for idx, threat in enumerate(threats):\n self.data[(idx,0)] = threat[0]\n self.data[(idx,1)] = threat[1]\n grid.BeginBatch()\n msg = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_ROWS_INSERTED,idx,1)\n grid.ProcessTableMessage(msg)\n grid.EndBatch()\n\n def AppendRows(self,numRows = 1):\n pos = (len(self.data) / 2) - 1\n self.InsertRows(pos,numRows)\n \n def InsertRows(self,pos,numRows = 1):\n newPos = pos + 1\n grid = self.GetView()\n if grid:\n grid.BeginBatch()\n msg = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_ROWS_INSERTED,newPos,numRows)\n grid.ProcessTableMessage(msg)\n grid.EndBatch()\n grid.SetCellEditor(pos,1,wx.grid.GridCellChoiceEditor(self.likelihoodChoices))\n return newPos\n\n def DeleteRows(self,pos,numRows = 1):\n del self.data[(pos,0)]\n del self.data[(pos,1)]\n grid = self.GetView()\n if grid:\n grid.BeginBatch()\n msg = wx.grid.GridTableMessage(self,wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED,pos,numRows)\n grid.ProcessTableMessage(msg)\n grid.EndBatch()\n\n\nclass ThreatGrid(wx.grid.Grid):\n def __init__(self,parent,threats):\n wx.grid.Grid.__init__(self,parent,armid.ENVIRONMENT_GRIDTHREATS_ID)\n self.SetTable(ThreatTable(threats))\n self.SetRowLabelSize(0)\n for x in range(self.GetNumberRows()):\n self.SetReadOnly(x,0)\n self.SetCellEditor(x,1,wx.grid.GridCellChoiceEditor(self.likelihoodChoices))\n self.SetColSize(0,200)\n self.SetColSize(1,200)\n\n\n\n def addThreat(self,threatName):\n grid = self.GetTable()\n grid.addThreat(threatName)\n\n\n def threats(self):\n grid = self.GetTable()\n threatList = []\n for x in range(0,self.GetNumberRows()):\n threatList.append( (grid.GetValue(x,0), grid.GetValue(x,1) ) )\n return threatList \n\n def deleteThreat(self):\n currentRowIndex = self.GetGridCursorRow()\n self.DeleteRows(currentRowIndex)\n \n def load(self,threats):\n grid = self.GetTable()\n grid.load(threats)\n for x in range(self.GetNumberRows()):\n self.SetReadOnly(x,0)\n self.SetCellEditor(x,1,wx.grid.GridCellChoiceEditor(grid.likelihoodChoices))\n","sub_path":"cairis/cairis/ThreatGrid.py","file_name":"ThreatGrid.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"495893628","text":"'''\nFile name: questmobile_top_apps.py\nPurpose: 每月找出MAU/DAU/每用户月使用时常的apps\nAuthor: Patrick Zhang(Patrick.zhang@bda.com)\nPython: Python 3.0\nHistory:\n 2016.02.17 Patrick Zhang write comments in this format\n 2016.02.18 Patrick Zhang add get_traffic and get_pc_traffic\n'''\nfrom helpers.utils import query\nfrom collections import OrderedDict\n\n\ndef main(a_date):\n sql = (\"SELECT app_id, app_name, active_users, total_use_time, daily_active_user, \"\n \" starting_date, sector\"\n \" FROM app WHERE source='QuestMobile' AND starting_date='%s'\") % (a_date)\n data = query(sql)\n\n # 收集数据\n mau_dict, dau_dict, time_dict, app_dict = {}, {}, {}, {}\n for row in data:\n # mau单位为千,dau单位为千,total_use_time单位为千小时\n app_id, app_name, mau, dau, total_use_time, sector = row[\"app_id\"], row[\"app_name\"], \\\n row[\"active_users\"], row[\"daily_active_user\"], row[\"total_use_time\"], row[\"sector\"]\n # 过滤“Games”品类App\n # if sector == \"Games\":\n # continue\n app_dict[app_id] = [app_name, sector, a_date]\n if app_id in dau_dict:\n dau_dict[app_id] += dau\n else:\n dau_dict[app_id] = dau\n # 确保时间不为0\n if mau:\n if app_id in mau_dict:\n mau_dict[app_id] += mau\n else:\n mau_dict[app_id] = mau\n # 月度人均使用时间(小时)\n time = total_use_time / mau\n if app_id in time_dict:\n time_dict[app_id] += time\n else:\n time_dict[app_id] = time\n\n # 排序\n sorted_mau = sorted(mau_dict.items(), key=lambda item: item[1], reverse=True)[0:300]\n sorted_dau = sorted(dau_dict.items(), key=lambda item: item[1], reverse=True)[0:300]\n sorted_time = sorted(time_dict.items(), key=lambda item: item[1], reverse=True)[0:300]\n\n # 打印结果 - 3个维度排名前150的App\n print(\"**************************MAU****************************\")\n for app in sorted_mau:\n print(app[0] + \"\\t\" + app_dict[app[0]][0] + \"\\t\" + app_dict[app[0]][1] + \"\\t\"\n + app_dict[app[0]][2] + \"\\t\" + str(app[1]))\n print(\"**************************DAU****************************\")\n for app in sorted_dau:\n print(app[0] + \"\\t\" + app_dict[app[0]][0] + \"\\t\" + app_dict[app[0]][1] + \"\\t\"\n + app_dict[app[0]][2] + \"\\t\" + str(app[1]))\n print(\"**************************TIME****************************\")\n for app in sorted_time:\n print(app[0] + \"\\t\" + app_dict[app[0]][0] + \"\\t\" + app_dict[app[0]][1] + \"\\t\"\n + app_dict[app[0]][2] + \"\\t\" + str(app[1]))\n\n print(\"**************************Shared Apps****************************\")\n # 找出两个列表都存在的App\n for key, value in app_dict.items():\n flag = 0\n for a_tuple in sorted_dau + sorted_time:\n if key in a_tuple:\n flag += 1\n if flag == 2:\n print(key + \"\\t\" + value[0] + \"\\t\" + value[1] + \"\\t\" + value[2] + \"\\t\" + str(dau_dict[key]))\n\ndef get_traffic():\n app_list = [\"2441\", \"149\", \"2085\", \"1912\", \"268\", \"928\", \"178\", \"2013\", \"2320\", \"2072\", \"46\",\n \"745\", \"2538\", \"1388\", \"998\", \"1670\", \"1944\", \"1209\", \"2387\", \"2210\", \"173\", \"1409\", \"843\",\n \"1022\", \"116\", \"2610\", \"2216\", \"1024\", \"1894\", \"1097\", \"2602\", \"1134\", \"2128\", \"1648\",\n \"1751\", \"1023\", \"431\", \"1390\", \"1933\", \"106\", \"1776\", \"1685\", \"2525\", \"1553\", \"1079\",\n \"1217\", \"704\", \"2343\", \"698\", \"904\", \"778\", \"1756\", \"1602\", \"617\", \"3958\", \"3957\", \"1031\",\n \"2550\", \"2586\", \"2700\", \"2741\", \"1896\", \"2229\", \"571\", \"488\", \"2668\", \"1023\", \"1312\",\n \"1020\", \"1685\", \"30\", \"1647\", \"1328\", \"2225\", \"583\", \"12553\", \"5551\", \"619\", \"2256\", ]\n # 拼凑SQL\n sql = (\"SELECT app_id, app_name, app_name_en, active_users, daily_active_user, total_use_time,\"\n \" starting_date FROM app WHERE source='QuestMobile' AND starting_date >= '2014-11-01'\"\n \" AND app_id IN (\")\n for app in app_list:\n sql += \"'\" + app + \"', \"\n else:\n sql = sql[:-2] + \")\"\n # 查询数据库\n data = query(sql)\n\n # 设置数据Container\n months = sorted(set(map(lambda x: x[\"starting_date\"], data)))\n mau_dict, dau_dict, time_dict, app_dict = [dict.fromkeys(app_list) for i in range(0, 4)]\n # 设置默认值\n for app in app_list:\n mau_dict[app] = [0] * len(months)\n dau_dict[app] = [0] * len(months)\n time_dict[app] = [0] * len(months)\n\n for row in data:\n # mau单位为千,dau单位为千,total_use_time单位为千小时\n app_id, app_name, mau, dau, total_use_time, app_name_en, starting_date = row[\"app_id\"], \\\n row[\"app_name\"], row[\"active_users\"], row[\"daily_active_user\"], row[\"total_use_time\"],\\\n row[\"app_name_en\"], row[\"starting_date\"]\n app_dict[app_id] = [app_name, app_name_en]\n index = months.index(starting_date)\n mau_dict[app_id][index] += mau / 1000\n dau_dict[app_id][index] += dau / 1000\n if not mau:\n time_dict[app_id][index] += 0\n else:\n time_dict[app_id][index] += total_use_time / mau\n\n\n # 打印结果\n print(\"**************************MAU****************************\")\n for app in app_list:\n print(app_dict[app][0] + \"\\t\" + app_dict[app][1], end=\"\\t\")\n print(*mau_dict[app], sep=\"\\t\")\n print(\"**************************DAU****************************\")\n for app in app_list:\n print(app_dict[app][0] + \"\\t\" + app_dict[app][1], end=\"\\t\")\n print(*dau_dict[app], sep=\"\\t\")\n print(\"**************************Time****************************\")\n for app in app_list:\n print(app_dict[app][0] + \"\\t\" + app_dict[app][1], end=\"\\t\")\n print(*time_dict[app], sep=\"\\t\")\n\n\ndef get_pc_traffic():\n pc_list = [\"腾讯\", \"百度\", \"360安全中心\", \"好搜\", \"淘宝网\", \"新浪\", \"凤凰网\", \"网易163\",\n \"搜狗\", \"搜狐\", \"天猫\", \"优酷\", \"新浪微博\", \"爱奇艺\", \"乐视网\", \"网址之家\", \"360影视\",\n \"2345\", \"PPTV网络电视\", \"京东商城\", \"东方财富网\", \"风行\", \"中国移动\", \"中青网\", \"土豆网\",\n \"一淘网\", \"光明网\", \"芒果TV\", \"汽车之家\", \"网易126\", \"易车网\", \"56网\", \"太平洋汽车网\",\n \"环球网\", \"酷6网\", \"北青网\", \"4399小游戏\", \"中国网络电视台\", \"中国铁路客户服务中心\", \"豆丁网\",\n \"爱卡汽车网\", \"返利网\", \"搜库\", \"哔哩哔哩动画\", \"豆瓣\", \"奇虎\", \"阿里巴巴1688\", \"中国广播网\",\n \"苏宁易购\", \"中国天气网\"]\n sql = (\"SELECT company_name, url, starting_date, daily_unique_visitors, total_length_of_visits FROM web_wap \"\n \" WHERE starting_date >= '2015-01-01' AND starting_date <= '2015-12-01'\"\n \" AND company_name IN (\")\n for pc in pc_list:\n sql += \"'\" + pc + \"', \"\n else:\n sql = sql[:-2] + \")\"\n\n # 查询数据库\n data = query(sql)\n # 设置数据Container\n months = sorted(set(map(lambda x: x[\"starting_date\"], data)))\n dau_dict, time_dict, pc_dict = [dict.fromkeys(pc_list) for i in range(0, 3)]\n # 设置默认值\n for pc in pc_list:\n dau_dict[pc] = [0] * len(months)\n time_dict[pc] = [0] * len(months)\n\n for row in data:\n # dau单位为千,total_length_of_visits单位为千小时\n company_name, url, starting_date, dau, time = row[\"company_name\"], row[\"url\"], \\\n row[\"starting_date\"], row[\"daily_unique_visitors\"], row[\"total_length_of_visits\"]\n pc_dict[company_name] = url\n index = months.index(starting_date)\n dau_dict[company_name][index] += dau / 1000\n time_dict[company_name][index] += time / 1000\n\n # 打印结果\n print(\"**************************DAU****************************\")\n for pc in pc_list:\n print(pc + \"\\t\" + str(pc_dict[pc]), end=\"\\t\")\n print(*dau_dict[pc], sep=\"\\t\")\n print(\"**************************Time****************************\")\n for pc in pc_list:\n print(pc + \"\\t\" + str(pc_dict[pc]), end=\"\\t\")\n print(*time_dict[pc], sep=\"\\t\")\n\n\nif __name__ == \"__main__\":\n # main(\"2016-01-01\")\n # get_traffic()\n get_pc_traffic()\n","sub_path":"analyzer/questmobile_top_apps.py","file_name":"questmobile_top_apps.py","file_ext":"py","file_size_in_byte":8308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"620653016","text":"\nimport json, os\nfrom tqdm import tqdm\nimport numpy as np\nimport logging, pickle\nfrom ttt.utils import add_filehandler_for_logger\n\nlogging.basicConfig(\n format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO\n)\nlogger = logging.getLogger(__name__)\ndef read_seq_single_cls_examples(data_path):\n texts = []\n labels = []\n with open(data_path, \"r\") as f:\n for line in tqdm(f, desc=f\"reading from {data_path}\"):\n example = json.loads(line.strip())\n texts.append(example[\"text\"])\n labels.append(example[\"label\"])\n return texts, labels\n\n\ndef convert_seq_single_cls_examples(data_path, tokenizer, max_seq_length, label2id):\n texts, labels = read_seq_single_cls_examples(data_path)\n y = np.array([label2id[label] for label in labels])\n encoded_texts = tokenizer(texts, padding=True, truncation=True, return_tensors=\"np\",\n max_length=max_seq_length)\n return texts, encoded_texts, y\n\n\ndef prepare_seq_single_cls_inputs(tokenizer, args, load_train_num=-1):\n logger.info(\"reading train set\")\n train_texts, train_labels = read_seq_single_cls_examples(os.path.join(args.data_path, \"train.json\"))\n\n if load_train_num > 0:\n assert load_train_num <= len(train_texts), f\"there are {len(train_texts)} training examples\"\n logger.info(f\"loading only {load_train_num} training examples out of the totaling {len(train_texts)}\")\n train_texts = train_texts[:load_train_num]\n train_labels = train_labels[:load_train_num]\n\n label2id = {}\n logger.info(\"building label2id from train examples\")\n for i, label in enumerate(list(set(train_labels))):\n label2id[label] = i\n\n logger.info(\"converting labels to its ids for train examples\")\n y_train = np.array([label2id[label] for label in train_labels])\n logger.info(f\"encoding train examples (num={len(train_texts)})\")\n logger.info(f\"using tokenizer with padding = True and truncation = True and max_length = {args.max_seq_length}\")\n logger.info(\"This may take a while\")\n\n encoded_train = tokenizer(train_texts, padding=True, truncation=True, return_tensors=\"np\",\n max_length=args.max_seq_length)\n\n if \"token_type_ids\" not in encoded_train:\n # we need this for roberta tokenizer that does not return token_type_ids\n encoded_train[\"token_type_ids\"]=np.zeros(encoded_train[\"input_ids\"].shape,dtype=np.int32)\n\n x_train = [encoded_train[\"input_ids\"], encoded_train[\"token_type_ids\"], encoded_train[\"attention_mask\"]]\n\n to_return = {\"x_train\": x_train, \"y_train\": y_train, \"label2id\": label2id}\n\n if os.path.isfile(os.path.join(args.data_path, \"val.json\")):\n logger.info(f\"found validation set in {os.path.join(args.data_path, 'val.json')}\")\n logger.info(f\"encoding validation examples\")\n val_texts, encoded_val, y_eval = convert_seq_single_cls_examples(os.path.join(args.data_path, 'val.json'),\n tokenizer, args.max_seq_length, label2id)\n if \"token_type_ids\" not in encoded_val:\n # we need this for roberta tokenizer that does not return token_type_ids\n encoded_val[\"token_type_ids\"] = np.zeros(encoded_val[\"input_ids\"].shape, dtype=np.int32)\n\n x_eval = [encoded_val[\"input_ids\"], encoded_val[\"token_type_ids\"], encoded_val[\"attention_mask\"]]\n\n to_return.update({\"x_eval\": x_eval, \"y_eval\": y_eval, \"eval_examples\": val_texts})\n # if os.path.isfile(os.path.join(args.data_path, \"test.json\")):\n # logger.info(f\"found test set in {os.path.join(args.data_path, 'test.json')}\")\n # logger.info(f\"encoding test examples\")\n # test_texts, encoded_test, y_test = convert_seq_single_cls_examples(os.path.join(args.data_path, 'test.json'),\n # tokenizer, args.max_seq_length, label2id)\n # x_test = [encoded_test[\"input_ids\"], encoded_test[\"token_type_ids\"], encoded_test[\"attention_mask\"]]\n # to_return.update({\"x_test\": x_test, \"y_test\": y_test, \"test_examples\": test_texts})\n return to_return\n\ndef read_t2t_examples(data_path):\n source_texts = []\n target_texts = []\n with open(data_path, \"r\") as f:\n for line in tqdm(f, desc=f\"reading from {data_path}\"):\n example = json.loads(line.strip())\n source_texts.append(example[\"text\"]) # the
will be added after batch padding\n target_texts.append(example[\"label\"]+\" \")\n # is added here because the target sequence usually does not exceed the length limit\n return source_texts, target_texts\n\n\ndef convert_t2t_examples(data_path, tokenizer, max_src_length, max_tgt_length,append_token=\" \"):\n source_texts, target_texts = read_t2t_examples(data_path)\n special_token_id=tokenizer.encode(append_token.strip())[0]\n\n encoded_source = tokenizer(source_texts, padding=True, truncation=True, return_tensors=\"np\",\n max_length=max_src_length)\n\n encoded_source[\"input_ids\"],encoded_source[\"attention_mask\"]=replace_with_special_token(encoded_source, special_token_id)\n\n encoded_target = tokenizer(target_texts, padding=True, truncation=True, return_tensors=\"np\",\n max_length=max_tgt_length)\n return source_texts, encoded_source, encoded_target\n\ndef replace_with_special_token(encoded,special_token_id,replace_token_id=0):\n #replace_token_id: padding id\n ids=encoded[\"input_ids\"]\n attention_mask = encoded[\"attention_mask\"]\n for i in range(ids.shape[0]):\n indices=np.where(ids[i,:] == replace_token_id)[0]\n if indices.size==0:\n ids[i, -1]=special_token_id\n else:\n ids[i, indices[0]]=special_token_id\n attention_mask[i, indices[0]] = 1\n return ids,attention_mask\n\ndef shift_to_right(input_ids,decoder_start_token_id):\n shifted_input_ids = np.zeros(input_ids.shape,dtype=input_ids.dtype)\n shifted_input_ids[..., 1:] = input_ids[..., :-1]\n shifted_input_ids[..., 0] = decoder_start_token_id\n return shifted_input_ids\n\ndef prepare_t2t_inputs(tokenizer, args, load_train_num=-1):\n logger.info(\"reading train set\")\n source_texts_train, target_texts_train = read_t2t_examples(os.path.join(args.data_path, \"train.json\"))\n\n if load_train_num > 0:\n assert load_train_num <= len(source_texts_train), f\"there are {len(source_texts_train)} training examples\"\n logger.info(f\"loading only {load_train_num} training examples out of the totaling {len(source_texts_train)}\")\n source_texts_train = source_texts_train[:load_train_num]\n target_texts_train = target_texts_train[:load_train_num]\n\n logger.info(f\"encoding source train examples (num={len(source_texts_train)})\")\n logger.info(f\"using tokenizer with padding = True and truncation = True and max_src_length = {args.max_src_length}\")\n logger.info(\"This may take a while\")\n encoded_source_train = tokenizer(source_texts_train, padding=True, truncation=True, return_tensors=\"np\",\n max_length=args.max_src_length)\n\n logger.info(f\"encoding target train examples (num={len(target_texts_train)})\")\n logger.info(f\"using tokenizer with padding = True and truncation = True and max_tgt_length = {args.max_tgt_length}\")\n logger.info(\"This may take a while\")\n encoded_target_train = tokenizer(target_texts_train, padding=True, truncation=True, return_tensors=\"np\",\n max_length=args.max_src_length)\n\n special_token_id = tokenizer.encode(\"\")[0]\n\n decoder_start_token_id = 0 # hard coded here, todo\n\n # add \"\" add the end of each sequence for source, it already appends to the target sequences when reading from file\n train_source_input_ids,train_source_attention_mask=replace_with_special_token(encoded_source_train,special_token_id)\n train_target_input_ids,train_target_attention_mask=encoded_target_train[\"input_ids\"],encoded_target_train[\"attention_mask\"]\n\n # this is pytorch's cross entropy's ignore index. to figure out this in tensorflow-2.0\n # train_target_input_ids[train_target_input_ids == 0] = -100\n x_train = [train_source_input_ids,train_source_attention_mask,\n shift_to_right(train_target_input_ids,decoder_start_token_id),train_target_attention_mask]\n\n to_return = {\"x_train\": x_train, \"y_train\":train_target_input_ids}\n if args.do_eval:\n assert os.path.isfile(os.path.join(args.data_path, \"val.json\")),\"do_eval=True, and no validation data (val.json) is found\"\n\n if os.path.isfile(os.path.join(args.data_path, \"val.json\")):\n logger.info(f\"found validation set in {os.path.join(args.data_path, 'val.json')}\")\n logger.info(f\"encoding validation examples\")\n source_texts, encoded_source, encoded_target = convert_t2t_examples(\n os.path.join(args.data_path, 'val.json'),\n tokenizer, args.max_src_length, args.max_tgt_length)\n\n # add \"\" add the end of each sequence\n source_input_ids, source_attention_mask = encoded_source[\"input_ids\"],encoded_source[\"attention_mask\"]\n\n target_input_ids, target_attention_mask = encoded_target[\"input_ids\"],encoded_target[\"attention_mask\"]\n x_eval = [source_input_ids, source_attention_mask,shift_to_right(target_input_ids,decoder_start_token_id), target_attention_mask]\n\n # this is pytorch's cross entropy's ignore index. to figure out this in tensorflow-2.0\n # target_input_ids[target_input_ids == 0] = -100\n to_return.update({\"x_eval\": x_eval, \"y_eval\": target_input_ids, \"eval_examples\": source_texts})\n\n # if os.path.isfile(os.path.join(args.data_path, \"test.json\")):\n # logger.info(f\"found test set in {os.path.join(args.data_path, 'test.json')}\")\n # logger.info(f\"encoding test examples\")\n # test_texts, encoded_test, y_test = convert_seq_single_cls_examples(os.path.join(args.data_path, 'test.json'),\n # tokenizer, args.max_seq_length, label2id)\n # x_test = [encoded_test[\"input_ids\"], encoded_test[\"token_type_ids\"], encoded_test[\"attention_mask\"]]\n # to_return.update({\"x_test\": x_test, \"y_test\": y_test, \"test_examples\": test_texts})\n return to_return\n\ndef get_with_prepare_func(tokenizer, args, prepare_func,load_train_num=-1, is_cache=False):\n '''\n :param tokenizer:\n :param args:\n :return:\n '''\n args.is_data_cache = is_cache\n if is_cache:\n if load_train_num > 0:\n data_cache_path = os.path.join(args.data_path, f\"{args.model_select.replace('/','-')}-data-{load_train_num}.pkl\")\n else:\n data_cache_path = os.path.join(args.data_path, f\"{args.model_select.replace('/','-')}-data.pkl\")\n args.data_cache_path = data_cache_path\n if os.path.isfile(data_cache_path):\n with open(data_cache_path, \"rb\") as f:\n logger.info(f\"reading cached data from {data_cache_path}\")\n logger.warning(f\"if you changed the max_seq_length/max_src_length/max_tgt_length, this may not correctly loaded, since the {data_cache_path} is pickled based on first time loading\")\n to_return = pickle.load(f)\n else:\n to_return = prepare_func(tokenizer, args, load_train_num=load_train_num)\n with open(data_cache_path, \"wb\") as f:\n logger.info(f\"caching data to {data_cache_path}\")\n pickle.dump(to_return, f)\n else:\n to_return = prepare_func(tokenizer, args, load_train_num=load_train_num)\n return to_return\n\ndef get_inputs(tokenizer, args):\n add_filehandler_for_logger(args.output_path, logger)\n if args.task == \"single-label-cls\":\n inputs=get_with_prepare_func(tokenizer, args,prepare_seq_single_cls_inputs, is_cache=True)\n args.input_seq_length = inputs[\"x_train\"][0].shape[-1]\n args.label2id = inputs[\"label2id\"]\n return inputs\n elif args.task == \"t2t\":\n data_dict=get_with_prepare_func(tokenizer, args, prepare_t2t_inputs, is_cache=True)\n args.source_sequence_length = data_dict[\"x_train\"][0].shape[-1]\n args.target_sequence_length = data_dict[\"x_train\"][2].shape[-1]\n return data_dict\n else:\n # when more tasks are supported -> todo\n pass","sub_path":"ttt/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":12524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"127565137","text":"import random\n\n\ndef player_action():\n action = input(\"Direction: \").lower() \n return action\n\ndef update_position(action, position):\n current_action = action\n current_position = position\n if current_action == (\"n\" or action == \"N\"):\n \n current_position = current_position + 0.1\n \n elif current_action == (\"s\" or action == \"S\"):\n \n current_position = current_position - 0.1\n \n elif current_action == (\"e\" or action == \"E\"):\n \n current_position = current_position + 1\n \n elif current_action == (\"w\" or action == \"W\"):\n \n current_position = current_position - 1\n\n else:\n print(\"Invalid Input\")\n\n current_position = round(current_position, 1)\n return current_position\n\ndef legal_input(action):\n \n if action == \"n\" or action == \"s\" or action == \"e\" or action == \"w\":\n return True\n else:\n print(\"Invalid Input\")\n return False\n\ndef legal_move(position, action):\n\n x = position \n if x == 1.1 and (action == 'start' or action == 'n'):\n return True\n elif x == 1.2 and (action != 'w'):\n return True\n elif x == 1.3 and (action == 'e' or action == 's'):\n return True\n elif x == 2.1 and (action == 'n'):\n return True\n elif x == 2.2 and (action == 's' or action == 'w'):\n return True\n elif x == 2.3 and (action == 'e' or action == 'w'):\n return True\n elif x == 3.2 and (action == 'n' or action == 's'):\n return True\n elif x == 3.3 and (action == 's' or action == 'w'):\n return True\n else:\n print(\"Not a valid direction!\")\n return False\n\ndef where_can_i_go(position, total_coins, total_moves):\n x = position\n moves = \"\"\n \n if x == 1.1:\n moves = (\"You can travel: (N)orth.\")\n \n elif x == 1.2:\n moves = (\"You can travel: (N)orth or (E)ast or (S)outh.\")\n \n elif x == 1.3:\n moves = (\"You can travel: (E)ast or (S)outh.\")\n \n elif x == 2.1:\n moves = (\"You can travel: (N)orth.\")\n \n elif x == 2.2:\n moves = (\"You can travel: (S)outh or (W)est.\")\n \n elif x == 2.3:\n moves = (\"You can travel: (E)ast or (W)est.\")\n \n elif x == 3.1:\n moves = (\"Victory! Total coins {}. Moves {}.\".format(total_coins, total_moves))\n \n elif x == 3.2:\n moves = (\"You can travel: (N)orth or (S)outh.\")\n \n elif x == 3.3:\n moves = (\"You can travel: (S)outh or (W)est.\")\n\n print(moves)\n\ndef coin_check(position):\n coin_positions = [1.2, 2.2, 2.3, 3.2]\n if position in coin_positions:\n return True\n else:\n return False\n\ndef get_coins(total_coins):\n lever_action = input(\"Pull a lever (y/n): \").lower()\n \n if lever_action == \"y\":\n total_coins += 1\n print(\"You received 1 coin, your total is now {}.\".format(total_coins))\n return total_coins\n else:\n return total_coins\n\ndef random_get_coins(total_coins):\n actions = [\"Y\",\"N\"]\n lever_action = random.choice(actions)\n print(\"Pull a lever (y/n):\",lever_action.lower())\n \n if lever_action.lower() == \"y\":\n total_coins += 1\n print(\"You received 1 coin, your total is now {}.\".format(total_coins))\n return total_coins\n else:\n return total_coins\n\ndef random_action():\n actions = [\"N\",\"E\",\"S\",\"W\"]\n action = random.choice(actions)\n print(\"Direction:\", action.lower()) \n return action.lower()\n\ndef get_seed():\n seed = int(input(\"Input seed: \"))\n random.seed(seed)\n\ndef play_again():\n play_again = input(\"Play again (y/n): \").lower()\n if play_again == \"y\":\n return True\n else:\n return False\n\n\n\ndef start_game():\n position = 1.1\n victory_condition = False\n coins_bool = False\n total_coins = 0\n total_moves = 0\n \n \n\n where_can_i_go(position,total_coins,total_moves)\n\n while victory_condition != True:\n \n #action = player_action()\n action = random_action()\n\n if legal_input(action):\n total_moves += 1\n if legal_move(position, action):\n \n \n position = update_position(action,position)\n coins_bool = coin_check(position)\n \n if coins_bool:\n #total_coins = get_coins(total_coins)\n total_coins = random_get_coins(total_coins)\n\n where_can_i_go(position, total_coins, total_moves)\n if position == 3.1:\n victory_condition = True\n \n \n else:\n where_can_i_go(position,total_coins,total_moves)\n \n return play_again()\n \n\ndef main ():\n run = True\n while run:\n get_seed()\n play = start_game()\n if play == False:\n run = False\n\n\nmain()","sub_path":"TileTraveller.py","file_name":"TileTraveller.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"56710494","text":"from sklearn.datasets import load_iris\r\n\r\n\r\n#下载鸢尾花数据\r\n#萼片长度、萼片宽度、花瓣长度、花瓣宽度\r\n\r\niris = load_iris()\r\n\r\n\r\n#data对应了样本的4个特征,150行4列。 target对应了样本的类别(目标属性),150行1列。iris.target用0、1和2三个整数分别代表了花的三个品种\r\n\r\nX = iris.data\r\ny = iris.target\r\n\r\n#Draw the ROC curve\r\n\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom itertools import cycle\r\nfrom sklearn import svm, datasets\r\nfrom sklearn.metrics import roc_curve, auc\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import label_binarize\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nfrom scipy import interp\r\n\r\n\r\n#将标签二值化\r\n#设置种类\r\n\r\ny = label_binarize(y, classes=[0, 1, 2])\r\nn_classes = y.shape[1]\r\n\r\n\r\n#训练模型并预测\r\n\r\nrandom_state = np.random.RandomState(0)\r\nn_samples, n_features = X.shape\r\n\r\n\r\n#分割训练和测试集\r\n#Learn to predict each class against the other\r\n#通过decision_function()计算得到的y_score的值,用在roc_curve()函数中\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,random_state=0)\r\nclassifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state))\r\ny_score = classifier.fit(X_train, y_train).decision_function(X_test)\r\n\r\n\r\n#计算每一类的ROC\r\n\r\nfpr = dict()\r\ntpr = dict()\r\nroc_auc = dict()\r\nfor i in range(n_classes):\r\n fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\r\n roc_auc[i] = auc(fpr[i], tpr[i])\r\n\r\n\r\n#fpr, tpr, thresholds = roc_curve(y_test, scores) \r\n#y_test为测试集的结果,score为模型预测的测试集得分\r\n#fpr,tpr 分别为假正率、真正率\r\n#roc_auc =auc(fpr, tpr)\r\n\r\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\r\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\r\n\r\n\r\n#Compute macro-average ROC curve and ROC area\r\n#First aggregate all false positive rates\r\n\r\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\r\n\r\n#interpolate all ROC curves at this points\r\n\r\nmean_tpr = np.zeros_like(all_fpr)\r\nfor i in range(n_classes):\r\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\r\n\r\n#average it and compute AUC\r\n\r\nmean_tpr /= n_classes\r\nfpr[\"macro\"] = all_fpr\r\ntpr[\"macro\"] = mean_tpr\r\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\r\n\r\n\r\n#Plot all ROC curves\r\n\r\nplt.figure()\r\nplt.plot(fpr[\"micro\"], tpr[\"micro\"],label='micro-average ROC curve (area = {0:0.2f})'''.format(roc_auc[\"micro\"]),color='deeppink', linestyle=':', linewidth=4)\r\nplt.plot(fpr[\"macro\"], tpr[\"macro\"],label='macro-average ROC curve (area = {0:0.2f})'''.format(roc_auc[\"macro\"]),color='navy', linestyle=':', linewidth=4)\r\ncolors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\r\nfor i, color in zip(range(n_classes), colors):\r\n plt.plot(fpr[i], tpr[i], color=color, linewidth=2,label='ROC curve of class {0} (area = {1:0.2f})'''.format(i, roc_auc[i]))\r\n\r\nplt.plot([0, 1], [0, 1], 'k--', linewidth=2)\r\nplt.xlim([0.0, 1.0])\r\nplt.ylim([0.0, 1.05])\r\nplt.xlabel('False Positive Rate')\r\nplt.ylabel('True Positive Rate')\r\nplt.title('ROC curve')\r\nplt.legend(loc=\"lower right\")\r\nplt.show()\r\n\r\n\r\n\r\n#Draw learning curve\r\n\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import learning_curve\r\n\r\nfeatures = X[:,0:2] \r\nlabels = y\r\nRF = RandomForestClassifier(max_depth = 8, random_state = 0)\r\nsize_grid = np.array([0.2,0.5,0.7,1])\r\ntrain_size,train_scores,validation_scores = learning_curve(RF,features,labels,train_sizes = size_grid, cv = 5)\r\n\r\n#学习曲线可视化\r\n\r\nplt.figure()\r\nplt.plot(size_grid,np.average(train_scores, axis = 1), color = 'red')\r\nplt.plot(size_grid, np.average(validation_scores, axis = 1), color = 'black')\r\nplt.title('Learning curve')\r\nplt.xlabel('sample size')\r\nplt.ylabel('accuracy')\r\nplt.show()\r\n\r\n\r\n\r\n#k-flod With parameter optimization\r\n\r\n\r\n\r\nfrom sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\n\r\n#选择总数据的30%的数据\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=1)\r\n\r\n\r\n#用KNN算法建模,参数优化,寻找最优模型参数\r\n\r\nknn_test = KNeighborsClassifier()\r\nparams = {\"n_neighbors\": [3, 4, 8, 10]}\r\ngridCv = GridSearchCV(knn_test, param_grid=params, cv=5)\r\ngridCv.fit(X_train, y_train) \r\nprint(\"k-flod交叉验证中最好的结果:\", gridCv.best_score_)\r\nprint(\"最好的模型参数是:\", gridCv.best_estimator_.n_neighbors)\r\nk_neighbor=gridCv.best_estimator_.n_neighbors\r\n\r\n\r\n#对特征值进行标准化处理\r\n\r\nstd = StandardScaler()\r\nX_train = std.fit_transform(X_train)\r\nX_test = std.transform(X_test)\r\n\r\n\r\n#建模并进行预测\r\n\r\nknn = KNeighborsClassifier(n_neighbors=k_neighbor) \r\nknn.fit(X_train, y_train) \r\ny_predict = knn.predict(X_test)\r\n\r\n\r\n#结果展示\r\n\r\nlabels = [\"山鸢尾\", \"虹膜锦葵\", \"变色鸢尾\"]\r\ntplt = \"{0:{3}^10}\\t{1:{3}^10}\\t{2:^10}\"\r\nprint(tplt.format(\"第i次测试\",\"真实值\",\"预测值\",chr(12288)))\r\nfor i in range(len(y_predict)):\r\n print(tplt.format((i+1),labels[y_predict[i]],labels[y_test[i]],chr(12288)))\r\nprint(\"准确率为\",knn.score(X_test, y_test))\r\n","sub_path":"320180942301-zuowei/homework11/IRIS作业.py","file_name":"IRIS作业.py","file_ext":"py","file_size_in_byte":5390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"392887215","text":"#!/usr/bin/env python3\n\n# How to use:\n#\n# LE_HOSTED_ZONE=XXXXXX LE_AWS_PROFILE=dns-access ./letsencrypt.sh --cron --domain example.org --challenge dns-01 --hook /tmp/hook-dns-01-lets-encrypt-route53.py\n#\n# More info about letsencrypt.sh: https://github.com/lukas2511/letsencrypt.sh/wiki/Examples-for-DNS-01-hooks\n# Using AWS Profiles: http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-multiple-profiles\n# Obtaining your Hosted Zone ID from Route 53: http://docs.aws.amazon.com/cli/latest/reference/route53/list-hosted-zones-by-name.html\n\n# modules declaration\nimport os\nimport sys\nimport boto3\nfrom time import sleep\n\nif 'LE_HOSTED_ZONE' not in os.environ:\n raise Exception(\"Environment variable LE_HOSTED_ZONE not defined\")\n\nif 'LE_AWS_PROFILE' not in os.environ:\n raise Exception(\"Environment variable LE_AWS_PROFILE not defined\")\n\n# declaring variables\naws_profile = os.environ['LE_AWS_PROFILE']\nhosted_zone_id = os.environ['LE_HOSTED_ZONE']\n\ndef setup_dns(domain, txt_challenge):\n global aws_profile\n global hosted_zone_id\n\n session = boto3.Session(profile_name=aws_profile)\n client = session.client(\"route53\")\n\n resp = client.change_resource_record_sets(\n HostedZoneId=hosted_zone_id,\n ChangeBatch={\n 'Changes': [{\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': '_acme-challenge.{0}'.format(domain),\n 'Type': 'TXT',\n 'TTL': 60,\n 'ResourceRecords': [{\n 'Value': '\"{0}\"'.format(txt_challenge)\n }]\n }\n }]\n }\n )\n\n # wait 30 seconds for DNS update\n sleep(30)\n\ndef delete_dns(domain, txt_challenge):\n global aws_profile\n global hosted_zone_id\n\n session = boto3.Session(profile_name=aws_profile)\n client = session.client(\"route53\")\n\n resp = client.change_resource_record_sets(\n HostedZoneId=hosted_zone_id,\n ChangeBatch={\n 'Changes': [{\n 'Action': 'DELETE',\n 'ResourceRecordSet': {\n 'Name': '_acme-challenge.{0}'.format(domain),\n 'Type': 'TXT',\n 'TTL': 60,\n 'ResourceRecords': [{\n 'Value': '\"{0}\"'.format(txt_challenge)\n }]\n }\n }]\n }\n )\n\nif __name__ == \"__main__\":\n hook = sys.argv[1]\n domain = sys.argv[2]\n txt_challenge = sys.argv[4]\n\n print(hook)\n print(domain)\n print(txt_challenge)\n\n if hook == \"deploy_challenge\":\n setup_dns(domain, txt_challenge)\n elif hook == \"clean_challenge\":\n delete_dns(domain, txt_challenge)\n","sub_path":"dockerized-gists/181979298149c5e74887f30fe09dcc71/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"102983936","text":"def is_valid(state):\n # Check whether the provided state is valid.\n for s in state.split('|'):\n if ('C' in s and 'G' in s and 'F' not in s):\n return False\n\n if ('W' in s and 'G' in s and 'F' not in s):\n return False\n\n return True\n\n\ndef is_goal(state):\n # Check whether the provided state is the goal state.\n return state.split('|')[0] == ''\n\n\ndef sort_string(str):\n # Reference: https://stackoverflow.com/a/15046263/16799596\n return ''.join(sorted(str))\n\n\ndef move(dir, state, item):\n # Move the provided item in the provided direction.\n s = state.split('|')\n\n if (dir == 'r'):\n s[0] = sort_string(s[0].replace(item, ''))\n s[1] = sort_string(s[1] + item)\n else:\n s[1] = sort_string(s[1].replace(item, ''))\n s[0] = sort_string(s[0] + item)\n\n return '|'.join(s)\n\n\ndef next(state):\n # Returns the next valid and invalid states based on the provided state.\n sides = state.split('|')\n states = []\n\n dir = 'r' if 'F' in sides[0] else 'l'\n\n for item in sides[0 if dir == 'r' else 1]:\n temp = state\n\n if item != 'F':\n temp = move(dir, state, item)\n\n states.append(move(dir, temp, 'F'))\n\n return states\n\n\ndef dfs(path):\n # Performs the deep first search algorithm.\n state, paths = path[::-1][0], []\n\n if is_goal(state):\n return [path]\n\n for s in next(state):\n\n if is_valid(s) and s not in path:\n\n for p in dfs(path + [s]):\n paths = paths + [p]\n\n return paths\n\n\nif __name__ == \"__main__\":\n state = 'FCGW|'\n\n for p in dfs([state]):\n print(p)\n","sub_path":"artificial-intelligence/river-crossing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"171738758","text":"from model.fonan import str_to_abc48\n\nclass HTK_Voc:\n def __init__(self, path, encoding='utf8'):\n with open(path, encoding=encoding) as f:\n lines = f.readlines()\n voc_list = [line.strip().split('\\t') for line in lines]\n del(voc_list[0])\n self._voc = {}\n for tran in voc_list:\n word = tran[1].lower()\n tr = tran[2:]\n self._voc[word] = tuple(tr)\n\n @property\n def voc(self): return self._voc\n\n def get_words(self, words):\n word_prons = {}\n missing_word_prons = []\n for word in words:\n prons = self._voc.get(word, None)\n if prons is not None:\n word_prons[word] = prons\n else:\n missing_word_prons.append(word)\n return word_prons, missing_word_prons\n\n def get_word(self, word):\n return self._voc.get(word, None)\n\n def prons_to_abc48(self):\n for w, p in self._voc.items():\n self._voc[w] = tuple(str_to_abc48(pron) for pron in p)\n\n\n @staticmethod\n def copy_prons(voc):\n voc_lst = []\n for word, prons in voc.items():\n if len(prons) > 1:\n for pron in prons:\n voc_lst.append((word, pron))\n else:\n voc_lst.append((word, *prons))\n return voc_lst\n\n\n @staticmethod\n def mk_voc(path, voc, encoding='utf8'):\n voc_lst = HTK_Voc.copy_prons(voc)\n voc_content = ''\n for x, y in voc_lst: \n voc_content += x + '\\t' + y + '\\n'\n with open(path, 'w', encoding=encoding) as f: f.write(voc_content)\n\n\n","sub_path":"model/htk_voc.py","file_name":"htk_voc.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"280649989","text":"import mxnet as mx\nfrom net.symbol_vgg import get_vgg\nfrom logger import logger\nimport time\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncontext = mx.gpu(5)\n\nprefix_path_train = '/home/liuliu/som/mini-imagenet/file/train_sym.rec'\ndata_path = '/home/liuliu/dna/data/dna/data/'\nim2rec_path = '/home/liuliu/mxnet/tools/im2rec.py'\n\n\ndata_iter = mx.io.ImageRecordIter(\n batch_size=1, data_shape=(3,224,224), path_imgrec=prefix_path_train, preprocess_threads=16)\n\nsym = get_vgg(num_classes=100, test=True)\n_, arg_params, aux_params = mx.model.load_checkpoint('model/aha/vgg16', 80)\n\nmod = mx.mod.Module(symbol = sym, context = context )\nmod.bind(data_shapes = data_iter.provide_data, label_shapes = data_iter.provide_label)\nmod.init_params(arg_params=arg_params, aux_params=aux_params)\n\ndata_iter.reset()\ntime_all = 0\nfor i in range(1000):\n data = data_iter.next()\n start = time.time()\n mod.forward(data)\n end = time.time()\n time_all += end - start\n\nprint(time_all)\n","sub_path":"evaluate_time.py","file_name":"evaluate_time.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"535656985","text":"urlfile = open('pixiv_urls.txt', 'r+')\nluafile = open('actions.lua', 'r+')\n\ncount = 0\nfor line in urlfile: \n\tcount += 1\n\tluafile.write('url' + str(count) + line +'\\n')\n\nluafile.close()\nurlfile.close()","sub_path":"pasteurls.py","file_name":"pasteurls.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"389014445","text":"from django.test import RequestFactory\nfrom django.test.utils import override_settings\n\nfrom ...allauth import NoNewUsersAccountAdapter\n\n\ndef test_nonewusersaccountadapter():\n adapter = NoNewUsersAccountAdapter()\n request = RequestFactory().get('/')\n\n assert adapter.is_open_for_signup(request) is False\n\n with override_settings(ENABLE_SIGNUP=False):\n assert adapter.is_open_for_signup(request) is False\n\n with override_settings(ENABLE_SIGNUP=True):\n assert adapter.is_open_for_signup(request) is True\n","sub_path":"src/dino/common/test/unit/test_accountadapter.py","file_name":"test_accountadapter.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"239497995","text":"\n# coding: utf-8\n\n# Name: Daniel Yan\n# \n# Email: daniel.yan@vanderbilt.edu\n# \n# Finds the shuffled parts of the human genome within the features matrices in files 50-99 from /dors/capra_lab/users/yand1/te_ml/data/2018_07_10_pca_te_enhancers/batch_output\n# and normalize them by dividing by the number of base pairs. Store the new features matrix containing only information about shuffled parts of the human genome to a /dors/capra_lab/users/yand1/te_ml/data/2018_07_10_pca_te_enhancers/shuffled_features_matrix.tsv\n\n# In[ ]:\n\n\n# Libraries\nimport pandas as pd\n\n\n# In[ ]:\n\n\n# Constants\nPAIRS = 4 # Column with base pairs\n\n\n# In[ ]:\n\n\ndef normalize_counts(df):\n \"\"\"Normalize all kmer counts by dividing by the total number of bases\n \"\"\"\n # Normalize counts by dividing kmer counts in each row by the number of bases\n df = df.apply(normalize_row, axis = \"columns\")\n return df\n\n\n# In[ ]:\n\n\ndef normalize_row(row):\n \"\"\"Divides the count of kmers by the number of pairs to get normalized value for PCA\n \n Args:\n row(pd.Series): Single row representing a HERV with counts of k-mers\n \n Return:\n row(pd.Series): Row that has k-mer counts divided by number of base pairs\n \"\"\"\n # Get number of pairs in current row\n pairs_length = len(row[PAIRS])\n \n # Update k-kmer counts\n for i in range(PAIRS + 1, len(row)):\n row.iloc[i] = (row.iloc[i])/pairs_length\n \n return row\n\n\n# In[ ]:\n\n\ndef combine(file_list, axis = \"index\"):\n \"\"\"Combines rows of the files together on the given axis and returns combined data frame\n \n Args:\n file_list(list): List of files with same columns\n axis(string): Concatenate on index or columns\n \"\"\"\n # List to store all the data frames to concatenate\n frames_list = []\n \n # Read in all files\n for file in file_list:\n frames_list.append(pd.read_table(file))\n \n # Combine data frames \n return pd.concat(frames_list, axis = axis) \n\n\n# In[ ]:\n\n\ndef main():\n \"\"\"Main\n \"\"\"\n # List of files to combine\n file_list = []\n \n # Directory the files are in \n directory = \"/dors/capra_lab/users/yand1/te_ml/data/2018_07_10_pca_te_enhancers/batch_output/\"\n \n # Generate list of files with shuffled human genome data to combine\n for i in range(50):\n file_list.append(directory + \"shuffle_{}_features_matrix.tsv\".format(i))\n \n # Get combined data frame\n combined_df = combine(file_list)\n \n # Normalize counts \n combined_df = normalize_counts(combined_df)\n \n # Save to new file\n combined_df.to_csv(\"/dors/capra_lab/users/yand1/te_ml/data/2018_07_10_pca_te_enhancers/shuffled_features_matrix.tsv\",\n header = False, Index = False, sep = '\\t')\n\n\n# In[ ]:\n\n\n# Call main to run\nmain()\n\n","sub_path":"bin/2018_07_10_pca_te_enhancers/format_shuffled_genome.py","file_name":"format_shuffled_genome.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"632347421","text":"import numpy as np\n\nfrom skimage import color\nfrom skimage.filters import gaussian\nfrom scipy import misc\nimport logging\n\nnoise_params = {\n 'gauss': {\n 'min': 0,\n 'max': 0.25,\n 'step': 0.025\n },\n 'quantization': {\n 'min': 0,\n 'max': 0.5,\n 'step': 0.05\n },\n 'sp': {\n 'min': 0,\n 'max': 0.2,\n 'step': 0.02\n },\n 'blur': {\n 'min': 0,\n 'max': 5,\n 'step': 0.5\n }\n}\n\n\ndef rescale(image, max_value=1.0):\n if max_value == 255:\n return np.clip(image, 0, max_value).astype(np.uint8)\n else:\n return np.clip(image, 0, max_value).astype(np.float32)\n\n\ndef apply_gaussian_noise(image, std, mean=0.0, max_value=1.0):\n assert max_value in [1.0, 255]\n\n noisy = image + np.random.normal(mean, std, image.shape) * max_value\n noisy = rescale(noisy, max_value)\n\n return noisy\n\n\ndef apply_gaussian_blur(image, sigma, max_value=1.0, multichannel=False):\n return rescale(gaussian(image, sigma=sigma, multichannel=multichannel), max_value)\n\n\ndef apply_salt_and_pepper_noise(image, p, max_value=1.0):\n assert max_value in [1.0, 255]\n\n mask = np.random.random(image.shape)\n\n noisy = np.copy(image)\n noisy[mask < p / 2] = 0\n noisy[mask > (1 - p / 2)] = max_value\n\n return rescale(noisy, max_value)\n\n\ndef apply_quantization_noise(image, q, max_value=1.0):\n assert max_value in [1.0, 255]\n\n noisy = image + q * (np.random.random(image.shape) - 0.5) * max_value\n noisy = rescale(noisy, max_value)\n\n return noisy\n\n\ndef lower_resolution(image, scaling_factor, max_value=1.0):\n assert max_value in [1.0, 255]\n\n if max_value == 1.0:\n image = (image * 255).astype(np.uint8)\n else:\n assert image.dtype == 'uint8'\n\n width = image.shape[0]\n height = image.shape[1]\n\n if len(image.shape) == 3:\n image_ycbcr = color.rgb2ycbcr(image)\n image_y = image_ycbcr[:, :, 0].astype(np.uint8)\n else:\n image_y = image.copy()\n\n downscaled = misc.imresize(image_y, 1 / float(scaling_factor), 'bicubic', mode='L')\n rescaled = misc.imresize(downscaled, (width, height), 'bicubic', mode='L').astype(np.float32)\n\n if len(image.shape) == 3:\n low_res_image = image_ycbcr\n low_res_image[:, :, 0] = rescaled\n low_res_image = color.ycbcr2rgb(low_res_image)\n low_res_image = (np.clip(low_res_image, 0.0, 1.0) * 255).astype(np.uint8)\n else:\n low_res_image = rescaled.astype(np.uint8)\n\n if max_value == 1.0:\n return low_res_image / 255\n else:\n return low_res_image\n\n\ndef apply_occlusion(image, fraction):\n assert 0.0 <= fraction <= 1.0\n\n image_width, image_height = image.shape[:2]\n image_area = image_width * image_height\n occlusion_area = fraction * image_area\n occlusion_width = int(np.round(np.sqrt(occlusion_area)))\n\n if occlusion_width > image_width or occlusion_width > image_height:\n logging.warning('Occlusion larger than the image. Occlusion shape: (%d, %d), image shape: (%d, %d).' %\n (occlusion_width, occlusion_width, image_width, image_height))\n\n occluded_image = image.copy()\n\n if occlusion_width < image_width:\n occlusion_start_x = np.random.randint(image_width - occlusion_width)\n else:\n occlusion_start_x = 0\n\n if occlusion_width < image_height:\n occlusion_start_y = np.random.randint(image_height - occlusion_width)\n else:\n occlusion_start_y = 0\n\n occluded_image[occlusion_start_x:(occlusion_start_x + occlusion_width),\n occlusion_start_y:(occlusion_start_y + occlusion_width)] = 0\n\n return occluded_image\n\n\ndef apply_noise(img, noise_type, noise_level):\n assert img.dtype in [np.float64, np.float32]\n assert img.max() <=1 and img.min() >= 0\n\n if noise_type == 'random':\n noise_type = np.random.choice(['sp', 'gauss', 'quantization'])\n if noise_level == 'random':\n noise_range = np.arange(noise_params[noise_type]['min'] + noise_params[noise_type]['step'],\n noise_params[noise_type]['max'] + noise_params[noise_type]['step'],\n noise_params[noise_type]['step'])\n noise_level = np.random.choice(noise_range)\n\n if noise_type == 'lres':\n noise_level = int(noise_level)\n else:\n noise_level = float(noise_level)\n\n if noise_type == 'gauss':\n noisy = apply_gaussian_noise(img, noise_level)\n elif noise_type == 'sp':\n noisy = apply_salt_and_pepper_noise(img, noise_level)\n elif noise_type == 'quantization':\n noisy = apply_quantization_noise(img, noise_level)\n elif noise_type == 'blur':\n noisy = apply_gaussian_blur(img, noise_level)\n elif noise_type == 'occlusion':\n noisy = apply_occlusion(img, noise_level)\n elif noise_type == 'lres':\n noisy = lower_resolution(img, noise_level)\n else:\n raise ValueError('Unknown noise_type: %s' % noise_type)\n\n assert noisy.dtype == img.dtype\n assert noisy.max() <= 1 and noisy.min() >= 0\n\n return noisy\n","sub_path":"noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"337331060","text":"def fully_corrective(q, p):\n comps = q.components\n\n if False:\n for i,comp in enumerate(comps):\n print(\"component\", i, \"\\tmean\", comp.mean().eval(), \"\\tstddev\", comp.stddev().eval())\n\n n_comps = len(comps)\n\n # randomly initialize, rather than take q.cat as the initialization\n weights = np.random.random(n_comps).astype(np.float32)\n weights /= np.sum(weights)\n\n n_samples = 1000\n samples = [comp.sample(n_samples).eval() for comp in comps] # comp.sample resamples each time, so eval once to keep samples fixed.\n\n p_log_probs = [tf.squeeze(p.log_prob(i)).eval() for i in samples]\n\n do_frank_wolfe = False\n if do_frank_wolfe:\n T = 1000000\n else:\n T = 100\n\n for t in range(T):\n # compute the gradient\n grad = np.zeros(n_comps)\n for i in range(n_comps):\n q_log_prob = Mixture(cat=Categorical(weights), components=comps).log_prob(samples[i]).eval()\n q_log_prob = np.sum(q_log_prob, axis=1)\n\n diff = q_log_prob - p_log_probs[i]\n grad[i] = np.mean(diff, axis=0) # take the expectation\n\n if do_frank_wolfe:\n min_i = np.argmin(grad)\n corner = np.zeros(weights.shape)\n corner[min_i] = 1.\n\n if t % 1000 == 0:\n print(\"grad\", grad)\n\n duality_gap = - np.dot(grad, (corner - weights))\n print(\"duality gap\", duality_gap)\n #assert False\n\n if t % 1000 == 0:\n print(\"duality_gap\", duality_gap)\n\n if duality_gap < 1e-10:\n print(\"weights\", weights, \"duality gap\", duality_gap, \"iteration\", t)\n return weights\n\n weights += 2. / (t + 2.) * (corner - weights)\n if t % 1000 == 0:\n print(\"weights\", weights, t)\n else:\n # gradient step\n step_size = 0.001\n weights_prime = weights - step_size * grad\n print(\"before\", weights_prime)\n weights_prime = euclidean_proj_simplex(weights_prime)\n print(\"after\", weights_prime)\n if np.max(np.abs(weights - weights_prime)) < 1e-6:\n weights = weights_prime.astype(np.float32)\n break\n weights = weights_prime.astype(np.float32)\n\n #print(\"weights\", weights, \"duality gap\", duality_gap, \"iteration\", t)\n return weights\n\ndef line_search(q, s, p):\n s_samples = s.sample(1000).eval()\n q_samples = q.sample(1000).eval()\n\n gamma = 0.5\n\n def get_new_weights(gamma):\n weights = q.cat.probs.eval()\n weights *= (1 - gamma)\n weights = np.append(weights, gamma).astype(np.float32)\n return weights\n\n comps = q.components\n comps = list(comps)\n comps.append(s)\n\n T = 50\n for t in range(T):\n weights = get_new_weights(gamma)\n\n mix = Mixture(cat=Categorical(weights), components=comps)\n s_expectation = tf.reduce_sum(mix.log_prob(s_samples), axis=1) - p.log_prob(s_samples)\n q_expectation = tf.reduce_sum(mix.log_prob(q_samples), axis=1) - p.log_prob(q_samples)\n grad = s_expectation - q_expectation\n grad = tf.reduce_mean(grad).eval()\n\n print(\"t\", t, \"gamma\", gamma, \"grad\", grad)\n\n step_size = 0.01 / (t+1)\n gamma_prime = gamma - grad * step_size\n if gamma_prime>= 1 or gamma_prime<=0:\n gamma_prime = max(min(gamma_prime,1.),0.)\n\n if np.abs(gamma - gamma_prime) < 1e-6:\n gamma = gamma_prime\n break\n gamma = gamma_prime\n\n\n if gamma < 1e-5:\n gamma = 1e-5\n\n print(\"final t\", t, \"gamma\", gamma, \"grad\", grad)\n return get_new_weights(gamma)\n","sub_path":"remainder/wip/frank_wolfe.py","file_name":"frank_wolfe.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"457005936","text":"# coding=utf-8\nimport MySQLdb\nimport random\nimport string\n\nVoucher = string.ascii_letters + string.digits\n\nf = open('voucher.txt', 'w')\n\nfor x in range(200):\n result = \"\"\n for y in range(20):\n result += random.choice(Voucher)\n f.write(result + '\\n')\n print(result)\n\nf.close()\n\n\ndef save_code():\n conn = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"123456\", db=\"pythontest\")\n cursor = conn.cursor() # connect the cursor with python\n\n with open('voucher.txt', 'r') as collect:\n codes = collect.readlines() # codes here is a list actually\n for i in range(200):\n cursor.execute(\"insert into code values('%d','%s')\" %(i, codes[i]))\n\n conn.commit() # store this operation\n cursor.close() # finish this connection\n\n\nif __name__ == '__main__':\n save_code()\n","sub_path":"0002.py","file_name":"0002.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"499250558","text":"#! python3\n\"\"\"The script should let the user add their own text anywhere the word ADJECTIVE,\nNOUN, ADVERB, or VERB appears in the text file.\nThe program would find these occurrences and prompt the user to replace them.\"\"\"\n\nimport re\n\ndef replace_some_words(file):\n \"\"\"Let the user replace words: ADJECTIVE, NOUN, ADVERB, or VERB in the file.\"\"\"\n with open(file, 'r') as f:\n text = f.read()\n pattern = re.compile('ADJECTIVE|NOUN|ADVERB|VERB')\n word_list = pattern.findall(text)\n new_list = []\n for i in range(len(word_list)):\n new_list.append(input('Enter a ' + word_list[i].lower() +' :\\n'))\n text = re.sub(word_list[i], new_list[i], text, 1)\n print(text)\n with open(file, 'w') as f:\n f.write(text)\n\n\ndef main():\n file_path = 'mad_libs.txt'\n replace_some_words(file_path)\n\nif __name__ == '__main__':\n main()","sub_path":"Chapter_08-Reading_and_Writing_Files/mad_libs.py","file_name":"mad_libs.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"276100418","text":"import sys\n\ndef merge_sort(A):\n merge_sort2(A,0,len(A)-1)\n return A\n \ndef merge_sort2(A,first,last):\n if first max_val:\n max_val = d[i]\n\n if i + T > N + 1:\n continue\n\n d[i + T] = max(max_val + P, d[i + T])\n\nprint(max(d))","sub_path":"김순석/DP/boj_15486_퇴사2.py","file_name":"boj_15486_퇴사2.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"330302740","text":"#=================================================================================================#\n# TensorFlow implementation of PGGAN\n# [Progressive Growing of GANs for Improved Quality, Stability, and Variation]\n# (https://arxiv.org/pdf/1710.10196.pdf)\n#=================================================================================================#\n\nimport tensorflow as tf\nimport argparse\nimport functools\nfrom dataset import celeba_input_fn\nfrom model import GAN\nfrom network import PGGAN\nfrom param import Param\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model_dir\", type=str, default=\"celeba_pggan_model\")\nparser.add_argument('--filenames', type=str, nargs=\"+\", default=[\"celeba_train.tfrecord\"])\nparser.add_argument(\"--batch_size\", type=int, default=16)\nparser.add_argument(\"--total_steps\", type=int, default=1000000)\nparser.add_argument(\"--train\", action=\"store_true\")\nparser.add_argument(\"--gpu\", type=str, default=\"0\")\nargs = parser.parse_args()\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nwith tf.Graph().as_default():\n\n tf.set_random_seed(0)\n\n pggan = PGGAN(\n min_resolution=[4, 4],\n max_resolution=[256, 256],\n min_channels=16,\n max_channels=512,\n growing_level=tf.cast(tf.get_variable(\n name=\"global_step\",\n initializer=0,\n trainable=False\n ) / args.total_steps, tf.float32)\n )\n\n gan = GAN(\n generator=pggan.generator,\n discriminator=pggan.discriminator,\n real_input_fn=functools.partial(\n celeba_input_fn,\n filenames=args.filenames,\n batch_size=args.batch_size,\n num_epochs=None,\n shuffle=True,\n image_size=[256, 256]\n ),\n fake_input_fn=lambda: (\n tf.random_normal([args.batch_size, 512])\n ),\n hyper_params=Param(\n generator_learning_rate=2e-3,\n generator_beta1=0.0,\n generator_beta2=0.99,\n discriminator_learning_rate=2e-3,\n discriminator_beta1=0.0,\n discriminator_beta2=0.99,\n one_centered_gradient_penalty_weight=10.0,\n generator_auxiliary_classification_weight=0.0,\n discriminator_auxiliary_classification_weight=0.0,\n )\n )\n\n if args.train:\n\n gan.train(\n total_steps=args.total_steps,\n model_dir=args.model_dir,\n save_checkpoint_steps=1000,\n save_summary_steps=100,\n log_step_count_steps=100,\n config=tf.ConfigProto(\n gpu_options=tf.GPUOptions(\n visible_device_list=args.gpu,\n allow_growth=True\n )\n )\n )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"173735836","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport random\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\ndef red_color_func(word, font_size, position, orientation, random_state=None,\n **kwargs):\n return \"hsl(0, 100%%, %d%%)\" % random.randint(60, 100)\n\ndef blue_color_func(word, font_size, position, orientation, random_state=None,\n **kwargs):\n return \"hsl(248, 100%%, %d%%)\" % random.randint(60, 100)\n\ndef remove_handles(content):\n\treturn \" \".join(filter(lambda x:x[0]!='@', content.split()))\n\nstopwords = list(STOPWORDS)\nfile = open(\"../dataset/left_tweet_dataset.tsv\")\nmask = np.array(Image.open(\"../images/gun.png\"))\ndataset = file.readlines()\ndata = \"\"\n\nfor row in dataset:\n\trecords = row.split(\"\\t\")\n\ttweet = remove_handles(records[0])\n\treply = remove_handles(records[1])\n\tif tweet not in data:\n\t\tdata += tweet\n\tdata += reply\n\nstopwords += [\"https\", \"co\"]\n\nwordcloud = WordCloud(max_font_size=30, background_color=\"white\", mode=\"RGB\",\n\t\t\t\t\t\tmax_words=100, stopwords=set(stopwords), mask=mask, margin=10,\n\t\t\t\t\t\trandom_state=1, collocations=False, contour_width=3,\n\t\t\t\t\t\tcontour_color='black').generate(data)\nprint(wordcloud)\nplt.figure(figsize=[20,10])\nplt.imshow(wordcloud.recolor(color_func=blue_color_func,random_state=3), interpolation='bilinear')\nplt.axis(\"off\")\nplt.savefig(\"../images/left.png\", format=\"png\")\nplt.show()","sub_path":"codebase/tag_cloud.py","file_name":"tag_cloud.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"234307854","text":"#!/usr/bin/env python\n# -*- encoding: utf-8\n\nimport configparser\nimport os\nimport sys\n\nimport boto3\nimport click\n\n\niam_client = boto3.client(\"iam\")\nsts_client = boto3.client(\"sts\")\n\n\ndef get_credentials(*, account_id, account_name, role_name):\n resp = sts_client.assume_role(\n RoleArn=f\"arn:aws:iam::{account_id}:role/{role_name}\",\n RoleSessionName=f\"{role_name}@{account_name}\"\n )\n\n return resp[\"Credentials\"]\n\n\ndef update_config(*, account_name, credentials):\n aws_dir = os.path.join(os.environ[\"HOME\"], \".aws\")\n\n credentials_path = os.path.join(aws_dir, \"credentials\")\n config = configparser.ConfigParser()\n config.read(credentials_path)\n\n if account_name not in config.sections():\n config.add_section(account_name)\n\n assert account_name in config.sections()\n\n config[account_name][\"aws_access_key_id\"] = credentials[\"AccessKeyId\"]\n config[account_name][\"aws_secret_access_key\"] = credentials[\"SecretAccessKey\"]\n config[account_name][\"aws_session_token\"] = credentials[\"SessionToken\"]\n\n config.write(open(credentials_path, \"w\"), space_around_delimiters=False)\n\n\n@click.command()\n@click.option(\"--account_id\", required=True)\n@click.option(\"--account_name\")\n@click.option(\"--role_name\", required=True)\ndef assume_role(account_id, account_name, role_name):\n if account_name is None:\n account_name = account_id\n\n credentials = get_credentials(\n account_id=account_id,\n account_name=account_name,\n role_name=role_name\n )\n\n update_config(account_name=account_name, credentials=credentials)\n\n\nif __name__ == '__main__':\n assume_role()\n#\n# resp = sts_client.assume_role(\n# RoleArn=sys.argv[1],\n# RoleSessionName=sys.argv[2]\n# )\n#\n# from pprint import pprint\n# pprint(resp)","sub_path":"aws/issue_temporary_credentials.py","file_name":"issue_temporary_credentials.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"15121173","text":"from bs4 import BeautifulSoup\nfrom graph import Vertex, Graph\nfrom gensim.models import Word2Vec\n\n\ncausePredicates = ['CAUSES','PREVENTS','DISRUPTS','INHIBITS',\n 'PREDISPOSES','PRODUCES']\ntwoDirectionalPredicates = ['COEXISTS_WITH','ASSOCIATED_WITH']\n\nwith open('predicates.xml') as f:\n \n soup = BeautifulSoup(f.read(), \"xml\").find_all('Utterance')\n \n preds = []\n i = 0\n\n for sent in soup:\n predication = sent.Predication\n if predication != None:\n pred = predication.Predicate['type']\n if True:#pred in causePredicates or pred in twoDirectionalPredicates:\n subj = sent.find(id=predication.Subject['entityID'])\n obj = sent.find(id=predication.Object['entityID'])\n dict = {}\n try:\n s = subj['name'].replace(':','')\n except:\n s = subj['entrezName'].replace(':','')\n try:\n o = [obj['name'].replace(':','')]\n except:\n o = [obj['entrezName'].replace(':','')]\n preds.append(Vertex(s, [pred], o))\n i += 1\n print(i, '/', len(soup), '\\r', end='')\n\nprint('\\n', len(preds), ' predications found')\n\n \ng = Graph(vertices=preds)\ng.causal()\n#g.filter_by(method='redundancy')\ng.filter_by('co-occurrence', threshold=0.05)\n#g.merge_vertices(g.v_mapping['Disease'], g.v_mapping['Virus Diseases'])\n#model = Word2Vec.load('../word-embedding/models/word2vec_window=6_size=300_min_count=7_iter=20.model')\n#g.word_embedding_filter(model, 'virus')\ng.draw()\n\n\n","sub_path":"causal_graph/causal_graph.py","file_name":"causal_graph.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"319342544","text":"\n\n#calss header\nclass _CONCERN():\n\tdef __init__(self,): \n\t\tself.name = \"CONCERN\"\n\t\tself.definitions = [u'a worried or nervous feeling about something, or something that makes you feel worried: ', u'a company: ', u'something that is important to you, or the fact of being important: ', u'something that involves or affects you or is important to you: ', u'to be important: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_concern.py","file_name":"_concern.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"619836684","text":"\n\n#calss header\nclass _TOXIC():\n\tdef __init__(self,): \n\t\tself.name = \"TOXIC\"\n\t\tself.definitions = [u'poisonous: ', u'very unpleasant or unacceptable', u'causing you a lot of harm and unhappiness over a long period of time: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_toxic.py","file_name":"_toxic.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"634867541","text":"from copy import deepcopy\nimport sys\nimport zipfile\nimport pytest\nfrom numpy import NaN\nimport pandas as pd\nfrom pandas.api.types import is_datetime64_any_dtype as is_datetime\n\nsys.path.append(\"python\")\nfrom cdhtools import ADMDatamart\n\n\n@pytest.fixture\ndef test():\n \"\"\"Fixture to serve as class to call functions from.\"\"\"\n return ADMDatamart(\n path=\"data\",\n model_filename=\"Data-Decision-ADM-ModelSnapshot_pyModelSnapshots_20210101T010000_GMT.zip\",\n predictor_filename=\"Data-Decision-ADM-PredictorBinningSnapshot_pyADMPredictorSnapshots_20210101T010000_GMT.zip\",\n context_keys=[\"Issue\", \"Group\", \"Channel\"],\n )\n\n\n# Test _capitalize function\ndef test_capitalize_behavior(test):\n assert set(test._capitalize([\"pyTest\", \"pzTest\", \"pxTest\"])) == {\"Test\"}\n assert test._capitalize([\"test\"]) == [\"Test\"]\n assert test._capitalize([\"RESPONSEcOUNT\"]) == [\"ResponseCount\"]\n assert test._capitalize([\"responsecounter\"]) == [\"ResponseCounter\"]\n assert test._capitalize([\"responsenumber\"]) == [\"Responsenumber\"]\n assert test._capitalize([\"Response Count\"]) == [\"Response Count\"]\n assert test._capitalize([\"Response_count1\"]) == [\"Response_Count1\"]\n\n\ndef test_basic_available_columns(test):\n input = pd.DataFrame(columns=[\"ModelID\", \"Issue\", \"Unknown\", \"Auc\", \"Response\"])\n output, variables, missing = test._available_columns(input)\n assert \"Unknown\" not in variables.values()\n assert \"Unknown\" not in missing\n assert \"ResponseCount\" in variables.values()\n assert (\"Response\", \"ResponseCount\") in variables.items()\n assert {\"ModelID\", \"Issue\", \"ResponseCount\"} not in missing\n assert \"ModelName\" in missing\n assert \"Auc\" not in variables.values()\n assert \"Performance\" not in variables.values()\n assert set(output.columns) == {\n \"ModelID\",\n \"Issue\",\n \"Unknown\",\n \"Auc\",\n \"ResponseCount\",\n }\n\n\ndef test_overwrite_mapping(test):\n input = pd.DataFrame(columns=[\"ModelID\", \"Issue\", \"Unknown\", \"Auc\", \"Response\"])\n mapping = {\"Unknown\": \"Unknown\", \"Performance\": \"Auc\"}\n output, variables, missing = test._available_columns(\n input, overwrite_mapping=mapping\n )\n assert \"Unknown\" in set(variables.values())\n assert \"Unknown\" not in missing\n assert \"ResponseCount\" in variables.values()\n assert (\"Response\", \"ResponseCount\") in variables.items()\n assert \"Auc\" not in set(variables.values())\n assert \"Performance\" in set(variables.values())\n assert (\"Auc\", \"Performance\") in variables.items()\n assert {\"ModelID\", \"Issue\", \"ResponseCount\"} not in missing\n assert \"ModelName\" in missing\n assert set(output.columns) == {\n \"ModelID\",\n \"Issue\",\n \"Unknown\",\n \"Performance\",\n \"ResponseCount\",\n }\n\n\ndef test_import_utils_with_importing(test):\n output, renamed, missing = test._import_utils(\n path=\"data\",\n name=\"Data-Decision-ADM-ModelSnapshot_pyModelSnapshots_20210101T010000_GMT.zip\",\n )\n assert output.shape == (20, 10)\n\n\n@pytest.fixture\ndef data():\n return pd.DataFrame(\n {\n \"pymodelid\": [\"model1\", \"model2\", \"model3\"],\n \"AUC\": [\"0.5000\", 0.700, 0.9],\n \"Junk\": [\"blabla\", \"blabla2\", \"blabla3\"],\n \"pyname\": [\n '{\"pyName\": \"ABC\", \"pyTreatment\": \"XYZ\"}',\n '{\"pyName\": \"abc\", \"pyTreatment\": \"xyz\"}',\n \"NormalName\",\n ],\n \"SnapshotTime\": [\n \"2022-03-01 05:00:00\",\n \"2022-03-01 05:00:00\",\n \"2022-03-01 05:00:00\",\n ],\n }\n )\n\n\ndef test_import_utils(test, data):\n output, renamed, missing = test._import_utils(name=deepcopy(data))\n assert output.shape == (3, 3)\n assert \"ModelName\" in output.columns\n assert list(output[\"ModelID\"]) == list(data[\"pymodelid\"])\n assert is_datetime(output[\"SnapshotTime\"])\n assert \"Performance\" not in output.columns\n assert renamed == {\n \"ModelID\": \"ModelID\",\n \"Name\": \"ModelName\",\n \"SnapshotTime\": \"SnapshotTime\",\n }\n assert \"Junk\" not in output.columns\n assert \"Treatment\" not in output.columns\n\n\ndef test_extract_treatment(test, data):\n mapping = {\"Performance\": \"auc\"}\n output, renamed, missing = test._import_utils(\n name=data, overwrite_mapping=mapping, extract_treatment=\"pyname\"\n )\n assert output.shape == (3, 5)\n assert output[\"Performance\"].dtype == \"float64\"\n assert list(output[\"Treatment\"]) == [\"XYZ\", \"xyz\", NaN]\n assert list(output[\"ModelName\"]) == [\"ABC\", \"abc\", \"NormalName\"]\n\n\ndef test_extract_treatment_all_json(test, data):\n df = deepcopy(data).reset_index(drop=True)\n df.loc[:, \"pyname\"] = [\n '{\"pyName\": \"ABC\", \"pyTreatment\": \"XYZ\"}',\n '{\"pyName\": \"abc\", \"pyTreatment\": \"xyz\"}',\n '{\"pyName\": \"ABCD\", \"pyTreatment\": \"XYZ1\"}',\n ]\n output, renamed, missing = test._import_utils(name=df, extract_treatment=\"pyname\")\n assert list(output[\"ModelName\"]) == [\"ABC\", \"abc\", \"ABCD\"]\n\n\ndef test_import_with_prequery(test, data):\n prequery = \"pymodelid != 'model2'\"\n output, renamed, missing = test._import_utils(name=data, prequery=prequery)\n assert output.shape == (2, 3)\n assert \"model2\" not in output[\"ModelID\"]\n\n\ndef test_import_with_wrong_prequery(test, data):\n prequery = \"non-existant-column != 'unknown'\"\n output, renamed, missing = test._import_utils(\n name=data, prequery=prequery, verbose=True\n )\n assert output.shape == (3, 3)\n\n\ndef test_import_with_query(test, data):\n \"\"\"Is actually also dependent on mapping and typing, but a good test nonetheless.\"\"\"\n query = \"Performance > 0.5\"\n mapping = {\"Performance\": \"auc\"}\n\n output, renamed, missing = test._import_utils(\n name=data, overwrite_mapping=mapping, query=query\n )\n assert output.shape == (2, 4)\n assert list(output[\"Performance\"]) == [0.7, 0.9]\n\n\ndef test_old_query(test):\n filtered = test._apply_query(deepcopy(test.modelData), query={\"Channel\": [\"Email\"]})\n assert filtered.shape == (11, 11)\n assert filtered.shape != test.modelData.shape\n\n\ndef test_error_old_query_1(test):\n with pytest.raises(TypeError):\n test._apply_query(deepcopy(test.modelData), query=[\"Email\"])\n\n\ndef test_error_old_query_2(test):\n with pytest.raises(ValueError):\n test._apply_query(deepcopy(test.modelData), query={\"Channel\": \"Email\"})\n\n\ndef test_import_with_wrong_query(test, data):\n query = \"non-existant-column != 'unknown'\"\n output, renamed, missing = test._import_utils(name=data, query=query)\n assert output.shape == (3, 3)\n\n\ndef test_no_subset(test, data):\n output, renamed, missing = test._import_utils(name=data, subset=False)\n assert \"Junk\" in output.columns\n assert output.shape == (3, 5)\n\n\ndef test_set_types_fails(test):\n df = pd.DataFrame(\n {\n \"Positives\": [1, 2, \"3b\"],\n \"Negatives\": [\"0\", 2, 4],\n \"SnapshotTime\": [\n \"2022-03-01 05:00:00\",\n \"2022-03-01 05:00:00\",\n \"2022-14-01 05:00:00\",\n ],\n }\n )\n output = test._set_types(df)\n assert output.shape == (3, 3)\n\n\ndef test_pdc_fix(test):\n pdc_extract = pd.DataFrame(\n {\n \"pxObjClass\": \"Code-Pega-List\",\n \"pxResults\": [\n {\n \"Channel\": \"Web\",\n \"Direction\": \"Inbound\",\n \"Group\": \"Cards\",\n \"Issue\": \"Sales\",\n \"ModelClass\": \"Data-Decision-Request-Customer\",\n \"ModelID\": \"abcdefgh\",\n \"ModelName\": \"OmniAdaptiveModel\",\n \"ModelType\": \"AdaptiveModel\",\n \"Name\": \"ExampleModelName\",\n \"Negatives\": \"100.000\",\n \"Performance\": \"0.800\",\n \"Positives\": \"200.000\",\n \"pxObjClass\": \"Pega-Data-CDHSnapshot-Models\",\n \"pzInsKey\": \"NotUsed\",\n \"ResponseCount\": \"300.000\",\n \"SnapshotTime\": \"20220301T000000.000 GMT\",\n \"TotalPositives\": \"200.000\",\n \"TotalResponses\": \"300.000\",\n }\n ],\n }\n )\n output = ADMDatamart(model_df=pdc_extract)\n assert output.modelData.shape == (1, 12)\n\n\n# More of the end-to-end main function tests\n\n\n@pytest.fixture\ndef cdhsample_models():\n with zipfile.ZipFile(\n \"data/Data-Decision-ADM-ModelSnapshot_pyModelSnapshots_20210101T010000_GMT.zip\"\n ) as zip:\n with zip.open(\"data.json\") as zippedfile:\n return pd.read_json(zippedfile, lines=True)\n\n\n@pytest.fixture\ndef cdhsample_predictors():\n with zipfile.ZipFile(\n \"data/Data-Decision-ADM-PredictorBinningSnapshot_pyADMPredictorSnapshots_20210101T010000_GMT.zip\"\n ) as zip:\n with zip.open(\"data.json\") as zippedfile:\n return pd.read_json(zippedfile, lines=True)\n\n\ndef test_import_models_only(test, cdhsample_models):\n assert cdhsample_models.shape == (20, 23)\n models, preds = test.import_data(model_df=deepcopy(cdhsample_models))\n assert preds == None\n assert models.shape == (20, 11)\n\n assert \"SuccessRate\" in models.columns\n # of course not strictly necessary, but just there as a reminder\n assert \"SuccessRate\" not in test._capitalize(list(cdhsample_models.columns))\n\n\ndef test_import_predictors_only(test, cdhsample_predictors):\n assert cdhsample_predictors.shape == (1755, 35)\n models, preds = test.import_data(predictor_df=deepcopy(cdhsample_predictors))\n assert models == None\n assert preds.shape == (1755, 19)\n\n assert \"BinResponseCount\" in preds.columns\n assert \"BinPropensity\" in preds.columns\n assert \"BinAdjustedPropensity\" in preds.columns\n\n\ndef test_import_both(test, cdhsample_models, cdhsample_predictors):\n models, preds = test.import_data(\n model_df=deepcopy(cdhsample_models), predictor_df=deepcopy(cdhsample_predictors)\n )\n assert models is not None\n assert preds is not None\n assert preds.shape == (1755, 19)\n assert models.shape == (20, 11)\n\n assert \"SuccessRate\" in models.columns\n\n assert \"BinResponseCount\" in preds.columns\n assert \"BinPropensity\" in preds.columns\n assert \"BinAdjustedPropensity\" in preds.columns\n\n\ndef test_import_both_from_file_autodiscovered(test):\n models, preds = test.import_data(path=\"data\")\n assert models is not None\n assert preds is not None\n assert preds.shape == (70735, 19)\n assert models.shape == (1047, 12)\n\n assert \"SuccessRate\" in models.columns\n\n assert \"BinResponseCount\" in preds.columns\n assert \"BinPropensity\" in preds.columns\n assert \"BinAdjustedPropensity\" in preds.columns\n\n\ndef test_import_both_from_file_manual(test):\n models, preds = test.import_data(\n path=\"data\",\n model_filename=\"Data-Decision-ADM-ModelSnapshot_pyModelSnapshots_20210101T010000_GMT.zip\",\n predictor_filename=\"Data-Decision-ADM-PredictorBinningSnapshot_pyADMPredictorSnapshots_20210101T010000_GMT.zip\",\n )\n\n assert models is not None\n assert preds is not None\n assert preds.shape == (1755, 19)\n assert models.shape == (20, 11)\n\n assert \"SuccessRate\" in models.columns\n\n assert \"BinResponseCount\" in preds.columns\n assert \"BinPropensity\" in preds.columns\n assert \"BinAdjustedPropensity\" in preds.columns\n\n\ndef test_drop_BinResponseCount(test):\n models, preds = test.import_data(path=\"data\", drop_cols=[\"BinResponseCount\"])\n assert preds.shape == (70735, 19)\n\n\ndef test_init_models_only(cdhsample_models):\n output = ADMDatamart(model_df=cdhsample_models)\n assert output.modelData is not None\n assert output.modelData.shape == (20, 11)\n assert not hasattr(output, \"combinedData\")\n assert output.context_keys == [\"Channel\", \"Direction\", \"Issue\", \"Group\"]\n\n\ndef test_init_preds_only(cdhsample_predictors):\n output = ADMDatamart(model_filename=None, predictor_df=cdhsample_predictors)\n assert output.predictorData is not None\n assert output.predictorData.shape == (1755, 19)\n assert not hasattr(output, \"combinedData\")\n assert output.context_keys == [\"Channel\", \"Direction\", \"Issue\", \"Group\"]\n\n\ndef test_init_both(cdhsample_models, cdhsample_predictors):\n output = ADMDatamart(model_df=cdhsample_models, predictor_df=cdhsample_predictors)\n assert output.modelData is not None\n assert output.modelData.shape == (20, 11)\n assert output.predictorData is not None\n assert output.predictorData.shape == (1755, 19)\n assert output.combinedData.shape == (1648, 29)\n assert output.context_keys == [\"Channel\", \"Direction\", \"Issue\", \"Group\"]\n\n\ndef test_describe_models(test):\n test.describe_models()\n\n\ndef test_describe_models_without_models():\n test = ADMDatamart(\"data\", model_filename=None)\n assert test.modelData is None\n with pytest.raises(ValueError):\n test.describe_models()\n\n\ndef test_model_summary(test):\n assert test.model_summary().shape == (3, 15)\n\n\ndef test_PredictorCategorization(test):\n assert test.defaultPredictorCategorization(\"Customer.Variable\") == \"Customer\"\n assert test.defaultPredictorCategorization(\"Variable\") == \"Primary\"\n","sub_path":"python/tests/test_ADMDatamart.py","file_name":"test_ADMDatamart.py","file_ext":"py","file_size_in_byte":13233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"307265989","text":"#>>> pip install bs4\r\n\r\nfrom base import BaseTest, Session\r\nfrom urllib.parse import quote_plus\r\nfrom bs4 import BeautifulSoup\r\nimport codecs\r\nimport json\r\n\r\n\r\nclass Settings(object):\r\n\r\n\tdef __init__(self, url, script):\r\n\t\tself.url = url\r\n\t\tself.session = Session.get()\r\n\t\tself.headers = {'Referer': BaseTest.stand+self.url, 'Content-Type': 'application/x-www-form-urlencoded'}\r\n\t\tself.script = script\r\n\t\tpayload = {'Login': BaseTest.login, 'Password': BaseTest.password}\r\n\t\tlogin_url = BaseTest.stand + '/Auth/LogOn'\r\n\t\tself.session.post(url=login_url, data=payload)\r\n\t\tself.cookies = self.session.cookies.get_dict()\r\n\t\tself.headers = {**self.headers, **self.cookies}\r\n\r\n\tdef get_raw_settings(self, mode='model'):\r\n\t\tt = self.session.get(BaseTest.stand+self.url, headers=self.headers)\r\n\t\tsoup = BeautifulSoup(t.text, 'html.parser')\r\n\t\tfor scr in soup.findAll('script'):\r\n\t\t\tif scr.get('src') == '/bundles/Setting/' + self.url.split('/')[-1] + '?v=' + self.script:\r\n\t\t\t\tstr_settings = scr\r\n\t\t\telse:\r\n\t\t\t\tpass\r\n\t\tsettings = []\r\n\t\tif mode == 'model':\r\n\t\t\tfor sett in str(str_settings.findNextSibling()).split('\\r\\n'):\r\n\t\t\t\ttry:\r\n\t\t\t\t\tsett = sett.strip()\r\n\t\t\t\t\tif sett.startswith('model.'):\r\n\t\t\t\t\t\tsettings.append(sett[6:])\r\n\t\t\t\texcept:\r\n\t\t\t\t\tpass\r\n\t\t\treturn settings\r\n\t\telse:\r\n\t\t\treturn str_settings\r\n\r\n\tdef get_settings(self):\r\n\t\tdic = {}\r\n\t\tfor i in self.get_raw_settings():\r\n\t\t\tdic[i.split('=')[0][:-1]] = i.split('=')[1][1:-1]\r\n\t\tfor i in dic:\r\n\t\t\tdic[i] = dic[i].strip(\"'\")\r\n\t\treturn dic\r\n\r\n\tdef post_settings(self, settings_dic):\r\n\t\trequest_body_list = []\r\n\t\tfor i in settings_dic:\r\n\t\t\trequest_body_list.append(i + '=' + settings_dic[i])\r\n\t\tself.request_body = '&'.join(request_body_list)\r\n\t\treturn self.session.post(BaseTest.stand + self.url, data=self.request_body, headers=self.headers)\r\n\r\n\r\nclass DonorSettings(Settings):\r\n\r\n\tdef __init__(self, script='k3PZb1rGL2OJptx7_Wq4Yu8kZSWVRVievzK9AFvF6b01', url='/Admin/Setting/EditDonor'):\r\n\t\tSettings.__init__(self, url, script)\r\n\r\n\tdef get_settings(self):\r\n\t\tsettings = self.get_raw_settings()\r\n\t\tdic = {}\r\n\t\tdic['ViewTabName'] = 'EditDonor'\r\n\t\tdic['NextTabName'] = ''\r\n\t\tfor i in settings:\r\n\t\t\tif i.startswith('HonorableDonorSettings') == True:\r\n\t\t\t\ti = i.replace(i[22], '[', 1)\r\n\t\t\t\ti = i.replace('__', '].')\r\n\t\t\t\ti = i.replace(i.split('=')[0], quote_plus(i.split('=')[0]))\r\n\t\t\tdic[i.split('=')[0][:-1]] = i.split('=')[1][1:-1]\r\n\t\tfor i in dic:\r\n\t\t\tdic[i] = dic[i].strip(\"'\")\r\n\t\tdic['DonorSubscription'] = quote_plus(\r\n\t\t\tdic['DonorSubscription'].replace('"', '\"').replace('\\\\', '\\r' + '\\\\').replace('\\\\n', codecs.decode('\\\\n', 'unicode_escape')))\r\n\t\tfor k, v in dic.items():\r\n\t\t\tdic[k] = v.strip(' ')\r\n\t\treturn dic\r\n\r\n\tdef edit_donor_settings(self, **edited_settings):\r\n\t\tcurrent_settings = self.get_settings()\r\n\t\tupdated = {}\r\n\t\tfor k, v in edited_settings.items():\r\n\t\t\tupdated[quote_plus(k)] = v\r\n\t\tupdated_donor_settings = {**current_settings, **updated}\r\n\t\treturn self.post_settings(updated_donor_settings)\r\n\r\n\r\nclass DonationsSettings(Settings):\r\n\r\n\tdef __init__(self, script='Q5M5c4m_DiE8N-vPmMI6ahTLJDkExwefMRrV3gZcX_U1', url='/Admin/Setting/EditDonation'):\r\n\t\tSettings.__init__(self, url, script)\r\n\r\n\tdef get_settings(self):\r\n\t\tsettings = self.get_raw_settings()\r\n\t\tstr_settings = self.get_raw_settings('numbers')\r\n\t\tstr_numbers = str_settings.find_next_sibling().get_text().split('\\r\\n')[4].strip().strip('DonationTabDiv.Init')[1:-2]\r\n\t\tjson_numbers = json.loads(str_numbers)\r\n\t\tdays = []\r\n\t\tfor y in range(len(json_numbers)):\r\n\t\t\tfor i in json_numbers[y]['Days']:\r\n\t\t\t\tif int(i) <= 5:\r\n\t\t\t\t\tdays.append(dict(Days=json_numbers[y]['Days'][i]['Count'], Id=json_numbers[y]['Days'][i]['Id']))\r\n\t\tdic = {}\r\n\t\tdic['ViewTabName'] = 'EditDonation'\r\n\t\tdic['NextTabName'] = ''\r\n\t\tfor i in settings:\r\n\t\t\tdic[i.split('=')[0][:-1]] = i.split('=')[1][1:-1]\r\n\t\tfor i in dic:\r\n\t\t\tdic[i] = dic[i].strip(\"'\")\r\n\t\tfor i in range(36):\r\n\t\t\tdic[quote_plus('EditDelays[' + str(i) + '].Id')] = str(days[i]['Id'])\r\n\t\t\tdic[quote_plus('EditDelays[' + str(i) + '].Days')] = str(days[i]['Days'])\r\n\t\treturn dic","sub_path":"system_settings/back_to_default.py","file_name":"back_to_default.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"421345746","text":"\n\"\"\"Logic to interact with de book store page\"\"\"\nfrom selenium.webdriver.remote.webdriver import WebDriver, WebElement\nfrom pages.base_page import BasePage\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nclass BookStore(BasePage):\n\n __URL = 'https://demoqa.com/books'\n __INPUT_LOC = (By.ID,'searchBox')\n __TABLE_ROW_LOC =(By.XPATH, \"//*[@class ='rt-tbody']//*[@class='rt-tr-group']\")\n\n def __init__(self, driver: WebDriver, timeout: int = 20):\n super().__init__(driver, timeout, self.__URL)\n\n\n def wait_until_loaded(self):\n \"\"\"Wait until boton submit is loaded\"\"\"\n self._wait.until(EC.presence_of_element_located(self.__INPUT_LOC))\n\n def search(self, value : str):\n \"\"\"Search entry\"\"\"\n element = self._wait.until(EC.visibility_of_element_located(self.__INPUT_LOC))\n element.clear()\n element.send_keys(value)\n\n def get_table_info(self) -> dict:\n \"\"\"Get table information\"\"\"\n rows = self._wait.until(EC.visibility_of_all_elements_located(self.__TABLE_ROW_LOC))\n info = {}\n for index, row in enumerate(rows):\n cells = row.findelemets_by_xpath(\".//*[@role='gridcell']\")\n title = cells[1].text\n author = cells[2].text\n publisher = cells[3].text\n info[index] = {'tile':title , 'author':author,'publisher' : publisher}\n return info\n\n\n\n\n","sub_path":"pages/demoqa/book_store.py","file_name":"book_store.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"100345581","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom torch.nn.utils.weight_norm import weight_norm\nimport copy\nimport math\n\ndef clones(module, N):\n \"Produce N identical layers.\"\n return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n\nclass LayerNorm(nn.Module):\n \"Construct a layernorm module (See citation for details).\"\n def __init__(self, feature_dim, eps=1e-6):\n super(LayerNorm, self).__init__()\n self.gain = nn.Parameter(torch.ones(feature_dim))\n self.bias = nn.Parameter(torch.zeros(feature_dim))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True) #(bsize,feature_nums,feature_dims)\n std = x.std(-1, keepdim=True)\n return self.gain * (x - mean) / (std + self.eps) + self.bias\n\nclass SublayerConnection(nn.Module):\n \"\"\"\n A residual connection followed by a layer norm.\n Note for code simplicity the norm is first as opposed to last.\n \"\"\"\n def __init__(self, size, dropout):\n super(SublayerConnection, self).__init__()\n self.norm = LayerNorm(feature_dim=size)\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, x, sublayer):\n \"Apply residual connection to any sublayer with the same size.\"\n return x + self.dropout(sublayer(self.norm(x)))\n\ndef DotProductAttention(query,key,value,mask=None,dropout=None):\n '''\n Compute 'Scaled Dot Product Attention'\n :param query:(bsize,num_heads,query_feature_nums,d_q)\n :param key:(bsize,num_heads,keyValue_feature_nums,d_k)\n :param value:(bsize,num_heads,keyValue_feature_nums,d_v)\n :param mask:(bsize,num_heads,query_feature_nums,keyValue_feature_nums)\n :param dropout:torch.nn.dropout()\n :return:value_:(bsize,num_heads,query_feature_nums,d_v)\n p_atten:(bsize,num_heads,query_feature_nums,keyValue_feature_nums)\n '''\n d_k = key.size(-1)\n scores = torch.matmul(query,key.transpose(-2,-1)) / math.sqrt(d_k) #(bsize,num_heads,feature_nums,feature_nums)\n if mask is not None:\n scores = scores.masked_fill(mask==0,-1e9)\n p_atten = torch.softmax(scores,dim=-1)\n if dropout is not None:\n p_atten = dropout(p_atten)\n value_ = torch.matmul(p_atten,value)\n return value_,p_atten\n\nclass AoABlock(nn.Module):\n def __init__(self,num_heads,d_model,dropout_aoa=0.3,dropout=0.1):\n super(AoABlock,self).__init__()\n #make sure the input features can be divided into N heads\n assert d_model % num_heads == 0\n self.num_heads = num_heads\n self.d_q = d_model // num_heads\n self.d_k = d_model // num_heads\n self.d_v = d_model // num_heads\n self.linear_Q = nn.Linear(in_features=d_model,out_features=d_model)\n self.linear_K = nn.Linear(in_features=d_model,out_features=d_model)\n self.linear_V = nn.Linear(in_features=d_model,out_features=d_model)\n self.aoa_layer = nn.Sequential(nn.Linear(in_features=2*d_model,out_features=2*d_model),nn.GLU())\n if dropout_aoa>0:\n self.dropout_aoa = nn.Dropout(p=dropout_aoa)\n else:\n self.dropout_aoa = lambda x:x\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self,query,key,value,mask=None):\n '''\n Compute AoA^E(f_mh-att,Q,K,V)\n :param query:(bsize,query_feature_nums,d_model)\n :param key:(bsize,key_value_feature_nums,d_model)\n :param value:(bsize,key_value_feature_nums,d_model)\n :param mask:(bsize,query_feature_nums,key_value_feature_nums)\n :return:x:(bsize,query_feature_nums,d_model)\n '''\n bsize = query.size(0)\n # (bsize,feature_nums,d_model)->(bsize,feature_nums,d_model)->\n # ->(bsize,feature_nums,num_heads,d_q/k/v)->(bsize,num_heads,feature_nums,d_q/k/v) d_k=d_q=d_v\n query_p = self.linear_Q(query).view(bsize,-1,self.num_heads,self.d_q).transpose(1,2)\n key_p = self.linear_K(key).view(bsize, -1, self.num_heads, self.d_k).transpose(1, 2)\n value_p = self.linear_V(value).view(bsize, -1, self.num_heads, self.d_v).transpose(1, 2)\n x,atten = DotProductAttention(query=query_p,key=key_p,value=value_p,mask=mask,dropout=self.dropout) #(bsize,num_heads,query_feature_nums,d_v)\n x = x.transpose(1,2).contiguous().view(bsize,-1,self.num_heads*self.d_v) #(bsize,query_feature_nums,d_model)\n x = self.aoa_layer(self.dropout_aoa(torch.cat([x,query],dim=-1))) #(bsize,query_feature_nums,d_model)\n return x\n\nclass AoA_Refine_Core(nn.Module):\n def __init__(self, num_heads, d_model=1024, dropout_aoa=0.3,dropout=0.1):\n super(AoA_Refine_Core,self).__init__()\n self.aoa_block = AoABlock(\n num_heads=num_heads,\n d_model=d_model,\n dropout_aoa=dropout_aoa,\n dropout=dropout\n )\n self.sublayer = SublayerConnection(size=d_model,dropout=dropout)\n self.aoa_layers = clones(self.sublayer,N=6)\n self.norm = LayerNorm(feature_dim=d_model)\n\n def forward(self,x,mask=None):\n '''\n Encoder with AoA\n :param x: (bsize,query_feature_nums,d_model)\n :param mask:\n :return:\n '''\n for layer in self.aoa_layers:\n x = layer(x,lambda x:self.aoa_block(query=x,key=x,value=x,mask=mask))\n return self.norm(x)\n\nclass EncoderCNN(nn.Module):\n def __init__(self,encoded_img_size=7):\n super(EncoderCNN,self).__init__()\n self.enc_img_size = encoded_img_size\n resnet = models.resnet101(pretrained=True)\n self.feature_extractor = nn.Sequential(\n resnet.conv1,\n resnet.bn1,\n resnet.relu,\n resnet.maxpool,\n resnet.layer1,\n resnet.layer2,\n resnet.layer3,\n resnet.layer4\n )\n self.adaptive_pool = nn.AdaptiveAvgPool2d((encoded_img_size,encoded_img_size))\n self.GAP = nn.AdaptiveAvgPool2d((1,1))\n\n def forward(self,images):\n features = self.feature_extractor(images) #(bsize,2048,H/32,W/32)\n features = self.adaptive_pool(features) #(bsize,2048,7,7)\n bsize = images.size(0)\n num_pixels = features.size(2) * features.size(3)\n num_channels = features.size(1)\n features = features.permute(0,2,3,1) #(bsize,7,7,2048)\n features = features.view(bsize,num_pixels,num_channels) #(bsize,49,2048)\n return features\n\nclass AoA_Decoder(nn.Module):\n def __init__(self,hidden_dim,num_heads,embed_dim,vocab_size,d_model,dropout=0.5,device='cpu'):\n super(AoA_Decoder,self).__init__()\n self.embed_dim = embed_dim\n self.hidden_dim = hidden_dim\n self.vocab_size = vocab_size\n self.ss_prob = 0.0\n self.lstm = nn.LSTMCell(input_size=self.embed_dim+hidden_dim,hidden_size=hidden_dim) #(x_t=[WeIIt,a_avg+c_t-1])\n self.aoa_block = AoABlock(num_heads=num_heads,d_model=d_model)\n self.embed = nn.Embedding(num_embeddings=vocab_size,embedding_dim=embed_dim)\n self.predict = weight_norm(nn.Linear(in_features=hidden_dim,out_features=vocab_size))\n self.dropout = nn.Dropout(p=dropout)\n self.device = device\n self.init_weights()\n\n def init_weights(self):\n self.embed.weight.data.uniform_(-0.1,0.1)\n self.predict.weight.data.uniform_(-0.1,0.1)\n self.predict.bias.data.fill_(0)\n\n def init_hidden_state(self,bsize):\n h = torch.zeros(bsize,self.hidden_dim).to(self.device)\n m = torch.zeros(bsize,self.hidden_dim).to(self.device)\n ctx = torch.zeros(bsize,self.hidden_dim).to(self.device)\n return h,m,ctx\n\n def forward(self,enc_features,captions,lengths,atten_masks=None):\n bsize = enc_features.size(0)\n num_pixels = enc_features.size(1) #(bsize,49,1024=hidden_dim)\n mean_features = torch.mean(enc_features,dim=1,keepdim=False) #(bsize,1024)\n embeddings = self.embed(captions)\n h,m,ctx = self.init_hidden_state(bsize)\n #ctx vector is initialized to zeros at the begining step (bsize,hidden_dim) so it is equal to h&m\n predictions = torch.zeros(bsize,max(lengths),self.vocab_size).to(self.device)\n for time_step in range(max(lengths)):\n bsize_t = sum([l > time_step for l in lengths])\n if time_step >= 2 and self.ss_prob > 0.0:\n sample_prob = torch.zeros(bsize_t).uniform_(0,1).to(self.device)\n sample_mask = sample_prob < self.ss_prob\n if sample_mask.sum() == 0:\n it = captions[:bsize_t,time_step]\n else:\n sample_ind = sample_mask.nonzero().view(-1)\n it = captions[:bsize_t,time_step].clone()\n prob_prev = torch.softmax(preds,dim=1)\n it.index_copy_(0, sample_ind, torch.multinomial(prob_prev, 1).view(-1).index_select(0, sample_ind))\n else:\n it = captions[:bsize_t,time_step]\n\n embeddings = self.embed(it) #(bsize_t,embed_dim)\n h,m = self.lstm(\n torch.cat([embeddings,mean_features[:bsize_t]+ctx[:bsize_t]],dim=1),\n (h[:bsize_t],m[:bsize_t])\n )\n if atten_masks is not None:\n atten_masks_this_step = atten_masks[:bsize_t]\n else:\n atten_masks_this_step = None\n ctx = self.aoa_block(\n query=h.unsqueeze(1),\n key=enc_features[:bsize_t],\n value=enc_features[:bsize_t],\n mask=atten_masks_this_step\n ) #(bsize,1,d_model)\n ctx = ctx.squeeze(1) #(bsize,d_model=hidden_dim)\n preds = self.predict(self.dropout(ctx))\n predictions[:bsize_t, time_step, :] = preds\n\n pack_predictions = pack_padded_sequence(predictions, lengths, batch_first=True)\n return pack_predictions\n\n def sample(self,enc_features,max_len=20,atten_masks=None):\n bsize = enc_features.size(0)\n num_pixels = enc_features.size(1) #(bsize,49,2048)\n mean_features = torch.mean(enc_features,dim=1,keepdim=False) #(bsize,1024)\n h,m,ctx = self.init_hidden_state(bsize)\n captions = torch.LongTensor(bsize,1).fill_(1).to(self.device)\n sampled_ids = []\n for time_step in range(max_len):\n embeddings = self.embed(captions).squeeze(1) #(bsize,embed_dim)\n h,m = self.lstm(\n torch.cat([embeddings,mean_features+ctx],dim=1),\n (h,m)\n )\n if atten_masks is not None:\n atten_masks_this_step = atten_masks\n else:\n atten_masks_this_step = None\n ctx = self.aoa_block(\n query=h.unsqueeze(1),\n key=enc_features,\n value=enc_features,\n mask=atten_masks_this_step\n ) #(bsize,1,d_model)\n ctx = ctx.squeeze(1) #(bsize,d_model=hidden_dim)\n preds = self.predict(self.dropout(ctx))\n pred_id = preds.max(1)[1] # (bsize,)\n captions = pred_id.unsqueeze(1) # (bsize,1)\n sampled_ids.append(captions)\n sampled_ids = torch.cat(sampled_ids, dim=1) # (bsize,max_seq)\n return sampled_ids\n\nclass AoASpatial_Captioner(nn.Module):\n def __init__(self,encoded_img_size,vocab_size,num_heads=8,hidden_dim=1024,embed_dim=1024,dropout_aoa=0.3,dropout=0.5,device='cpu'):\n super(AoASpatial_Captioner,self).__init__()\n #img_embed_dim=hidden_dim=1024\n self.encoder = EncoderCNN(encoded_img_size=encoded_img_size)\n self.img_feats_porjection = nn.Linear(in_features=2048,out_features=hidden_dim)\n self.aoa_refine = AoA_Refine_Core(num_heads=num_heads,d_model=hidden_dim,dropout_aoa=dropout_aoa)\n self.decoder = AoA_Decoder(hidden_dim=hidden_dim,num_heads=num_heads,embed_dim=embed_dim,vocab_size=vocab_size,d_model=hidden_dim,dropout=dropout,device=device)\n self.cnn_fine_tune(flag=False)\n\n def cnn_fine_tune(self, flag=False):\n if flag:\n for module in list(self.encoder.feature_extractor.children())[7:]:\n for param in module.parameters():\n param.requires_grad = True\n else:\n for params in self.encoder.feature_extractor.parameters():\n params.requires_grad = False\n\n def forward(self,images,captions,lengths):\n enc_features = self.encoder(images) #(bsize,49,2048)\n projected_enc_features = self.img_feats_porjection(enc_features) #(bsize,1024)\n refined_features = self.aoa_refine(x=projected_enc_features)\n packed_predictions = self.decoder(refined_features,captions,lengths)\n return packed_predictions\n\n def sampler(self,images,max_len=20):\n enc_features = self.encoder(images) #(bsize,49,2048)\n projected_enc_features = self.img_feats_porjection(enc_features) #(bsize,49,1024)\n refined_features = self.aoa_refine(x=projected_enc_features)\n sampled_ids = self.decoder.sample(refined_features,max_len=max_len)\n return sampled_ids\n\nif __name__ == '__main__':\n x = torch.randn(4,49,1024)\n net = AoA_Refine_Core(num_heads=8)\n out = net(x)\n print(out.shape)\n img = torch.randn(4,3,224,224)\n cap = AoASpatial_Captioner(encoded_img_size=7,num_heads=8,hidden_dim=1024,embed_dim=512,vocab_size=10102)\n sam = cap.sampler(images=img)\n print(sam)","sub_path":"Models/AoASpatial_Model.py","file_name":"AoASpatial_Model.py","file_ext":"py","file_size_in_byte":13499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"347959368","text":"\"\"\" Main driver for pycomics \"\"\"\nimport os\nfrom dilbert import Dilbert\nfrom generic import Generic\nfrom mail import Mail\nfrom qotd import Qotd\nfrom xkcd import Xkcd\n\ndef main():\n \"\"\" Main entry method. \"\"\"\n creators = 'class=\"fancybox\"'\n king_features = '> output_grdp_file, '''\n\n '''\n\n resource_list_in_header_file = ''\n modules = set()\n\n for root, _, filenames in sorted(os.walk(input_path)):\n relroot = os.path.relpath(root, input_path)\n if relroot == '.':\n # We don't include top-level files under resources/layered_api,\n # including generated resources.grdp.\n continue\n\n # Get e.g. \"kKvStorage\" for kv-storage.\n module_name = relroot.split('/')[0]\n module_name = \"k\" + module_name.title().replace('-', '')\n modules.add(module_name)\n\n for filename in sorted(filenames):\n if filename.startswith('.') or filename.startswith(\n 'README') or filename.startswith('OWNERS'):\n continue\n relpath = os.path.relpath(os.path.join(root, filename), input_path)\n relpath = relpath.replace('\\\\', '/')\n resource_id = relpath\n resource_id = resource_id.replace('/', '_')\n resource_id = resource_id.replace('-', '_')\n resource_id = resource_id.replace('.', '_')\n resource_id = resource_id.upper()\n resource_id = \"IDR_LAYERED_API_\" + resource_id\n resource_list_in_header_file += \\\n ' {\"%s\",\\n %s,\\n Module::%s},\\n' % (relpath, resource_id, module_name)\n print >> output_grdp_file, (\n ' '\n % (resource_id, input_relative_path, relpath))\n resource_list_in_header_file += '\\n'\n print >> output_grdp_file, ''\n\n module_list_in_header_file = ''\n for module in modules:\n module_list_in_header_file += (' %s,\\n' % module)\n\n print >> output_module_header_file, '''// Copyright 2019 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_LAYERED_API_MODULE_H_\n#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_LAYERED_API_MODULE_H_\n\n// This file is generated by\n// core/script/generate_lapi_grdp.py and shouldn't modified manually.\n// A corresponding grdp file (layered_api_resources.grdp) is also generated.\n\nnamespace blink {\n\nnamespace layered_api {\n\nenum class Module {\n%s};\n\n} // namespace layered_api\n\n} // namespace blink\n\n#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_LAYERED_API_MODULE_H_''' % \\\n module_list_in_header_file\n\n print >> output_header_file, '''// Copyright 2019 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"third_party/blink/public/resources/grit/blink_resources.h\"\n#include \"third_party/blink/renderer/core/script/layered_api_module.h\"\n\n#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_LAYERED_API_RESOURCES_H_\n#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_LAYERED_API_RESOURCES_H_\n\n// This file is generated by\n// core/script/generate_lapi_grdp.py and shouldn't modified manually.\n// A corresponding grdp file (layered_api_resources.grdp) is also generated.\n\n// This file should be included only once from core/script/layered_api.cc.\n\nnamespace blink {\n\nnamespace layered_api {\n\nnamespace {\n\nstruct LayeredAPIResource {\n const char* path;\n int resource_id;\n Module module;\n};\n\nconst LayeredAPIResource kLayeredAPIResources[] = {\n%s};\n\n} // namespace\n\n} // namespace layered_api\n\n} // namespace blink\n\n#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_LAYERED_API_RESOURCES_H_''' % \\\n resource_list_in_header_file\n\n output_grdp_file.close()\n output_header_file.close()\n output_module_header_file.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"third_party/blink/renderer/core/script/generate_lapi_grdp.py","file_name":"generate_lapi_grdp.py","file_ext":"py","file_size_in_byte":5224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"55839267","text":"import os\nfrom shutil import rmtree\nfrom subprocess import check_call, PIPE\nfrom tempfile import mkdtemp\n\nfrom trac_triager.wc.subversion import Subversion\n\n\ndef create_spamegg_repo(repository):\n files = {\n \"spam\" : \"\"\"This is\n\nsome nice & neat\nspam\n\nrepository\n \"\"\",\n \"egg\" : \"\"\"Secret\n egg of mine\n\n dropped into\n Django pony\n \"\"\"\n }\n\n for file in files:\n f = open(os.path.join(repository, file), \"w+b\")\n f.write(files[file])\n f.close()\n\n check_call([\"svn\", \"add\", file], cwd=repository, stdout=PIPE, stderr=PIPE)\n\n check_call([\"svn\", \"commit\", \"-m\", \"Creating spammegg repo\"], cwd=repository, stdout=PIPE, stderr=PIPE)\n\nclass SvnTestCase(object):\n def setUp(self):\n# super(SvnTestCase, self).setUp()\n self.create_test_repository()\n\n def create_test_repository(self, repository_name=\"test_repository\"):\n self.repository = mkdtemp(prefix=\"trac_triager_repository_\")\n wc = mkdtemp(prefix=\"trac_triager_wc_\")\n check_call(['svnadmin', 'create', repository_name], cwd=self.repository)\n check_call(['svn', 'checkout', \"file://%s\" % os.path.join(self.repository, repository_name)], cwd=wc, stdout=PIPE, stderr=PIPE)\n\n self.wc = Subversion(dir=os.path.join(wc, repository_name))\n return wc\n\n def tearDown(self):\n rmtree(self.repository)\n # rmtree(self.wc.dir)\n\n self.repository = None\n self.wc = None\n \n # super(SvnTestCase, self).tearDown()\n\nclass SvnSpamEggTestCase(SvnTestCase):\n def setUp(self):\n super(SvnSpamEggTestCase, self).setUp()\n create_spamegg_repo(self.wc.dir)\n","sub_path":"tests/test_subversion/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"553972703","text":"import numpy as np\nfrom preprocessing import hypercube_normalization, centralize\n\nclass Oja(object):\n \"\"\" A method for doing dimensionality reduction by transforming the feature\n space to a lower dimensionality, removing correlation between features and\n maximizing the variance along each feature axis.\n \n The Oja learning rule is an enhancement of Hebbian learning rule, which \n based on normalized weights. The artificial neuron learns to compute \n a principal component of its input stream.\n\n http://www.scholarpedia.org/article/Oja_learning_rule\n \n Attributes:\n principal_components: list of principal components arrays\n eigenvectors: list of eigenvectors arrays\n feature_n: An integer number of a dataset features\n sample_n: An integer size of a dataset\n \"\"\"\n \n def __init__(self):\n self.principal_components = []\n self.eigenvectors = []\n self.feature_n = 0\n self.sample_n = 0\n\n def fit(self, X):\n \"\"\" Fit the dataset to the number of principal components.\n \n Args:\n 2d array, where a horizontal axis is equal to the number of \n features, a vertical axis is equal to the number of dataset samples.\n \n Returns: \n lists of arrays of the principal components and the eigenvectors.\n \"\"\"\n \n X = self.__preprocess(X)\n \n self.sample_n = X.shape[0]\n self.feature_n = X.shape[1]\n \n # Set the initial vector of weight coefficients in the range [-1, 1]\n w = np.random.uniform(-1, 1, (1, self.feature_n))\n w = w / np.linalg.norm(w)\n\n learning_rate = 1 / self.sample_n\n for k in range(1, self.feature_n + 1):\n PC = np.array([0.0 for _ in range(X.shape[0])], ndmin=2).T\n # 10^k is the number of iterations necessary to find the eigenvector\n for _ in range(10 ** k):\n for i, x in enumerate(X):\n # Recalculation of the principal component element in accordance with the updated weights.\n y = np.dot(w, x)\n # Recalculation of the eigenvector by Oya's recurrent formula\n w = w + learning_rate * y * (x - y * w)\n w = w / np.linalg.norm(w)\n PC[i] = y\n \n # After each next eigenvector and principal component need to \n # subtract the principal components and eigenvector of the sample.\n X = X - PC * w\n self.principal_components.append(PC)\n self.eigenvectors.append(w)\n\n return self.principal_components, self.eigenvectors\n\n def __preprocess(self, X):\n \"\"\" A method for normalizing data to mean=0 and setting the range [-1, 1]. \n \n Args:\n 2d array, where a horizontal axis is equal to the number of \n features, a vertical axis is equal to the number of dataset samples.\n \n Returns:\n An array which represents normalized and centralized data that \n has the same dimension as the argument.\n \"\"\"\n \n return centralize(hypercube_normalization(X))\n\n def decompress(self):\n \"\"\" A method for decompressing principal components. \n \n Returns:\n 2d array which represents approximate data after compression \n and decompression. A horizontal axis is equal to the number of \n features, a vertical axis is equal to the number of dataset samples.\n \"\"\"\n \n X_apx = np.array([[0.0] * self.feature_n for _ in range(self.sample_n)])\n\n for w, PC in zip(self.eigenvectors, self.principal_components):\n for i in range(PC.shape[0]):\n X_apx[i] = X_apx[i] + w * PC[i]\n\n return X_apx","sub_path":"unsupervised_learning/oja.py","file_name":"oja.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"639398944","text":"from bot_math import Pose, Position\nimport pacbot_rs\nimport pygame as pg\nfrom grid import GRID_WIDTH, GRID_HEIGHT, GRID\nimport math\n\nDRAW_SCALE = 30\n\nSCREENRECT = pg.Rect(\n 0, 0, (GRID_WIDTH + 2) * DRAW_SCALE, (GRID_HEIGHT + 2) * DRAW_SCALE\n)\nCOLOR_BG_WHITE = (255, 255, 255)\nCOLOR_LINE_BLACK = (0, 0, 0)\nCOLOR_WALL_FILL_GREY = (192, 192, 192)\nCOLOR_ROBOT_BLUE = (0, 0, 255)\nCOLOR_SIMULATED_RAYCAST_RED = (255, 0, 0)\nCOLOR_SENSOR_DISTANCE_GREEN = (0, 200, 0)\nCOLOR_POINT_YELLOW = (255, 255, 0)\nCOLOR_TEXT_BLACK = (0, 0, 0)\n\nFPS = 60\n\nROBOT_RADIUS_GRID_UNITS = (6 / 3.5) / 2\nROBOT_RADIUS = DRAW_SCALE * ROBOT_RADIUS_GRID_UNITS\nSENSOR_ANGLES = [math.pi / 2, math.pi / 4, 0, -math.pi / 4, -math.pi / 2]\nSENSOR_DISTANCE_FROM_CENTER = 2 * 0.75 / 2.0 # a passage is 2 grid units wide\n\n\ndef world2screen(world_pos: tuple[float, float]) -> tuple[float, float]:\n \"\"\"Convert world coordinates to screen coordinates.\"\"\"\n wx, wy = world_pos\n return (wx + 1) * DRAW_SCALE, (wy + 1) * DRAW_SCALE\n\n\nfrom robot import Robot\n\n\ndef get_alt_grid():\n alt_grid = [[True] * (GRID_HEIGHT + 1) for _ in range(GRID_WIDTH + 1)]\n for x in range(GRID_WIDTH - 1):\n for y in range(GRID_HEIGHT - 1):\n alt_grid[x + 1][y + 1] = (\n GRID[x][y] and GRID[x + 1][y] and GRID[x][y + 1] and GRID[x + 1][y + 1]\n )\n return alt_grid\n\n\nclass SimCanvas:\n def __init__(self, game_state: pacbot_rs.GameState, particle_filter: pacbot_rs.ParticleFilter):\n self.game_state = game_state\n self.particle_filter = particle_filter\n\n pg.display.init()\n pg.font.init()\n\n win_style = 0 # |FULLSCREEN\n\n best_depth = pg.display.mode_ok(SCREENRECT.size, win_style, 32)\n self.display = pg.display.set_mode(SCREENRECT.size, win_style, best_depth)\n\n self.background_image = pg.Surface(SCREENRECT.size).convert()\n self.bg_rect = self.background_image.get_rect(\n center=(SCREENRECT.width // 2, SCREENRECT.height // 2)\n )\n\n # fill the background color\n pg.draw.rect(self.background_image, COLOR_BG_WHITE, self.bg_rect)\n\n # fill the walls\n alt_grid = get_alt_grid()\n for x in range(GRID_WIDTH + 1):\n for y in range(GRID_HEIGHT + 1):\n if alt_grid[x][y]:\n rect = pg.Rect(*world2screen((x - 1, GRID_HEIGHT - y - 1)), DRAW_SCALE, DRAW_SCALE)\n pg.draw.rect(self.background_image, COLOR_WALL_FILL_GREY, rect)\n\n # draw edges\n rect = pg.Rect(*world2screen((-1, GRID_HEIGHT)), (GRID_WIDTH + 1) * DRAW_SCALE, DRAW_SCALE)\n pg.draw.rect(self.background_image, COLOR_WALL_FILL_GREY, rect)\n rect = pg.Rect(*world2screen((GRID_WIDTH, -1)), DRAW_SCALE, (GRID_HEIGHT + 2) * DRAW_SCALE)\n pg.draw.rect(self.background_image, COLOR_WALL_FILL_GREY, rect)\n\n pg.display.flip()\n\n def update(self, game_state: pacbot_rs.GameState, particle_filter: pacbot_rs.ParticleFilter, robot: Robot,\n destination: (int, int), test_path: list[Position], sensors: list[float]):\n self.game_state = game_state\n self.particle_filter = particle_filter\n\n # process quit event\n for event in pg.event.get():\n if event.type == pg.QUIT:\n return\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n return\n elif event.key == pg.K_f:\n pass # ...\n\n # clear / draw the background\n self.display.blit(self.background_image, self.bg_rect)\n\n # draw the map segments\n for (x1, x2, y1, y2) in particle_filter.get_map_segments_list():\n pg.draw.line(self.display, COLOR_LINE_BLACK, world2screen((x1, y1)), world2screen((x2, y2)), 1)\n\n # draw the particle filter positions\n for point in particle_filter.get_points():\n pg.draw.circle(self.display, COLOR_POINT_YELLOW, world2screen(point[0]), 1)\n\n # draw the path\n path = [world2screen((p.x, p.y)) for p in test_path]\n if len(path) > 1:\n pg.draw.lines(self.display, COLOR_ROBOT_BLUE, False, path, 2)\n\n # draw the robot\n robot.draw(self.display)\n\n # pf_robot is the particle filter's idea of where the robot is\n pf_pose = particle_filter.get_pose()\n pf_robot = Robot()\n pf_robot.pose = Pose(\n Position(pf_pose[0][0], pf_pose[0][1]),\n pf_pose[1]\n )\n pf_robot.draw(self.display)\n\n # this dot represents the robot's destination\n pg.draw.circle(self.display, COLOR_SENSOR_DISTANCE_GREEN, world2screen((destination[0], destination[1])), 5)\n\n # draw the sensor distances, both simulated raycast and measured\n # print(sensors[:4])\n for i in range(5):\n if i == 4:\n continue # sensor broken\n angle = SENSOR_ANGLES[i]\n\n for (color, distance) in [\n # draw line from pacbot to the simulated wall\n (COLOR_SIMULATED_RAYCAST_RED, particle_filter.get_sense_distances()[i])\n # draw a line representing the measured sensor distance\n # (COLOR_SENSOR_DISTANCE_GREEN, sensors[i] + SENSOR_DISTANCE_FROM_CENTER)\n ]:\n if distance - ROBOT_RADIUS_GRID_UNITS <= 0:\n continue\n # draw the line\n pg.draw.line(self.display, color, world2screen((\n # start of line\n pf_pose[0][0] + ROBOT_RADIUS_GRID_UNITS * math.cos(pf_pose[1] + angle),\n pf_pose[0][1] + ROBOT_RADIUS_GRID_UNITS * math.sin(pf_pose[1] + angle)\n )), world2screen((\n # end of line\n pf_pose[0][0] + distance * math.cos(pf_pose[1] + angle),\n pf_pose[0][1] + distance * math.sin(pf_pose[1] + angle)\n )), 2)\n # draw the dot at the end of the line\n pg.draw.circle(self.display, color, world2screen((\n pf_pose[0][0] + distance * math.cos(pf_pose[1] + angle),\n pf_pose[0][1] + distance * math.sin(pf_pose[1] + angle)\n )), 3)\n\n # draw coordinate markers for y axis on screen; draw the numbers upside down\n font = pg.font.SysFont(\"Arial\", 12)\n for y in range(GRID_HEIGHT + 1):\n text = font.render(str(y), True, COLOR_LINE_BLACK)\n text_rect = text.get_rect()\n text_rect.center = world2screen((-0.5, y))\n self.display.blit(pg.transform.flip(text, False, True), text_rect)\n\n # draw coordinate markers for x axis on screen\n for x in range(GRID_WIDTH + 1):\n text = font.render(str(x), True, COLOR_LINE_BLACK)\n text_rect = text.get_rect()\n text_rect.center = world2screen((x, -0.5))\n self.display.blit(pg.transform.flip(text, False, True), text_rect)\n\n # flip display to match orientation of other visualization\n self.display.blit(pg.transform.flip(self.display, False, True), (0, 0))\n # update display\n pg.display.update()\n","sub_path":"2022-2023/pacbot_rpi/sim_canvas.py","file_name":"sim_canvas.py","file_ext":"py","file_size_in_byte":7184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"283790076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 4 13:01:53 2019\n\n@author: Brad\n\"\"\"\n\nimport requests\nimport re\nimport pandas as pd\nimport csv\n\nfrom random import choice\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom time import mktime\n\nclass Stock():\n def __init__(self, stock, interval, begin_date, end_date):\n self.stock = stock\n self.interval = interval\n self.url = 'https://finance.yahoo.com/quote/{0}/history'.format(stock)\n self.begin_date = self._convert_to_unix(begin_date)\n self.end_date = self._convert_to_unix(end_date)\n self._request()\n \n def _convert_to_unix(self, date):\n return int(mktime(datetime.strptime(date, '%d-%m-%Y').timetuple()))\n\n def _load(self, data):\n [self.crumb] = re.findall('\"CrumbStore\":{\"crumb\":\"(.+?)\"}', str(\n BeautifulSoup(data.text, 'lxml')\n ))\n self.cookies = data.cookies\n self.csv_url = 'https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval={3}&events=history&crumb={4}'.format(\n self.stock, self.begin_date, self.end_date, self.interval, self.crumb\n )\n\n def _request(self):\n req = requests.get(self.url)\n self._load(\n req\n )\n\n def get(self):\n _csv = requests.get(self.csv_url, cookies=self.cookies, verify=False)\n decoded_content = _csv.content.decode('utf-8')\n cr = csv.reader(decoded_content.splitlines(), delimiter=',')\n for row in list(cr):\n print(row)\n\ndef main():\n amzn = Stock('AMZN', '1d', \"03-03-2019\", \"03-04-2019\")\n omg_my_shares_are_up = amzn.get()\n print(omg_my_shares_are_up)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Flynn's code.py","file_name":"Flynn's code.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"448702984","text":"#!/usr/bin/env python\n\nimport bhtsne\n\nfrom datetime import datetime\nimport os\nimport numpy as np\n\n# MNIST\nimport mnist\n\nimport notification\nimport logging\nfrom streamlogger import StreamToLogger\nfrom data_initializer import get_initial_embedding, get_supported_non_random_methods\nimport sys\nfrom argparse import ArgumentParser\nimport shutil\n\n# directory structure\nCWD = os.path.dirname(os.path.realpath(__file__))\nRESULT_DIR = os.path.join(CWD, \"results\")\nRESULT_ZIP = os.path.join(CWD, \"results.zip\")\n\n# DATA SUBDIRECTORIES\nMNIST_TEST = \"mnist2500\"\nMNIST = \"mnist\"\nFASHION_MNIST = \"fashion_mnist\"\nFASHION_MNIST10 = \"fashion_mnist10\"\nFASHION_MNIST100 = \"fashion_mnist100\"\nFASHION_MNIST200 = \"fashion_mnist200\"\nFASHION_MNIST500 = \"fashion_mnist500\"\nFASHION_MNIST1000 = \"fashion_mnist1000\"\nFASHION_MNIST2500 = \"fashion_mnist2500\"\nFASHION_MNIST5000 = \"fashion_mnist5000\"\nFASHION_MNIST7000 = \"fashion_mnist7000\"\nFASHION_MNIST10000 = \"fashion_mnist10000\"\nFASHION_MNIST20000 = \"fashion_mnist20000\"\n\n\nDATA_SETS = [MNIST_TEST, MNIST, FASHION_MNIST, FASHION_MNIST10, FASHION_MNIST100, FASHION_MNIST200, FASHION_MNIST500, FASHION_MNIST1000, FASHION_MNIST2500,\n FASHION_MNIST5000, FASHION_MNIST7000, FASHION_MNIST10000, FASHION_MNIST20000]\n\n# Runtime testing\nRUNTIME_DIR = \"run_time\"\n\n# Parameter tuning\nPARAMTUNING_DIR = \"parametertuning\"\n\nTMAX_TUNING_DIR = \"iterations\"\nPERPLEXITY_TUNING_DIR = \"perplexity\"\nEXAGGERATION_TUNING_DIR = \"exaggeration\"\nTHETA_TUNING_DIR = \"theta\"\nLEARNING_RATE_TUNING_DIR = \"learningrate\"\nMOMENTUM_TUNING_DIR = \"momentum\"\nFINAL_MOMENTUM_TUNING_DIR = \"finalmomentum\"\nSTOP_LYING_TUNING_DIR = \"stoplying\"\nRESTART_LYING_TUNING_DIR = \"restartlying\"\nMOMENTUM_SWITCH_TUNING_DIR = \"momentumswitch\"\n\n# Initial solutions\nINIT = os.path.join(CWD, \"initial_solutions\")\n\n# Building block experiments\nBUILDINGBLOCK_DIR = \"buildingblocks\"\n\nINITIAL_EMBEDDING_DIR = os.path.join(BUILDINGBLOCK_DIR, \"initial_embeddings\")\n\n# Freeze index dir\nFREEZE_DIR = \"freeze_index\"\nFREEZE_INITIAL_DIR = os.path.join(FREEZE_DIR, \"trained_embeddings\")\n\nLOGGING_DIR = os.path.join(CWD, \"logging\")\nDAY = datetime.now().strftime(\"%d-%m-%Y\")\nLOGGING_FILE_NAME = \"bhtsne-\" + DAY + \".log\"\nLOGGING_FILE_ABSPATH = os.path.join(LOGGING_DIR, LOGGING_FILE_NAME)\n\n# PARAMETER TESTING LIST\n# TMAX is also default case, removed default variable setting from parameter list\n\n# main\nT_MAX = [1000]\nPERPLEXITY = [2, 5, 10, 20, 30, 40, 100]\nEXAGGERATION = [1, 4, 8, 20]\nTHETA = [0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1]\nLEARNING_RATE = [50, 100, 500, 1000]\n\n# secondary\nMOMENTUM = [0.0, 0.2, 0.4, 0.6, 0.8]\nFINAL_MOMENTUM = [0.0, 0.2, 0.4, 0.5, 0.6]\nSTOP_LYING_ITER = [500, 750, 1000]\nRESTART_LYING_ITER = [750]\nMOMENTUM_SWITCH_ITER = [500, 750, 1000]\n\n\n#############################################\n# PARAMETER TUNING - DICTIONARY #\n#############################################\n\n# Python dict to retrieve all params by key\n# parameter-name: [value-list, directory to store results]\nPARAM_DICT = {\n \"max_iter\": [T_MAX, TMAX_TUNING_DIR],\n \"perplexity\": [PERPLEXITY, PERPLEXITY_TUNING_DIR],\n \"theta\": [THETA, THETA_TUNING_DIR],\n \"lying_factor\": [EXAGGERATION, EXAGGERATION_TUNING_DIR],\n \"learning_rate\": [LEARNING_RATE, LEARNING_RATE_TUNING_DIR],\n \"momentum\": [MOMENTUM, MOMENTUM_TUNING_DIR],\n \"final_momentum\": [FINAL_MOMENTUM, FINAL_MOMENTUM_TUNING_DIR],\n \"stop_lying_iter\": [STOP_LYING_ITER, STOP_LYING_TUNING_DIR],\n \"restart_lying_iter\": [RESTART_LYING_ITER, RESTART_LYING_TUNING_DIR],\n \"momentum_switch_iter\": [MOMENTUM_SWITCH_ITER, MOMENTUM_SWITCH_TUNING_DIR]\n}\n\n\ndef init_directories():\n try:\n os.makedirs(os.path.join(RESULT_DIR, \"tSNE\", PARAMTUNING_DIR))\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(os.path.join(RESULT_DIR, \"BHtSNE\", PARAMTUNING_DIR))\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(os.path.join(RESULT_DIR, \"tSNE\", BUILDINGBLOCK_DIR))\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(os.path.join(RESULT_DIR, \"BHtSNE\", BUILDINGBLOCK_DIR))\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(os.path.join(RESULT_DIR, \"tSNE\", FREEZE_INITIAL_DIR))\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(os.path.join(RESULT_DIR, \"BHtSNE\", FREEZE_INITIAL_DIR))\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(LOGGING_DIR)\n except FileExistsError:\n # directory already exists\n pass\n\n try:\n os.makedirs(INIT)\n except FileExistsError:\n # directory already exists\n pass\n\n\ndef init_logger(logfile=LOGGING_FILE_ABSPATH):\n # logging stuff\n\n logging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',\n filename=logfile,\n filemode='a'\n )\n\n stdout_logger = logging.getLogger('STDOUT')\n out_l = StreamToLogger(stdout_logger, logging.INFO, logfile)\n sys.stdout = out_l\n\n stderr_logger = logging.getLogger('STDERR')\n err_l = StreamToLogger(stderr_logger, logging.ERROR, logfile)\n sys.stderr = err_l\n\n\ndef load_data(data_identifier):\n if data_identifier == MNIST:\n return mnist.load_mnist_data(all_data=True)\n elif data_identifier == MNIST_TEST:\n return mnist.load_mnist_data(all_data=False)\n elif data_identifier == FASHION_MNIST:\n return mnist.load_fashion_mnist_data(all_data=True)\n elif data_identifier == FASHION_MNIST10:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=10)\n elif data_identifier == FASHION_MNIST100:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=100)\n elif data_identifier == FASHION_MNIST200:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=200)\n elif data_identifier == FASHION_MNIST500:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=500)\n elif data_identifier == FASHION_MNIST1000:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=1000)\n elif data_identifier == FASHION_MNIST2500:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=2500)\n elif data_identifier == FASHION_MNIST5000:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=5000)\n elif data_identifier == FASHION_MNIST7000:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=7000)\n elif data_identifier == FASHION_MNIST10000:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=10000)\n elif data_identifier == FASHION_MNIST20000:\n return mnist.load_fashion_mnist_data(all_data=False, len_sample=20000)\n else:\n print(\"unsupported data identifier: \" + data_identifier)\n print(\"Shutting down...\")\n quit()\n\n\ndef _argparse():\n argparse = ArgumentParser('Script to run parametertuning and building block analysis of bh_tsne')\n argparse.add_argument('-e', '--exact', action='store_true', default=False)\n argparse.add_argument('-d', '--data_set', choices=DATA_SETS, default=MNIST_TEST,\n help=\"use one of the following available data identifiers: {}\".format(str(DATA_SETS)))\n available_parameters = [\"all\"]\n available_parameters.extend(PARAM_DICT.keys())\n argparse.add_argument('-p', '--parameter_list', choices=available_parameters, nargs='+', default=[\"max_iter\"],\n help=\"use all or selected parameter identifiers from the following list: {}\"\n .format(str(PARAM_DICT.keys())))\n argparse.add_argument('-i', '--initial_embedding', choices=[\"gaussian\", \"pca\", \"lle\"], default=\"gaussian\")\n argparse.add_argument('-pt', '--parametertuning', action='store_true', default=False)\n argparse.add_argument('-y', '--y_init', action='store_true', default=False)\n argparse.add_argument('-f', '--freeze_index', type=int, default=0)\n argparse.add_argument('-r', '--run_time', action='store_true', default=False)\n argparse.add_argument('-insim', '--input_similarities', default=\"gaussian\",\n choices=bhtsne.BUILDING_BLOCK_DICT[\"input_similarities\"].keys())\n argparse.add_argument('-outsim', '--output_similarities', default=\"student\",\n choices=bhtsne.BUILDING_BLOCK_DICT[\"output_similarities\"].keys())\n argparse.add_argument('-cf', '--cost_function', default=\"KL\",\n choices=bhtsne.BUILDING_BLOCK_DICT[\"cost_function\"].keys())\n argparse.add_argument('-opt', '--optimization', default=\"gradient_descent\",\n choices=bhtsne.BUILDING_BLOCK_DICT[\"optimization\"].keys())\n\n return argparse\n\n\ndef tsne_workflow(parameter_name, value_list, data, result_base_dir, data_result_subdirectory,\n initial_embedding_method=None, **kwargs):\n \"\"\"\n\n :param parameter_name:\n :param value_list:\n :param data:\n :param result_base_dir:\n :param data_result_subdirectory:\n :param initial_embedding_method:\n :return:\n\n \"\"\"\n\n for value in value_list:\n print(\"###########################################\")\n print(\"## Start t-SNE ##\")\n print(\"###########################################\")\n\n print(\"Using Dataset: {}\".format(data_result_subdirectory))\n\n print(\"Tuning parameter: \" + parameter_name + \", value: \" + str(value))\n # 5 times to validate for random methods, once for specified inputs\n\n max_round = 6 if initial_embedding_method in ['gaussian', 'random'] else 2\n\n for i in range(1, max_round):\n print(\"###\", \"### Round:\" + str(i), \"###\")\n # create directory if non-existent\n result_dir = os.path.join(result_base_dir, str(value), data_result_subdirectory, str(i))\n try:\n os.makedirs(result_dir)\n except FileExistsError:\n # directory already exists\n pass\n\n # load the initial embedding if specified\n _initial_embedding = None\n if initial_embedding_method is not None:\n _initial_embedding = get_initial_embedding(data_name=data_result_subdirectory,\n method_name=initial_embedding_method, i=i)\n filename = \"initial_solution_\" + data_result_subdirectory + \"_\" + initial_embedding_method \\\n + \"{}\" + \".pickle\"\n filename = filename.format(\"_\" + str(i) if initial_embedding_method in ['random', 'gaussian'] else \"\")\n\n print(\"Using initial embedding file: {}\".format(filename))\n\n # run t-SNE\n # perform PCA to 50 dims beforehand\n # use initial embedding\n bh_tsne_dict = bhtsne.run_bh_tsne(data, verbose=True, initial_solution=_initial_embedding,\n **{parameter_name: value}, **kwargs)\n\n # save results\n # timestamp\n timestamp = datetime.now().strftime(\"%d-%m-%Y_%H-%M-%S\")\n bhtsne.write_bh_tsne_result(bh_tsne_dict, result_dir, \"-\", timestamp)\n\n\nif __name__ == \"__main__\":\n # put everything into try except clause and send error notification on failure\n from sys import argv\n from distutils.util import strtobool\n import traceback\n try:\n parser = _argparse()\n\n if len(argv) <= 1:\n print(parser.print_help())\n while True:\n try:\n debug = strtobool(input(\"Do you want to run in debug mode? [y/n] \"))\n if debug:\n print(\"Running in debug mode: tsne_main.py mnist2500 max_iter\")\n break\n else:\n print(\"Shutting down...\")\n quit()\n except ValueError:\n print(\"Please answer 'yes' ('y') or 'no' ('n').\")\n continue\n\n argp = parser.parse_args(argv[1:])\n\n print(\"Using exact tSNE\" if argp.exact else \"Using BH-tSNE\")\n exact = argp.exact\n algorithm = \"tSNE\" if exact else \"BHtSNE\"\n algorithm_dir = os.path.join(RESULT_DIR, algorithm)\n print(\"Using data set: {}\".format(argp.data_set))\n data_name = argp.data_set\n print(\"Using parameters: {}\".format(argp.parameter_list))\n param_list = PARAM_DICT.keys() if \"all\" in argp.parameter_list else argp.parameter_list\n # Remove theta if algorithm is exact!\n if exact:\n param_list = [x for x in param_list if x != 'theta']\n if not param_list:\n # if param_list is now empty, quit\n print(\"Exact tsne cannot be run with theta parameter tuning!\")\n quit()\n if not argp.parametertuning and argp.y_init:\n print(\"Running y_init buildingblock test with initial embeddings: {}\"\n .format(get_supported_non_random_methods()))\n else:\n print(\"Using initial embeddings: {}\".format(argp.initial_embedding))\n initial_embedding = argp.initial_embedding\n operation_dir = os.path.join(algorithm_dir, PARAMTUNING_DIR if argp.parametertuning else BUILDINGBLOCK_DIR)\n print(\"Using base directory: {}\".format(str(operation_dir)))\n\n # initialize directories\n init_directories()\n\n # for very paranoid beings...\n os.chdir(CWD)\n\n # initialize logging to file\n init_logger()\n\n ###########################################################\n # LOAD DATA #\n ###########################################################\n\n data, labels = load_data(data_name)\n\n ###########################################################\n # DEBUG #\n ###########################################################\n\n\n #bhtsne.debug_bh_tsne_pre(data, data_name)\n #quit()\n # bhtsne.debug_data_file(\"windows\", 2500, 784)\n #embedding_dict = bhtsne.debug_bh_tsne_post()\n #bhtsne.plot_bh_tsne_post(embedding_dict, labels)\n #quit()\n # sanity check of error\n # np.sum(embedding_array[:, 2])\n # quit()\n\n ###########################################################\n # RUNTIME Evaluation #\n ###########################################################\n\n if argp.run_time:\n if exact:\n for param in param_list:\n for num_samples in [200, 500, 1000, 2500, 5000, 7500, 10000, 20000, 30000]:\n\n data, _ = mnist.load_fashion_mnist_data(False, len_sample=num_samples)\n\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=\"fashion_mnist\" + str(num_samples),\n result_base_dir=os.path.join(algorithm_dir, RUNTIME_DIR),\n theta=0.0)\n else:\n for param in param_list:\n for num_samples in [200, 500, 1000, 2500, 5000, 7500, 10000, 20000, 30000, 40000, 50000, 60000, 70000]:\n data, _ = mnist.load_fashion_mnist_data(False, len_sample=num_samples)\n\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=\"fashion_mnist\" + str(num_samples),\n result_base_dir=os.path.join(algorithm_dir, RUNTIME_DIR))\n\n ###########################################################\n # RUN PARAMETER TUNING #\n ###########################################################\n\n # For each Data set and parameter, perform tsne 5 times to have some reliable data\n elif argp.parametertuning:\n for param in param_list:\n if exact:\n \"\"\"\n pass an additional theta=0.0 if running exact tSNE\n \"\"\"\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=data_name,\n result_base_dir=os.path.join(operation_dir, PARAM_DICT[param][1]),\n initial_embedding_method=initial_embedding, theta=0.0)\n else:\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=data_name,\n result_base_dir=os.path.join(operation_dir, PARAM_DICT[param][1]),\n initial_embedding_method=initial_embedding)\n\n ###########################################################\n # INITIAL EMBEDDINGS #\n ###########################################################\n elif argp.y_init:\n for param in param_list:\n for method in get_supported_non_random_methods():\n if exact:\n \"\"\"\n pass an additional theta=0.0 if running exact tSNE\n \"\"\"\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=data_name,\n result_base_dir=os.path.join(algorithm_dir, INITIAL_EMBEDDING_DIR,\n method, PARAM_DICT[param][1]),\n initial_embedding_method=method, theta=0.0)\n else:\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=data_name,\n result_base_dir=os.path.join(algorithm_dir, INITIAL_EMBEDDING_DIR,\n method, PARAM_DICT[param][1]),\n initial_embedding_method=method,)\n\n elif argp.freeze_index != 0:\n\n #load train and test data\n # clear previously loaded...yeah it's ugly\n data = None\n labels = None\n\n if data_name == FASHION_MNIST2500:\n (x_train, x_test), (y_train, y_test) = mnist.load_fashion_mnist_data(False, len_sample=2500,\n train_test_split=argp.freeze_index)\n #initial_embedding = \"fashion_mnist2000\"\n elif data_name == FASHION_MNIST7000:\n (x_train, x_test), (y_train, y_test) = mnist.load_fashion_mnist_data(False, len_sample=7000,\n train_test_split=argp.freeze_index)\n #initial_embedding = \"fashion_mnist2000\"\n else:\n (x_train, x_test), (y_train, y_test) = mnist.load_fashion_mnist_data(False, len_sample=70000,\n train_test_split=argp.freeze_index)\n\n # now, embed the train data:\n # load default initial gaussian embedding\n #_initial_embedding = get_initial_embedding(data_name=x_train, method_name=\"gaussian\", i=1)\n if exact:\n \"\"\"\n pass an additional theta=0.0 if running exact tSNE\n \"\"\"\n # use initial embedding\n bh_tsne_dict = bhtsne.run_bh_tsne(x_train, verbose=True, initial_solution=None, theta=0.0)\n\n # save results\n # timestamp\n timestamp = datetime.now().strftime(\"%d-%m-%Y_%H-%M-%S\")\n bhtsne.write_bh_tsne_result(bh_tsne_dict, os.path.join(RESULT_DIR, algorithm_dir, FREEZE_INITIAL_DIR),\n \"-\", timestamp)\n else:\n # use initial embedding\n bh_tsne_dict = bhtsne.run_bh_tsne(x_train, verbose=True, initial_solution=None)\n\n # save results\n # timestamp\n timestamp = datetime.now().strftime(\"%d-%m-%Y_%H-%M-%S\")\n bhtsne.write_bh_tsne_result(bh_tsne_dict, os.path.join(RESULT_DIR, algorithm_dir, FREEZE_INITIAL_DIR),\n \"-\", timestamp)\n\n\n # now, we embed the test data using the freeze index\n\n #_initial_embedding = bhtsne.read_bh_tsne_result(os.path.join(RESULT_DIR, algorithm_dir, FREEZE_INITIAL_DIR,\n # \"bh_tsne_result-\" + \"-\".join(timestamp) + '.pickle'))\n\n _initial_embedding = bh_tsne_dict[(1000,)][:, :2]\n\n combined_data = np.vstack((x_train, x_test))\n\n if exact:\n \"\"\"\n pass an additional theta=0.0 if running exact tSNE\n \"\"\"\n # use initial embedding\n bh_tsne_dict = bhtsne.run_bh_tsne(combined_data, verbose=True, initial_solution=_initial_embedding,\n freeze_index=argp.freeze_index, theta=0.0)\n\n # save results\n # timestamp\n timestamp = datetime.now().strftime(\"%d-%m-%Y_%H-%M-%S\")\n bhtsne.write_bh_tsne_result(bh_tsne_dict, os.path.join(RESULT_DIR, algorithm_dir, FREEZE_DIR, data_name,\n str(argp.freeze_index)), \"-\", timestamp)\n else:\n # use initial embedding\n bh_tsne_dict = bhtsne.run_bh_tsne(combined_data, verbose=True, initial_solution=_initial_embedding,\n freeze_index=argp.freeze_index)\n\n # save results\n # timestamp\n timestamp = datetime.now().strftime(\"%d-%m-%Y_%H-%M-%S\")\n bhtsne.write_bh_tsne_result(bh_tsne_dict, os.path.join(RESULT_DIR, algorithm_dir, FREEZE_DIR, data_name,\n str(argp.freeze_index)), \"-\", timestamp)\n\n\n\n\n ###########################################################\n # RUN BUILDINGBLOCK ANALYSIS #\n ###########################################################\n else:\n building_blocks = [(\"input_similarities\", argp.input_similarities)]\n building_blocks.append((\"output_similarities\", argp.output_similarities))\n building_blocks.append((\"cost_function\", argp.cost_function))\n building_blocks.append((\"optimization\", argp.optimization))\n\n modified_buildingblocks = list(filter(lambda x: bhtsne.BUILDING_BLOCK_DICT[x[0]][x[1]] != 0,\n building_blocks))\n\n if not modified_buildingblocks:\n modified_buildingblocks = [(\"default\", \"default\")]\n\n directory = os.path.join(\"-\".join([x[0] for x in modified_buildingblocks]),\n \"-\".join([x[1] for x in modified_buildingblocks]))\n kwargs = {x[0]: bhtsne.BUILDING_BLOCK_DICT[x[0]][x[1]] for x in building_blocks}\n if exact:\n kwargs['theta'] = 0.0\n if argp.cost_function == \"RKL\" or argp.cost_function == \"JS\":\n param_list = [x for x in param_list if x != 'lying_factor']\n if not param_list:\n # if param_list is now empty, quit\n print(\"Exact tsne with RKL cannot be run with theta or exaggeration parameter tuning!\")\n quit()\n kwargs['lying_factor'] = 1\n for param in param_list:\n tsne_workflow(parameter_name=param, value_list=PARAM_DICT[param][0], data=data,\n data_result_subdirectory=data_name,\n result_base_dir=os.path.join(operation_dir, directory, PARAM_DICT[param][1]),\n initial_embedding_method=initial_embedding if argp.optimization != \"genetic\" else None,\n **kwargs)\n\n # skip zip attachment as it simply grows too big\n # create zip archive of results\n # shutil.make_archive(RESULT_DIR, 'zip', RESULT_DIR)\n\n # send final notification\n # notification.send_mail(LOGGING_FILE_NAME, LOGGING_FILE_ABSPATH, \"results.zip\", RESULT_ZIP, argv)\n notification.send_mail(LOGGING_FILE_NAME, LOGGING_FILE_ABSPATH, argv)\n except Exception:\n traceback.print_exc()\n notification.send_error(LOGGING_FILE_NAME, LOGGING_FILE_ABSPATH, argv)\n\n\n","sub_path":"tsne_main.py","file_name":"tsne_main.py","file_ext":"py","file_size_in_byte":25307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"96734725","text":"import numpy as np\r\n# from matplotlib import pyplot as plt\r\n# from mpl_toolkits.mplot3d import Axes3D\r\nfrom scipy.linalg import norm\r\n\r\ndef draw_cylinders(x1,y1,z1,x2,y2,z2,R,valid_x_range_lowerbound,valid_x_range_upperbound,matrix,images):\r\n\t# fig = plt.figure()\r\n\t# ax = fig.add_subplot(111, projection='3d')\r\n\t# origin = np.array([0, 0, 0])\r\n#axis and radius\r\n\tp0 = np.array([x1, y1, z1])\r\n\tp1 = np.array([x2, y2, z2])\r\n#vector in direction of axis\r\n\tv = p1 - p0\r\n#find magnitude of vector\r\n\tmag = norm(v)\r\n\tif mag<=10:\r\n\t\tnum_seg_mag=10\r\n\telif( mag>10 and mag<=20):\r\n\t\tnum_seg_mag=20\r\n\telif( mag>20 and mag<=50):\r\n\t\tnum_seg_mag=50\r\n\telif( mag>50 and mag<=100):\r\n\t\tnum_seg_mag=100\r\n\telif( mag>100 and mag<=200):\r\n\t\tnum_seg_mag=200\r\n\telif( mag>200 and mag<=300):\r\n\t\tnum_seg_mag=300\r\n\telif( mag>300 and mag<=400):\r\n\t\tnum_seg_mag=400\r\n\telif( mag>400 and mag<=500):\r\n\t\tnum_seg_mag=500\r\n\telif( mag>500 and mag<=600):\r\n\t\tnum_seg_mag=600\r\n\telif( mag>600 and mag<=700):\r\n\t\tnum_seg_mag=700\r\n\telif( mag>700 and mag<=800):\r\n\t\tnum_seg_mag=800\r\n\telif( mag>800 and mag<=900):\r\n\t\tnum_seg_mag=900\r\n\telse:\r\n\t\tnum_seg_mag=1000\r\n#unit vector in direction of axis\r\n\tv = v / mag\r\n#make some vector not in the same direction as v\r\n\tnot_v = np.array([1, 0, 0])\r\n\tif (v == not_v).all():\r\n\t\tnot_v = np.array([0, 1, 0])\r\n#make vector perpendicular to v\r\n\tn1 = np.cross(v, not_v)\r\n#normalize n1\r\n\tn1 /= norm(n1)\r\n#make unit vector perpendicular to v and n1\r\n\tn2 = np.cross(v, n1)\r\n#surface ranges over t from 0 to length of axis and 0 to 2*pi\r\n\tt = np.linspace(0, mag,num_seg_mag)\r\n\ttheta = np.linspace(0, 2 * np.pi, 30)\r\n\tr=np.linspace(1,R,R)\r\n#use meshgrid to make 2d arrays\r\n\t#t, theta = np.meshgrid(t, theta)\r\n#generate coordinates for surface\r\n\tfor R in r:\r\n\t\tfor k in t:\r\n\t\t\tfor j in theta:\r\n\t\t\t\tX, Y, Z = [p0[i] + v[i] * k + R * np.sin(j) * n1[i] + R * np.cos(j) * n2[i] for i in [0, 1, 2]]\r\n\t\t#ax.scatter(X, Y, Z)\r\n\t\t\t\tx=np.floor(X).astype(np.int16)\r\n\t\t\t\ty=np.floor(Y).astype(np.int16)\r\n\t\t\t\tz=np.floor(Z).astype(np.int16)\r\n\t\t\t\tif (valid_x_range_lowerbound<=x<=valid_x_range_upperbound):\r\n\t\t\t\t\tmatrix[x][y][z]=255\t\r\n\t\t\t\t\timages[0][x][z]=255\r\n\t\t\t\t\timages[1][y][z]=255\r\n\t\t\t\t\timages[2][y][x]=255\r\n\t\t\r\n\treturn matrix,images","sub_path":"draw_cylinders.py","file_name":"draw_cylinders.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"569295507","text":"import csv\nimport re\n\nstocks = []\nnewstocks = []\n\n\n\n\ndef csv_writer(newstocks):\n\tprint('csv_writer\\n')\n\t#print('stock {}\\n'.format(stocks))\n\twith open('stocks_new.csv', 'wb') as csvfile:\n\t\tstockwriter = csv.writer(csvfile, delimiter='\\n',\n\t quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\t\t#for stock in newstocks:\n\t\tstockwriter.writerow(newstocks)\n\t\tprint('successful')\n\n\nwith open('stocks.csv', 'rb') as csvfile:\n\tstockreader = csv.reader(csvfile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\tfor row in stockreader:\n\t\tstocks.append(row)\n\t\t\n\t#for stock in stocks:\n\t#\tfor x in stock:\n\t#\t\tre.sub(r'\\s', '', x)\n\t#print stock\t\t \n\n[[\"\".join(x.split()) for x in stock] for stock in stocks]\nfor stock in stocks:\n\tfor x in stock:\n\t\t\"\".join(x.split())\n\t\tholder = \"\".join(x.split())\n\t\tnewstocks.append(holder)\n\nprint(newstocks)\ncsv_writer(newstocks)\n\n#print([(re.sub(r'\\s', '', stock)) for stock in stocks])\n\n#print(stocks)\n#[stocks.append(re.sub(r'\\s', '', stock)) for stock in stocks]\n#print(stocks)\n\n#print(stocks)\n\n","sub_path":"convert_csv.py","file_name":"convert_csv.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"449672342","text":"import os.path\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nDEBUG = True\n\nSQLALCHEMY_DATABASE_URI = 'sqlite:///'+os.path.join(basedir,'tasks.db')\n\nSQLALCHEMY_TRACK_MODIFICATIONS = True\n\nSECRET_KEY = 'Eu-Não-Sei-pilotar-ua-a-modtod-moto-do-fernando_60945'\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"503245004","text":"from database import Drama\nfrom request import Parser\n\n\nclass DramaDetailParser(Parser):\n def __init__(self, path_):\n self._path = path_\n self._poster = None\n self._title = None\n self._plot = []\n self._country = None\n self._genre = []\n self._year = None\n self._is_span = False\n self._is_poster = False\n self._is_title = False\n self._is_plot = False\n self._is_country = False\n self._is_genre = False\n self._is_genre_a = False\n self._is_year = False\n\n def close(self):\n return Drama.create(path=self._path, poster=self._poster, title=self._title, plot=' '.join(self._plot), country=self._country, genre=self._genre, year=self._year)\n\n def data(self, data):\n if self._is_span:\n self._is_plot = True if 'Description' in data else False\n self._is_country = True if 'Country' in data else False\n self._is_genre = True if 'Genre' in data else False\n self._is_year = True if 'Released' in data else False\n elif self._is_title:\n self._title = data.strip()\n self._is_title = False\n elif self._is_plot:\n data = data.strip()\n\n if data:\n self._plot.append(data.replace('\\r\\n\\r\\n', '\\r\\n'))\n elif self._is_country:\n self._country = data\n elif self._is_genre and self._is_genre_a:\n self._genre.append(data)\n self._is_genre_a = False\n elif self._is_year and data.isdigit():\n self._year = int(data)\n\n def end(self, tag):\n if tag == 'p':\n self._is_country = False\n self._is_genre = False\n self._is_year = False\n\n self._is_span = False\n\n def start(self, tag, attrs):\n if tag == 'span':\n self._is_span = True\n elif tag == 'h1':\n self._is_title = True\n elif self._is_poster:\n self._poster = attrs['src']\n self._is_poster = False\n elif tag == 'div' and 'class' in attrs and 'img' in attrs['class']:\n self._is_poster = True\n elif self._is_genre and tag == 'a':\n self._is_genre_a = True\n","sub_path":"resources/lib/request/dramadetail.py","file_name":"dramadetail.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"573768126","text":"import numpy as np\nimport logging\nimport os\n\nfrom keras.preprocessing import text, sequence\nfrom keras import layers, models, optimizers\nfrom keras.models import load_model\nfrom sklearn import metrics\n\nfrom gensim.models.fasttext import FastText\n\nclass LSTM:\n train_seq_X = None\n test_seq_X = None\n train_Y = None\n test_Y = None\n hidden_state = 300\n batch_size = 64\n model_path = 'lstm.h5'\n\n classifier = None\n\n def __init__(self, train_X, train_Y, test_X, test_Y, model):\n self.model_path = model\n # embedding_index = {}\n # for i, line in enumerate(open('glove.6B/glove.6B.100d.txt')):\n # values = line.split()\n # embedding_index[values[0]] = np.asarray(values[1:], dtype='float32')\n embedding_index = FastText.load_fasttext_format('cc.id.300.bin')\n\n # Create tokenizer object\n tokenizer = text.Tokenizer()\n tokenizer.fit_on_texts(train_X)\n word_index = tokenizer.word_index\n\n # Convert text to padded sequence of tokens and load previous model if available, disable train method\n self.test_seq_X = sequence.pad_sequences(tokenizer.texts_to_sequences(test_X), maxlen=70)\n if os.path.isfile(self.model_path):\n self.classifier = load_model(self.model_path)\n return\n\n # Save if no previous model loaded\n self.train_seq_X = sequence.pad_sequences(tokenizer.texts_to_sequences(train_X), maxlen=70)\n self.train_Y = train_Y\n self.test_Y = test_Y\n\n if os.path.isfile(self.model_path):\n self.classifier = load_model(self.model_path)\n return\n\n # Create word embeddings mapping\n embedding_matrix = np.zeros((len(word_index) + 1), 300)\n for word, i in word_index.items():\n embedding_vector = embedding_index.wv.most_similar(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\n # Creating layer\n # Add input layer\n input_layer = layers.Input((70, ))\n\n # Add the word embedding layer\n embedding_layer = layers.Embedding(len(word_index) + 1, 300, weights=[embedding_matrix], trainable=False)(input_layer)\n embedding_layer = layers.SpatialDropout1D(0.3)(embedding_layer)\n\n # Add LSTM layer\n lstm_layer = layers.LSTM(self.hidden_state)(embedding_layer)\n\n # Output layers\n output_layer1 = layers.Dense(50, activation=\"relu\")(lstm_layer)\n output_layer1 = layers.Dropout(0.25)(output_layer1)\n output_layer2 = layers.Dense(1, activation=\"sigmoid\")(output_layer1)\n\n # Compile model\n model = models.Model(inputs=input_layer, outputs=output_layer2)\n model.compile(optimizer=optimizers.Adam(), loss='binary_crossentropy')\n\n self.classifier = model\n \n logging.info(\"LSTM model created\")\n\n # def preprocessing(self, train_X, test_X):\n def train(self):\n if self.train_seq_X is None:\n return\n\n self.classifier.fit(self.train_seq_X, self.train_Y, batch_size=self.batch_size)\n\n predictions = self.classifier.predict(self.test_seq_X)\n\n predictions = predictions.argmax(axis=-1)\n\n self.classifier.save(self.model_path)\n\n return metrics.accuracy_score(predictions, self.test_Y)\n\n def predict(self):\n if not os.path.isfile(self.model_path) or self.train_seq_X is None:\n self.train()\n \n predictions = self.classifier.predict(self.test_Y)\n\n return predictions.argmax(axis=-1), predictions\n ","sub_path":"classifier/deep_learning/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":3586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"198881282","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(\n regex=r\"^api/$\",\n view=views.PaymentCreateReadView.as_view(),\n name=\"payment_rest_api\"\n ),\n url(\n regex=r\"^api/(?P[0-9]+)/$\",\n view=views.PaymentReadUpdateDeleteView.as_view(),\n name=\"payment_rest_api\"\n ),\n url(\n regex=r\"^$\",\n view=views.calendar,\n name=\"calendar\"\n ),\n]\n","sub_path":"payments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"428610475","text":"import time\nimport copy\n\nfrom core import helpers, logging\n\nclass _cache():\n objects = dict()\n\n def newCache(self,cacheName,maxSize=10485760,cacheExpiry=60,sessionData=None):\n userID = None\n if sessionData:\n if \"_id\" in sessionData:\n userID = sessionData[\"_id\"]\n cacheName = \"{0},-,{1}\".format(userID,cacheName)\n if cacheName not in self.objects:\n self.objects[cacheName] = { \"objects\" : {}, \"maxSize\" : maxSize, \"cacheExpiry\" : cacheExpiry, \"userID\" : userID }\n logging.debug(\"New cache store created, name={0}, maxSize={1}, cacheExpry={2}, userID={3}\".format(cacheName,maxSize,cacheExpiry,userID),20)\n\n def clearCache(self,cacheName,sessionData=None):\n authedCacheName = self.checkSessionData(cacheName,sessionData)\n if authedCacheName == None:\n return\n if cacheName == \"ALL\":\n for cacheName, cacheValue in self.objects.items():\n self.objects[cacheName][\"objects\"].clear()\n elif authedCacheName in self.objects:\n self.objects[authedCacheName][\"objects\"].clear()\n logging.debug(\"Cache store cleared, name={0}\".format(authedCacheName),20)\n \n # BUG this function does not check for size so it would be possibel to go over the defined max memory size -- Add this at a later date\n def sync(self,objects):\n for cacheKey, cacheValue in objects.items():\n if cacheKey not in self.objects:\n self.objects[cacheKey] = cacheValue\n else:\n for objectKey, objectValue in objects[cacheKey].items():\n if objectKey not in self.objects:\n objects[cacheKey][objectKey] = objectValue\n\n def export(self):\n c = copy.deepcopy(self.objects)\n return c\n\n\n def get(self,cacheName,uid,setFunction,*args,sessionData=None,extendCacheTime=False,forceUpdate=False):\n authedCacheName = self.checkSessionData(cacheName,sessionData)\n if authedCacheName == None:\n return\n now = time.time()\n if authedCacheName not in self.objects:\n self.newCache(authedCacheName)\n if ((uid in self.objects[authedCacheName][\"objects\"]) and (not forceUpdate)):\n if ((self.objects[authedCacheName][\"objects\"][uid][\"cacheExpiry\"] > now) or (extendCacheTime)):\n self.objects[authedCacheName][\"objects\"][uid][\"accessCount\"] += 1\n if extendCacheTime:\n self.objects[authedCacheName][\"objects\"][uid][\"cacheFor\"] = ( now + self.objects[authedCacheName][\"cacheExpiry\"] )\n return self.objects[authedCacheName][\"objects\"][uid][\"objectValue\"]\n cache, objectValue = self.getObjectValue(cacheName,uid,setFunction,*args,sessionData=sessionData)\n if cache and objectValue:\n if uid in self.objects[authedCacheName][\"objects\"]:\n self.objects[authedCacheName][\"objects\"][uid][\"objectValue\"] = objectValue\n self.objects[authedCacheName][\"objects\"][uid][\"cacheExpiry\"] = (now + self.objects[authedCacheName][\"cacheExpiry\"])\n self.objects[authedCacheName][\"objects\"][uid][\"accessCount\"] += 1\n else:\n self.objects[authedCacheName][\"objects\"][uid] = { \"objectValue\" : objectValue, \"accessCount\" : 0, \"cacheExpiry\" : (now + self.objects[authedCacheName][\"cacheExpiry\"]) }\n if objectValue:\n return objectValue\n else:\n return None\n\n def getObjectValue(self,cacheName,uid,setFunction,*args,sessionData=None):\n authedCacheName = self.checkSessionData(cacheName,sessionData)\n if cacheName == None:\n return\n if len(args) > 0:\n newObject = setFunction(uid,sessionData,*args)\n else:\n newObject = setFunction(uid,sessionData)\n newObjectSize = helpers.getObjectMemoryUsage(newObject)\n currentCacheSzie = helpers.getObjectMemoryUsage(self.objects[authedCacheName][\"objects\"])\n memoryNeeded = (currentCacheSzie + newObjectSize) - self.objects[authedCacheName][\"maxSize\"]\n if memoryNeeded > 0:\n if not self.reduceSize(cacheName,memoryNeeded,sessionData=sessionData):\n logging.debug(\"ERROR - Cache store full and unable to free enough space for new object, name={0}\".format(authedCacheName),5)\n return (False, newObject)\n return (True, newObject)\n\n def reduceSize(self,cacheName,amountToFree,sessionData=None):\n authedCacheName = self.checkSessionData(cacheName,sessionData)\n if authedCacheName == None:\n return\n logging.debug(\"Cache store attempting to reduce memory, name={0}, amount={1}\".format(authedCacheName,amountToFree),20)\n # No objects to clear\n if len(self.objects[authedCacheName][\"objects\"]) == 0:\n return False\n \n now = time.time()\n amountReduced = 0\n poplist = []\n accessCount = {}\n for cacheObjectKey, cacheObjectValue in self.objects[authedCacheName][\"objects\"].items():\n if cacheObjectValue[\"cacheExpiry\"] < now:\n amountReduced += helpers.getObjectMemoryUsage(cacheObjectValue)\n poplist.append(cacheObjectKey)\n else:\n if cacheObjectValue[\"accessCount\"] not in accessCount:\n accessCount[cacheObjectValue[\"accessCount\"]] = []\n accessCount[cacheObjectValue[\"accessCount\"]].append(cacheObjectKey)\n if amountReduced >= amountToFree:\n break\n if amountReduced < amountToFree:\n for count in accessCount.keys():\n for item in accessCount[count]:\n amountReduced += helpers.getObjectMemoryUsage(self.objects[authedCacheName][\"objects\"][item])\n poplist.append(item)\n if amountReduced >= amountToFree:\n break\n if amountReduced >= amountToFree:\n break\n\n for item in poplist:\n del self.objects[authedCacheName][\"objects\"][item]\n\n if amountReduced >= amountToFree:\n return True\n\n return False\n\n def checkSessionData(self,cacheName,sessionData):\n if sessionData:\n authedCacheName = \"{0},-,{1}\".format(sessionData[\"_id\"],cacheName)\n if sessionData[\"_id\"] == self.objects[authedCacheName][\"userID\"]:\n return authedCacheName\n else:\n logging.debug(\"ERROR - Cache store access denied due to mismatched ID, name={0}, userID={1}\".format(cacheName,sessionData[\"_id\"]),5)\n return None\n else:\n return cacheName\n return None\n\n def getSummary(self):\n result = \"\"\n totalSize = 0\n for cacheName, cacheValue in self.objects.items():\n cacheSzie = helpers.getObjectMemoryUsage(cacheValue)\n totalSize+=cacheSzie\n result+=\"name='{0}', size='{1}'\\r\\n\".format(cacheName,cacheSzie)\n result+=\"\\r\\n\\r\\nTotal Size='{0}'\".format(totalSize)\n return result\n\nglobalCache = _cache()","sub_path":"core/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":7203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"230065336","text":"# -*- coding: iso-8859-1 -*-\n# Copyright (C) 2005 France Telecom R&D\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n\"\"\"unit tests for Text and HTML parsers\"\"\"\n\n\n\nimport unittest\nfrom os.path import join, dirname\n\nfrom maay.texttool import MaayHTMLParser, TextParser, guessEncoding, \\\n universalOpen, untagText, normalizeText, removeControlChar, makeAbstract, \\\n LStringIO\n\nRAW_TEXT = u\"foo été bar baz top bim bam boum\"\n\nSIMPLE_HTML = u\"\"\"\nmaille Maay\nHello été world\nThis is a link\nand this is another link\n\n\n\"\"\"\n\nDATADIR = join(dirname(__file__), 'data')\n\n\nclass TextParserTC(unittest.TestCase):\n\n def setUp(self):\n self.parser = TextParser()\n\n def testTitleGuess(self): #XXX: complete this with PDF/PS files before commit time !!!\n \"\"\"Make sure the title is the filename when we treat a text file\n or no title could be found\n \"\"\"\n title, text, links, offset = self.parser.parseFile(join(DATADIR, 'latin1.txt'), 'latin1.txt', 'ISO-8859-1')\n self.assertEquals(title, 'latin1.txt')\n self.assertEquals(normalizeText(text), \"c'est l'ete\")\n self.assertEquals(links, [])\n # Now, PS file\n title, text, links, offset = self.parser.parseFile(join(DATADIR, 'utf8.ps'), 'utf8.ps', 'UTF-8')\n self.assertEquals(title, 'utf8.ps')\n self.assertEquals(links, [])\n # The PDF (yes, it's important to test this too)\n title, text, links, offset = self.parser.parseFile(join(DATADIR, 'utf8.pdf'), 'utf8.pdf', 'UTF-8')\n self.assertEquals(title, 'utf8.pdf')\n self.assertEquals(links, [])\n\n\nclass HTMLParserTC(unittest.TestCase):\n\n def setUp(self):\n self.parser = MaayHTMLParser()\n\n def testParseRaw(self):\n html = '%s' % RAW_TEXT\n title, text, links, offset = self.parser.parseString(html)\n # parseString() should return empty title when non available in the HTML\n self.assertEquals(title, '')\n self.assertEquals(normalizeText(text),\n RAW_TEXT.replace(u'é', 'e'))\n self.assertEquals(links, [])\n\n def testTitleGuess(self):\n \"\"\"Make sure the title is the filename when we treat a text file\n or no title could be found\n \"\"\"\n title, text, links, offset = self.parser.parseFile(join(DATADIR, \"notitle.html\"), 'notitle.html')\n self.assertEquals(title, 'notitle.html')\n self.assertEquals(normalizeText(text), \"maille maay\")\n self.assertEquals(links, [])\n\n\n def testParseSimpleHtml(self):\n title, text, links, offset = self.parser.parseString(SIMPLE_HTML)\n self.assertEquals(title, 'maille Maay')\n self.assertEquals(normalizeText(text),\n 'hello ete world this is a link and this is another link')\n self.assertEquals(links, ['something.com', 'somethingelse.com'])\n \n\n def testParseHtmlFileWithEncoding(self):\n filename = join(DATADIR, 'encoded.html')\n title, text, links, offset = self.parser.parseFile(filename, 'encoded.html', 'iso-8859-1')\n self.assertEquals(title, 'maille Maay')\n self.assertEquals(normalizeText(text),\n 'hello ete world this is a link and this is another link')\n self.assertEquals(links, ['something.com', 'somethingelse.com'])\n \n def testParseHtmlFileAndGuessEncoding(self):\n filename = join(DATADIR, 'encoded.html')\n title, text, links, offset = self.parser.parseFile(filename, 'encoded.html')\n self.assertEquals(title, 'maille Maay')\n self.assertEquals(normalizeText(text),\n 'hello ete world this is a link and this is another link')\n self.assertEquals(links, ['something.com', 'somethingelse.com'])\n \n def test_normalizeHTMLEncoding(self):\n data = [\n 'latin1', 'ISO-8859-1',\n 'iso-88591', 'ISO-8859-1',\n \n ]\n\n def _test_parseDifficultFile(self):\n \"\"\"test_parseDifficultFile: This test fails for now\"\"\"\n # This file has got some weird, non HTML compliant content\n # and is not handled properly by HTMLParser \n stream = file(join(DATADIR, 'node22.html'))\n data = stream.read()\n stream.close()\n title, text, links, offset = self.parser.parseString(data)\n self.assertEquals(title, u'21 Porting to Python 2.3')\n self.failUnless(len(text)>10)\n \n\nclass GuessEncofingTC(unittest.TestCase):\n def testGuessEncoding(self):\n self.assertEquals(guessEncoding(join(DATADIR, 'utf8.txt')), 'UTF-8')\n self.assertEquals(guessEncoding(join(DATADIR, 'utf16.txt')), 'UTF-16')\n # self.assertEquals(guessEncoding(join(DATADIR, 'utf16be.txt')), 'UTF-16')\n self.assertEquals(guessEncoding(join(DATADIR, 'utf32.txt')), 'UTF-32')\n # self.assertEquals(guessEncoding(join(DATADIR, 'utf32be.txt')), 'UTF-32')\n self.assertEquals(guessEncoding(join(DATADIR, 'latin1.xml')), 'ISO-8859-1')\n self.assertEquals(guessEncoding(join(DATADIR, 'utf8.xml')), 'UTF-8')\n self.assertEquals(guessEncoding(join(DATADIR, 'latin1.xml')), 'ISO-8859-1')\n self.assertEquals(guessEncoding(join(DATADIR, 'encoded.html')), 'ISO-8859-1')\n\n def test_guessEncodingRawUTF8Text(self):\n filename = join(DATADIR, 'guess_encoding.txt')\n enc = guessEncoding(filename)\n self.assertEquals(enc, 'UTF-8')\n\n\nclass OpenTC(unittest.TestCase):\n def testGzip(self):\n f = universalOpen(join(DATADIR, 'compressed_gzip.txt.gz'), 'rb', 'utf-8')\n data = f.read()\n f.close()\n self.assertEquals(type(data), unicode)\n self.failUnless(u'entête' in data)\n \n def testBz2(self):\n f = universalOpen(join(DATADIR, 'compressed_bzip2.txt.bz2'), 'rb', 'utf-8')\n data = f.read()\n f.close()\n self.assertEquals(type(data), unicode)\n self.failUnless(u'entête' in data)\n\nclass UtilitiesTC(unittest.TestCase):\n def testUntag(self):\n text = 'Hello world !\"\"'\n self.assertEquals(untagText(text), 'Hello world !')\n\n def testNormalizeText(self):\n text = u\"À Paris,\\t\\x02l'été \\nsera chaud\"\n norm = normalizeText(text)\n self.assertEquals(u\"a paris, l'ete sera chaud\", norm)\n self.assertEquals(unicode, type(norm))\n \n def testRemoveControlChar(self):\n text = u''.join([chr(i) for i in range(32)])\n text += u'\\uFFEF\\uFFFE\\uFFFF'\n text += u'\\uDA00toto\\U00011234'\n norm = removeControlChar(text)\n self.assertEquals(u\"\\t\\n\\r\\uFFEFtoto\\U00011234\", norm)\n self.assertEquals(unicode, type(norm))\n\n def testBasicLStringIO(self):\n buf = LStringIO()\n buf.write('foo')\n buf.write('bar')\n self.assertEquals(buf.getvalue(), 'foobar')\n buf.write(u'baz')\n self.assertEquals(buf.getvalue(), 'foobarbaz')\n\n def testLStringIOWithUnicodeStrings(self):\n buf = LStringIO()\n buf.write(unicode('été', 'iso-8859-1'))\n buf.write('foo')\n buf.write(u'bar')\n self.assertEquals(buf.getvalue(), unicode('étéfoobar', 'iso-8859-1'))\n buf.write(u'baz')\n self.assertEquals(buf.getvalue(), unicode('étéfoobarbaz', 'iso-8859-1'))\n\n\n\nclass AbstractTC(unittest.TestCase):\n text = \"This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\"\n\n def testSimple(self):\n # Check excerpt at the beginning of the text\n\n abstract = makeAbstract(self.text, [u\"free\"])\n expected = u'This program is free software; you can redistribute it and/or modify it under the terms of ... Public License as published by the Free Software Foundation; either version 2 of the License, or (at your ... this program; if not, write to the Free Software Foundation, Inc., 51 ...'\n self.assertEquals(expected, abstract)\n\n def testMixedCase(self):\n abstract = makeAbstract(self.text, [u\"pUrPoSe\"])\n expected = ' ... or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public ...'\n self.assertEquals(expected, abstract)\n\n def testUnknownWord(self):\n abstract = makeAbstract(self.text, [u\"FOOBAR\"])\n expected = 'This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, ...'\n self.assertEquals(expected, abstract)\n\n def testWordAtEnd(self):\n abstract = makeAbstract(self.text, [u\"Boston\"])\n expected = ' ... Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA'\n self.assertEquals(expected, abstract)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tags/release-0.2.1/maay/test/test_texttool.py","file_name":"test_texttool.py","file_ext":"py","file_size_in_byte":10296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"244514538","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 10 12:13:05 2017\r\n\r\n@author: Simon\r\n\"\"\"\r\n\r\nfrom __future__ import division\r\nimport numpy as np\r\nfrom fluo3S_H_avr17_I import *\r\n\r\n##### STRUCTURE DU PROGRAMME #####\r\n# 1. Définition des bases et matrices de passage\r\n# 2. Définition des hamiltoniens\r\n# 3. Calcul de la forme de raie\r\n# 4. Ajustement, enregistrement, affichage\r\n\r\n##### 2. Définition des hamiltoniens\r\n\r\n##### CONSTANTES #####\r\nmub = 1.3996245042 # magnéton de Bohr en MHz/G (CODATA14)\r\nme = 9.10938356e-31 # masse de l'électron en kg (CODATA14)\r\nmN = 1.672621898e-27 # masse du proton en kg (CODATA14)\r\nqe = 1.6021766208e-19 # charge de l'électron en C (CODATA14)\r\na0 = 0.52917721067e-10 # rayon de Bohr en m (CODATA14)\r\nh = 6.626070040e-34 # constante de Planck en J.s (CODATA14)\r\ngN = 5.585694702 # facteur de Landé du noyau (CODATA14)\r\nge = 2.00231930436182 # facteur de Landé de l'électron (CODATA14)\r\ngS_1S = 2.00228377 # facteur de Landé de l'électron (Indelicato)\r\ngS_3S = 2.0023152 # facteur de Landé de l'électron (Indelicato)\r\n\r\n##### NIVEAUX D'ÉNERGIE #####\r\nA1S = 1420.405751768 # Écart hyperfin en MHz en champ nul (Hellwig70)\r\nSF = {1/2:0, 10+1/2:-314.784, 10+3/2:2934.968} # Structure fine\r\n# A3S = A1S/3**3 # Sans correction de Breit : *1/n^3\r\nA3S = 52.6094446 # Avec correction de Breit (Galtier thèse) \r\n\r\n##### CLASSE #####\r\nclass Hamiltonien:\r\n def __init__(self,base,H1S,H3S3P):\r\n self.base = base\r\n self.H1S, self.H3S3P = H1S, H3S3P\r\n \r\n def convert(self,P):\r\n if self.base is not P.base_depart:\r\n return False\r\n H1S_conv = np.dot(P.M1S,np.dot(self.H1S,P.M1S.transpose()))\r\n H3S3P_conv = np.dot(P.M3S3P,np.dot(self.H3S3P,P.M3S3P.transpose()))\r\n return Hamiltonien(P.base_arrivee,H1S_conv,H3S3P_conv)\r\n \r\n def diagonaliser(self):\r\n self.base = 'base H0'\r\n self.E1S, self.M1S = np.linalg.eigh(self.H1S)\r\n self.H1S = np.diag(self.E1S)\r\n self.E3S, self.M3S = np.linalg.eigh(self.H3S3P[-4:,-4:])\r\n self.E3P, self.M3P = np.linalg.eigh(self.H3S3P[:-4,:-4])\r\n self.E3S3P = np.concatenate((self.E3S,self.E3P))\r\n self.H3S3P[-4:,-4:] = np.diag(self.E3S)\r\n self.H3S3P[:-4,:-4] = np.diag(self.E3P)\r\n self.M3S3P = np.zeros((16,16))\r\n self.M3S3P[-4:,-4:] = self.M3S\r\n self.M3S3P[:-4,:-4] = self.M3P\r\n self.LJF_vers_baseH0 = Passage('LJFmF',self.base,self.M1S.transpose(),\r\n self.M3S3P.transpose()) \r\n \r\n def additionner(self,H_ajoute):\r\n if self.base is not H_ajoute.base:\r\n return False\r\n return Hamiltonien(self.base,self.H1S + H_ajoute.H1S,\r\n self.H3S3P + H_ajoute.H3S3P)\r\n \r\n##### CALCUL DES 3 HAMILTONIENS #####\r\ndef H_SHF(): # en MHz (Hagel thèse, Brodsky67, Glass thèse) \r\n base = 'LJFmF' \r\n H1S = A1S/4*np.diag([1,1,-3,1])\r\n H3S3P = np.zeros((16,16))\r\n for n, niv1 in enumerate(LJFmF()):\r\n for m, niv2 in enumerate(LJFmF()):\r\n if n == m: # (I·J)\r\n H3S3P[n,m] = SF[niv1.L*10+niv1.J] \\\r\n + (3/16)*A3S \\\r\n *(niv1.F*(niv1.F+1)-niv1.J*(niv1.J+1)-niv1.I*(niv1.I+1)) \\\r\n /(niv1.J*(niv1.J+1)*(niv1.L+1/2))\r\n if niv1.L != 0 and niv1.J != niv2.J \\\r\n and niv1.L==niv2.L and niv1.F==niv2.F and niv1.mF==niv2.mF: # (I·L)\r\n H3S3P[n,m] = (3/16)*A3S \\\r\n *(-1)**(2*niv1.J+niv1.L+niv1.F+niv1.I+3/2) \\\r\n *np.sqrt((2*niv1.J+1)*(2*niv2.J+1) \\\r\n *(2*niv1.I+1)*(niv1.I+1)*niv1.I \\\r\n *(2*niv1.L+1)*(niv1.L+1)*niv1.L) \\\r\n *wigner6j(niv1.F,niv1.I,niv2.J,1,niv1.J,niv1.I) \\\r\n *wigner6j(niv1.L,niv2.J,1/2,niv1.J,niv1.L,1) \\\r\n /(niv1.L*(niv1.L+1)*(niv1.L+1/2))\r\n return Hamiltonien(base,H1S,H3S3P) \r\n \r\ndef H_Zeeman(B): # en MHz (Hagel thèse, Glass thèse)\r\n base = 'LmSmLmI'\r\n H1S = np.zeros((4,4))\r\n H1S = mub*B*(1/2*gS_1S*np.diag([1,1,-1,-1]) \\\r\n -1/2*gN*me/mN*np.diag([1,-1,1,-1])) \\\r\n -diamagnetique(1,0,0)*B**2*np.diag([1,1,1,1])\r\n H3S3P = np.zeros((16,16))\r\n for n, niv in enumerate(LmSmLmI()):\r\n H3S3P[n,n] = (gS_3S*niv.mS + (1-me/mN)*niv.mL - gN*me/mN*niv.mI)*mub*B\r\n H3S3P[n,n] -= diamagnetique(niv.n,niv.L,niv.mL)*B**2\r\n return Hamiltonien(base,H1S,H3S3P)\r\n \r\ndef diamagnetique(n,L,mL): # en MHz/G² (Delande thèse)\r\n r_perp_2 = n**2*(5*n**2+1-3*L*(L+1))*(L**2+L-1+mL**2)/((2*L-1)*(2*L+3))\r\n return r_perp_2 * qe**2*a0**2/(8*me*h) * 1e-14 # Hz/T² -> MHz/G²\r\n\r\ndef H_Stark(B): # en MHz/(km/s) (Hagel thèse, Glass thèse)\r\n base = 'LJmJmI'\r\n H3S3P = np.zeros((16,16))\r\n for n, niv1 in enumerate(LJmJmI()):\r\n for m, niv2 in enumerate(LJmJmI()):\r\n if niv1.mI != niv2.mI:\r\n H3S3P[n,m] = 0\r\n else:\r\n H3S3P[n,m] = R(niv1.n, niv1.L, niv2.n, niv2.L) \\\r\n *A(niv1.L,niv1.I,niv1.J,niv1.mJ,\r\n niv2.L,niv2.I,niv2.J,niv2.mJ) \\\r\n *a0*qe*B/h * 1e-7 # Hz/(T*m/s) -> MHz/(G*km/s)\r\n return Hamiltonien(base,np.zeros((4,4)),H3S3P)\r\n \r\ndef A(L1,I1,J1,mJ1,L2,I2,J2,mJ2):\r\n # Polarisation du champ motionnel normale à l'axe de quantification\r\n k, S = 1, 1/2 # ordre, spin\r\n return np.sum([-q*np.sin(np.pi/2)/np.sqrt(2) \\\r\n * (-1)**(S+mJ1) \\\r\n * np.sqrt((2*J1+1)*(2*J2+1)*(2*L1+1)*(2*L2+1)) \\\r\n * wigner6j(J1,k,J2,L2,S,L1) \\\r\n * wigner3j(J1,k,J2,-mJ1,q,mJ2) \\\r\n * wigner3j(L1,k,L2,0,0,0) for q in [-1,1]]) # q = delta_mI = +-1\r\n \r\ndef R(n1,L1,n2,L2):\r\n if n1==n2 and np.abs(L1-L2)==1:\r\n return 3/2*n1*np.sqrt(n1**2-max(L1,L2)**2)\r\n else:\r\n return 0","sub_path":"fluo3S_H_avr17_II.py","file_name":"fluo3S_H_avr17_II.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"446796069","text":"from random import random\n\nimport numpy as np\nfrom visual import *\nfrom visual.graph import *\n\nR=0.3\n\nscene.width = 800\nscene.height = 800\n#cir = shapes.circle(radius=R+R*0.1)\n#circ = shapes.circle(radius=R)\n#wash = extrusion(pos=[(0, 0, R), (0, 0, -R)], shape=cir-circ, color=color.white)\n#bottom = extrusion(pos=[(0,0,-R), (0, 0, -R)], shape=circ, color=color.white)\n\n\nN=11\nM=5\nW=0.2\nL=0.1\nsize=0.01\nbal=[]\nnxt=[]\nstri=[]\nstor=[]\nK=100000\nKQQ=0.00000\nKQQ_D=10.03\nrot_speed=100\nwater=15\nair=30\nchg_T=0.25\ng=vector(0,-9.8,0)*100\nstr_max=1.2\nwater_level=-0.7*R\n\n\ncir = shapes.circle(radius=R+R*0.1)\ncirc = shapes.circle(radius=R)\n#semicircle = paths.arc(radius=R, angle1=5*pi/4, angle2=7*pi/4)\nboxbox = shapes.rectangle(pos=(0,0), width=3*R)\nbb=extrusion(pos=[(0, 0, R), (0, 0, -R)], shape=boxbox-cir, color=color.white)\nwash = extrusion(pos=[(0, 0, R), (0, 0, -R)], shape=cir-circ, color=color.white)\nbottom = extrusion(pos=[(0,0,-R), (0, 0, -R)], shape=circ, color=color.white)\n#water = extrusion(pos=[(0, 0, R), (0, 0, -R)], shape=semicircle, color=color.cyan)\nwater_box = box(pos=(0, (water_level-R)/2, 0), length=R*2, height=R+water_level, width=2*R-0.01, color=color.cyan, opacity=0.2)\npointer_rad=0.\npointer_scaler=0.0015\npointer = arrow(pos=(cos(pointer_rad)*R,sin(pointer_rad)*R,R),axis=(cos(pointer_rad)*R/3,sin(pointer_rad)*R/3,0),color=color.black)\nRR=R\nR-=size\n\n\"\"\"\nfor i in range(N):\n for j in range(M):\n pos=vector( (-W*(N-1-i)+W*(i))/(N-1),0, (-L*(M-1-j)+L*(j))/(N-1) )\n #bal.append(sphere(pos=pos, radius = size, color=(random(), random(), random())))\n bal.append(sphere(pos=pos, radius = size, color=(0, 0, 255)))\n nxt.append([])\n if i>0:\n nxt[-1].append((i-1)*M+j)\n if j>0:\n nxt[-1].append(i*M+j-1)\n if i0:\n nxt[-1].append((i-1)*M+j)\n if j>0:\n nxt[-1].append(i*M+j-1)\n if i0 and j0:\n nxt[-1].append((i+1)*M+j-1)\n else:\n if i>0 and j>0:\n nxt[-1].append((i-1)*M+j-1)\n if ij:\n stri[-1][-1].visible=False\nv=[]\nfor i in range(N*M):\n v.append(vector(0,0,0))\nv=np.array(v)\npos=[]\nfor i in range(N*M):\n pos.append(vector(0,0,0))\npos=np.array(pos)\ndt=0.001\nt=0\nwhile True:\n t+=dt\n rate(1/dt)\n for i in range(N*M):\n pos[i]=bal[i].pos\n will_pos=pos+v*dt\n\n now_rot_speed=rot_speed*sin(t/chg_T*3.1415926)\n pointer_rad+=pointer_scaler*now_rot_speed\n pointer.pos=(cos(pointer_rad)*RR,sin(pointer_rad)*RR,RR)\n pointer.axis=(cos(pointer_rad)*RR/3,sin(pointer_rad)*RR/3,0)\n\n for i in range(N*M):\n if (will_pos[i][0]**2+will_pos[i][1]**2)>=R**2:\n v[i]=v[i]\n a=vector(v[i])\n will_pos[i][2]=0\n b=vector(-will_pos[i])\n pos_norm=will_pos[i]/np.sum(will_pos[i]**2)**0.5\n \"\"\"c=(a-2*(a-a.dot(b)/b.mag*b.norm()))\n c_pos=np.dot(c,pos_norm)*pos_norm\n \"\"\"\n\n c=a.dot(b)/b.mag*pos_norm\n #print(a,c,a.dot(b)/b.mag)\n c=a+c*1.01\n\n #c=c-c_pos+c_pos*0.2\n vec=np.cross(-will_pos[i],[0,0,1])\n vec=vec/np.sum(vec**2)**0.5\n #print(vec)\n rot=vec*max(-np.dot(-pos_norm,g),0)/g.mag * now_rot_speed\n #print(t)\n #if int(t/0.25) %2 == 0:\n # rot*=-1\n #print(rot)\n c+=rot\n col=bal[i].color\n #print(col)\n if col[1]<1.0:\n col=(col[0],col[1]+np.sum(rot**2)**0.5/10000,col[2])\n bal[i].color=col\n #print(i,-pos_norm,g,-np.dot(-pos_norm,g),max(-np.dot(-pos_norm,g),0))\n v[i][0]=c.x\n v[i][1]=c.y\n v[i][2]=c.z\n #dot=v[i][0]*will_pos[i][0]+v[i][1]*will_pos[i][1]+v[i][2]*will_pos[i][2]\n #dot/\n if will_pos[i][2]>R:\n v[i][2]=-abs(v[i][2])\n if will_pos[i][2]<-R:\n v[i][2]=abs(v[i][2])\n for i in range(N*M):\n if (np.sum(v[i]**2))**0.5>water and pos[i][1]air:\n v[i]=v[i]/((np.sum(v[i]**2))**0.5)*air\n for i in range(N*M):\n for j in range(len(nxt[i])):\n now=np.sum((pos[i]-pos[nxt[i][j]])**2)**0.5\n #if(now > stor[i][j]):\n F=-K*(now-stor[i][j])\n if F>100:\n F=100\n if F<-100:\n F=-100\n F=F*((pos[i]-pos[nxt[i][j]])/now)\n if(now > stor[i][j]*str_max):\n ve=v[i].dot((pos[i]-pos[nxt[i][j]]))/np.sum((pos[i]-pos[nxt[i][j]])**2)\n if ve > 0:\n v[i]-=ve*(pos[i]-pos[nxt[i][j]])*0.2\n v[i]+=F*dt\n for i in range(N*M):\n for j in range(N*M):\n if i!=j:\n r=np.sum((pos[i]-pos[j])**2)**0.5\n if r < KQQ_D:\n v[i]+=KQQ*((pos[i]-pos[j])/r)/r/r\n #print(v)\n for i in range(N*M):\n if (np.sum(v[i]**2))**0.5>water and pos[i][1]air:\n v[i]=v[i]/((np.sum(v[i]**2))**0.5)*air\n v=v+dt*g\n pos=pos+v*dt\n for i in range(N*M):\n if (pos[i][0]**2+pos[i][1]**2)>=R**2:\n pos_norm=pos[i]/((pos[i][0]**2+pos[i][1]**2)**0.5)*R\n pos[i][0]=pos_norm[0]\n pos[i][1]=pos_norm[1]\n #print(pos[i])\n for i in range(N*M):\n bal[i].pos=pos[i]\n for i in range(N*M):\n for j in range(len(nxt[i])):\n stri[i][j].pos=bal[i].pos\n stri[i][j].axis=bal[nxt[i][j]].pos-bal[i].pos\n\nquit()\n","sub_path":"2017Final_Group15/FIN.py","file_name":"FIN.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"157477162","text":"import os\nimport numpy as np\nimport pandas as pd\n\nfrom keras.models import Sequential,model_from_json\nfrom keras.layers import Dense,Dropout,Activation\nfrom keras import optimizers\nfrom keras.callbacks import EarlyStopping\n\nimport binascii\nfrom sklearn.metrics import r2_score\nfrom multiprocessing import cpu_count\nimport tempfile\n\nfrom deepimpute.util import get_int, set_int, get_input_genes\nfrom deepimpute.util import wMSE, poisson_loss\nfrom deepimpute.util import score_model\n\nos.environ[\"TF_CPP_MIN_VLOG_LEVEL\"] = \"0\"\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\nclass Net(object):\n\n def __init__(\n self,\n dims=[20, 500],\n NN_id=None,\n n_cores=1,\n seed=1234,\n layers=None,\n runDir=os.path.join(tempfile.gettempdir(), \"run\"),\n **kwargs\n ):\n self.seed = int(seed)\n self.runDir = runDir\n self.n_cores = n_cores\n self.NNid = NN_id\n self._sessionDir = None\n\n # Some Network Parameters\n self.step = 0\n self._max_epochs = 500\n self.loss = \"wMSE\"\n self.optimizer = \"Adam\"\n self.learning_rate = 1e-4\n self._dims = dims\n self._batch_size = 64\n\n # Default layers\n if layers is None:\n layers = [\n {\"label\": \"dense\", \"activation\": \"relu\", \"nb_neurons\": 128},\n {\"label\": \"dropout\", \"activation\": \"dropout\", \"rate\": 0.2},\n {\"label\": \"dense\", \"activation\": \"softplus\"},\n ]\n self.layers = layers\n\n \"\"\" Builds the whole neural network model based on the configuration file (if any)\"\"\"\n self.set_params(**kwargs)\n\n \"\"\"Define some properties to control attributes value and assignment\"\"\"\n\n dims = property(get_int(\"_dims\"), set_int(\"_dims\"))\n max_epochs = property(get_int(\"_max_epochs\"), set_int(\"_max_epochs\"))\n batch_size = property(get_int(\"_batch_size\"), set_int(\"_batch_size\"))\n\n @property\n def sessionDir(self):\n if self._sessionDir is None:\n self.sessionDir = None\n return self._sessionDir\n\n @sessionDir.setter\n def sessionDir(self, value):\n if value is None:\n self._sessionDir = os.path.join(self.runDir, self.NNid)\n else:\n self._sessionDir = value\n if not os.path.exists(self.sessionDir):\n os.makedirs(self.sessionDir)\n\n def get_params(self, deep=False):\n return self.__dict__\n\n def display_params(self):\n for nb,layer in enumerate(self.layers):\n pretty_display = ['{}: {}'.format(k,v) for (k,v) in layer.items()]\n print('Layer-{}'.format(nb),pretty_display)\n print('Batch size',self.batch_size)\n print('Learning rate',self.learning_rate)\n print('Loss function',self.loss) \n\n # Load parameters from the configuration file\n def set_params(self, **params):\n if self.n_cores == \"all\":\n self.n_cores = cpu_count()\n\n for key, par in params.items():\n if type(par) is dict:\n setattr(self, key, par.copy())\n else:\n setattr(self, key, par)\n self._check_layer_params()\n\n try:\n self.loss = eval(self.loss)\n except:\n pass\n\n if self.NNid == \"auto\":\n rand = binascii.b2a_hex(os.urandom(3))\n\n if type(rand) is bytes:\n rand = rand.decode()\n \n self.NNid = \"lr={}_bs={}_dims={}-{}_nodes={}_dp={}_{}\".format(\n self.learning_rate,\n self.batch_size,\n self.dims[0],\n self.dims[1],\n self.layers[0][\"nb_neurons\"],\n self.layers[1][\"rate\"],\n rand,\n )\n return self\n\n def _check_layer_params(self):\n for layer in self.layers:\n if \"nb_neurons\" in layer.keys() and type(layer[\"nb_neurons\"]) is not int:\n print(\n \"Warning: nb_neurons must be an integer ({})\".format(\n layer[\"nb_neurons\"]\n )\n )\n layer[\"nb_neurons\"] = int(layer[\"nb_neurons\"])\n if layer[\"label\"] == \"dropout\":\n self.layers += [{\"label\": \"dense\", \"activation\": \"relu\"}]\n if \"nb_neurons\" in layer.keys():\n if layer[\"nb_neurons\"] != self.dims[1]:\n print(\"Addind a dense layer to connect to output neurons\")\n self.layers += [{\"label\": \"dense\", \"activation\": \"relu\"}]\n\n def _build(self, inputDim, outputDim, trainable=True): # build network\n \"\"\" Build the whole network \"\"\"\n\n model = Sequential()\n\n for layer in self.layers:\n if layer[\"label\"] == \"dense\" and \"nb_neurons\" not in layer.keys():\n layer[\"nb_neurons\"] = outputDim\n\n if layer[\"label\"] == \"dense\":\n model.add(Dense(layer[\"nb_neurons\"]))\n if layer[\"activation\"] is not None:\n model.add(Activation(layer[\"activation\"]))\n elif layer[\"label\"] == \"dropout\":\n model.add(Dropout(layer[\"rate\"]))\n else:\n print(\"Unknown layer type. Aborting.\")\n exit(1)\n\n optimizer = getattr(optimizers,self.optimizer)\n model.compile(optimizer=optimizer(lr=self.learning_rate),\n loss=self.loss)\n return model\n \n\n def _fit(self, features, targets, retrieve_training=False):\n \"\"\" Network training \"\"\"\n\n test_samples = np.random.choice(targets.shape[0],\n int(targets.shape[0]/10.),\n replace=False)\n train_samples = np.setdiff1d(range(targets.shape[0]),\n test_samples)\n \n model = self._build(features.shape[1],targets.shape[1])\n model.fit(features[train_samples,:],\n targets[train_samples,:],\n epochs=self.max_epochs,\n batch_size=self.batch_size,\n callbacks=[EarlyStopping(monitor='val_loss', patience=10)],\n validation_data=(features[test_samples,:],targets[test_samples,:]),\n verbose=0\n )\n\n # serialize model to JSON\n model_json = model.to_json()\n \n with open(\"{}/model.json\".format(self.sessionDir), \"w\") as json_file:\n json_file.write(model_json)\n \n # serialize weights to HDF5\n model.save_weights(\"{}/model.h5\".format(self.sessionDir))\n print(\"Saved model to disk\")\n \n return model\n\n def fit(\n self,\n X,\n targetGenes=None,\n predictorGenes=None,\n dists=None,\n labels=None,\n retrieve_training=False,\n **params\n ): # Extract features and start training\n\n if labels is not None:\n data = pd.DataFrame(\n np.reshape(X, list(map(len, labels))),\n index=labels[0],\n columns=labels[1],\n )\n else:\n data = X\n\n if not retrieve_training:\n self.set_params(NNid=\"auto\", **params)\n\n if targetGenes is not None:\n if len(targetGenes) < self.dims[1]:\n self._dims[1] = len(targetGenes)\n\n if predictorGenes is None:\n self.predictorGenes, self.targetGenes = get_input_genes(\n data,\n self.dims[1],\n nbest=self.dims[0],\n distanceMatrix=dists,\n targets=targetGenes\n )[0]\n else:\n self.predictorGenes, self.targetGenes = predictorGenes, targetGenes\n \n features, targets = (\n data.loc[:, self.predictorGenes].values,\n data.loc[:, self.targetGenes].values,\n )\n\n model = self._fit(features, targets, retrieve_training=retrieve_training)\n\n return model\n \n\n def predict(\n self, X_test, saver_path=\"\", checkpoint=None\n ): # Prediction on (new) dataset\n\n # load json and create model\n json_file = open('{}/model.json'.format(self.sessionDir), 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n model = model_from_json(loaded_model_json)\n model.load_weights('{}/model.h5'.format(self.sessionDir))\n \n Y_impute = model.predict(X_test[self.predictorGenes])\n \n if np.sum(np.isnan(Y_impute)) > 0:\n print(\"Removing NaN values\")\n Y_impute = Y_impute.fillna(0)\n return pd.DataFrame(Y_impute, index=X_test.index, columns=self.targetGenes)\n\n def score(self, X, metric=r2_score):\n print(\"Scoring model by masking the matrix.\")\n return score_model(self, X, metric=metric)\n","sub_path":"deepimpute/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":8830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"223671434","text":"from django.urls import path, include\nfrom codestudy import views\n\n# To add a new path, first import the app:\n# import blog\n#\n# Then add the new path:\n# path('blog/', blog.urls, name=\"blog\")\n#\n# Learn more here: https://docs.djangoproject.com/en/2.1/topics/http/urls/\n\nurlpatterns = [\n path('', include('codestudy.urls'))\n]\n\nhandler404 = views.handler404\nhandler500 = views.handler500\nhandler403 = views.handler403\nhandler400 = views.handler400\n","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"144037978","text":"from numpy import *\nimport matplotlib.pyplot as plt\n#define variables\nm = 1. #kg\nk = 100 #N/m\nb = 0.1 #m\nv_0 = 0 # m/s\nu = 0.1 # m/s\nn = 10000 # number of itterations\nT = 2 #s\ng = 9.8 #m/s\nmu_s = 0.6\nmu_d = 0.3\ndt = float(T)/n\n\n\nt = linspace(0,T,n)\nx = zeros_like(t)\nv = zeros_like(t)\na = zeros_like(t)\nF_t = zeros_like(t)\n\nx[0],v[0],a[0] = 0,v_0,0\n\nfor i in range(len(t)-1):\n F = k* (u*t[i] - x[i])\n if v[i] <= 1e-8:\n v[i] = 0.\n if F < g*mu_s*m:\n a[i] = 0.\n else:\n a[i] = F/m - g*mu_s\n else:\n a[i] = F/m - g*mu_d\n\n # a[i] = k/m*((u*dt)-x[i]) -\n v[i+1] = v[i] + a[i] * dt\n x[i+1] = x[i] + v[i+1] * dt\n F_t[i] = k*(u*t[i]-x[i])\n# plt.plot(t,x)\n# plt.grid('on')\n# plt.figure()\n# plt.plot(t,v)\n# plt.grid('on')\n# plt.figure()\n# plt.plot(t,a)\n# plt.grid('on')\n# plt.figure()\nplt.plot(t,F_t)\nplt.xlabel('t [s]');plt.ylabel('N [ kg m/s**2]')\nplt.title('Force in the Spring m = 1')\nplt.grid('on')\n# plt.legend(['x','v','a'])\n\nplt.show()\n","sub_path":"Oblig_3/oppg_t.py","file_name":"oppg_t.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"494965750","text":"import sys\nimport numpy as np\nsys.path.insert(0,'/mnt/data/Proposals/Activity_proposals/sparseprop/sparseprop') #This path contains the C3D feature reading code\nfrom feature import C3D\nclass Utilities:\n \n def save_no_keys(self):#Which creates a list of ids which is only presented in id file not in csv file\n no_keys = []\n cap_labs = []\n frame_dic = {}\n save_data = {}\n with open(self.csv_file) as csvfile:\n captions = csv.reader(csvfile, delimiter=',')\n stat = 1\n for row in captions:\n if(stat):\n stat = 0\n else:\n cap_labs.append(row[0])\n frame_dic[row[0]] = [int(row[1]), int(row[2]), int(row[3])] \n cap_labs = list(set(cap_labs))\n \n for key in self.vid_ids:\n if(key not in self.training_labels):\n print(key,\"1\")\n no_keys.append(key)\n elif(key not in cap_labs):\n print(key,\"2\")\n no_keys.append(key)\n \n save_data['no_keys'] = no_keys\n save_data['frame_dic'] = frame_dic\n\n with open(self.pkl_file, 'wb') as f:\n pickle.dump(save_data, f)\n \n return no_keys, frame_dic\n \n def extract_video_features(self, file, init, num_frames, vid_frames, frame_limit):\n video_features = np.zeros((self.num_frames_out,self.num_features))\n obj = C3D(filename=self.feature_file, t_stride=1, t_size=5)\n obj.open_instance()\n video = obj.read_feat(video_name=file)\n m = video.shape[0]\n ratio = 1.0*m/vid_frames\n init_n = int(ratio*init)\n if(num_frames>=vid_frames):\n nums_n = m - init_n\n else:\n nums_n = int(ratio*num_frames)\n features = obj.read_feat(video_name=file, f_init=init_n, duration=nums_n)\n obj.close_instance()\n if(m>=frame_limit):\n video_features = video[:frame_limit,:]\n else:\n video_features[:m,:] = video\n video_features[m:,:].fill(0)\n \n mx = np.max(video_features)\n mn = np.min(video_features)\n video_features = (video_features-mn)/(mx-mn)\n return video_features\n ","sub_path":"Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"567849083","text":"# -*- coding: utf-8 -*-\n#\n# ICRAR - International Centre for Radio Astronomy Research\n# (c) UWA - The University of Western Australia\n# Copyright by UWA (in the framework of the ICRAR)\n# All rights reserved\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307 USA\n#\n\n\"\"\"\nUtilities for loading LBA files\n\"\"\"\n\nimport mmap\nimport os\nimport sys\nimport numpy as np\n\n\nclass LBAFile(object):\n \"\"\"\n Allows reading a huge LBA file using memory mapping so my IDE doesn't\n crash while trying to load 4+gb of data into ram.\n\n with open open('file', 'r') as f:\n lba = LBAfile(f)\n data = lba.read()\n \"\"\"\n\n def __init__(self, f):\n \"\"\"\n :param f: opened file\n \"\"\"\n self.mm = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)\n self.header = self._read_header()\n self.size = os.fstat(f.fileno()).st_size\n\n @property\n def bytes_per_sample(self):\n num_chan = int(self.header[\"NCHAN\"])\n num_bits = int(self.header[\"NUMBITS\"])\n bandwidth = int(float(self.header[\"BANDWIDTH\"]))\n\n # Each sample contains num_chan channels, the reading for each channel is num_bits\n # bandwidth >> 4 converts a bandwidth value into a byte value\n # e.g. 64 bandwidth = 4, 32 bandwidth = 2, 16 bandwidth = 1\n # final divide by 8 converts from bits to bytes\n return num_chan * num_bits * (bandwidth >> 4) // 8\n\n @property\n def max_samples(self):\n data_size = self.size - int(self.header[\"HEADERSIZE\"])\n max_samples = data_size // self.bytes_per_sample\n # Skip over this number of samples, because every 32 million samples there is\n # a 65535 marker which is meaningless\n max_samples -= max_samples // 32000000\n return max_samples\n\n def _read_header(self):\n \"\"\"\n Reads in an LBA header and stores it in self.header\n It's basically just a flat key = value structure\n :return:\n \"\"\"\n header = {}\n\n bytecount = 0\n expected_size = None # Expected size of the header. We'll know this once we hit the \"HEADERSIZE\" field\n while True:\n line = self.mm.readline()\n if line is None:\n break\n\n bytecount += len(line)\n if expected_size is not None and bytecount >= expected_size:\n break # Gone over expected size of header\n\n line = line.strip()\n\n if line == b\"END\":\n break # Hit the end of header flag\n\n k, v = line.split(b' ', 1)\n header_key = k.decode(\"utf-8\")\n header_value = v.decode(\"utf-8\")\n header[header_key] = header_value\n\n if header_key == \"HEADERSIZE\":\n expected_size = int(header_value)\n\n return header\n\n def read(self, offset=0, samples=0):\n \"\"\"\n Reads a set of samples out of the lba file.\n Note that you can read samples from anywhere in the file by specifying\n an offset to start at.\n :param offset: Sample index to start at (0 indexed)\n :param samples: Number of samples to read from that index.\n :return: ndarray with X = samples, Y = frequencies(4), Z = polarisations(2)\n \"\"\"\n if samples < 0:\n raise Exception(\"Negative samples requested\")\n\n num_chan = int(self.header[\"NCHAN\"])\n num_bits = int(self.header[\"NUMBITS\"])\n data_start = int(self.header[\"HEADERSIZE\"])\n # Richard orginally gave this map [3, -3, 1, -1], but it seems to be wrong as\n # I don't get the correct spread of output values (about 2x the number of 1s as there are 3s)\n # This map was taken from some ancient csiro C code\n val_map = [3, 1, -1, -3] # 2 bit encoding map\n\n # 2 polarisations per frequency, so there are half as many frequencies as channels\n # and twice as many bits per frequency.\n num_freq = num_chan // 2\n num_freq_bits = num_bits * 2\n\n # Calculate number of bytes per sample\n bytes_per_sample = self.bytes_per_sample\n\n # Max samples that can be requested from the file\n max_samples = self.max_samples\n if samples == 0:\n samples = max_samples\n elif samples > max_samples:\n raise Exception(\"{0} samples requested with {1} max samples\".format(samples, max_samples))\n\n # Confirm that the user requested a sane offset\n if offset > max_samples:\n raise Exception(\"Offset {0} > Maxsamples {1}\".format(offset, max_samples))\n elif offset < 0:\n raise Exception(\"Offset {0} < 0\".format(offset))\n\n if offset + samples > max_samples:\n raise Exception(\"Offset {0}, samples {1} will overflow lba file\".format(offset, samples))\n\n sample_offset = offset * bytes_per_sample\n\n # This will result in a mask for the number of bits in each frequency\n # e.g. for 4 bits per frequency, this will have the low 4 bits set\n freq_mask = (1 << num_freq_bits) - 1\n\n # This will result in a mask for the number of bits in a single sample\n # e.g. for 2 bits per sample, this will have the low 2 bits set\n sample_mask = (1 << num_bits) - 1\n\n # Seek to the desired offset\n self.mm.seek(data_start + sample_offset, os.SEEK_SET)\n\n # X = samples, Y = frequency, Z = polarisation\n nparray = np.zeros((samples, num_freq, 2), dtype=np.int8)\n\n samples_output = 0 # Number of samples we dumped into nparray\n samples_read = 0 # Number of samples read, including skipped samples every 32M samples\n while True:\n data = self.mm.read(bytes_per_sample)\n # Read one sample into a byte (should be a short between 0 and 65535)\n intdata = int.from_bytes(data, byteorder=sys.byteorder)\n\n if (samples_read + offset) % 32000000 == 0:\n # Richard said this was all 0s but it was actually all 1s, I hope this is correct.\n if intdata != 65535:\n print(\"Skip value should have been 65535 @ sample {0}, data may be corrupted.\".format(offset + samples_read))\n else:\n print(\"Skip {0} marker @ sample {1}\".format(intdata, offset + samples_read))\n else:\n for frequency in range(num_freq):\n # One sample contains data across all frequencies (4), with two polarisations per frequency\n # e.g. 16 bit sample: 1001,1010,0101,0000\n # freq1: 0000, P0: 00, P1: 11\n # freq2: 0101, P0: 01, P1: 01\n # freq3: 1010, P0: 10, P1: 10\n # freq4: 1001, p0: 01, p1: 10\n freqdata = intdata >> frequency * num_freq_bits & freq_mask # Pull out the low 4 bits for this frequency\n nparray[samples_output][frequency][0] = val_map[freqdata & sample_mask] # Pull out the low two bits for P0\n nparray[samples_output][frequency][1] = val_map[freqdata >> num_bits & sample_mask] # Pull out the high two bits for P1\n samples_output += 1\n\n if samples_output == samples:\n break # Got everything we need\n samples_read += 1\n\n return nparray\n\n def __del__(self):\n self.mm.close()\n","sub_path":"src/lba.py","file_name":"lba.py","file_ext":"py","file_size_in_byte":8060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}